def default_perturb_func(inputs: TensorOrTupleOfTensorsGeneric, baselines: BaselineType = None): r""" """ inputs_perturbed = (pertub_func(inputs, baselines) if baselines is not None else pertub_func(inputs)) inputs_perturbed = _format_tensor_into_tuples(inputs_perturbed) inputs = _format_tensor_into_tuples(inputs) baselines = _format_baseline(baselines, inputs) if baselines is None: perturbations = tuple( safe_div( input - input_perturbed, input, default_denom=1.0, ) if multipy_by_inputs else input - input_perturbed for input, input_perturbed in zip(inputs, inputs_perturbed)) else: perturbations = tuple( safe_div( input - input_perturbed, input - baseline, default_denom=1.0, ) if multipy_by_inputs else input - input_perturbed for input, input_perturbed, baseline in zip( inputs, inputs_perturbed, baselines)) return perturbations, inputs_perturbed
def _next_infidelity(current_n_perturb_samples: int) -> Tensor: perturbations, inputs_perturbed = _generate_perturbations( current_n_perturb_samples ) perturbations = _format_tensor_into_tuples(perturbations) inputs_perturbed = _format_tensor_into_tuples(inputs_perturbed) _validate_inputs_and_perturbations( cast(Tuple[Tensor, ...], inputs), cast(Tuple[Tensor, ...], inputs_perturbed), cast(Tuple[Tensor, ...], perturbations), ) targets_expanded = _expand_target( target, current_n_perturb_samples, expansion_type=ExpansionTypes.repeat_interleave, ) additional_forward_args_expanded = _expand_additional_forward_args( additional_forward_args, current_n_perturb_samples, expansion_type=ExpansionTypes.repeat_interleave, ) inputs_perturbed_fwd = _run_forward( forward_func, inputs_perturbed, targets_expanded, additional_forward_args_expanded, ) inputs_fwd = _run_forward(forward_func, inputs, target, additional_forward_args) inputs_fwd = torch.repeat_interleave( inputs_fwd, current_n_perturb_samples, dim=0 ) inputs_minus_perturb = inputs_fwd - inputs_perturbed_fwd attributions_expanded = tuple( torch.repeat_interleave(attribution, current_n_perturb_samples, dim=0) for attribution in attributions ) attributions_times_perturb = tuple( (attribution_expanded * perturbation).view(attribution_expanded.size(0), -1) for attribution_expanded, perturbation in zip( attributions_expanded, perturbations ) ) attribution_times_perturb_sums = sum( [ torch.sum(attribution_times_perturb, dim=1) for attribution_times_perturb in attributions_times_perturb ] ) return torch.sum( torch.pow( attribution_times_perturb_sums - inputs_minus_perturb.view(-1), 2 ).view(bsz, -1), dim=1, )
def update(self, x: Union[Tensor, Tuple[Tensor, ...]]): r""" Calls `update` on each `Stat` object within the summarizer Args: x (Tensor or Tuple[Tensor, ...]): The input(s) you wish to summarize """ if self._is_inputs_tuple is None: self._is_inputs_tuple = isinstance(x, tuple) else: # we want input to be consistently a single input or a tuple assert not (self._is_inputs_tuple ^ isinstance(x, tuple)) from captum._utils.common import _format_tensor_into_tuples x = _format_tensor_into_tuples(x) for i, inp in enumerate(x): if i >= len(self._summarizers): # _summarizers[i] is a new SummarizerSingleTensor, which # aims to summarize input i (i.e. x[i]) # # Thus, we must copy our stats, as otherwise # in the best case the statistics for each input will be mangled # and in the worst case we will run into an error due to different # dimensionality in the input tensors tensors (i.e. # x[i].shape != x[j].shape for some pair i, j) stats = self._copy_stats() self._summarizers.append( SummarizerSingleTensor( stats=stats, summary_stats_indices=self._summary_stats_indicies)) self._summarizers[i].update(inp)
def compute_partial_attribution( inputs_with_noise_partition: Tuple[Tensor, ...], kwargs_partition: Any ) -> Tuple[Tuple[Tensor, ...], bool, Union[None, Tensor]]: # smoothgrad_Attr(x) = 1 / n * sum(Attr(x + N(0, sigma^2)) # NOTE: using __wrapped__ such that it does not log the inner logs attributions = attr_func.__wrapped__( # type: ignore self.attribution_method, # self inputs_with_noise_partition if is_inputs_tuple else inputs_with_noise_partition[0], **kwargs_partition, ) delta = None if self.is_delta_supported and return_convergence_delta: attributions, delta = attributions is_attrib_tuple = _is_tuple(attributions) attributions = _format_tensor_into_tuples(attributions) return ( cast(Tuple[Tensor, ...], attributions), cast(bool, is_attrib_tuple), delta, )
def _forward_pre_hook(self, module: Module, inputs: Union[Tensor, Tuple[Tensor, ...]]) -> None: """ For the modules that perform in-place operations such as ReLUs, we cannot use inputs from forward hooks. This is because in that case inputs and outputs are the same. We need access the inputs in pre-hooks and set necessary hooks on inputs there. """ inputs = _format_tensor_into_tuples(inputs) module.input = inputs[0].clone().detach() module.input_grad_fns = inputs[0].grad_fn # type: ignore def tensor_backward_hook(grad): if module.saved_grad is None: raise RuntimeError( """Module {} was detected as not supporting correctly module backward hook. You should modify your hook to ignore the given grad_inputs (recompute them by hand if needed) and save the newly computed grad_inputs in module.saved_grad. See MaxPool1d as an example.""".format(module)) return module.saved_grad # the hook is set by default but it will be used only for # failure cases and will be removed otherwise handle = inputs[0].register_hook(tensor_backward_hook) module.input_hook = handle
def _forward_hook( self, module: Module, inputs: Union[Tensor, Tuple[Tensor, ...]], outputs: Union[Tensor, Tuple[Tensor, ...]], ) -> None: r""" we need forward hook to access and detach the inputs and outputs of a neuron """ outputs = _format_tensor_into_tuples(outputs) module.output = outputs[0].clone().detach() if not _check_valid_module(module.input_grad_fns, outputs[0]): warnings.warn( """An invalid module {} is detected. Saved gradients will be used as the gradients of the module's input tensor. See MaxPool1d as an example.""".format(module)) module.is_invalid = True # type: ignore module.saved_grad = None # type: ignore self.forward_handles.append( cast(RemovableHandle, module.input_hook)) else: module.is_invalid = False # type: ignore # removing the hook if there is no failure case cast(RemovableHandle, module.input_hook).remove() del module.input_hook del module.input_grad_fns
def _forward_pre_hook_ref( self, module: Module, inputs: Union[Tensor, Tuple[Tensor, ...]] ) -> None: inputs = _format_tensor_into_tuples(inputs) module.input_ref = tuple( # type: ignore input.clone().detach() for input in inputs )
def attribute( self, inputs: TensorOrTupleOfTensorsGeneric, target: TargetType = None, additional_forward_args: Any = None, ) -> TensorOrTupleOfTensorsGeneric: r""" Computes attribution by overriding relu gradients. Based on constructor flag use_relu_grad_output, performs either GuidedBackpropagation if False and Deconvolution if True. This class is the parent class of both these methods, more information on usage can be found in the docstrings for each implementing class. """ # Keeps track whether original input is a tuple or not before # converting it into a tuple. is_inputs_tuple = _is_tuple(inputs) inputs = _format_tensor_into_tuples(inputs) gradient_mask = apply_gradient_requirements(inputs) # set hooks for overriding ReLU gradients warnings.warn( "Setting backward hooks on ReLU activations." "The hooks will be removed after the attribution is finished") try: self.model.apply(self._register_hooks) gradients = self.gradient_func(self.forward_func, inputs, target, additional_forward_args) finally: self._remove_hooks() undo_gradient_requirements(inputs, gradient_mask) return _format_output(is_inputs_tuple, gradients)
def _forward_hook_fn( self, module: Module, module_input: Union[Tensor, Tuple[Tensor, ...]], module_output: Union[Tensor, Tuple[Tensor, ...]], ): inp_tuple = _format_tensor_into_tuples(module_input) self.activation_dict[module].append(inp_tuple[0].clone().detach())
def _backward_hook_fn( self, module: Module, grad_input: Union[Tensor, Tuple[Tensor, ...]], grad_output: Union[Tensor, Tuple[Tensor, ...]], ): grad_output_tuple = _format_tensor_into_tuples(grad_output) self.gradient_dict[module].append( grad_output_tuple[0].clone().detach())
def update( # type: ignore self, x: TensorOrTupleOfTensorsGeneric, labels: TargetType = None, ): r""" Updates the stats of the summarizer, optionally associated to classes. This accepts either a single tensor to summarise or a tuple of tensors. Args: x (Tensor or Tuple[Tensor, ...]): The input tensor to be summarised. The first dimension of this input must be associated to the batch size of the inputs. labels (int, tuple, tensor or list, optional): The associated labels for `x`. If Any, we assume `labels` represents the label for all inputs in `x`. If this is None we simply aggregate the total summary. """ if labels is None: super().update(x) return x = _format_tensor_into_tuples(x) num_labels = 1 labels_typed: Union[List[Any], Tensor] if isinstance(labels, list) or isinstance(labels, Tensor): labels_typed = labels num_labels = len(labels) # = labels.size(0) if tensor else: labels_typed = [labels] # mypy doesn't realise I have made the int a list if len(labels_typed) > 1: for x_i in x: assert x_i.size(0) == num_labels, ( "batch size does not equal amount of labels; " "please ensure length of labels is equal to 1 " "or to the `batch_size` corresponding to the " "number of examples in the input(s)") batch_size = x[0].size(0) for i in range(batch_size): tensors_to_summarize = tuple(tensor[i] for tensor in x) tensors_to_summarize_copy = tuple(tensor[i].clone() for tensor in x) label = labels_typed[0] if len( labels_typed) == 1 else labels_typed[i] self.summaries[label].update(tensors_to_summarize) super().update(tensors_to_summarize_copy)
def _format_callable_baseline( baselines: Union[None, Callable[..., Union[Tensor, Tuple[Tensor, ...]]], Tensor, int, float, Tuple[Union[Tensor, int, float], ...], ], inputs: Union[Tensor, Tuple[Tensor, ...]], ) -> Tuple[Union[Tensor, int, float], ...]: if callable(baselines): # Note: this assumes that if baselines is a function and if it takes # arguments, then the first argument is the `inputs`. # This can be expanded in the future with better type checks baseline_parameters = signature(baselines).parameters if len(baseline_parameters) == 0: baselines = baselines() else: baselines = baselines(inputs) return _format_baseline(baselines, _format_tensor_into_tuples(inputs))
def _batched_generator( inputs: TensorOrTupleOfTensorsGeneric, additional_forward_args: Any = None, target_ind: TargetType = None, internal_batch_size: Union[None, int] = None, ) -> Iterator[Tuple[Tuple[Tensor, ...], Any, TargetType]]: """ Returns a generator which returns corresponding chunks of size internal_batch_size for both inputs and additional_forward_args. If batch size is None, generator only includes original inputs and additional args. """ assert internal_batch_size is None or ( isinstance(internal_batch_size, int) and internal_batch_size > 0 ), "Batch size must be greater than 0." inputs = _format_tensor_into_tuples(inputs) additional_forward_args = _format_additional_forward_args(additional_forward_args) num_examples = inputs[0].shape[0] # TODO Reconsider this check if _batched_generator is used for non gradient-based # attribution algorithms if not (inputs[0] * 1).requires_grad: warnings.warn( """It looks like that the attribution for a gradient-based method is computed in a `torch.no_grad` block or perhaps the inputs have no requires_grad.""" ) if internal_batch_size is None: yield inputs, additional_forward_args, target_ind else: for current_total in range(0, num_examples, internal_batch_size): with torch.autograd.set_grad_enabled(True): inputs_splice = _tuple_splice_range( inputs, current_total, current_total + internal_batch_size ) yield inputs_splice, _tuple_splice_range( additional_forward_args, current_total, current_total + internal_batch_size, ), target_ind[ current_total : current_total + internal_batch_size ] if isinstance( target_ind, list ) or ( isinstance(target_ind, torch.Tensor) and target_ind.numel() > 1 ) else target_ind
def perturb( self, inputs: TensorOrTupleOfTensorsGeneric, radius: float, step_size: float, step_num: int, target: Any, additional_forward_args: Any = None, targeted: bool = False, random_start: bool = False, norm: str = "Linf", ) -> TensorOrTupleOfTensorsGeneric: r""" This method computes and returns the perturbed input for each input tensor. It supports both targeted and non-targeted attacks. Args: inputs (tensor or tuple of tensors): Input for which adversarial attack is computed. It can be provided as a single tensor or a tuple of multiple tensors. If multiple input tensors are provided, the batch sizes must be aligned accross all tensors. radius (float): Radius of the neighbor ball centered around inputs. The perturbation should be within this range. step_size (float): Step size of each gradient step. step_num (int): Step numbers. It usually guarantees that the perturbation can reach the border. target (any): True labels of inputs if non-targeted attack is desired. Target class of inputs if targeted attack is desired. Target will be passed to the loss function to compute loss, so the type needs to match the argument type of the loss function. If using the default negative log as loss function, labels should be of type int, tuple, tensor or list. For general 2D outputs, labels can be either: - a single integer or a tensor containing a single integer, which is applied to all input examples - a list of integers or a 1D tensor, with length matching the number of examples in inputs (dim 0). Each integer is applied as the label for the corresponding example. For outputs with > 2 dimensions, labels can be either: - A single tuple, which contains #output_dims - 1 elements. This label 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 label for the corresponding example. 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. These arguments are provided to forward_func in order following the arguments in inputs. Default: None. targeted (bool, optional): If attack should be targeted. Default: False. random_start (bool, optional): If a random initialization is added to inputs. Default: False. norm (str, optional): Specifies the norm to calculate distance from original inputs: 'Linf'|'L2'. Default: 'Linf'. Returns: - **perturbed inputs** (*tensor* or tuple of *tensors*): Perturbed input for each input tensor. The perturbed inputs have the same shape and dimensionality as the inputs. If a single tensor is provided as inputs, a single tensor is returned. If a tuple is provided for inputs, a tuple of corresponding sized tensors is returned. """ def _clip(inputs: Tensor, outputs: Tensor) -> Tensor: diff = outputs - inputs if norm == "Linf": return inputs + torch.clamp(diff, -radius, radius) elif norm == "L2": return inputs + torch.renorm(diff, 2, 0, radius) else: raise AssertionError("Norm constraint must be L2 or Linf.") is_inputs_tuple = _is_tuple(inputs) formatted_inputs = _format_tensor_into_tuples(inputs) perturbed_inputs = formatted_inputs if random_start: perturbed_inputs = tuple( self.bound( self._random_point(formatted_inputs[i], radius, norm)) for i in range(len(formatted_inputs))) for _i in range(step_num): perturbed_inputs = self.fgsm.perturb(perturbed_inputs, step_size, target, additional_forward_args, targeted) perturbed_inputs = tuple( _clip(formatted_inputs[j], perturbed_inputs[j]) for j in range(len(perturbed_inputs))) # Detaching inputs to avoid dependency of gradient between steps perturbed_inputs = tuple( self.bound(perturbed_inputs[j]).detach() for j in range(len(perturbed_inputs))) return _format_output(is_inputs_tuple, perturbed_inputs)
def attribute( self, inputs: TensorOrTupleOfTensorsGeneric, neuron_selector: Union[int, Tuple[Union[int, slice], ...], Callable], additional_forward_args: Any = None, attribute_to_neuron_input: bool = False, ) -> TensorOrTupleOfTensorsGeneric: r""" Args: inputs (tensor or tuple of tensors): Input for which neuron gradients 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, and if multiple input tensors are provided, the examples must be aligned appropriately. neuron_selector (int, callable, or tuple of ints or slices): Selector for neuron in given layer for which attribution is desired. Neuron selector can be provided as: - a single integer, if the layer output is 2D. This integer selects the appropriate neuron column in the layer input or output - a tuple of integers or slice objects. Length of this tuple must be one less than the number of dimensions in the input / output of the given layer (since dimension 0 corresponds to number of examples). The elements of the tuple can be either integers or slice objects (slice object allows indexing a range of neurons rather individual ones). If any of the tuple elements is a slice object, the indexed output tensor is used for attribution. Note that specifying a slice of a tensor would amount to computing the attribution of the sum of the specified neurons, and not the individual neurons independantly. - a callable, which should take the target layer as input (single tensor or tuple if multiple tensors are in layer) and return a neuron or aggregate of the layer's neurons for attribution. For example, this function could return the sum of the neurons in the layer or sum of neurons with activations in a particular range. It is expected that this function returns either a tensor with one element or a 1D tensor with length equal to batch_size (one scalar per input example) 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 attributions are not computed with respect to these arguments. Default: None attribute_to_neuron_input (bool, optional): Indicates whether to compute the attributions with respect to the neuron input or output. If `attribute_to_neuron_input` is set to True then the attributions will be computed with respect to neuron's inputs, otherwise it will be computed with respect to neuron's outputs. Note that currently it is assumed that either the input or the output of internal neurons, depending on whether we attribute to the input or output, is a single tensor. Support for multiple tensors will be added later. Default: False Returns: *tensor* or tuple of *tensors* of **attributions**: - **attributions** (*tensor* or tuple of *tensors*): Gradients of particular neuron with respect to each input feature. Attributions will always be the same size as the provided inputs, with each value providing the attribution of the corresponding input index. If a single tensor is provided as inputs, a single tensor is returned. If a tuple is provided for inputs, a tuple of corresponding sized tensors is returned. Examples:: >>> # ImageClassifier takes a single input tensor of images Nx3x32x32, >>> # and returns an Nx10 tensor of class probabilities. >>> # It contains an attribute conv1, which is an instance of nn.conv2d, >>> # and the output of this layer has dimensions Nx12x32x32. >>> net = ImageClassifier() >>> neuron_ig = NeuronGradient(net, net.conv1) >>> input = torch.randn(2, 3, 32, 32, requires_grad=True) >>> # To compute neuron attribution, we need to provide the neuron >>> # index for which attribution is desired. Since the layer output >>> # is Nx12x32x32, we need a tuple in the form (0..11,0..31,0..31) >>> # which indexes a particular neuron in the layer output. >>> # For this example, we choose the index (4,1,2). >>> # Computes neuron gradient for neuron with >>> # index (4,1,2). >>> attribution = neuron_ig.attribute(input, (4,1,2)) """ is_inputs_tuple = _is_tuple(inputs) inputs = _format_tensor_into_tuples(inputs) additional_forward_args = _format_additional_forward_args( additional_forward_args ) gradient_mask = apply_gradient_requirements(inputs) _, input_grads = _forward_layer_eval_with_neuron_grads( self.forward_func, inputs, self.layer, additional_forward_args, gradient_neuron_selector=neuron_selector, device_ids=self.device_ids, attribute_to_layer_input=attribute_to_neuron_input, ) undo_gradient_requirements(inputs, gradient_mask) return _format_output(is_inputs_tuple, input_grads)
def attribute( self, inputs: TensorOrTupleOfTensorsGeneric, baselines: BaselineType = None, target: TargetType = None, additional_forward_args: Any = None, feature_mask: Union[None, TensorOrTupleOfTensorsGeneric] = None, perturbations_per_eval: int = 1, show_progress: bool = False, ) -> TensorOrTupleOfTensorsGeneric: r""" NOTE: The feature_mask argument differs from other perturbation based methods, since feature indices can overlap across tensors. See the description of the feature_mask argument below for more details. Args: inputs (tensor or tuple of tensors): Input for which Shapley value sampling 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 scalars or tensors, optional): Baselines define reference value which replaces each feature when ablated. Baselines can be provided 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. In the cases when `baselines` is not provided, we internally use zero scalar corresponding to each input tensor. Default: None target (int, tuple, tensor or list, optional): Output indices for which difference is computed (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 outputs, targets can be either: - a single integer or a tensor containing a single integer, which is applied to all input examples - a list of integers or a 1D tensor, with length matching the number of examples in inputs (dim 0). Each integer is applied as the target 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 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. For a tensor, the first dimension of the tensor must correspond to the number of examples. For all other types, the given argument is used for all forward evaluations. Note that attributions are not computed with respect to these arguments. Default: None feature_mask (tensor or tuple of tensors, optional): feature_mask defines a mask for the input, grouping features which should be added 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. Values across all tensors should be integers in the range 0 to num_features - 1, and indices corresponding to the same feature should have the same value. Note that features are grouped across tensors (unlike feature ablation and occlusion), so if the same index is used in different tensors, those features are still grouped and added simultaneously. 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 Default: None perturbations_per_eval (int, optional): Allows multiple ablations to be processed simultaneously in one call to forward_fn. Each forward pass will contain a maximum of perturbations_per_eval * #examples samples. For DataParallel models, each batch is split among the available devices, so evaluations on each available device contain at most (perturbations_per_eval * #examples) / num_devices samples. If the forward function returns a single scalar per batch, perturbations_per_eval must be set to 1. Default: 1 show_progress (bool, optional): Displays the progress of computation. It will try to use tqdm if available for advanced features (e.g. time estimation). Otherwise, it will fallback to a simple output of progress. Default: False Returns: *tensor* or tuple of *tensors* of **attributions**: - **attributions** (*tensor* or tuple of *tensors*): The attributions with respect to each input feature. If the forward function returns a scalar value per example, attributions will be the same size as the provided inputs, with each value providing the attribution of the corresponding input index. If the forward function returns a scalar per batch, then attribution tensor(s) will have first dimension 1 and the remaining dimensions will match the input. If a single tensor is provided as inputs, a single tensor is returned. If a tuple is provided for inputs, a tuple of corresponding sized tensors is returned. Examples:: >>> # SimpleClassifier takes a single input tensor of size Nx4x4, >>> # and returns an Nx3 tensor of class probabilities. >>> net = SimpleClassifier() >>> # Generating random input with size 2 x 4 x 4 >>> input = torch.randn(2, 4, 4) >>> # We may want to add features in groups, e.g. >>> # grouping each 2x2 square of the inputs and adding them together. >>> # This can be done by creating a feature mask as follows, which >>> # defines the feature groups, e.g.: >>> # +---+---+---+---+ >>> # | 0 | 0 | 1 | 1 | >>> # +---+---+---+---+ >>> # | 0 | 0 | 1 | 1 | >>> # +---+---+---+---+ >>> # | 2 | 2 | 3 | 3 | >>> # +---+---+---+---+ >>> # | 2 | 2 | 3 | 3 | >>> # +---+---+---+---+ >>> # With this mask, all inputs with the same value are added >>> # together, and the attribution for each input in the same >>> # group (0, 1, 2, and 3) per example are the same. >>> # The attributions can be calculated as follows: >>> # feature mask has dimensions 1 x 4 x 4 >>> feature_mask = torch.tensor([[[0,0,1,1],[0,0,1,1], >>> [2,2,3,3],[2,2,3,3]]]) >>> # With only 4 features, it is feasible to compute exact >>> # Shapley Values. These can be computed as follows: >>> sv = ShapleyValues(net) >>> attr = sv.attribute(input, target=1, feature_mask=feature_mask) """ if feature_mask is None: total_features = sum( torch.numel(inp[0]) for inp in _format_tensor_into_tuples(inputs) ) else: total_features = ( int(max(torch.max(single_mask).item() for single_mask in feature_mask)) + 1 ) if total_features >= 10: warnings.warn( "You are attempting to compute Shapley Values with at least 10 " "features, which will likely be very computationally expensive." "Consider using Shapley Value Sampling instead." ) return super().attribute.__wrapped__( self, inputs=inputs, baselines=baselines, target=target, additional_forward_args=additional_forward_args, feature_mask=feature_mask, perturbations_per_eval=perturbations_per_eval, show_progress=show_progress, )
def attribute( # type: ignore self, inputs: TensorOrTupleOfTensorsGeneric, baselines: Union[TensorOrTupleOfTensorsGeneric, Callable[..., TensorOrTupleOfTensorsGeneric]], target: TargetType = None, additional_forward_args: Any = None, return_convergence_delta: bool = False, custom_attribution_func: Union[None, Callable[..., Tuple[Tensor, ...]]] = None, ) -> Union[TensorOrTupleOfTensorsGeneric, Tuple[ TensorOrTupleOfTensorsGeneric, Tensor]]: r""" Args: inputs (tensor or tuple of tensors): 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 (tensor, tuple of tensors, callable): Baselines define reference samples that are compared with the inputs. In order to assign attribution scores DeepLift computes the differences between the inputs/outputs and corresponding references. Baselines can be provided as: - a single tensor, if inputs is a single tensor, with the first dimension equal to the number of examples in the baselines' distribution. The remaining dimensions must match with input tensor's dimension starting from the second dimension. - a tuple of tensors, if inputs is a tuple of tensors, with the first dimension of any tensor inside the tuple equal to the number of examples in the baseline's distribution. The remaining dimensions must match the dimensions of the corresponding input tensor starting from the second dimension. - callable function, optionally takes `inputs` as an argument and either returns a single tensor or a tuple of those. It is recommended that the number of samples in the baselines' tensors is larger than one. target (int, tuple, tensor or list, optional): Output indices for which gradients are computed (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 outputs, targets can be either: - a single integer or a tensor containing a single integer, which is applied to all input examples - a list of integers or a 1D tensor, with length matching the number of examples in inputs (dim 0). Each integer is applied as the target 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 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 attributions are not computed with respect to these arguments. Default: None return_convergence_delta (bool, optional): Indicates whether to return convergence delta or not. If `return_convergence_delta` is set to True convergence delta will be returned in a tuple following attributions. Default: False custom_attribution_func (callable, optional): A custom function for computing final attribution scores. This function can take at least one and at most three arguments with the following signature: - custom_attribution_func(multipliers) - custom_attribution_func(multipliers, inputs) - custom_attribution_func(multipliers, inputs, baselines) In case this function is not provided we use the default logic defined as: multipliers * (inputs - baselines) It is assumed that all input arguments, `multipliers`, `inputs` and `baselines` are provided in tuples of same length. `custom_attribution_func` returns a tuple of attribution tensors that have the same length as the `inputs`. Default: None Returns: **attributions** or 2-element tuple of **attributions**, **delta**: - **attributions** (*tensor* or tuple of *tensors*): Attribution score computed based on DeepLift rescale rule with respect to each input feature. Attributions will always be the same size as the provided inputs, with each value providing the attribution of the corresponding input index. If a single tensor is provided as inputs, a single tensor is returned. If a tuple is provided for inputs, a tuple of corresponding sized tensors is returned. - **delta** (*tensor*, returned if return_convergence_delta=True): This is computed using the property that the total sum of forward_func(inputs) - forward_func(baselines) must be very close to the total sum of attributions computed based on approximated SHAP values using Deeplift's rescale rule. Delta is calculated for each example input and baseline pair, meaning that the number of elements in returned delta tensor is equal to the `number of examples in input` * `number of examples in baseline`. The deltas are ordered in the first place by input example, followed by the baseline. Note that the logic described for deltas is guaranteed when the default logic for attribution computations is used, meaning that the `custom_attribution_func=None`, otherwise it is not guaranteed and depends on the specifics of the `custom_attribution_func`. Examples:: >>> # ImageClassifier takes a single input tensor of images Nx3x32x32, >>> # and returns an Nx10 tensor of class probabilities. >>> net = ImageClassifier() >>> dl = DeepLiftShap(net) >>> input = torch.randn(2, 3, 32, 32, requires_grad=True) >>> # Computes shap values using deeplift for class 3. >>> attribution = dl.attribute(input, target=3) """ baselines = _format_callable_baseline(baselines, inputs) assert isinstance( baselines[0], torch.Tensor ) and baselines[0].shape[0] > 1, ( "Baselines distribution has to be provided in form of a torch.Tensor" " with more than one example but found: {}." " If baselines are provided in shape of scalars or with a single" " baseline example, `DeepLift`" " approach can be used instead.".format(baselines[0])) # Keeps track whether original input is a tuple or not before # converting it into a tuple. is_inputs_tuple = _is_tuple(inputs) inputs = _format_tensor_into_tuples(inputs) # batch sizes inp_bsz = inputs[0].shape[0] base_bsz = baselines[0].shape[0] ( exp_inp, exp_base, exp_tgt, exp_addit_args, ) = self._expand_inputs_baselines_targets(baselines, inputs, target, additional_forward_args) attributions = super().attribute.__wrapped__( # type: ignore self, exp_inp, exp_base, target=exp_tgt, additional_forward_args=exp_addit_args, return_convergence_delta=cast(Literal[True, False], return_convergence_delta), custom_attribution_func=custom_attribution_func, ) if return_convergence_delta: attributions, delta = cast(Tuple[Tuple[Tensor, ...], Tensor], attributions) attributions = tuple( self._compute_mean_across_baselines(inp_bsz, base_bsz, cast(Tensor, attribution)) for attribution in attributions) if return_convergence_delta: return _format_output(is_inputs_tuple, attributions), delta else: return _format_output(is_inputs_tuple, attributions)
def attribute( # type: ignore self, inputs: TensorOrTupleOfTensorsGeneric, baselines: BaselineType = None, target: TargetType = None, additional_forward_args: Any = None, return_convergence_delta: bool = False, custom_attribution_func: Union[None, Callable[..., Tuple[Tensor, ...]]] = None, ) -> Union[TensorOrTupleOfTensorsGeneric, Tuple[ TensorOrTupleOfTensorsGeneric, Tensor]]: r""" Args: inputs (tensor or tuple of tensors): 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 scalars or tensors, optional): Baselines define reference samples that are compared with the inputs. In order to assign attribution scores DeepLift computes the differences between the inputs/outputs and corresponding references. Baselines can be provided 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. In the cases when `baselines` is not provided, we internally use zero scalar corresponding to each input tensor. Default: None target (int, tuple, tensor or list, optional): Output indices for which gradients are computed (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 outputs, targets can be either: - a single integer or a tensor containing a single integer, which is applied to all input examples - a list of integers or a 1D tensor, with length matching the number of examples in inputs (dim 0). Each integer is applied as the target 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 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 attributions are not computed with respect to these arguments. Default: None return_convergence_delta (bool, optional): Indicates whether to return convergence delta or not. If `return_convergence_delta` is set to True convergence delta will be returned in a tuple following attributions. Default: False custom_attribution_func (callable, optional): A custom function for computing final attribution scores. This function can take at least one and at most three arguments with the following signature: - custom_attribution_func(multipliers) - custom_attribution_func(multipliers, inputs) - custom_attribution_func(multipliers, inputs, baselines) In case this function is not provided, we use the default logic defined as: multipliers * (inputs - baselines) It is assumed that all input arguments, `multipliers`, `inputs` and `baselines` are provided in tuples of same length. `custom_attribution_func` returns a tuple of attribution tensors that have the same length as the `inputs`. Default: None Returns: **attributions** or 2-element tuple of **attributions**, **delta**: - **attributions** (*tensor* or tuple of *tensors*): Attribution score computed based on DeepLift rescale rule with respect to each input feature. Attributions will always be the same size as the provided inputs, with each value providing the attribution of the corresponding input index. If a single tensor is provided as inputs, a single tensor is returned. If a tuple is provided for inputs, a tuple of corresponding sized tensors is returned. - **delta** (*tensor*, returned if return_convergence_delta=True): This is computed using the property that the total sum of forward_func(inputs) - forward_func(baselines) must equal the total sum of the attributions computed based on DeepLift's rescale rule. Delta is calculated per example, meaning that the number of elements in returned delta tensor is equal to the number of of examples in input. Note that the logic described for deltas is guaranteed when the default logic for attribution computations is used, meaning that the `custom_attribution_func=None`, otherwise it is not guaranteed and depends on the specifics of the `custom_attribution_func`. Examples:: >>> # ImageClassifier takes a single input tensor of images Nx3x32x32, >>> # and returns an Nx10 tensor of class probabilities. >>> net = ImageClassifier() >>> dl = DeepLift(net) >>> input = torch.randn(2, 3, 32, 32, requires_grad=True) >>> # Computes deeplift attribution scores for class 3. >>> attribution = dl.attribute(input, target=3) """ # Keeps track whether original input is a tuple or not before # converting it into a tuple. is_inputs_tuple = _is_tuple(inputs) inputs = _format_tensor_into_tuples(inputs) baselines = _format_baseline(baselines, inputs) gradient_mask = apply_gradient_requirements(inputs) _validate_input(inputs, baselines) # set hooks for baselines warnings.warn( """Setting forward, backward hooks and attributes on non-linear activations. The hooks and attributes will be removed after the attribution is finished""") baselines = _tensorize_baseline(inputs, baselines) main_model_hooks = [] try: main_model_hooks = self._hook_main_model() self.model.apply(self._register_hooks) additional_forward_args = _format_additional_forward_args( additional_forward_args) expanded_target = _expand_target( target, 2, expansion_type=ExpansionTypes.repeat) wrapped_forward_func = self._construct_forward_func( self.model, (inputs, baselines), expanded_target, additional_forward_args, ) gradients = self.gradient_func(wrapped_forward_func, inputs) if custom_attribution_func is None: if self.multiplies_by_inputs: attributions = tuple((input - baseline) * gradient for input, baseline, gradient in zip( inputs, baselines, gradients)) else: attributions = gradients else: attributions = _call_custom_attribution_func( custom_attribution_func, gradients, inputs, baselines) finally: # Even if any error is raised, remove all hooks before raising self._remove_hooks(main_model_hooks) undo_gradient_requirements(inputs, gradient_mask) return _compute_conv_delta_and_format_attrs( self, return_convergence_delta, attributions, baselines, inputs, additional_forward_args, target, is_inputs_tuple, )
def attribute( self, inputs: TensorOrTupleOfTensorsGeneric, baselines: BaselineType = None, target: TargetType = None, additional_forward_args: Any = None, feature_mask: Union[None, TensorOrTupleOfTensorsGeneric] = None, n_samples: int = 25, perturbations_per_eval: int = 1, show_progress: bool = False, ) -> TensorOrTupleOfTensorsGeneric: r""" NOTE: The feature_mask argument differs from other perturbation based methods, since feature indices can overlap across tensors. See the description of the feature_mask argument below for more details. Args: inputs (tensor or tuple of tensors): Input for which Shapley value sampling 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 scalars or tensors, optional): Baselines define reference value which replaces each feature when ablated. Baselines can be provided 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. In the cases when `baselines` is not provided, we internally use zero scalar corresponding to each input tensor. Default: None target (int, tuple, tensor or list, optional): Output indices for which difference is computed (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 outputs, targets can be either: - a single integer or a tensor containing a single integer, which is applied to all input examples - a list of integers or a 1D tensor, with length matching the number of examples in inputs (dim 0). Each integer is applied as the target 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 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. For a tensor, the first dimension of the tensor must correspond to the number of examples. For all other types, the given argument is used for all forward evaluations. Note that attributions are not computed with respect to these arguments. Default: None feature_mask (tensor or tuple of tensors, optional): feature_mask defines a mask for the input, grouping features which should be added 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. Values across all tensors should be integers in the range 0 to num_features - 1, and indices corresponding to the same feature should have the same value. Note that features are grouped across tensors (unlike feature ablation and occlusion), so if the same index is used in different tensors, those features are still grouped and added simultaneously. 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 Default: None n_samples (int, optional): The number of feature permutations tested. Default: `25` if `n_samples` is not provided. perturbations_per_eval (int, optional): Allows multiple ablations to be processed simultaneously in one call to forward_fn. Each forward pass will contain a maximum of perturbations_per_eval * #examples samples. For DataParallel models, each batch is split among the available devices, so evaluations on each available device contain at most (perturbations_per_eval * #examples) / num_devices samples. If the forward function returns a single scalar per batch, perturbations_per_eval must be set to 1. Default: 1 show_progress (bool, optional): Displays the progress of computation. It will try to use tqdm if available for advanced features (e.g. time estimation). Otherwise, it will fallback to a simple output of progress. Default: False Returns: *tensor* or tuple of *tensors* of **attributions**: - **attributions** (*tensor* or tuple of *tensors*): The attributions with respect to each input feature. If the forward function returns a scalar value per example, attributions will be the same size as the provided inputs, with each value providing the attribution of the corresponding input index. If the forward function returns a scalar per batch, then attribution tensor(s) will have first dimension 1 and the remaining dimensions will match the input. If a single tensor is provided as inputs, a single tensor is returned. If a tuple is provided for inputs, a tuple of corresponding sized tensors is returned. Examples:: >>> # SimpleClassifier takes a single input tensor of size Nx4x4, >>> # and returns an Nx3 tensor of class probabilities. >>> net = SimpleClassifier() >>> # Generating random input with size 2 x 4 x 4 >>> input = torch.randn(2, 4, 4) >>> # Defining ShapleyValueSampling interpreter >>> svs = ShapleyValueSampling(net) >>> # Computes attribution, taking random orderings >>> # of the 16 features and computing the output change when adding >>> # each feature. We average over 200 trials (random permutations). >>> attr = svs.attribute(input, target=1, n_samples=200) >>> # Alternatively, we may want to add features in groups, e.g. >>> # grouping each 2x2 square of the inputs and adding them together. >>> # This can be done by creating a feature mask as follows, which >>> # defines the feature groups, e.g.: >>> # +---+---+---+---+ >>> # | 0 | 0 | 1 | 1 | >>> # +---+---+---+---+ >>> # | 0 | 0 | 1 | 1 | >>> # +---+---+---+---+ >>> # | 2 | 2 | 3 | 3 | >>> # +---+---+---+---+ >>> # | 2 | 2 | 3 | 3 | >>> # +---+---+---+---+ >>> # With this mask, all inputs with the same value are added >>> # together, and the attribution for each input in the same >>> # group (0, 1, 2, and 3) per example are the same. >>> # The attributions can be calculated as follows: >>> # feature mask has dimensions 1 x 4 x 4 >>> feature_mask = torch.tensor([[[0,0,1,1],[0,0,1,1], >>> [2,2,3,3],[2,2,3,3]]]) >>> attr = svs.attribute(input, target=1, feature_mask=feature_mask) """ # Keeps track whether original input is a tuple or not before # converting it into a tuple. is_inputs_tuple = _is_tuple(inputs) inputs, baselines = _format_input_baseline(inputs, baselines) additional_forward_args = _format_additional_forward_args( additional_forward_args ) feature_mask = ( _format_tensor_into_tuples(feature_mask) if feature_mask is not None else None ) assert ( isinstance(perturbations_per_eval, int) and perturbations_per_eval >= 1 ), "Ablations per evaluation must be at least 1." with torch.no_grad(): baselines = _tensorize_baseline(inputs, baselines) num_examples = inputs[0].shape[0] if feature_mask is None: feature_mask, total_features = _construct_default_feature_mask(inputs) else: total_features = int( max(torch.max(single_mask).item() for single_mask in feature_mask) + 1 ) if show_progress: attr_progress = progress( desc=f"{self.get_name()} attribution", total=self._get_n_evaluations( total_features, n_samples, perturbations_per_eval ) + 1, # add 1 for the initial eval ) attr_progress.update(0) initial_eval = _run_forward( self.forward_func, baselines, target, additional_forward_args ) if show_progress: attr_progress.update() agg_output_mode = _find_output_mode_and_verify( initial_eval, num_examples, perturbations_per_eval, feature_mask ) # Initialize attribution totals and counts total_attrib = [ torch.zeros_like( input[0:1] if agg_output_mode else input, dtype=torch.float ) for input in inputs ] iter_count = 0 # Iterate for number of samples, generate a permutation of the features # and evalute the incremental increase for each feature. for feature_permutation in self.permutation_generator( total_features, n_samples ): iter_count += 1 prev_results = initial_eval for ( current_inputs, current_add_args, current_target, current_masks, ) in self._perturbation_generator( inputs, additional_forward_args, target, baselines, feature_mask, feature_permutation, perturbations_per_eval, ): if sum(torch.sum(mask).item() for mask in current_masks) == 0: warnings.warn( "Feature mask is missing some integers between 0 and " "num_features, for optimal performance, make sure each" " consecutive integer corresponds to a feature." ) # modified_eval dimensions: 1D tensor with length # equal to #num_examples * #features in batch modified_eval = _run_forward( self.forward_func, current_inputs, current_target, current_add_args, ) if show_progress: attr_progress.update() if agg_output_mode: eval_diff = modified_eval - prev_results prev_results = modified_eval else: all_eval = torch.cat((prev_results, modified_eval), dim=0) eval_diff = all_eval[num_examples:] - all_eval[:-num_examples] prev_results = all_eval[-num_examples:] for j in range(len(total_attrib)): current_eval_diff = eval_diff if not agg_output_mode: # current_eval_diff dimensions: # (#features in batch, #num_examples, 1,.. 1) # (contains 1 more dimension than inputs). This adds extra # dimensions of 1 to make the tensor broadcastable with the # inputs tensor. current_eval_diff = current_eval_diff.reshape( (-1, num_examples) + (len(inputs[j].shape) - 1) * (1,) ) total_attrib[j] += ( current_eval_diff * current_masks[j].float() ).sum(dim=0) if show_progress: attr_progress.close() # Divide total attributions by number of random permutations and return # formatted attributions. attrib = tuple( tensor_attrib_total / iter_count for tensor_attrib_total in total_attrib ) formatted_attr = _format_output(is_inputs_tuple, attrib) return formatted_attr
def _next_sensitivity_max(current_n_perturb_samples: int) -> Tensor: inputs_perturbed = _generate_perturbations(current_n_perturb_samples) # copy kwargs and update some of the arguments that need to be expanded nonlocal kwarg_expanded_for nonlocal kwargs_copy if (kwarg_expanded_for is None or kwarg_expanded_for != current_n_perturb_samples): kwarg_expanded_for = current_n_perturb_samples kwargs_copy = deepcopy(kwargs) _expand_and_update_additional_forward_args( current_n_perturb_samples, kwargs_copy) _expand_and_update_target(current_n_perturb_samples, kwargs_copy) if "baselines" in kwargs: baselines = kwargs["baselines"] baselines = _format_baseline(baselines, cast(Tuple[Tensor, ...], inputs)) if (isinstance(baselines[0], Tensor) and baselines[0].shape == inputs[0].shape): _expand_and_update_baselines( cast(Tuple[Tensor, ...], inputs), current_n_perturb_samples, kwargs_copy, ) expl_perturbed_inputs = explanation_func(inputs_perturbed, **kwargs_copy) # tuplize `expl_perturbed_inputs` in case it is not expl_perturbed_inputs = _format_tensor_into_tuples( expl_perturbed_inputs) expl_inputs_expanded = tuple( expl_input.repeat_interleave(current_n_perturb_samples, dim=0) for expl_input in expl_inputs) sensitivities = torch.cat( [(expl_input - expl_perturbed).view(expl_perturbed.size(0), -1) for expl_perturbed, expl_input in zip(expl_perturbed_inputs, expl_inputs_expanded)], dim=1, ) # compute the norm of original input explanations expl_inputs_norm_expanded = torch.norm( torch.cat( [ expl_input.view(expl_input.size(0), -1) for expl_input in expl_inputs ], dim=1, ), p=norm_ord, dim=1, keepdim=True, ).repeat_interleave(current_n_perturb_samples, dim=0) expl_inputs_norm_expanded = torch.where( expl_inputs_norm_expanded == 0.0, torch.tensor( 1.0, device=expl_inputs_norm_expanded.device, dtype=expl_inputs_norm_expanded.dtype, ), expl_inputs_norm_expanded, ) # compute the norm for each input noisy example sensitivities_norm = ( torch.norm(sensitivities, p=norm_ord, dim=1, keepdim=True) / expl_inputs_norm_expanded) return max_values(sensitivities_norm.view(bsz, -1))
def attribute( self, inputs: Union[Tensor, Tuple[Tensor, ...]], nt_type: str = "smoothgrad", nt_samples: int = 5, stdevs: Union[float, Tuple[float, ...]] = 1.0, draw_baseline_from_distrib: bool = False, **kwargs: Any, ): r""" Args: inputs (tensor or tuple of tensors): Input for which integrated gradients 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, and if multiple input tensors are provided, the examples must be aligned appropriately. nt_type (string, optional): Smoothing type of the attributions. `smoothgrad`, `smoothgrad_sq` or `vargrad` Default: `smoothgrad` if `type` is not provided. nt_samples (int, optional): The number of randomly generated examples per sample in the input batch. Random examples are generated by adding gaussian random noise to each sample. Default: `5` if `nt_samples` is not provided. stdevs (float, or a tuple of floats optional): The standard deviation of gaussian noise with zero mean that is added to each input in the batch. If `stdevs` is a single float value then that same value is used for all inputs. If it is a tuple, then it must have the same length as the inputs tuple. In this case, each stdev value in the stdevs tuple corresponds to the input with the same index in the inputs tuple. Default: `1.0` if `stdevs` is not provided. draw_baseline_from_distrib (bool, optional): Indicates whether to randomly draw baseline samples from the `baselines` distribution provided as an input tensor. Default: False **kwargs (Any, optional): Contains a list of arguments that are passed to `attribution_method` attribution algorithm. Any additional arguments that should be used for the chosen attribution method should be included here. For instance, such arguments include `additional_forward_args` and `baselines`. Returns: **attributions** or 2-element tuple of **attributions**, **delta**: - **attributions** (*tensor* or tuple of *tensors*): Attribution with respect to each input feature. attributions will always be the same size as the provided inputs, with each value providing the attribution of the corresponding input index. If a single tensor is provided as inputs, a single tensor is returned. If a tuple is provided for inputs, a tuple of corresponding sized tensors is returned. - **delta** (*float*, returned if return_convergence_delta=True): Approximation error computed by the attribution algorithm. Not all attribution algorithms return delta value. It is computed only for some algorithms, e.g. integrated gradients. Delta is computed for each input in the batch and represents the arithmetic mean across all `n_sample` perturbed tensors for that input. Examples:: >>> # ImageClassifier takes a single input tensor of images Nx3x32x32, >>> # and returns an Nx10 tensor of class probabilities. >>> net = ImageClassifier() >>> ig = IntegratedGradients(net) >>> input = torch.randn(2, 3, 32, 32, requires_grad=True) >>> # Creates noise tunnel >>> nt = NoiseTunnel(ig) >>> # Generates 10 perturbed input tensors per image. >>> # Computes integrated gradients for class 3 for each generated >>> # input and averages attributions accros all 10 >>> # perturbed inputs per image >>> attribution = nt.attribute(input, nt_type='smoothgrad', >>> nt_samples=10, target=3) """ def add_noise_to_inputs() -> Tuple[Tensor, ...]: if isinstance(stdevs, tuple): assert len(stdevs) == len(inputs), ( "The number of input tensors " "in {} must be equal to the number of stdevs values {}".format( len(inputs), len(stdevs) ) ) else: assert isinstance( stdevs, float ), "stdevs must be type float. " "Given: {}".format(type(stdevs)) stdevs_ = (stdevs,) * len(inputs) return tuple( add_noise_to_input(input, stdev).requires_grad_() if self.is_gradient_method else add_noise_to_input(input, stdev) for (input, stdev) in zip(inputs, stdevs_) ) def add_noise_to_input(input: Tensor, stdev: float) -> Tensor: # batch size bsz = input.shape[0] # expand input size by the number of drawn samples input_expanded_size = (bsz * nt_samples,) + input.shape[1:] # expand stdev for the shape of the input and number of drawn samples stdev_expanded = torch.tensor(stdev, device=input.device).repeat( input_expanded_size ) # draws `np.prod(input_expanded_size)` samples from normal distribution # with given input parametrization # FIXME it look like it is very difficult to make torch.normal # deterministic this needs an investigation noise = torch.normal(0, stdev_expanded) return input.repeat_interleave(nt_samples, dim=0) + noise def compute_expected_attribution_and_sq(attribution): bsz = attribution.shape[0] // nt_samples attribution_shape = (bsz, nt_samples) if len(attribution.shape) > 1: attribution_shape += attribution.shape[1:] attribution = attribution.view(attribution_shape) expected_attribution = attribution.mean(dim=1, keepdim=False) expected_attribution_sq = torch.mean(attribution ** 2, dim=1, keepdim=False) return expected_attribution, expected_attribution_sq with torch.no_grad(): # Keeps track whether original input is a tuple or not before # converting it into a tuple. is_inputs_tuple = isinstance(inputs, tuple) inputs = _format_input(inputs) _validate_noise_tunnel_type(nt_type, SUPPORTED_NOISE_TUNNEL_TYPES) delta = None inputs_with_noise = add_noise_to_inputs() # if the algorithm supports targets, baselines and/or # additional_forward_args they will be expanded based # on the n_steps and corresponding kwargs # variables will be updated accordingly _expand_and_update_additional_forward_args(nt_samples, kwargs) _expand_and_update_target(nt_samples, kwargs) _expand_and_update_baselines( inputs, nt_samples, kwargs, draw_baseline_from_distrib=draw_baseline_from_distrib, ) # smoothgrad_Attr(x) = 1 / n * sum(Attr(x + N(0, sigma^2)) # NOTE: using __wrapped__ such that it does not log the inner logs attr_func = self.attribution_method.attribute attributions = attr_func.__wrapped__( # type: ignore self.attribution_method, # self inputs_with_noise if is_inputs_tuple else inputs_with_noise[0], **kwargs, ) return_convergence_delta = ( "return_convergence_delta" in kwargs and kwargs["return_convergence_delta"] ) if self.is_delta_supported and return_convergence_delta: attributions, delta = attributions is_attrib_tuple = _is_tuple(attributions) attributions = _format_tensor_into_tuples(attributions) expected_attributions = [] expected_attributions_sq = [] for attribution in attributions: expected_attr, expected_attr_sq = compute_expected_attribution_and_sq( attribution ) expected_attributions.append(expected_attr) expected_attributions_sq.append(expected_attr_sq) if NoiseTunnelType[nt_type] == NoiseTunnelType.smoothgrad: return self._apply_checks_and_return_attributions( tuple(expected_attributions), is_attrib_tuple, return_convergence_delta, delta, ) if NoiseTunnelType[nt_type] == NoiseTunnelType.smoothgrad_sq: return self._apply_checks_and_return_attributions( tuple(expected_attributions_sq), is_attrib_tuple, return_convergence_delta, delta, ) vargrad = tuple( expected_attribution_sq - expected_attribution * expected_attribution for expected_attribution, expected_attribution_sq in zip( expected_attributions, expected_attributions_sq ) ) return self._apply_checks_and_return_attributions( vargrad, is_attrib_tuple, return_convergence_delta, delta )
def compute_convergence_delta( self, attributions: Union[Tensor, Tuple[Tensor, ...]], start_point: Union[None, int, float, Tensor, Tuple[Union[int, float, Tensor], ...]], end_point: Union[Tensor, Tuple[Tensor, ...]], target: TargetType = None, additional_forward_args: Any = None, ) -> Tensor: r""" Here we provide a specific implementation for `compute_convergence_delta` which is based on a common property among gradient-based attribution algorithms. In the literature sometimes it is also called completeness axiom. Completeness axiom states that the sum of the attribution must be equal to the differences of NN Models's function at its end and start points. In other words: sum(attributions) - (F(end_point) - F(start_point)) is close to zero. Returned delta of this method is defined as above stated difference. This implementation assumes that both the `start_point` and `end_point` have the same shape and dimensionality. It also assumes that the target must have the same number of examples as the `start_point` and the `end_point` in case it is provided in form of a list or a non-singleton tensor. Args: attributions (tensor or tuple of tensors): Precomputed attribution scores. The user can compute those using any attribution algorithm. It is assumed the the shape and the dimensionality of attributions must match the shape and the dimensionality of `start_point` and `end_point`. It also assumes that the attribution tensor's dimension 0 corresponds to the number of examples, and if multiple input tensors are provided, the examples must be aligned appropriately. start_point (tensor or tuple of tensors, optional): `start_point` is passed as an input to model's forward function. It is the starting point of attributions' approximation. It is assumed that both `start_point` and `end_point` have the same shape and dimensionality. end_point (tensor or tuple of tensors): `end_point` is passed as an input to model's forward function. It is the end point of attributions' approximation. It is assumed that both `start_point` and `end_point` have the same shape and dimensionality. target (int, tuple, tensor or list, optional): Output indices for which gradients are computed (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 outputs, targets can be either: - a single integer or a tensor containing a single integer, which is applied to all input examples - a list of integers or a 1D tensor, with length matching the number of examples in inputs (dim 0). Each integer is applied as the target 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 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. For a tensor, the first dimension of the tensor must correspond to the number of examples. `additional_forward_args` is used both for `start_point` and `end_point` when computing the forward pass. Default: None Returns: *tensor* of **deltas**: - **deltas** (*tensor*): This implementation returns convergence delta per sample. Deriving sub-classes may do any type of aggregation of those values, if necessary. """ end_point, start_point = _format_input_baseline(end_point, start_point) additional_forward_args = _format_additional_forward_args( additional_forward_args) # tensorizing start_point in case it is a scalar or one example baseline # If the batch size is large we could potentially also tensorize only one # sample and expand the output to the rest of the elements in the batch start_point = _tensorize_baseline(end_point, start_point) attributions = _format_tensor_into_tuples(attributions) # verify that the attributions and end_point match on 1st dimension for attribution, end_point_tnsr in zip(attributions, end_point): assert end_point_tnsr.shape[0] == attribution.shape[0], ( "Attributions tensor and the end_point must match on the first" " dimension but found attribution: {} and end_point: {}". format(attribution.shape[0], end_point_tnsr.shape[0])) num_samples = end_point[0].shape[0] _validate_input(end_point, start_point) _validate_target(num_samples, target) with torch.no_grad(): start_out_sum = _sum_rows( _run_forward(self.forward_func, start_point, target, additional_forward_args)) end_out_sum = _sum_rows( _run_forward(self.forward_func, end_point, target, additional_forward_args)) row_sums = [_sum_rows(attribution) for attribution in attributions] attr_sum = torch.stack( [cast(Tensor, sum(row_sum)) for row_sum in zip(*row_sums)]) _delta = attr_sum - (end_out_sum - start_out_sum) return _delta
def attribute( self, inputs: TensorOrTupleOfTensorsGeneric, target: TargetType = None, additional_forward_args: Any = None, return_convergence_delta: bool = False, attribute_to_layer_input: bool = False, verbose: bool = False, ) -> Union[Tensor, Tuple[Tensor, ...], List[Union[Tensor, Tuple[ Tensor, ...]]], Tuple[Union[Tensor, Tuple[Tensor, ...], List[Union[ Tensor, Tuple[Tensor, ...]]]], Union[Tensor, List[Tensor]], ], ]: r""" Args: inputs (tensor or tuple of tensors): Input for which relevance is propagated. 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, and if multiple input tensors are provided, the examples must be aligned appropriately. target (int, tuple, tensor or list, optional): Output indices for which gradients are computed (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 outputs, targets can be either: - a single integer or a tensor containing a single integer, which is applied to all input examples - a list of integers or a 1D tensor, with length matching the number of examples in inputs (dim 0). Each integer is applied as the target 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 additional_forward_args (tuple, 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 attributions are not computed with respect to these arguments. Default: None return_convergence_delta (bool, optional): Indicates whether to return convergence delta or not. If `return_convergence_delta` is set to True convergence delta will be returned in a tuple following attributions. Default: False attribute_to_layer_input (bool, optional): Indicates whether to compute the attribution with respect to the layer input or output. If `attribute_to_layer_input` is set to True then the attributions will be computed with respect to layer input, otherwise it will be computed with respect to layer output. verbose (bool, optional): Indicates whether information on application of rules is printed during propagation. Default: False Returns: *tensor* or tuple of *tensors* of **attributions** or 2-element tuple of **attributions**, **delta** or lists of **attributions** and **delta**: - **attributions** (*tensor* or tuple of *tensors*): The propagated relevance values with respect to each input feature. Attributions will always be the same size as the provided inputs, with each value providing the attribution of the corresponding input index. If a single tensor is provided as inputs, a single tensor is returned. If a tuple is provided for inputs, a tuple of corresponding sized tensors is returned. The sum of attributions is one and not corresponding to the prediction score as in other implementations. If attributions for all layers are returned (layer=None) a list of tensors or tuples of tensors is returned with entries for each layer. - **delta** (*tensor* or list of *tensors* returned if return_convergence_delta=True): Delta is calculated per example, meaning that the number of elements in returned delta tensor is equal to the number of of examples in input. If attributions for all layers are returned (layer=None) a list of tensors is returned with entries for each layer. Examples:: >>> # ImageClassifier takes a single input tensor of images Nx3x32x32, >>> # and returns an Nx10 tensor of class probabilities. It has one >>> # Conv2D and a ReLU layer. >>> net = ImageClassifier() >>> lrp = LRP(net, net.conv1) >>> input = torch.randn(3, 3, 32, 32) >>> # Attribution size matches input size: 3x3x32x32 >>> attribution = lrp.attribute(input, target=5) """ self.verbose = verbose self._original_state_dict = self.model.state_dict() self.layers = [] self._get_layers(self.model) self._check_and_attach_rules() self.attribute_to_layer_input = attribute_to_layer_input self.backward_handles = [] self.forward_handles = [] inputs = _format_tensor_into_tuples(inputs) gradient_mask = apply_gradient_requirements(inputs) try: # 1. Forward pass output = self._compute_output_and_change_weights( inputs, target, additional_forward_args) self._register_forward_hooks() # 2. Forward pass + backward pass _ = compute_gradients(self._forward_fn_wrapper, inputs, target, additional_forward_args) relevances = self._get_output_relevance(output) finally: self._restore_model() undo_gradient_requirements(inputs, gradient_mask) if return_convergence_delta: delta: Union[Tensor, List[Tensor]] if isinstance(self.layer, list): delta = [] for relevance_layer in relevances: delta.append( self.compute_convergence_delta(relevance_layer, output)) else: delta = self.compute_convergence_delta( cast(Tuple[Tensor, ...], relevances), output) return relevances, delta # type: ignore else: return relevances # type: ignore
def attribute( # type: ignore self, inputs: TensorOrTupleOfTensorsGeneric, sliding_window_shapes: Union[Tuple[int, ...], Tuple[Tuple[int, ...], ...]], strides: Union[None, int, Tuple[int, ...], Tuple[Union[int, Tuple[int, ...]], ...]] = None, baselines: BaselineType = None, target: TargetType = None, additional_forward_args: Any = None, perturbations_per_eval: int = 1, show_progress: bool = False, ) -> TensorOrTupleOfTensorsGeneric: r""" Args: inputs (tensor or tuple of tensors): Input for which occlusion 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. sliding_window_shapes (tuple or tuple of tuples): Shape of patch (hyperrectangle) to occlude each input. For a single input tensor, this must be a tuple of length equal to the number of dimensions of the input tensor - 1, defining the dimensions of the patch. If the input tensor is 1-d, this should be an empty tuple. For multiple input tensors, this must be a tuple containing one tuple for each input tensor defining the dimensions of the patch for that input tensor, as described for the single tensor case. strides (int or tuple or tuple of ints or tuple of tuples, optional): This defines the step by which the occlusion hyperrectangle should be shifted by in each direction for each iteration. For a single tensor input, this can be either a single integer, which is used as the step size in each direction, or a tuple of integers matching the number of dimensions in the occlusion shape, defining the step size in the corresponding dimension. For multiple tensor inputs, this can be either a tuple of integers, one for each input tensor (used for all dimensions of the corresponding tensor), or a tuple of tuples, providing the stride per dimension for each tensor. To ensure that all inputs are covered by at least one sliding window, the stride for any dimension must be <= the corresponding sliding window dimension if the sliding window dimension is less than the input dimension. If None is provided, a stride of 1 is used for each dimension of each input tensor. Default: None baselines (scalar, tensor, tuple of scalars or tensors, optional): Baselines define reference value which replaces each feature when occluded. Baselines can be provided as: - a single tensor, if inputs is a single tensor, with exactly the same dimensions as inputs or broadcastable to match the dimensions of 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. In the cases when `baselines` is not provided, we internally use zero scalar corresponding to each input tensor. Default: None target (int, tuple, tensor or list, optional): Output indices for which difference is computed (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 outputs, targets can be either: - a single integer or a tensor containing a single integer, which is applied to all input examples - a list of integers or a 1D tensor, with length matching the number of examples in inputs (dim 0). Each integer is applied as the target 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 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. For a tensor, the first dimension of the tensor must correspond to the number of examples. For all other types, the given argument is used for all forward evaluations. Note that attributions are not computed with respect to these arguments. Default: None perturbations_per_eval (int, optional): Allows multiple occlusions to be included in one batch (one call to forward_fn). By default, perturbations_per_eval is 1, so each occlusion is processed individually. Each forward pass will contain a maximum of perturbations_per_eval * #examples samples. For DataParallel models, each batch is split among the available devices, so evaluations on each available device contain at most (perturbations_per_eval * #examples) / num_devices samples. Default: 1 show_progress (bool, optional): Displays the progress of computation. It will try to use tqdm if available for advanced features (e.g. time estimation). Otherwise, it will fallback to a simple output of progress. Default: False Returns: *tensor* or tuple of *tensors* of **attributions**: - **attributions** (*tensor* or tuple of *tensors*): The attributions with respect to each input feature. Attributions will always be the same size as the provided inputs, with each value providing the attribution of the corresponding input index. If a single tensor is provided as inputs, a single tensor is returned. If a tuple is provided for inputs, a tuple of corresponding sized tensors is returned. Examples:: >>> # SimpleClassifier takes a single input tensor of size Nx4x4, >>> # and returns an Nx3 tensor of class probabilities. >>> net = SimpleClassifier() >>> # Generating random input with size 2 x 4 x 4 >>> input = torch.randn(2, 4, 4) >>> # Defining Occlusion interpreter >>> ablator = Occlusion(net) >>> # Computes occlusion attribution, ablating each 3x3 patch, >>> # shifting in each direction by the default of 1. >>> attr = ablator.attribute(input, target=1, sliding_window_shapes=(3,3)) """ formatted_inputs = _format_tensor_into_tuples(inputs) # Formatting strides strides = _format_and_verify_strides(strides, formatted_inputs) # Formatting sliding window shapes sliding_window_shapes = _format_and_verify_sliding_window_shapes( sliding_window_shapes, formatted_inputs) # Construct tensors from sliding window shapes sliding_window_tensors = tuple( torch.ones(window_shape, device=formatted_inputs[i].device) for i, window_shape in enumerate(sliding_window_shapes)) # Construct counts, defining number of steps to make of occlusion block in # each dimension. shift_counts = [] for i, inp in enumerate(formatted_inputs): current_shape = np.subtract(inp.shape[1:], sliding_window_shapes[i]) # Verify sliding window doesn't exceed input dimensions. assert (np.array(current_shape) >= 0).all(), ( "Sliding window dimensions {} cannot exceed input dimensions" "{}.").format(sliding_window_shapes[i], tuple(inp.shape[1:])) # Stride cannot be larger than sliding window for any dimension where # the sliding window doesn't cover the entire input. assert np.logical_or( np.array(current_shape) == 0, np.array(strides[i]) <= sliding_window_shapes[i], ).all(), ( "Stride dimension {} cannot be larger than sliding window " "shape dimension {}.").format(strides[i], sliding_window_shapes[i]) shift_counts.append( tuple( np.add( np.ceil(np.divide(current_shape, strides[i])).astype(int), 1))) # Use ablation attribute method return super().attribute.__wrapped__( self, inputs, baselines=baselines, target=target, additional_forward_args=additional_forward_args, perturbations_per_eval=perturbations_per_eval, sliding_window_tensors=sliding_window_tensors, shift_counts=tuple(shift_counts), strides=strides, show_progress=show_progress, )
def interpret( self, inputs: TensorOrTupleOfTensorsGeneric, experimental_sets: List[List[Concept]], target: TargetType = None, additional_forward_args: Any = None, processes: int = None, **kwargs: Any, ) -> Dict[str, Dict[str, Dict[str, Tensor]]]: r""" This method computes magnitude and sign-based TCAV scores for each experimental sets in `experimental_sets` list. TCAV scores are computed using a dot product between layer attribution scores for specific predictions and CAV vectors. Args: inputs (tensor or tuple of tensors): Inputs for which predictions are performed and attributions are computed. If model takes a single tensor as input, a single input tensor should be provided. If model 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. experimental_sets (list[list[Concept]]): A list of list of Concept instances. target (int, tuple, tensor or list, optional): Output indices for which attributions are computed (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 outputs, targets can be either: - a single integer or a tensor containing a single integer, which is applied to all input examples - a list of integers or a 1D tensor, with length matching the number of examples in inputs (dim 0). Each integer is applied as the target 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. additional_forward_args (Any, optional): Extra arguments that are passed to model when computing the attributions for `inputs` w.r.t. layer output. Default: None processes (int, optional): The number of processes to be created. if processes is larger than one then CAV computations will be performed in parallel using the number of processes equal to `processes`. Otherwise, CAV computations will be performed sequential. Default:None **kwargs (Any, optional): A list of arguments that are passed to layer attribution algorithm's attribute method. This could be for example `n_steps` in case of integrated gradients. Default: None Returns: results (dict): A dictionary of sign and magnitude -based tcav scores for each concept set per layer. The order of TCAV scores in the resulting tensor for each experimental set follows the order in which concepts are passed in `experimental_sets` input argument. results example:: >>> # >>> # scores = >>> # {'0-1': >>> # {'inception4c': >>> # {'sign_count': tensor([0.5800, 0.4200]), >>> # 'magnitude': tensor([0.6613, 0.3387])}, >>> # 'inception4d': >>> # {'sign_count': tensor([0.6200, 0.3800]), >>> # 'magnitude': tensor([0.7707, 0.2293])}}), >>> # '0-2': >>> # {'inception4c': >>> # {'sign_count': tensor([0.6200, 0.3800]), >>> # 'magnitude': tensor([0.6806, 0.3194])}, >>> # 'inception4d': >>> # {'sign_count': tensor([0.6400, 0.3600]), >>> # 'magnitude': tensor([0.6563, 0.3437])}})}) >>> # """ assert "attribute_to_layer_input" not in kwargs, ( "Please, set `attribute_to_layer_input` flag as a constructor " "argument to TCAV class. In that case it will be applied " "consistently to both layer activation and layer attribution methods." ) self.compute_cavs(experimental_sets, processes=processes) scores: Dict[str, Dict[str, Dict[str, Tensor]]] = defaultdict( lambda: defaultdict() ) # Retrieves the lengths of the experimental sets so that we can sort # them by the length and compute TCAV scores in batches. exp_set_lens = np.array( list(map(lambda exp_set: len(exp_set), experimental_sets)), dtype=object ) exp_set_lens_arg_sort = np.argsort(exp_set_lens) # compute offsets using sorted lengths using their indices exp_set_lens_sort = exp_set_lens[exp_set_lens_arg_sort] exp_set_offsets_bool = [False] + list( exp_set_lens_sort[:-1] == exp_set_lens_sort[1:] ) exp_set_offsets = [] for i, offset in enumerate(exp_set_offsets_bool): if not offset: exp_set_offsets.append(i) exp_set_offsets.append(len(exp_set_lens)) # sort experimental sets using the length of the concepts in each set experimental_sets_sorted = np.array(experimental_sets, dtype=object)[ exp_set_lens_arg_sort ] for layer in self.layers: layer_module = _get_module_from_name(self.model, layer) self.layer_attr_method.layer = layer_module attribs = self.layer_attr_method.attribute.__wrapped__( # type: ignore self.layer_attr_method, # self inputs, target=target, additional_forward_args=additional_forward_args, attribute_to_layer_input=self.attribute_to_layer_input, **kwargs, ) attribs = _format_tensor_into_tuples(attribs) # n_inputs x n_features attribs = torch.cat( [torch.reshape(attrib, (attrib.shape[0], -1)) for attrib in attribs], dim=1, ) # n_experiments x n_concepts x n_features cavs = [] classes = [] for concepts in experimental_sets: concepts_key = concepts_to_str(concepts) cavs_stats = cast(Dict[str, Any], self.cavs[concepts_key][layer].stats) cavs.append(cavs_stats["weights"].float().detach().tolist()) classes.append(cavs_stats["classes"]) # sort cavs and classes using the length of the concepts in each set cavs_sorted = np.array(cavs, dtype=object)[exp_set_lens_arg_sort] classes_sorted = np.array(classes, dtype=object)[exp_set_lens_arg_sort] i = 0 while i < len(exp_set_offsets) - 1: cav_subset = np.array( cavs_sorted[exp_set_offsets[i] : exp_set_offsets[i + 1]], dtype=object, ).tolist() classes_subset = classes_sorted[ exp_set_offsets[i] : exp_set_offsets[i + 1] ].tolist() # n_experiments x n_concepts x n_features cav_subset = torch.tensor(cav_subset) cav_subset = cav_subset.to(attribs.device) assert len(cav_subset.shape) == 3, ( "cav should have 3 dimensions: n_experiments x " "n_concepts x n_features." ) experimental_subset_sorted = experimental_sets_sorted[ exp_set_offsets[i] : exp_set_offsets[i + 1] ] self._tcav_sub_computation( scores, layer, attribs, cav_subset, classes_subset, experimental_subset_sorted, ) i += 1 return scores
def attribute( self, inputs: Union[Tensor, Tuple[Tensor, ...]], layer_baselines: BaselineType = None, target: TargetType = None, additional_forward_args: Any = None, layer_mask: Union[None, Tensor, Tuple[Tensor, ...]] = None, attribute_to_layer_input: bool = False, perturbations_per_eval: int = 1, ) -> Union[Tensor, Tuple[Tensor, ...]]: r""" Args: inputs (tensor or tuple of tensors): Input for which layer 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, and if multiple input tensors are provided, the examples must be aligned appropriately. layer_baselines (scalar, tensor, tuple of scalars or tensors, optional): Layer baselines define reference values which replace each layer input / output value when ablated. Layer baselines should be a single tensor with dimensions matching the input / output of the target layer (or broadcastable to match it), based on whether we are attributing to the input or output of the target layer. In the cases when `baselines` is not provided, we internally use zero as the baseline for each neuron. Default: None target (int, tuple, tensor or list, optional): Output indices for which gradients are computed (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 outputs, targets can be either: - a single integer or a tensor containing a single integer, which is applied to all input examples - a list of integers or a 1D tensor, with length matching the number of examples in inputs (dim 0). Each integer is applied as the target 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 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 attributions are not computed with respect to these arguments. Default: None layer_mask (tensor or tuple of tensors, optional): layer_mask defines a mask for the layer, grouping elements of the layer input / output which should be ablated together. layer_mask should be a single tensor with dimensions matching the input / output of the target layer (or broadcastable to match it), based on whether we are attributing to the input or output of the target layer. layer_mask should contain integers in the range 0 to num_groups - 1, and all elements with the same value are considered to be in the same group. If None, then a layer mask is constructed which assigns each neuron within the layer as a separate group, which is ablated independently. Default: None attribute_to_layer_input (bool, optional): Indicates whether to compute the attributions with respect to the layer input or output. If `attribute_to_layer_input` is set to True then the attributions will be computed with respect to layer's inputs, otherwise it will be computed with respect to layer's outputs. Note that currently it is assumed that either the input or the output of the layer, depending on whether we attribute to the input or output, is a single tensor. Support for multiple tensors will be added later. Default: False perturbations_per_eval (int, optional): Allows ablation of multiple neuron (groups) to be processed simultaneously in one call to forward_fn. Each forward pass will contain a maximum of perturbations_per_eval * #examples samples. For DataParallel models, each batch is split among the available devices, so evaluations on each available device contain at most (perturbations_per_eval * #examples) / num_devices samples. Default: 1 Returns: *tensor* or tuple of *tensors* of **attributions**: - **attributions** (*tensor* or tuple of *tensors*): Attribution of each neuron in given layer input or output. Attributions will always be the same size as the input or output of the given layer, depending on whether we attribute to the inputs or outputs of the layer which is decided by the input flag `attribute_to_layer_input` Attributions are returned in a tuple if the layer inputs / outputs contain multiple tensors, otherwise a single tensor is returned. Examples:: >>> # SimpleClassifier takes a single input tensor of size Nx4x4, >>> # and returns an Nx3 tensor of class probabilities. >>> # It contains an attribute conv1, which is an instance of nn.conv2d, >>> # and the output of this layer has dimensions Nx12x3x3. >>> net = SimpleClassifier() >>> # Generating random input with size 2 x 4 x 4 >>> input = torch.randn(2, 4, 4) >>> # Defining LayerFeatureAblation interpreter >>> ablator = LayerFeatureAblation(net, net.conv1) >>> # Computes ablation attribution, ablating each of the 108 >>> # neurons independently. >>> attr = ablator.attribute(input, target=1) >>> # Alternatively, we may want to ablate neurons in groups, e.g. >>> # grouping all the layer outputs in the same row. >>> # This can be done by creating a layer mask as follows, which >>> # defines the groups of layer inputs / outouts, e.g.: >>> # +---+---+---+ >>> # | 0 | 0 | 0 | >>> # +---+---+---+ >>> # | 1 | 1 | 1 | >>> # +---+---+---+ >>> # | 2 | 2 | 2 | >>> # +---+---+---+ >>> # With this mask, all the 36 neurons in a row / channel are ablated >>> # simultaneously, and the attribution for each neuron in the same >>> # group (0 - 2) per example are the same. >>> # The attributions can be calculated as follows: >>> # layer mask has dimensions 1 x 3 x 3 >>> layer_mask = torch.tensor([[[0,0,0],[1,1,1], >>> [2,2,2]]]) >>> attr = ablator.attribute(input, target=1, >>> layer_mask=layer_mask) """ def layer_forward_func(*args): layer_length = args[-1] layer_input = args[:layer_length] original_inputs = args[layer_length:-1] device_ids = self.device_ids if device_ids is None: device_ids = getattr(self.forward_func, "device_ids", None) all_layer_inputs = {} if device_ids is not None: scattered_layer_input = scatter(layer_input, target_gpus=device_ids) for device_tensors in scattered_layer_input: all_layer_inputs[device_tensors[0].device] = device_tensors else: all_layer_inputs[layer_input[0].device] = layer_input def forward_hook(module, inp, out=None): device = _extract_device(module, inp, out) is_layer_tuple = (isinstance(out, tuple) if out is not None else isinstance(inp, tuple)) if device not in all_layer_inputs: raise AssertionError( "Layer input not placed on appropriate " "device. If using a DataParallel model, either provide the " "DataParallel model as forward_func or provide device ids" " to the constructor.") if not is_layer_tuple: return all_layer_inputs[device][0] return all_layer_inputs[device] hook = None try: if attribute_to_layer_input: hook = self.layer.register_forward_pre_hook(forward_hook) else: hook = self.layer.register_forward_hook(forward_hook) eval = _run_forward(self.forward_func, original_inputs, target=target) finally: if hook is not None: hook.remove() return eval with torch.no_grad(): inputs = _format_tensor_into_tuples(inputs) additional_forward_args = _format_additional_forward_args( additional_forward_args) layer_eval = _forward_layer_eval( self.forward_func, inputs, self.layer, additional_forward_args, device_ids=self.device_ids, attribute_to_layer_input=attribute_to_layer_input, ) layer_eval_len = (len(layer_eval), ) all_inputs = ((inputs + additional_forward_args + layer_eval_len) if additional_forward_args is not None else inputs + layer_eval_len) ablator = FeatureAblation(layer_forward_func) layer_attribs = ablator.attribute.__wrapped__( ablator, # self layer_eval, baselines=layer_baselines, additional_forward_args=all_inputs, feature_mask=layer_mask, perturbations_per_eval=perturbations_per_eval, ) _attr = _format_output(len(layer_attribs) > 1, layer_attribs) return _attr
def infidelity( forward_func: Callable, perturb_func: Callable, inputs: TensorOrTupleOfTensorsGeneric, attributions: TensorOrTupleOfTensorsGeneric, baselines: BaselineType = None, additional_forward_args: Any = None, target: TargetType = None, n_perturb_samples: int = 10, max_examples_per_batch: int = None, normalize: bool = False, ) -> Tensor: r""" Explanation infidelity represents the expected mean-squared error between the explanation multiplied by a meaningful input perturbation and the differences between the predictor function at its input and perturbed input. More details about the measure can be found in the following paper: https://arxiv.org/pdf/1901.09392.pdf It is derived from the completeness property of well-known attribution algorithms and is a computationally more efficient and generalized notion of Sensitivy-n. The latter measures correlations between the sum of the attributions and the differences of the predictor function at its input and fixed baseline. More details about the Sensitivity-n can be found here: https://arxiv.org/pdf/1711.06104.pdfs The users can perturb the inputs any desired way by providing any perturbation function that takes the inputs (and optionally baselines) and returns perturbed inputs or perturbed inputs and corresponding perturbations. This specific implementation is primarily tested for attribution-based explanation methods but the idea can be expanded to use for non attribution-based interpretability methods as well. Args: forward_func (callable): The forward function of the model or any modification of it. perturb_func (callable): The perturbation function of model inputs. This function takes model inputs and optionally baselines as input arguments and returns either a tuple of perturbations and perturbed inputs or just perturbed inputs. For example: >>> def my_perturb_func(inputs): >>> <MY-LOGIC-HERE> >>> return perturbations, perturbed_inputs If we want to only return perturbed inputs and compute perturbations internally then we can wrap perturb_func with `infidelity_perturb_func_decorator` decorator such as: >>> from captum.metrics import infidelity_perturb_func_decorator >>> @infidelity_perturb_func_decorator(<multipy_by_inputs flag>) >>> def my_perturb_func(inputs): >>> <MY-LOGIC-HERE> >>> return perturbed_inputs In case `multipy_by_inputs` is False we compute perturbations by `input - perturbed_input` difference and in case `multipy_by_inputs` flag is True we compute it by dividing (input - perturbed_input) by (input - baselines). The user needs to only return perturbed inputs in `perturb_func` as described above. `infidelity_perturb_func_decorator` needs to be used with `multipy_by_inputs` flag set to False in case infidelity score is being computed for attribution maps that are local aka that do not factor in inputs in the final attribution score. Such attribution algorithms include Saliency, GradCam, Guided Backprop, or Integrated Gradients and DeepLift attribution scores that are already computed with `multipy_by_inputs=False` flag. If there are more than one inputs passed to infidelity function those will be passed to `perturb_func` as tuples in the same order as they are passed to infidelity function. If inputs - is a single tensor, the function needs to return a tuple of perturbations and perturbed input such as: perturb, perturbed_input and only perturbed_input in case `infidelity_perturb_func_decorator` is used. - is a tuple of tensors, corresponding perturbations and perturbed inputs must be computed and returned as tuples in the following format: (perturb1, perturb2, ... perturbN), (perturbed_input1, perturbed_input2, ... perturbed_inputN) Similar to previous case here as well we need to return only perturbed inputs in case `infidelity_perturb_func_decorator` decorates out `perturb_func`. It is important to note that for performance reasons `perturb_func` isn't called for each example individually but on a batch of input examples that are repeated `max_examples_per_batch / batch_size` times within the batch. inputs (tensor or tuple of tensors): 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 scalars or tensors, optional): Baselines define reference values 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 of tensors): 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/pdf/1711.06104.pdf 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/pdf/1901.09392.pdf 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. `infidelity_perturb_func_decorator` function decorator is a helper function that computes perturbations under the hood if perturbed inputs are provided. For more details about how to use `infidelity_perturb_func_decorator`, please, read the documentation about `perturb_func` 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. 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. This means that these arguments aren't being passed to `perturb_func` as an input argument. 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 outputs, targets can be either: - A single integer or a tensor containing a single integer, which is applied to all input examples - A list of integers or a 1D tensor, with length matching the number of examples in inputs (dim 0). Each integer is applied as the target 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 n_perturb_samples (int, optional): The number of times input tensors are perturbed. Each input example in the inputs tensor is expanded `n_perturb_samples` times before calling `perturb_func` function. Default: 10 max_examples_per_batch (int, optional): The number of maximum input examples that are processed together. In case the number of examples (`input batch size * n_perturb_samples`) exceeds `max_examples_per_batch`, they will be sliced into batches of `max_examples_per_batch` examples and processed in a sequential order. If `max_examples_per_batch` is None, all examples are processed together. `max_examples_per_batch` should at least be equal `input batch size` and at most `input batch size * n_perturb_samples`. Default: None normalize (bool, optional): Normalize the dot product of the input perturbation and the attribution so the infidelity value is invariant to constant scaling of the attribution values. The normalization factor beta is defined as the ratio of two mean values: $$ \beta = \frac{ \mathbb{E}_{I \sim \mu_I} [ I^T \Phi(f, x) (f(x) - f(x - I)) ] }{ \mathbb{E}_{I \sim \mu_I} [ (I^T \Phi(f, x))^2 ] } $$. Please refer the original paper for the meaning of the symbols. Same normalization can be found in the paper's official implementation https://github.com/chihkuanyeh/saliency_evaluation Default: False Returns: infidelities (tensor): A tensor of scalar infidelity scores per input example. The first dimension is equal to the number of examples in the input batch and the second dimension is one. 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) >>> # Computes saliency maps for class 3. >>> attribution = saliency.attribute(input, target=3) >>> # define a perturbation function for the input >>> def perturb_fn(inputs): >>> noise = torch.tensor(np.random.normal(0, 0.003, inputs.shape)).float() >>> return noise, inputs - noise >>> # Computes infidelity score for saliency maps >>> infid = infidelity(net, perturb_fn, input, attribution) """ def _generate_perturbations( current_n_perturb_samples: int, ) -> Tuple[TensorOrTupleOfTensorsGeneric, TensorOrTupleOfTensorsGeneric]: r""" The perturbations are generated for each example `current_n_perturb_samples` times. For performance reasons we are not calling `perturb_func` on each example but on a batch that contains `current_n_perturb_samples` repeated instances per example. """ def call_perturb_func(): r""" """ baselines_pert = None inputs_pert: Union[Tensor, Tuple[Tensor, ...]] if len(inputs_expanded) == 1: inputs_pert = inputs_expanded[0] if baselines_expanded is not None: baselines_pert = cast(Tuple, baselines_expanded)[0] else: inputs_pert = inputs_expanded baselines_pert = baselines_expanded return ( perturb_func(inputs_pert, baselines_pert) if baselines_pert is not None else perturb_func(inputs_pert) ) inputs_expanded = tuple( torch.repeat_interleave(input, current_n_perturb_samples, dim=0) for input in inputs ) baselines_expanded = baselines if baselines is not None: baselines_expanded = tuple( baseline.repeat_interleave(current_n_perturb_samples, dim=0) if isinstance(baseline, torch.Tensor) and baseline.shape[0] == input.shape[0] and baseline.shape[0] > 1 else baseline for input, baseline in zip(inputs, cast(Tuple, baselines)) ) return call_perturb_func() def _validate_inputs_and_perturbations( inputs: Tuple[Tensor, ...], inputs_perturbed: Tuple[Tensor, ...], perturbations: Tuple[Tensor, ...], ) -> None: # asserts the sizes of the perturbations and inputs assert len(perturbations) == len(inputs), ( """The number of perturbed inputs and corresponding perturbations must have the same number of elements. Found number of inputs is: {} and perturbations: {}""" ).format(len(perturbations), len(inputs)) # asserts the shapes of the perturbations and perturbed inputs for perturb, input_perturbed in zip(perturbations, inputs_perturbed): assert perturb[0].shape == input_perturbed[0].shape, ( """Perturbed input and corresponding perturbation must have the same shape and dimensionality. Found perturbation shape is: {} and the input shape is: {}""" ).format(perturb[0].shape, input_perturbed[0].shape) def _next_infidelity_tensors( current_n_perturb_samples: int, ) -> Union[Tuple[Tensor], Tuple[Tensor, Tensor, Tensor]]: perturbations, inputs_perturbed = _generate_perturbations( current_n_perturb_samples ) perturbations = _format_tensor_into_tuples(perturbations) inputs_perturbed = _format_tensor_into_tuples(inputs_perturbed) _validate_inputs_and_perturbations( cast(Tuple[Tensor, ...], inputs), cast(Tuple[Tensor, ...], inputs_perturbed), cast(Tuple[Tensor, ...], perturbations), ) targets_expanded = _expand_target( target, current_n_perturb_samples, expansion_type=ExpansionTypes.repeat_interleave, ) additional_forward_args_expanded = _expand_additional_forward_args( additional_forward_args, current_n_perturb_samples, expansion_type=ExpansionTypes.repeat_interleave, ) inputs_perturbed_fwd = _run_forward( forward_func, inputs_perturbed, targets_expanded, additional_forward_args_expanded, ) inputs_fwd = _run_forward(forward_func, inputs, target, additional_forward_args) inputs_fwd = torch.repeat_interleave( inputs_fwd, current_n_perturb_samples, dim=0 ) perturbed_fwd_diffs = inputs_fwd - inputs_perturbed_fwd attributions_expanded = tuple( torch.repeat_interleave(attribution, current_n_perturb_samples, dim=0) for attribution in attributions ) attributions_times_perturb = tuple( (attribution_expanded * perturbation).view(attribution_expanded.size(0), -1) for attribution_expanded, perturbation in zip( attributions_expanded, perturbations ) ) attr_times_perturb_sums = sum( torch.sum(attribution_times_perturb, dim=1) for attribution_times_perturb in attributions_times_perturb ) attr_times_perturb_sums = cast(Tensor, attr_times_perturb_sums) # reshape as Tensor(bsz, current_n_perturb_samples) attr_times_perturb_sums = attr_times_perturb_sums.view(bsz, -1) perturbed_fwd_diffs = perturbed_fwd_diffs.view(bsz, -1) if normalize: # in order to normalize, we have to aggregate the following tensors # to calculate MSE in its polynomial expansion: # (a-b)^2 = a^2 - 2ab + b^2 return ( attr_times_perturb_sums.pow(2).sum(-1), (attr_times_perturb_sums * perturbed_fwd_diffs).sum(-1), perturbed_fwd_diffs.pow(2).sum(-1), ) else: # returns (a-b)^2 if no need to normalize return ((attr_times_perturb_sums - perturbed_fwd_diffs).pow(2).sum(-1),) def _sum_infidelity_tensors(agg_tensors, tensors): return tuple(agg_t + t for agg_t, t in zip(agg_tensors, tensors)) # perform argument formattings inputs = _format_input(inputs) # type: ignore if baselines is not None: baselines = _format_baseline(baselines, cast(Tuple[Tensor, ...], inputs)) additional_forward_args = _format_additional_forward_args(additional_forward_args) attributions = _format_tensor_into_tuples(attributions) # type: ignore # Make sure that inputs and corresponding attributions have matching sizes. assert len(inputs) == len(attributions), ( """The number of tensors in the inputs and attributions must match. Found number of tensors in the inputs is: {} and in the attributions: {}""" ).format(len(inputs), len(attributions)) for inp, attr in zip(inputs, attributions): assert inp.shape == attr.shape, ( """Inputs and attributions must have matching shapes. One of the input tensor's shape is {} and the attribution tensor's shape is: {}""" ).format(inp.shape, attr.shape) bsz = inputs[0].size(0) with torch.no_grad(): # if not normalize, directly return aggrgated MSE ((a-b)^2,) # else return aggregated MSE's polynomial expansion tensors (a^2, ab, b^2) agg_tensors = _divide_and_aggregate_metrics( cast(Tuple[Tensor, ...], inputs), n_perturb_samples, _next_infidelity_tensors, agg_func=_sum_infidelity_tensors, max_examples_per_batch=max_examples_per_batch, ) if normalize: beta_num = agg_tensors[1] beta_denorm = agg_tensors[0] beta = safe_div( beta_num, beta_denorm, torch.tensor(1.0, dtype=beta_denorm.dtype, device=beta_denorm.device), ) infidelity_values = ( beta ** 2 * agg_tensors[0] - 2 * beta * agg_tensors[1] + agg_tensors[2] ) else: infidelity_values = agg_tensors[0] infidelity_values /= n_perturb_samples return infidelity_values
def attribute( self, inputs: TensorOrTupleOfTensorsGeneric, target: TargetType = None, additional_forward_args: Any = None, ) -> TensorOrTupleOfTensorsGeneric: r""" Args: inputs (tensor or tuple of tensors): 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. target (int, tuple, tensor or list, optional): Output indices for which gradients are computed (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 outputs, targets can be either: - a single integer or a tensor containing a single integer, which is applied to all input examples - a list of integers or a 1D tensor, with length matching the number of examples in inputs (dim 0). Each integer is applied as the target 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 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 attributions are not computed with respect to these arguments. Default: None Returns: *tensor* or tuple of *tensors* of **attributions**: - **attributions** (*tensor* or tuple of *tensors*): The input x gradient with respect to each input feature. Attributions will always be the same size as the provided inputs, with each value providing the attribution of the corresponding input index. If a single tensor is provided as inputs, a single tensor is returned. If a tuple is provided for inputs, a tuple of corresponding sized tensors is returned. Examples:: >>> # ImageClassifier takes a single input tensor of images Nx3x32x32, >>> # and returns an Nx10 tensor of class probabilities. >>> net = ImageClassifier() >>> # Generating random input with size 2x3x3x32 >>> input = torch.randn(2, 3, 32, 32, requires_grad=True) >>> # Defining InputXGradient interpreter >>> input_x_gradient = InputXGradient(net) >>> # Computes inputXgradient for class 4. >>> attribution = input_x_gradient.attribute(input, target=4) """ # Keeps track whether original input is a tuple or not before # converting it into a tuple. is_inputs_tuple = _is_tuple(inputs) inputs = _format_tensor_into_tuples(inputs) gradient_mask = apply_gradient_requirements(inputs) gradients = self.gradient_func(self.forward_func, inputs, target, additional_forward_args) attributions = tuple(input * gradient for input, gradient in zip(inputs, gradients)) undo_gradient_requirements(inputs, gradient_mask) return _format_output(is_inputs_tuple, attributions)
def _next_infidelity_tensors( current_n_perturb_samples: int, ) -> Union[Tuple[Tensor], Tuple[Tensor, Tensor, Tensor]]: perturbations, inputs_perturbed = _generate_perturbations( current_n_perturb_samples ) perturbations = _format_tensor_into_tuples(perturbations) inputs_perturbed = _format_tensor_into_tuples(inputs_perturbed) _validate_inputs_and_perturbations( cast(Tuple[Tensor, ...], inputs), cast(Tuple[Tensor, ...], inputs_perturbed), cast(Tuple[Tensor, ...], perturbations), ) targets_expanded = _expand_target( target, current_n_perturb_samples, expansion_type=ExpansionTypes.repeat_interleave, ) additional_forward_args_expanded = _expand_additional_forward_args( additional_forward_args, current_n_perturb_samples, expansion_type=ExpansionTypes.repeat_interleave, ) inputs_perturbed_fwd = _run_forward( forward_func, inputs_perturbed, targets_expanded, additional_forward_args_expanded, ) inputs_fwd = _run_forward(forward_func, inputs, target, additional_forward_args) inputs_fwd = torch.repeat_interleave( inputs_fwd, current_n_perturb_samples, dim=0 ) perturbed_fwd_diffs = inputs_fwd - inputs_perturbed_fwd attributions_expanded = tuple( torch.repeat_interleave(attribution, current_n_perturb_samples, dim=0) for attribution in attributions ) attributions_times_perturb = tuple( (attribution_expanded * perturbation).view(attribution_expanded.size(0), -1) for attribution_expanded, perturbation in zip( attributions_expanded, perturbations ) ) attr_times_perturb_sums = sum( torch.sum(attribution_times_perturb, dim=1) for attribution_times_perturb in attributions_times_perturb ) attr_times_perturb_sums = cast(Tensor, attr_times_perturb_sums) # reshape as Tensor(bsz, current_n_perturb_samples) attr_times_perturb_sums = attr_times_perturb_sums.view(bsz, -1) perturbed_fwd_diffs = perturbed_fwd_diffs.view(bsz, -1) if normalize: # in order to normalize, we have to aggregate the following tensors # to calculate MSE in its polynomial expansion: # (a-b)^2 = a^2 - 2ab + b^2 return ( attr_times_perturb_sums.pow(2).sum(-1), (attr_times_perturb_sums * perturbed_fwd_diffs).sum(-1), perturbed_fwd_diffs.pow(2).sum(-1), ) else: # returns (a-b)^2 if no need to normalize return ((attr_times_perturb_sums - perturbed_fwd_diffs).pow(2).sum(-1),)
def attribute( self, inputs: Union[Tensor, Tuple[Tensor, ...]], baselines: BaselineType = None, target: TargetType = None, additional_forward_args: Any = None, return_convergence_delta: bool = False, attribute_to_layer_input: bool = False, custom_attribution_func: Union[None, Callable[..., Tuple[Tensor, ...]]] = None, ) -> Union[ Tensor, Tuple[Tensor, ...], Tuple[Union[Tensor, Tuple[Tensor, ...]], Tensor] ]: r""" Args: inputs (tensor or tuple of tensors): Input for which layer 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 scalars or tensors, optional): Baselines define reference samples that are compared with the inputs. In order to assign attribution scores DeepLift computes the differences between the inputs/outputs and corresponding references. Baselines can be provided 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. In the cases when `baselines` is not provided, we internally use zero scalar corresponding to each input tensor. Default: None target (int, tuple, tensor or list, optional): Output indices for which gradients are computed (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 outputs, targets can be either: - a single integer or a tensor containing a single integer, which is applied to all input examples - a list of integers or a 1D tensor, with length matching the number of examples in inputs (dim 0). Each integer is applied as the target 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 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 attributions are not computed with respect to these arguments. Default: None return_convergence_delta (bool, optional): Indicates whether to return convergence delta or not. If `return_convergence_delta` is set to True convergence delta will be returned in a tuple following attributions. Default: False attribute_to_layer_input (bool, optional): Indicates whether to compute the attribution with respect to the layer input or output. If `attribute_to_layer_input` is set to True then the attributions will be computed with respect to layer input, otherwise it will be computed with respect to layer output. Note that currently it is assumed that either the input or the output of internal layer, depending on whether we attribute to the input or output, is a single tensor. Support for multiple tensors will be added later. Default: False custom_attribution_func (callable, optional): A custom function for computing final attribution scores. This function can take at least one and at most three arguments with the following signature: - custom_attribution_func(multipliers) - custom_attribution_func(multipliers, inputs) - custom_attribution_func(multipliers, inputs, baselines) In case this function is not provided, we use the default logic defined as: multipliers * (inputs - baselines) It is assumed that all input arguments, `multipliers`, `inputs` and `baselines` are provided in tuples of same length. `custom_attribution_func` returns a tuple of attribution tensors that have the same length as the `inputs`. Default: None Returns: **attributions** or 2-element tuple of **attributions**, **delta**: - **attributions** (*tensor* or tuple of *tensors*): Attribution score computed based on DeepLift's rescale rule with respect to layer's inputs or outputs. Attributions will always be the same size as the provided layer's inputs or outputs, depending on whether we attribute to the inputs or outputs of the layer. If the layer input / output is a single tensor, then just a tensor is returned; if the layer input / output has multiple tensors, then a corresponding tuple of tensors is returned. - **delta** (*tensor*, returned if return_convergence_delta=True): This is computed using the property that the total sum of forward_func(inputs) - forward_func(baselines) must equal the total sum of the attributions computed based on DeepLift's rescale rule. Delta is calculated per example, meaning that the number of elements in returned delta tensor is equal to the number of of examples in input. Note that the logic described for deltas is guaranteed when the default logic for attribution computations is used, meaning that the `custom_attribution_func=None`, otherwise it is not guaranteed and depends on the specifics of the `custom_attribution_func`. Examples:: >>> # ImageClassifier takes a single input tensor of images Nx3x32x32, >>> # and returns an Nx10 tensor of class probabilities. >>> net = ImageClassifier() >>> # creates an instance of LayerDeepLift to interpret target >>> # class 1 with respect to conv4 layer. >>> dl = LayerDeepLift(net, net.conv4) >>> input = torch.randn(1, 3, 32, 32, requires_grad=True) >>> # Computes deeplift attribution scores for conv4 layer and class 3. >>> attribution = dl.attribute(input, target=1) """ inputs = _format_tensor_into_tuples(inputs) baselines = _format_baseline(baselines, inputs) _validate_input(inputs, baselines) baselines = _tensorize_baseline(inputs, baselines) main_model_hooks = [] try: main_model_hooks = self._hook_main_model() self.model.apply( lambda mod: self._register_hooks( mod, attribute_to_layer_input=attribute_to_layer_input ) ) additional_forward_args = _format_additional_forward_args( additional_forward_args ) expanded_target = _expand_target( target, 2, expansion_type=ExpansionTypes.repeat ) wrapped_forward_func = self._construct_forward_func( self.model, (inputs, baselines), expanded_target, additional_forward_args, ) def chunk_output_fn(out: TensorOrTupleOfTensorsGeneric) -> Sequence: if isinstance(out, Tensor): return out.chunk(2) return tuple(out_sub.chunk(2) for out_sub in out) gradients, attrs = compute_layer_gradients_and_eval( wrapped_forward_func, self.layer, inputs, attribute_to_layer_input=attribute_to_layer_input, output_fn=lambda out: chunk_output_fn(out), ) attr_inputs = tuple(map(lambda attr: attr[0], attrs)) attr_baselines = tuple(map(lambda attr: attr[1], attrs)) gradients = tuple(map(lambda grad: grad[0], gradients)) if custom_attribution_func is None: if self.multiplies_by_inputs: attributions = tuple( (input - baseline) * gradient for input, baseline, gradient in zip( attr_inputs, attr_baselines, gradients ) ) else: attributions = gradients else: attributions = _call_custom_attribution_func( custom_attribution_func, gradients, attr_inputs, attr_baselines ) finally: # remove hooks from all activations self._remove_hooks(main_model_hooks) return _compute_conv_delta_and_format_attrs( self, return_convergence_delta, attributions, baselines, inputs, additional_forward_args, target, cast(Union[Literal[True], Literal[False]], len(attributions) > 1), )