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:

  • model

    (Module) –

    The PyTorch model for which explanations will be computed.

Attributes:

  • model

    The model used for attribution computation.

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
class Explainer(ABC):
    """Abstract base class for TorchXAI explainers.

    Provides a common interface for all explanation methods in TorchXAI,
    supporting both single-target and multi-target attribution.

    Args:
        model: The PyTorch model for which explanations will be computed.

    Attributes:
        model: The model used for attribution computation.
    """

    __repr_attrs__: list[str] = []

    def __init__(self, model: torch.nn.Module) -> None:
        self._model = model

    @abstractmethod
    def explain(
        self, *args, **kwargs
    ) -> TensorOrTupleOfTensorsGeneric | list[TensorOrTupleOfTensorsGeneric]:
        """Compute attributions for the given inputs.

        Args:
            *args: Positional arguments passed to the underlying attribution method.
            **kwargs: Keyword arguments including `inputs`, `target`, and method-specific
                parameters such as `baselines`, `feature_mask`, and `sliding_window_shapes`.

        Returns:
            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.
        """

    def __repr__(self) -> str:
        attr_str = ", ".join(
            f"{attr.lstrip('_')}={getattr(self, attr)}" for attr in self.__repr_attrs__
        )
        return f"{self.__class__.__name__}({attr_str})"

explain abstractmethod

explain(
    *args, **kwargs
) -> TensorOrTupleOfTensorsGeneric | list[TensorOrTupleOfTensorsGeneric]

Compute attributions for the given inputs.

Parameters:

  • *args

    Positional arguments passed to the underlying attribution method.

  • **kwargs

    Keyword arguments including inputs, target, and method-specific parameters such as baselines, feature_mask, and sliding_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
@abstractmethod
def explain(
    self, *args, **kwargs
) -> TensorOrTupleOfTensorsGeneric | list[TensorOrTupleOfTensorsGeneric]:
    """Compute attributions for the given inputs.

    Args:
        *args: Positional arguments passed to the underlying attribution method.
        **kwargs: Keyword arguments including `inputs`, `target`, and method-specific
            parameters such as `baselines`, `feature_mask`, and `sliding_window_shapes`.

    Returns:
        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.
    """

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:

  • model

    (Module) –

    The PyTorch model for which explanations will be computed.

  • multi_target

    (bool, default: False ) –

    When True the explainer accepts a list of ExplanationTargetType objects as target and returns a list[Tensor]. Defaults to False.

  • internal_batch_size

    (int, default: 64 ) –

    Batch size used internally for attribution computation. Defaults to 64.

  • grad_batch_size

    (int, 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

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
class FeatureAttributionExplainer(Explainer):
    """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.

    Args:
        model: The PyTorch model for which explanations will be computed.
        multi_target: When ``True`` the explainer accepts a list of
            `ExplanationTargetType` objects as ``target`` and returns a
            ``list[Tensor]``. Defaults to ``False``.
        internal_batch_size: Batch size used internally for attribution computation.
            Defaults to 64.
        grad_batch_size: Batch size used for gradient computation operations.
            Defaults to 64.

    Attributes:
        model: The model used for attribution computation.
        multi_target: Flag controlling single- vs. multi-target mode.
        internal_batch_size: Internal batch size for computations.
        grad_batch_size: 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
    """

    __repr_attrs__ = ["_multi_target", "_internal_batch_size", "_grad_batch_size"]

    def __init__(
        self,
        model: torch.nn.Module,
        multi_target: bool = False,
        internal_batch_size: int = 64,
        grad_batch_size: int = 64,
    ) -> None:
        super().__init__(model)
        self._multi_target = multi_target
        self._internal_batch_size = internal_batch_size
        self._grad_batch_size = grad_batch_size
        self._explanation_fn = self._init_explanation_fn()

    @property
    def model(self) -> torch.nn.Module:
        """The model used for attribution computation."""
        return self._model

    @model.setter
    def model(self, model: torch.nn.Module) -> None:
        """Set the model and reinitialize the explanation function.

        Args:
            model: The new PyTorch model to use for explanations.
        """
        self._model = model
        self._explanation_fn = self._init_explanation_fn()

    @property
    def multi_target(self) -> bool:
        """Whether the explainer uses multi-target mode."""
        return self._multi_target

    @multi_target.setter
    def multi_target(self, multi_target: bool) -> None:
        """Set multi-target mode and reinitialize the explanation function.

        Args:
            multi_target: Whether to enable multi-target mode.
        """
        self._multi_target = multi_target
        self._explanation_fn = self._init_explanation_fn()

    def _init_explanation_fn(self) -> Callable:
        """Initialize the appropriate explanation function based on mode.

        Returns:
            A callable that computes attributions for the configured model.
        """
        if self._multi_target:
            return self._init_multi_target_explanation_fn()
        else:
            return self._init_single_target_explanation_fn()

    @abstractmethod
    def _init_single_target_explanation_fn(self) -> Callable:
        """Initialize the single-target attribution generation callable.

        This method must be implemented by subclasses to provide the specific
        single-target attribution computation logic.

        Returns:
            A callable that computes single-target attributions.
        """

    def _init_multi_target_explanation_fn(self) -> Callable:
        """Initialize the multi-target attribution generation callable.

        This method provides a default implementation that falls back to iterative
        calls to the single-target explainer if not overridden by subclasses.
        Subclasses should override this method for more efficient multi-target implementations.

        Returns:
            A callable that computes multi-target attributions by iterating over targets.
        """
        # Fix: Call single-target method directly to avoid infinite recursion
        single_target_fn = self._init_single_target_explanation_fn()

        def _default_multi_target_explanation_fn(*args, **kwargs):
            targets = kwargs.pop("target", [])
            return [
                single_target_fn(*args, target=target, **kwargs) for target in targets
            ]

        return _default_multi_target_explanation_fn

    def _single_target_forward(
        self, **explanation_inputs
    ) -> TensorOrTupleOfTensorsGeneric:
        """Forward pass for single-target explanations.

        Args:
            explanation_inputs: Structured explanation inputs containing features and target.

        Returns:
            Dictionary mapping feature names to their corresponding attributions.
        """
        # inspect explainer signature and save
        target = explanation_inputs.pop("target")
        assert isinstance(target, ExplanationTarget), (
            "Explainer explain method must be called with target of type ExplanationTarget."
        )
        return self._explanation_fn(**explanation_inputs, target=target.value)

    def _multi_target_forward(
        self, **explanation_inputs
    ) -> list[TensorOrTupleOfTensorsGeneric]:
        """Forward pass for multi-target explanations.

        Args:
            explanation_inputs: Structured explanation inputs with list of targets.

        Returns:
            List of Tensors, one per target.

        Raises:
            AssertionError: If targets are not properly formatted for multi-target mode.
        """
        # inspect explainer signature and saveexplanation_inputs
        target = explanation_inputs.pop("target")
        assert isinstance(target, list), (
            "Target must be a list for multi-target explanation."
        )
        target_validated = []
        for t in target:
            assert isinstance(t, ExplanationTarget), (
                "Each target in multi-target explanation must be of type ExplanationTarget."
            )
            target_validated.append(t.value)
        per_target_explanations = self._explanation_fn(
            **explanation_inputs, target=target_validated
        )
        assert isinstance(per_target_explanations, list), (
            "Explanations must be a list for multi-target explanation."
        )
        assert len(per_target_explanations) == len(target), (
            "Number of explanations must match number of targets."
        )

        return per_target_explanations

    def _default_explain(
        self, **kwargs
    ) -> TensorOrTupleOfTensorsGeneric | list[TensorOrTupleOfTensorsGeneric]:
        # get the explanation_outputs
        # get value of the target

        if self._multi_target:
            return self._multi_target_forward(**kwargs)
        else:
            return self._single_target_forward(**kwargs)

    @abstractmethod
    def explain(
        self, *args, **kwargs
    ) -> TensorOrTupleOfTensorsGeneric | list[TensorOrTupleOfTensorsGeneric]:
        """Compute attributions for the given inputs.

        Args:
            inputs: Input tensor(s) for which attributions are computed.
            target: An `ExplanationTargetType` (e.g. `SingleTargetAcrossBatch`) for
                single-target mode, or a list of them for multi-target mode.
            **kwargs: Additional method-specific arguments (`baselines`,
                `feature_mask`, `sliding_window_shapes`, etc.).

        Returns:
            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.
        """

    def __repr__(self) -> str:
        attr_str = ", ".join(
            f"{attr.lstrip('_')}={getattr(self, attr)}" for attr in self.__repr_attrs__
        )
        return f"{self.__class__.__name__}({attr_str})"

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:

  • inputs

    Input tensor(s) for which attributions are computed.

  • target

    An ExplanationTargetType (e.g. SingleTargetAcrossBatch) for single-target mode, or a list of them for multi-target mode.

  • **kwargs

    Additional 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
@abstractmethod
def explain(
    self, *args, **kwargs
) -> TensorOrTupleOfTensorsGeneric | list[TensorOrTupleOfTensorsGeneric]:
    """Compute attributions for the given inputs.

    Args:
        inputs: Input tensor(s) for which attributions are computed.
        target: An `ExplanationTargetType` (e.g. `SingleTargetAcrossBatch`) for
            single-target mode, or a list of them for multi-target mode.
        **kwargs: Additional method-specific arguments (`baselines`,
            `feature_mask`, `sliding_window_shapes`, etc.).

    Returns:
        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.
    """

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.