Estimates explanation faithfulness by measuring how often the model output changes in the same direction as feature attribution sign when features are progressively masked. ↑ better.

faithfulness_estimate

faithfulness_estimate(
    forward_func: Callable,
    inputs: TensorOrTupleOfTensorsGeneric,
    attributions: list[TensorOrTupleOfTensorsGeneric] | TensorOrTupleOfTensorsGeneric,
    baselines: BaselineType = None,
    feature_mask: TensorOrTupleOfTensorsGeneric | None = None,
    additional_forward_args: Any = None,
    target: ExplanationTarget | list[ExplanationTarget] = NoTarget(),
    frozen_features: list[Tensor] | None = None,
    max_features_processed_per_batch: int | None = None,
    percentage_feature_removal_per_step: float = 0.0,
    multi_target: bool = False,
    show_progress: bool = True,
    return_intermediate_results: bool = False,
    return_dict: bool = False,
) -> dict | tuple | Tensor | list[Tensor]

Implementation of Faithfulness Estimate by Alvares-Melis at el., 2018a and 2018b. This implementation reuses the batch-computation ideas from captum and therefore it is fully compatible with the Captum library. In addition, the implementation takes some ideas about the implementation of the metric from the python Quantus library.

Computes the correlations of probability drops and the relevance scores on various points, showing the aggregate statistics.

References

1) David Alvarez-Melis and Tommi S. Jaakkola.: "Towards robust interpretability with self-explaining neural networks." NeurIPS (2018): 7786-7795.

Parameters:

  • forward_func

    (Callable) –
    The forward function of the model or any modification of it.
    
  • inputs

    (Tensor or tuple[Tensor, ...]) –

    Input for which attributions are computed. If forward_func takes a single tensor as input, a single input tensor should be provided. If forward_func takes multiple tensors as input, a tuple of the input tensors should be provided. It is assumed that for all given input tensors, dimension 0 corresponds to the number of examples (aka batch size), and if multiple input tensors are provided, the examples must be aligned appropriately.

  • baselines

    (scalar, Tensor, tuple of scalar, or Tensor, default: None ) –
    Baselines define reference values against which the completeness is measured which sometimes
    represent ablated values and are used to compare with the actual inputs to compute
    importance scores in attribution algorithms. They can be represented
    as:
    
    - a single tensor, if inputs is a single tensor, with
      exactly the same dimensions as inputs or the first
      dimension is one and the remaining dimensions match
      with inputs.
    
    - a single scalar, if inputs is a single tensor, which will
      be broadcasted for each input value in input tensor.
    
    - a tuple of tensors or scalars, the baseline corresponding
      to each tensor in the inputs' tuple can be:
    
    - either a tensor with matching dimensions to
      corresponding tensor in the inputs' tuple
      or the first dimension is one and the remaining
      dimensions match with the corresponding
      input tensor.
    
    - or a scalar, corresponding to a tensor in the
      inputs' tuple. This scalar value is broadcasted
      for corresponding input tensor.
    
    Default: None
    
  • attributions

    (Tensor or tuple[Tensor, ...]) –
    Attribution scores computed based on an attribution algorithm.
    This attribution scores can be computed using the implementations
    provided in the `captum.attr` package. Some of those attribution
    approaches are so called global methods, which means that
    they factor in model inputs' multiplier, as described in:
    https://arxiv.org/abs/1711.06104
    Many global attribution algorithms can be used in local modes,
    meaning that the inputs multiplier isn't factored in the
    attribution scores.
    This can be done duing the definition of the attribution algorithm
    by passing `multipy_by_inputs=False` flag.
    For example in case of Integrated Gradients (IG) we can obtain
    local attribution scores if we define the constructor of IG as:
    ig = IntegratedGradients(multipy_by_inputs=False)
    
    Some attribution algorithms are inherently local.
    Examples of inherently local attribution methods include:
    Saliency, Guided GradCam, Guided Backprop and Deconvolution.
    
    For local attributions we can use real-valued perturbations
    whereas for global attributions that perturbation is binary.
    https://arxiv.org/abs/1901.09392
    
    If we want to compute the infidelity of global attributions we
    can use a binary perturbation matrix that will allow us to select
    a subset of features from `inputs` or `inputs - baselines` space.
    This will allow us to approximate sensitivity-n for a global
    attribution algorithm.
    
    Attributions have the same shape and dimensionality as the inputs.
    If inputs is a single tensor then the attributions is a single
    tensor as well. If inputs is provided as a tuple of tensors
    then attributions will be tuples of tensors as well.
    
  • feature_mask

    (Tensor or tuple[Tensor, ...], default: None ) –
        feature_mask defines a mask for the input, grouping
        features which should be perturbed together. feature_mask
        should contain the same number of tensors as inputs.
        Each tensor should
        be the same size as the corresponding input or
        broadcastable to match the input tensor. Each tensor
        should contain integers in the range 0 to num_features
        - 1, and indices corresponding to the same feature should
        have the same value.
        Note that features within each input tensor are perturbed
        independently (not across tensors).
        If the forward function returns a single scalar per batch,
        we enforce that the first dimension of each mask must be 1,
        since attributions are returned batch-wise rather than per
        example, so the attributions must correspond to the
        same features (indices) in each input example.
        If None, then a feature mask is constructed which assigns
        each scalar within a tensor as a separate feature, which
        is perturbed independently.
        Default: None
    
  • additional_forward_args

    (Any, default: None ) –

    If the forward function requires additional arguments other than the inputs for which attributions should not be computed, this argument can be provided. It must be either a single additional argument of a Tensor or arbitrary (non-tuple) type or a tuple containing multiple additional arguments including tensors or any arbitrary python types. These arguments are provided to forward_func in order, following the arguments in inputs. Note that the perturbations are not computed with respect to these arguments.

    Default: None
    
  • target

    (int, tuple, Tensor, or list, default: NoTarget() ) –

    Indices for selecting predictions from output(for classification cases, this is usually the target class). If the network returns a scalar value per example, no target index is necessary. For general 2D outputsattributions_sum_perturbedrget for the corresponding example.

      For outputs with > 2 dimensions, targets can be either:
    
    - A single tuple, which contains #output_dims - 1
      elements. This target index is applied to all examples.
    
    - A list of tuples with length equal to the number of
      examples in inputs (dim 0), and each tuple containing
      #output_dims - 1 elements. Each tuple is applied as the
      target for the corresponding example.
    
    Default: None
    
  • max_features_processed_per_batch

    (int, default: None ) –

    The number of maximum input features that are processed together for every example. In case the number of features to be perturbed in each example (total_features_perturbed) exceeds max_features_processed_per_batch, they will be sliced into batches of max_features_processed_per_batch examples and processed in a sequential order.

  • frozen_features

    (List[Tensor], default: None ) –

    A list of frozen features that are not perturbed. This can be useful for ignoring the input structure features like padding, etc. Default: None In case CLS,PAD,SEP tokens are present in the input, they can be frozen by passing the indices of feature masks that correspond to these tokens.

  • multi_target

    (bool, default: False ) –

    A boolean flag that indicates whether the metric computation is for multi-target explanations. if set to true, the targets are required to be a list of integers each corresponding to a required target class in the output. The corresponding metric outputs are then returned as a list of metric outputs corresponding to each target class. Default is False.

  • show_progress

    (bool, default: True ) –

    Indicates whether to print the progress of the computation.

  • return_intermediate_results

    (bool, default: False ) –

    Indicates whether to return intermediate results of the computation. If set to True, the function will return the sum of attributions for each perturbation step and the forward difference between perturbed and unperturbed input for each perturbation step. Default is False.

  • return_dict

    (bool, default: False ) –

    Indicates whether to return the metric outputs as a dictionary with keys as the metric names and values as the corresponding metric outputs. Default is False.

Returns: Returns: A tuple of three tensors: Tensor: - The faithfulness estimate scores of the batch. The first dimension is equal to the number of examples in the input batch and the second dimension is 1. Tensor: - The sum of attributions for each perturbation step of the batch. Tensor: - The forward difference between perturbed and unperturbed input for each perturbation step of the batch. Examples:: >>> # ImageClassifier takes a single input tensor of images Nx3x32x32, >>> # and returns an Nx10 tensor of class probabilities. >>> net = ImageClassifier() >>> saliency = Saliency(net) >>> input = torch.randn(2, 3, 32, 32, requires_grad=True) >>> baselines = torch.zeros(2, 3, 32, 32) >>> # Computes saliency maps for class 3. >>> attribution = saliency.attribute(input, target=3) >>> # define a perturbation function for the input

>>> # Computes the faithfulness estimate scores for saliency maps
>>> faithfulness_estimate, attr_sums, p_fwds = faithfulness_estimate(net, input, attribution, baselines)
Source code in torchxai/metrics/faithfulness/faithfulness_estimate.py
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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
def faithfulness_estimate(
    forward_func: Callable,
    inputs: TensorOrTupleOfTensorsGeneric,
    attributions: list[TensorOrTupleOfTensorsGeneric] | TensorOrTupleOfTensorsGeneric,
    baselines: BaselineType = None,
    feature_mask: TensorOrTupleOfTensorsGeneric | None = None,
    additional_forward_args: Any = None,
    target: ExplanationTarget | list[ExplanationTarget] = NoTarget(),
    frozen_features: list[torch.Tensor] | None = None,
    max_features_processed_per_batch: int | None = None,
    percentage_feature_removal_per_step: float = 0.0,
    multi_target: bool = False,
    show_progress: bool = True,
    return_intermediate_results: bool = False,
    return_dict: bool = False,
) -> dict | tuple | torch.Tensor | list[torch.Tensor]:
    """
    Implementation of Faithfulness Estimate by Alvares-Melis at el., 2018a and 2018b. This implementation
    reuses the batch-computation ideas from captum and therefore it is fully compatible with the Captum library.
    In addition, the implementation takes some ideas about the implementation of the metric from the python
    Quantus library.

    Computes the correlations of probability drops and the relevance scores on various points,
    showing the aggregate statistics.

    References:
        1) David Alvarez-Melis and Tommi S. Jaakkola.: "Towards robust interpretability with self-explaining
        neural networks." NeurIPS (2018): 7786-7795.

    Args:
        forward_func (Callable):
                The forward function of the model or any modification of it.

        inputs (Tensor or tuple[Tensor, ...]): Input for which
                attributions are computed. If forward_func takes a single
                tensor as input, a single input tensor should be provided.
                If forward_func takes multiple tensors as input, a tuple
                of the input tensors should be provided. It is assumed
                that for all given input tensors, dimension 0 corresponds
                to the number of examples (aka batch size), and if
                multiple input tensors are provided, the examples must
                be aligned appropriately.

        baselines (scalar, Tensor, tuple of scalar, or Tensor):
                Baselines define reference values against which the completeness is measured which sometimes
                represent ablated values and are used to compare with the actual inputs to compute
                importance scores in attribution algorithms. They can be represented
                as:

                - a single tensor, if inputs is a single tensor, with
                  exactly the same dimensions as inputs or the first
                  dimension is one and the remaining dimensions match
                  with inputs.

                - a single scalar, if inputs is a single tensor, which will
                  be broadcasted for each input value in input tensor.

                - a tuple of tensors or scalars, the baseline corresponding
                  to each tensor in the inputs' tuple can be:

                - either a tensor with matching dimensions to
                  corresponding tensor in the inputs' tuple
                  or the first dimension is one and the remaining
                  dimensions match with the corresponding
                  input tensor.

                - or a scalar, corresponding to a tensor in the
                  inputs' tuple. This scalar value is broadcasted
                  for corresponding input tensor.

                Default: None

        attributions (Tensor or tuple[Tensor, ...]):
                Attribution scores computed based on an attribution algorithm.
                This attribution scores can be computed using the implementations
                provided in the `captum.attr` package. Some of those attribution
                approaches are so called global methods, which means that
                they factor in model inputs' multiplier, as described in:
                https://arxiv.org/abs/1711.06104
                Many global attribution algorithms can be used in local modes,
                meaning that the inputs multiplier isn't factored in the
                attribution scores.
                This can be done duing the definition of the attribution algorithm
                by passing `multipy_by_inputs=False` flag.
                For example in case of Integrated Gradients (IG) we can obtain
                local attribution scores if we define the constructor of IG as:
                ig = IntegratedGradients(multipy_by_inputs=False)

                Some attribution algorithms are inherently local.
                Examples of inherently local attribution methods include:
                Saliency, Guided GradCam, Guided Backprop and Deconvolution.

                For local attributions we can use real-valued perturbations
                whereas for global attributions that perturbation is binary.
                https://arxiv.org/abs/1901.09392

                If we want to compute the infidelity of global attributions we
                can use a binary perturbation matrix that will allow us to select
                a subset of features from `inputs` or `inputs - baselines` space.
                This will allow us to approximate sensitivity-n for a global
                attribution algorithm.

                Attributions have the same shape and dimensionality as the inputs.
                If inputs is a single tensor then the attributions is a single
                tensor as well. If inputs is provided as a tuple of tensors
                then attributions will be tuples of tensors as well.

        feature_mask (Tensor or tuple[Tensor, ...], optional):
                    feature_mask defines a mask for the input, grouping
                    features which should be perturbed together. feature_mask
                    should contain the same number of tensors as inputs.
                    Each tensor should
                    be the same size as the corresponding input or
                    broadcastable to match the input tensor. Each tensor
                    should contain integers in the range 0 to num_features
                    - 1, and indices corresponding to the same feature should
                    have the same value.
                    Note that features within each input tensor are perturbed
                    independently (not across tensors).
                    If the forward function returns a single scalar per batch,
                    we enforce that the first dimension of each mask must be 1,
                    since attributions are returned batch-wise rather than per
                    example, so the attributions must correspond to the
                    same features (indices) in each input example.
                    If None, then a feature mask is constructed which assigns
                    each scalar within a tensor as a separate feature, which
                    is perturbed independently.
                    Default: None

        additional_forward_args (Any, optional): If the forward function
                requires additional arguments other than the inputs for
                which attributions should not be computed, this argument
                can be provided. It must be either a single additional
                argument of a Tensor or arbitrary (non-tuple) type or a tuple
                containing multiple additional arguments including tensors
                or any arbitrary python types. These arguments are provided to
                forward_func in order, following the arguments in inputs.
                Note that the perturbations are not computed with respect
                to these arguments.

                Default: None
        target (int, tuple, Tensor, or list, optional): Indices for selecting
                predictions from output(for classification cases,
                this is usually the target class).
                If the network returns a scalar value per example, no target
                index is necessary.
                For general 2D outputsattributions_sum_perturbedrget for the corresponding example.

                  For outputs with > 2 dimensions, targets can be either:

                - A single tuple, which contains #output_dims - 1
                  elements. This target index is applied to all examples.

                - A list of tuples with length equal to the number of
                  examples in inputs (dim 0), and each tuple containing
                  #output_dims - 1 elements. Each tuple is applied as the
                  target for the corresponding example.

                Default: None
        max_features_processed_per_batch (int, optional): The number of maximum input
                features that are processed together for every example. In case the number of
                features to be perturbed in each example (`total_features_perturbed`) exceeds
                `max_features_processed_per_batch`, they will be sliced
                into batches of `max_features_processed_per_batch` examples and processed
                in a sequential order.
        frozen_features (List[torch.Tensor], optional): A list of frozen features that are not perturbed.
                This can be useful for ignoring the input structure features like padding, etc. Default: None
                In case CLS,PAD,SEP tokens are present in the input, they can be frozen by passing the indices
                of feature masks that correspond to these tokens.
        multi_target (bool, optional): A boolean flag that indicates whether the metric computation is for
                multi-target explanations. if set to true, the targets are required to be a list of integers
                each corresponding to a required target class in the output. The corresponding metric outputs
                are then returned as a list of metric outputs corresponding to each target class.
                Default is False.
        show_progress (bool, optional): Indicates whether to print the progress of the computation.
        return_intermediate_results (bool, optional): Indicates whether to return intermediate results
                of the computation. If set to True, the function will return the sum of attributions for each
                perturbation step and the forward difference between perturbed and unperturbed input for each
                perturbation step. Default is False.
        return_dict (bool, optional): Indicates whether to return the metric outputs as a dictionary
                with keys as the metric names and values as the corresponding metric outputs.
                Default is False.
    Returns:
        Returns:
            A tuple of three tensors:
            Tensor: - The faithfulness estimate scores of the batch. The first dimension is equal to the
                    number of examples in the input batch and the second dimension is 1.
            Tensor: - The sum of attributions for each perturbation step
                    of the batch.
            Tensor: - The forward difference between perturbed and unperturbed input for each perturbation step
                    of the batch.
    Examples::
        >>> # ImageClassifier takes a single input tensor of images Nx3x32x32,
        >>> # and returns an Nx10 tensor of class probabilities.
        >>> net = ImageClassifier()
        >>> saliency = Saliency(net)
        >>> input = torch.randn(2, 3, 32, 32, requires_grad=True)
        >>> baselines = torch.zeros(2, 3, 32, 32)
        >>> # Computes saliency maps for class 3.
        >>> attribution = saliency.attribute(input, target=3)
        >>> # define a perturbation function for the input

        >>> # Computes the faithfulness estimate scores for saliency maps
        >>> faithfulness_estimate, attr_sums, p_fwds = faithfulness_estimate(net, input, attribution, baselines)
    """
    with torch.no_grad():
        if multi_target:
            # faithfulness_estimate computation cannot be batched across targets, this is because it requires the removal
            # of attribution features for each target in an desencding order of their importance. Since for each target
            # the order of importance of features can be different, we cannot batch the computation across targets.
            attributions_list = attributions
            targets_list = target
            assert isinstance(attributions_list, list), (
                "attributions must be a list of tensors or list of tuples of tensors"
            )
            assert isinstance(targets_list, list), "targets must be a list of targets"
            assert len(targets_list) == len(
                attributions_list
            ), f"""The number of targets in the targets_list and
                attributions_list must match. Found number of targets in the targets_list is: {len(targets_list)} and in the
                attributions_list: {len(attributions_list)}"""

            faithfulness_estimate_batch_list = []
            attributions_sum_perturbed_batch_list = []
            inputs_perturbed_fwd_diffs_batch_list = []
            for attributions, target in zip(
                attributions_list, targets_list, strict=True
            ):
                (
                    faithfulness_estimate_batch,
                    attributions_sum_perturbed_batch,
                    inputs_perturbed_fwd_diffs_batch,
                ) = faithfulness_estimate(
                    forward_func=forward_func,
                    inputs=inputs,
                    attributions=attributions,
                    baselines=baselines,
                    feature_mask=feature_mask,
                    additional_forward_args=additional_forward_args,
                    target=target,
                    max_features_processed_per_batch=max_features_processed_per_batch,
                    percentage_feature_removal_per_step=percentage_feature_removal_per_step,
                    frozen_features=frozen_features,
                    show_progress=show_progress,
                    return_dict=False,
                    return_intermediate_results=True,
                )
                faithfulness_estimate_batch_list.append(faithfulness_estimate_batch)
                attributions_sum_perturbed_batch_list.append(
                    attributions_sum_perturbed_batch
                )
                inputs_perturbed_fwd_diffs_batch_list.append(
                    inputs_perturbed_fwd_diffs_batch
                )

            if return_intermediate_results:
                if return_dict:
                    return {
                        "faithfulness_estimate_score": faithfulness_estimate_batch_list,
                        "attributions_sum_perturbed": attributions_sum_perturbed_batch_list,
                        "inputs_perturbed_fwd_diffs": inputs_perturbed_fwd_diffs_batch_list,
                    }
                else:
                    return (
                        faithfulness_estimate_batch_list,
                        attributions_sum_perturbed_batch_list,
                        inputs_perturbed_fwd_diffs_batch_list,
                    )
            else:
                if return_dict:
                    return {
                        "faithfulness_estimate_score": faithfulness_estimate_batch_list
                    }
                return faithfulness_estimate_batch_list
        else:
            assert not isinstance(attributions, list), (
                "attributions must be a single tensor or a tuple of tensors"
            )
            assert isinstance(target, (ExplanationTarget)), (
                "target must be a single target for single-target faithfulness_estimate"
            )
            # perform argument formattings
            inputs = _format_tensor_into_tuples(inputs)  # type: ignore
            if baselines is None:
                baselines = tuple(torch.zeros_like(inp) for inp in inputs)
            else:
                baselines = cast(
                    tuple[Tensor, ...], _format_baseline(baselines, inputs)
                )
            additional_forward_args = _format_additional_forward_args(
                additional_forward_args
            )
            attributions = _format_tensor_into_tuples(attributions)  # type: ignore
            feature_mask = _format_tensor_into_tuples(feature_mask)  # type: ignore

            # Make sure that inputs and corresponding attributions have matching sizes.
            assert len(inputs) == len(
                attributions
            ), f"""The number of tensors in the inputs and
                attributions must match. Found number of tensors in the inputs is: {len(inputs)} and in the
                attributions: {len(attributions)}"""
            if feature_mask is not None:
                assert len(feature_mask) == len(
                    feature_mask
                ), f"""The number of tensors in the inputs and
                    feature_masks must match. Found number of tensors in the inputs is: {len(feature_mask)} and in the
                    attributions: {len(feature_mask)}"""
                for input, attribution, mask in zip(
                    inputs, attributions, feature_mask, strict=True
                ):
                    assert input.shape == mask.shape == attribution.shape, f"""
                        The shape of the input, attribution and feature mask must match. Found shapes are: input {input.shape}
                        attribution {attribution.shape} and feature mask {mask.shape}
                        """

            bsz = inputs[0].size(0)
            faithfulness_estimate_batch = []
            attributions_sum_perturbed_batch = []
            inputs_perturbed_fwd_diffs_batch = []
            for sample_idx in tqdm.tqdm(range(bsz), disable=not show_progress):
                (
                    faithfulness_estimate_score,
                    attributions_sum_perturbed,
                    inputs_perturbed_fwd_diffs,
                ) = eval_faithfulness_estimate_single_sample(
                    forward_func=forward_func,
                    inputs=tuple(input[sample_idx].unsqueeze(0) for input in inputs),
                    attributions=tuple(
                        attr[sample_idx].unsqueeze(0) for attr in attributions
                    ),
                    feature_mask=(
                        tuple(mask[sample_idx].unsqueeze(0) for mask in feature_mask)
                        if feature_mask is not None
                        else None
                    ),
                    baselines=(
                        tuple(
                            baseline[sample_idx].unsqueeze(0) for baseline in baselines
                        )
                    ),
                    additional_forward_args=(
                        tuple(
                            (
                                arg[sample_idx].unsqueeze(0)
                                if isinstance(arg, torch.Tensor)
                                else arg
                            )
                            for arg in additional_forward_args
                        )
                        if additional_forward_args is not None
                        else None
                    ),
                    target=(
                        target.value[sample_idx]
                        if isinstance(target.value, (list, torch.Tensor))
                        else target.value
                    ),
                    max_features_processed_per_batch=max_features_processed_per_batch,
                    percentage_feature_removal_per_step=percentage_feature_removal_per_step,
                    frozen_features=(
                        frozen_features[sample_idx]
                        if frozen_features is not None
                        else frozen_features
                    ),
                    show_progress=show_progress,
                )
                faithfulness_estimate_batch.append(faithfulness_estimate_score)
                attributions_sum_perturbed_batch.append(attributions_sum_perturbed)
                inputs_perturbed_fwd_diffs_batch.append(inputs_perturbed_fwd_diffs)
            faithfulness_estimate_batch = torch.tensor(faithfulness_estimate_batch)

            if return_intermediate_results:
                if return_dict:
                    return {
                        "faithfulness_estimate_score": faithfulness_estimate_batch,
                        "attributions_sum_perturbed": attributions_sum_perturbed_batch,
                        "inputs_perturbed_fwd_diffs": inputs_perturbed_fwd_diffs_batch,
                    }
                else:
                    return (
                        faithfulness_estimate_batch,
                        attributions_sum_perturbed_batch,
                        inputs_perturbed_fwd_diffs_batch,
                    )
            else:
                if return_dict:
                    return {"faithfulness_estimate_score": faithfulness_estimate_batch}
                return faithfulness_estimate_batch