GuidedBackpropExplainer

Guided Backpropagation explainer for computing modified gradient attributions.

This explainer computes attributions using Guided Backpropagation, which modifies the backward pass through ReLU activations to only propagate positive gradients. This technique highlights features that have a positive influence on the prediction. Supports both single-target and multi-target modes for both single-target and multi-target scenarios.

The Guided Backpropagation method helps visualize which input features contribute positively to the model's decision by suppressing negative gradients at ReLU layers.

Parameters:

  • model

    (Module) –

    The PyTorch model whose output is to be explained.

  • multi_target

    (bool, default: False ) –

    Whether to use multi-target mode. When True, can compute attributions for multiple targets simultaneously. Defaults to False.

  • internal_batch_size

    (int, default: 64 ) –

    Batch size for internal computations. Defaults to 64.

  • grad_batch_size

    (int, default: 64 ) –

    Batch size for gradient computations. Defaults to 64.

Examples:

Single-target usage:

>>> import torch
>>> from torchxai.data_types import SingleTargetAcrossBatch
>>>
>>> model = torch.nn.Sequential(
...     torch.nn.Linear(10, 5), torch.nn.ReLU(), torch.nn.Linear(5, 2)
... )
>>> explainer = GuidedBackpropExplainer(model)
>>> attributions = explainer.explain(
...     inputs=torch.randn(1, 10),
...     target=SingleTargetAcrossBatch(index=0),
... )
>>> attributions.shape   # (1, 10)

Multi-target usage:

>>> explainer_mt = GuidedBackpropExplainer(model, multi_target=True)
>>> mt_attributions = explainer_mt.explain(
...     inputs=torch.randn(1, 10),
...     target=[SingleTargetAcrossBatch(index=0), SingleTargetAcrossBatch(index=1)],
... )
>>> len(mt_attributions), mt_attributions[0].shape   # 2, (1, 10)

Methods:

  • explain

    Compute Guided Backpropagation attributions for the given inputs.

Source code in torchxai/explainers/_grad/_guided_backprop.py
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
class GuidedBackpropExplainer(FeatureAttributionExplainer):
    """Guided Backpropagation explainer for computing modified gradient attributions.

    This explainer computes attributions using Guided Backpropagation, which modifies
    the backward pass through ReLU activations to only propagate positive gradients.
    This technique highlights features that have a positive influence on the prediction.
    Supports both single-target and multi-target modes for both single-target and multi-target scenarios.

    The Guided Backpropagation method helps visualize which input features contribute
    positively to the model's decision by suppressing negative gradients at ReLU layers.

    Args:
        model: The PyTorch model whose output is to be explained.
        multi_target: Whether to use multi-target mode. When True, can compute
            attributions for multiple targets simultaneously. Defaults to False.
        internal_batch_size: Batch size for internal computations. Defaults to 64.
        grad_batch_size: Batch size for gradient computations. Defaults to 64.

    Examples:
        Single-target usage:
        >>> import torch
        >>> from torchxai.data_types import SingleTargetAcrossBatch
        >>>
        >>> model = torch.nn.Sequential(
        ...     torch.nn.Linear(10, 5), torch.nn.ReLU(), torch.nn.Linear(5, 2)
        ... )
        >>> explainer = GuidedBackpropExplainer(model)
        >>> attributions = explainer.explain(
        ...     inputs=torch.randn(1, 10),
        ...     target=SingleTargetAcrossBatch(index=0),
        ... )
        >>> attributions.shape   # (1, 10)

        Multi-target usage:
        >>> explainer_mt = GuidedBackpropExplainer(model, multi_target=True)
        >>> mt_attributions = explainer_mt.explain(
        ...     inputs=torch.randn(1, 10),
        ...     target=[SingleTargetAcrossBatch(index=0), SingleTargetAcrossBatch(index=1)],
        ... )
        >>> len(mt_attributions), mt_attributions[0].shape   # 2, (1, 10)
    """

    def _init_single_target_explanation_fn(self) -> Callable:
        """Initialize single-target Guided Backpropagation attribution function.

        Returns:
            Captum GuidedBackprop attribution function for single targets.
        """
        return GuidedBackprop(self._model).attribute

    def _init_multi_target_explanation_fn(self) -> Callable:
        """Initialize multi-target Guided Backpropagation attribution function.

        Returns:
            MultiTargetGuidedBackprop attribution function for multiple targets.
        """
        return MultiTargetGuidedBackprop(
            self._model, grad_batch_size=self._grad_batch_size
        ).attribute

    def explain(
        self,
        inputs: TensorOrTupleOfTensorsGeneric,
        target: ExplanationTargetType | list[ExplanationTargetType],
        additional_forward_args: tuple[Any, ...] | None = None,
    ) -> TensorOrTupleOfTensorsGeneric | list[TensorOrTupleOfTensorsGeneric]:
        """Compute Guided Backpropagation attributions for the given inputs.

        Args:
            inputs: Input tensor(s) for attribution computation.
            target: An `ExplanationTargetType` (e.g. `SingleTargetAcrossBatch`) for single-target
                mode, or a list of them for multi-target mode.
            additional_forward_args: Additional arguments for model forward pass.

        Returns:
            Tensor in single-target mode. List of Tensors, one per target, in multi-target mode.

        Note:
            This method temporarily modifies ReLU backward hooks during computation.
            Hooks are automatically removed after attribution computation completes.

        Examples:
            >>> # Single tensor input (wrapped automatically)
            >>> attributions = explainer.explain(
            ...     inputs=torch.randn(2, 10), target=torch.tensor([0, 1])
            ... )
            >>>
            >>> # Multiple features (use OrderedDict)
            >>> attributions = explainer.explain(
            ...     inputs=OrderedDict(
            ...         {"feat1": torch.randn(2, 5), "feat2": torch.randn(2, 5)}
            ...     ),
            ...     target=torch.tensor([0, 1]),
            ... )
        """
        return self._default_explain(
            inputs=inputs,
            target=target,
            additional_forward_args=additional_forward_args,
        )

explain

explain(
    inputs: TensorOrTupleOfTensorsGeneric,
    target: ExplanationTargetType | list[ExplanationTargetType],
    additional_forward_args: tuple[Any, ...] | None = None,
) -> TensorOrTupleOfTensorsGeneric | list[TensorOrTupleOfTensorsGeneric]

Compute Guided Backpropagation attributions for the given inputs.

Parameters:

  • inputs
    (TensorOrTupleOfTensorsGeneric) –

    Input tensor(s) for attribution computation.

  • target
    (ExplanationTargetType | list[ExplanationTargetType]) –

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

  • additional_forward_args
    (tuple[Any, ...] | None, default: None ) –

    Additional arguments for model forward pass.

Returns:

  • TensorOrTupleOfTensorsGeneric | list[TensorOrTupleOfTensorsGeneric]

    Tensor in single-target mode. List of Tensors, one per target, in multi-target mode.

Note

This method temporarily modifies ReLU backward hooks during computation. Hooks are automatically removed after attribution computation completes.

Examples:

>>> # Single tensor input (wrapped automatically)
>>> attributions = explainer.explain(
...     inputs=torch.randn(2, 10), target=torch.tensor([0, 1])
... )
>>>
>>> # Multiple features (use OrderedDict)
>>> attributions = explainer.explain(
...     inputs=OrderedDict(
...         {"feat1": torch.randn(2, 5), "feat2": torch.randn(2, 5)}
...     ),
...     target=torch.tensor([0, 1]),
... )
Source code in torchxai/explainers/_grad/_guided_backprop.py
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
def explain(
    self,
    inputs: TensorOrTupleOfTensorsGeneric,
    target: ExplanationTargetType | list[ExplanationTargetType],
    additional_forward_args: tuple[Any, ...] | None = None,
) -> TensorOrTupleOfTensorsGeneric | list[TensorOrTupleOfTensorsGeneric]:
    """Compute Guided Backpropagation attributions for the given inputs.

    Args:
        inputs: Input tensor(s) for attribution computation.
        target: An `ExplanationTargetType` (e.g. `SingleTargetAcrossBatch`) for single-target
            mode, or a list of them for multi-target mode.
        additional_forward_args: Additional arguments for model forward pass.

    Returns:
        Tensor in single-target mode. List of Tensors, one per target, in multi-target mode.

    Note:
        This method temporarily modifies ReLU backward hooks during computation.
        Hooks are automatically removed after attribution computation completes.

    Examples:
        >>> # Single tensor input (wrapped automatically)
        >>> attributions = explainer.explain(
        ...     inputs=torch.randn(2, 10), target=torch.tensor([0, 1])
        ... )
        >>>
        >>> # Multiple features (use OrderedDict)
        >>> attributions = explainer.explain(
        ...     inputs=OrderedDict(
        ...         {"feat1": torch.randn(2, 5), "feat2": torch.randn(2, 5)}
        ...     ),
        ...     target=torch.tensor([0, 1]),
        ... )
    """
    return self._default_explain(
        inputs=inputs,
        target=target,
        additional_forward_args=additional_forward_args,
    )