TorchXAI provides two abstract base classes that all concrete explainers inherit from.
Explainer
The root abstract base class. Defines the explain() interface and a default __repr__.
Explainer
Abstract base class for TorchXAI explainers.
Provides a common interface for all explanation methods in TorchXAI, supporting both single-target and multi-target attribution.
Parameters:
-
(modelModule) –The PyTorch model for which explanations will be computed.
Attributes:
-
model–The model used for attribution computation.
-
sensitivity_max_and_avg - Metrics Robustness
Methods:
-
explain–Compute attributions for the given inputs.
Source code in torchxai/explainers/_explainer.py
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | |
explain
abstractmethod
Compute attributions for the given inputs.
Parameters:
-
–*argsPositional arguments passed to the underlying attribution method.
-
–**kwargsKeyword arguments including
inputs,target, and method-specific parameters such asbaselines,feature_mask, andsliding_window_shapes.
Returns:
-
TensorOrTupleOfTensorsGeneric | list[TensorOrTupleOfTensorsGeneric]–Tensor in single-target mode. List of Tensors, one per target, in multi-target mode.
Raises:
-
AssertionError–If target format doesn't match the explainer mode.
Source code in torchxai/explainers/_explainer.py
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | |
FeatureAttributionExplainer
Extends Explainer with multi_target support, configurable batch sizes, and the routing logic that dispatches explain() calls to single-target or multi-target Captum attribution functions. All concrete explainers inherit from this class.
FeatureAttributionExplainer
Concrete base class for all TorchXAI feature-attribution explainers.
Extends Explainer with multi_target support, configurable batch sizes, and
the plumbing that routes explain() calls to single-target or multi-target
Captum attribution functions.
All concrete explainers (SaliencyExplainer, IntegratedGradientsExplainer,
etc.) inherit from this class.
Parameters:
-
(modelModule) –The PyTorch model for which explanations will be computed.
-
(multi_targetbool, default:False) –When
Truethe explainer accepts a list ofExplanationTargetTypeobjects astargetand returns alist[Tensor]. Defaults toFalse. -
(internal_batch_sizeint, default:64) –Batch size used internally for attribution computation. Defaults to 64.
-
(grad_batch_sizeint, default:64) –Batch size used for gradient computation operations. Defaults to 64.
Attributes:
-
model(Module) –The model used for attribution computation.
-
multi_target(bool) –Flag controlling single- vs. multi-target mode.
-
internal_batch_size(bool) –Internal batch size for computations.
-
grad_batch_size(bool) –Batch size for gradient operations.
Examples:
>>> import torch
>>> from torchxai.explainers import SaliencyExplainer
>>> from torchxai.data_types import SingleTargetAcrossBatch
>>>
>>> model = torch.nn.Linear(10, 3)
>>> inputs = torch.randn(1, 10)
>>>
>>> # Single-target
>>> explainer = SaliencyExplainer(model, multi_target=False)
>>> attrs = explainer.explain(inputs=inputs, target=SingleTargetAcrossBatch(index=0))
>>> attrs.shape # (1, 10)
>>>
>>> # Multi-target
>>> explainer_mt = SaliencyExplainer(model, multi_target=True)
>>> targets = [SingleTargetAcrossBatch(index=i) for i in range(3)]
>>> attrs_list = explainer_mt.explain(inputs=inputs, target=targets)
>>> len(attrs_list) # 3
-
Metrics
Axiomatic
input_invarianceinput_invariance
Methods:
-
explain–Compute attributions for the given inputs.
Source code in torchxai/explainers/_explainer.py
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 | |
model
property
writable
model: Module
The model used for attribution computation.
multi_target
property
writable
multi_target: bool
Whether the explainer uses multi-target mode.
explain
abstractmethod
explain(
*args, **kwargs
) -> TensorOrTupleOfTensorsGeneric | list[TensorOrTupleOfTensorsGeneric]
Compute attributions for the given inputs.
Parameters:
-
–inputsInput tensor(s) for which attributions are computed.
-
–targetAn
ExplanationTargetType(e.g.SingleTargetAcrossBatch) for single-target mode, or a list of them for multi-target mode. -
–**kwargsAdditional method-specific arguments (
baselines,feature_mask,sliding_window_shapes, etc.).
Returns:
-
TensorOrTupleOfTensorsGeneric | list[TensorOrTupleOfTensorsGeneric]–Tensor in single-target mode. List of Tensors, one per target, in multi-target mode.
Raises:
-
AssertionError–If target format doesn't match the explainer mode.
Source code in torchxai/explainers/_explainer.py
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 | |
Implementing a custom explainer
Subclass FeatureAttributionExplainer and implement _init_single_target_explanation_fn() plus explain():
from collections.abc import Callable
import torch
from captum.attr import Saliency
from torchxai.explainers import FeatureAttributionExplainer
from torchxai.data_types import SingleTargetAcrossBatch
class MySaliencyExplainer(FeatureAttributionExplainer):
def _init_single_target_explanation_fn(self) -> Callable:
return Saliency(self._model).attribute
def explain(self, inputs: torch.Tensor, target, **kwargs) -> torch.Tensor:
return self._default_explain(inputs=inputs, target=target, **kwargs)
model = torch.nn.Sequential(torch.nn.Linear(10, 3), torch.nn.ReLU())
explainer = MySaliencyExplainer(model, multi_target=False)
attrs = explainer.explain(
inputs=torch.randn(1, 10),
target=SingleTargetAcrossBatch(index=0),
)
print(attrs.shape) # (1, 10)
To override the multi-target implementation (e.g. for a more efficient batched approach), also implement _init_multi_target_explanation_fn(). Otherwise the default falls back to iterating _init_single_target_explanation_fn() once per target.