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 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_input(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 attribute( # type: ignore self, inputs: TensorOrTupleOfTensorsGeneric, baselines: BaselineType = None, target: TargetType = None, additional_forward_args: Any = None, return_convergence_delta: bool = False, ) -> Union[TensorOrTupleOfTensorsGeneric, Tuple[ TensorOrTupleOfTensorsGeneric, Tensor]]: # 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) rand_coefficient = torch.tensor( np.random.uniform(0.0, 1.0, inputs[0].shape[0]), device=inputs[0].device, dtype=inputs[0].dtype, ) input_baseline_scaled = tuple( _scale_input(input, baseline, rand_coefficient) for input, baseline in zip(inputs, baselines)) grads = self.gradient_func(self.forward_func, input_baseline_scaled, target, additional_forward_args) if self.multiplies_by_inputs: input_baseline_diffs = tuple( input - baseline for input, baseline in zip(inputs, baselines)) attributions = tuple(input_baseline_diff * grad for input_baseline_diff, grad in zip( input_baseline_diffs, grads)) else: attributions = grads 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, target: TargetType = 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, i.e., batch size, and if multiple input tensors are provided, the examples must be aligned appropriately. target (int, tuple, tensor or list, optional): """ is_inputs_tuple = _is_tuple(inputs) inputs = _format_input(inputs)
def attribute( self, inputs: TensorOrTupleOfTensorsGeneric, neuron_selector: Union[int, Tuple[int, ...], Callable], baselines: BaselineType = None, target: TargetType = None, additional_forward_args: Any = None, n_steps: int = 50, method: str = "riemann_trapezoid", internal_batch_size: Union[None, int] = None, attribute_to_neuron_input: bool = False, ) -> TensorOrTupleOfTensorsGeneric: r""" Args: inputs (tensor or tuple of tensors): Input for which neuron conductance is 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. 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). This can be used as long as the layer input / output is a single tensor. - a callable, which should take the target layer as input (single tensor or tuple if multiple tensors are in layer) and return a selected neuron - output shape should be 1D with length equal to batch_size (one scalar per input example) NOTE: Callables applicable for neuron conductance are less general than those of other methods and should NOT aggregate values of the layer, only return a specific output. This option should only be used in cases where the layer input / output is a tuple of tensors, where the other options would not suffice. This limitation is necessary since neuron conductance, unlike other neuron methods, also utilizes the gradient of output with respect to the intermedite neuron, which cannot be computed for aggregations of multiple intemediate neurons. baselines (scalar, tensor, tuple of scalars or tensors, optional): Baselines define the starting point from which integral is computed and 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. For a tensor, the first dimension of the tensor must correspond to the number of examples. It will be repeated for each of `n_steps` along the integrated path. 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 n_steps (int, optional): The number of steps used by the approximation method. Default: 50. method (string, optional): Method for approximating the integral, one of `riemann_right`, `riemann_left`, `riemann_middle`, `riemann_trapezoid` or `gausslegendre`. Default: `gausslegendre` if no method is provided. internal_batch_size (int, optional): Divides total #steps * #examples data points into chunks of size at most internal_batch_size, which are computed (forward / backward passes) sequentially. internal_batch_size must be at least equal to #examples. For DataParallel models, each batch is split among the available devices, so evaluations on each available device contain internal_batch_size / num_devices examples. If internal_batch_size is None, then all evaluations are processed in one batch. 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 neuron, 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*): Conductance for 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_cond = NeuronConductance(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. >>> # Computes neuron conductance for neuron with >>> # index (4,1,2). >>> attribution = neuron_cond.attribute(input, (4,1,2)) """ if callable(neuron_selector): warnings.warn( "The neuron_selector provided is a callable. Please ensure that this" " function only selects neurons from the given layer; aggregating" " or performing other operations on the tensor may lead to inaccurate" " results.") is_inputs_tuple = _is_tuple(inputs) inputs, baselines = _format_input_baseline(inputs, baselines) _validate_input(inputs, baselines, n_steps, method) num_examples = inputs[0].shape[0] if internal_batch_size is not None: num_examples = inputs[0].shape[0] attrs = _batch_attribution( self, num_examples, internal_batch_size, n_steps, inputs=inputs, baselines=baselines, neuron_selector=neuron_selector, target=target, additional_forward_args=additional_forward_args, method=method, attribute_to_neuron_input=attribute_to_neuron_input, ) else: attrs = self._attribute( inputs=inputs, neuron_selector=neuron_selector, baselines=baselines, target=target, additional_forward_args=additional_forward_args, n_steps=n_steps, method=method, attribute_to_neuron_input=attribute_to_neuron_input, ) return _format_output(is_inputs_tuple, attrs)
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_input(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 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 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( # 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 perturb( self, inputs: TensorOrTupleOfTensorsGeneric, epsilon: float, target: Any, additional_forward_args: Any = None, targeted: bool = False, ) -> 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. epsilon (float): Step size of perturbation. 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. 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. """ is_inputs_tuple = _is_tuple(inputs) inputs: Tuple[Tensor, ...] = _format_input(inputs) gradient_mask = apply_gradient_requirements(inputs) def _forward_with_loss() -> Tensor: additional_inputs = _format_additional_forward_args(additional_forward_args) outputs = self.forward_func( # type: ignore *(*inputs, *additional_inputs) # type: ignore if additional_inputs is not None else inputs ) if self.loss_func is not None: return self.loss_func(outputs, target) else: loss = -torch.log(outputs) return _select_targets(loss, target) grads = compute_gradients(_forward_with_loss, inputs) undo_gradient_requirements(inputs, gradient_mask) perturbed_inputs = self._perturb(inputs, grads, epsilon, targeted) perturbed_inputs = tuple( self.bound(perturbed_inputs[i]) for i in range(len(perturbed_inputs)) ) return _format_output(is_inputs_tuple, perturbed_inputs)
def attribute( self, inputs: TensorOrTupleOfTensorsGeneric, target: TargetType = None, additional_forward_args: Any = None, return_convergence_delta: bool = False, verbose: bool = False, ) -> Union[ TensorOrTupleOfTensorsGeneric, Tuple[TensorOrTupleOfTensorsGeneric, 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 verbose (bool, optional): Indicates whether information on application of rules is printed during propagation. Returns: *tensor* or tuple of *tensors* of **attributions** or 2-element tuple of **attributions**, **delta**:: - **attributions** (*tensor* or tuple of *tensors*): The propagated relevance values with respect to each input feature. The values are normalized by the output score value (sum(relevance)=1). To obtain values comparable to other methods or implementations these values need to be multiplied by the output score. 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. - **delta** (*tensor*, 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 the inputs. 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) >>> 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: List[Module] = [] self._get_layers(self.model) self._check_and_attach_rules() self.backward_handles: List[RemovableHandle] = [] self.forward_handles: List[RemovableHandle] = [] is_inputs_tuple = _is_tuple(inputs) inputs = _format_input(inputs) gradient_mask = apply_gradient_requirements(inputs) try: # 1. Forward pass: Change weights of layers according to selected rules. output = self._compute_output_and_change_weights( inputs, target, additional_forward_args ) # 2. Forward pass + backward pass: Register hooks to configure relevance # propagation and execute back-propagation. self._register_forward_hooks() normalized_relevances = self.gradient_func( self._forward_fn_wrapper, inputs, target, additional_forward_args ) relevances = tuple( normalized_relevance * output.reshape((-1,) + (1,) * (normalized_relevance.dim() - 1)) for normalized_relevance in normalized_relevances ) finally: self._restore_model() undo_gradient_requirements(inputs, gradient_mask) if return_convergence_delta: return ( _format_output(is_inputs_tuple, relevances), self.compute_convergence_delta(relevances, output), ) else: return _format_output(is_inputs_tuple, relevances) # type: ignore
def attribute( self, inputs: TensorOrTupleOfTensorsGeneric, baselines: BaselineType = None, target: TargetType = None, additional_forward_args: Any = None, feature_mask: Union[None, Tensor, Tuple[Tensor, ...]] = None, perturbations_per_eval: int = 1, **kwargs: Any ) -> TensorOrTupleOfTensorsGeneric: r""" Args: inputs (tensor or tuple of tensors): Input for which ablation 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 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 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. 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 ablated together. feature_mask should contain the same number of tensors as inputs. Each tensor should be the same size as the corresponding input or broadcastable to match the input tensor. Each tensor should contain integers in the range 0 to num_features - 1, and indices corresponding to the same feature should have the same value. Note that features within each input tensor are ablated independently (not across tensors). If the forward function returns a single scalar per batch, we enforce that the first dimension of each mask must be 1, since attributions are returned batch-wise rather than per example, so the attributions must correspond to the same features (indices) in each input example. If None, then a feature mask is constructed which assigns each scalar within a tensor as a separate feature, which is ablated independently. Default: None perturbations_per_eval (int, optional): Allows ablation of multiple features 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's number of outputs does not change as the batch size grows (e.g. if it outputs a scalar value), you must set perturbations_per_eval to 1 and use a single feature mask to describe the features for all examples in the batch. Default: 1 **kwargs (Any, optional): Any additional arguments used by child classes of FeatureAblation (such as Occlusion) to construct ablations. These arguments are ignored when using FeatureAblation directly. Default: None 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 of tensors 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 FeatureAblation interpreter >>> ablator = FeatureAblation(net) >>> # Computes ablation attribution, ablating each of the 16 >>> # scalar input independently. >>> attr = ablator.attribute(input, target=1) >>> # Alternatively, we may want to ablate features in groups, e.g. >>> # grouping each 2x2 square of the inputs and ablating 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 ablated >>> # simultaneously, 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 = ablator.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 ) num_examples = inputs[0].shape[0] feature_mask = _format_input(feature_mask) if feature_mask is not None else None assert ( isinstance(perturbations_per_eval, int) and perturbations_per_eval >= 1 ), "Perturbations per evaluation must be an integer and at least 1." with torch.no_grad(): # Computes initial evaluation with all features, which is compared # to each ablated result. initial_eval = _run_forward( self.forward_func, inputs, target, additional_forward_args ) agg_output_mode = FeatureAblation._find_output_mode( perturbations_per_eval, feature_mask ) # get as a 2D tensor (if it is not a scalar) if isinstance(initial_eval, torch.Tensor): initial_eval = initial_eval.reshape(1, -1) num_outputs = initial_eval.shape[1] else: num_outputs = 1 if not agg_output_mode: assert ( isinstance(initial_eval, torch.Tensor) and num_outputs == num_examples ), ( "expected output of `forward_func` to have " + "`batch_size` elements for perturbations_per_eval > 1 " + "and all feature_mask.shape[0] > 1" ) # Initialize attribution totals and counts attrib_type = cast( dtype, initial_eval.dtype if isinstance(initial_eval, Tensor) else type(initial_eval), ) total_attrib = [ torch.zeros( (num_outputs,) + input.shape[1:], dtype=attrib_type, device=input.device, ) for input in inputs ] # Weights are used in cases where ablations may be overlapping. if self.use_weights: weights = [ torch.zeros( (num_outputs,) + input.shape[1:], device=input.device ).float() for input in inputs ] # Iterate through each feature tensor for ablation for i in range(len(inputs)): # Skip any empty input tensors if torch.numel(inputs[i]) == 0: continue for ( current_inputs, current_add_args, current_target, current_mask, ) in self._ablation_generator( i, inputs, additional_forward_args, target, baselines, feature_mask, perturbations_per_eval, **kwargs ): # 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, ) # (contains 1 more dimension than inputs). This adds extra # dimensions of 1 to make the tensor broadcastable with the inputs # tensor. if not isinstance(modified_eval, torch.Tensor): eval_diff = initial_eval - modified_eval else: if not agg_output_mode: assert ( modified_eval.numel() == current_inputs[0].shape[0] ), """expected output of forward_func to grow with batch_size. If this is not the case for your model please set perturbations_per_eval = 1""" eval_diff = ( initial_eval - modified_eval.reshape((-1, num_outputs)) ).reshape((-1, num_outputs) + (len(inputs[i].shape) - 1) * (1,)) if self.use_weights: weights[i] += current_mask.float().sum(dim=0) total_attrib[i] += (eval_diff * current_mask.to(attrib_type)).sum( dim=0 ) # Divide total attributions by counts and return formatted attributions if self.use_weights: attrib = tuple( single_attrib.float() / weight for single_attrib, weight in zip(total_attrib, weights) ) else: attrib = tuple(total_attrib) _result = _format_output(is_inputs_tuple, attrib) return _result
def attribute( self, inputs: TensorOrTupleOfTensorsGeneric, target: TargetType = None, additional_forward_args: Any = None, interpolate_mode: str = "nearest", attribute_to_layer_input: bool = False, ) -> 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, 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 interpolate_mode (str, optional): Method for interpolation, which must be a valid input interpolation mode for torch.nn.functional. These methods are "nearest", "area", "linear" (3D-only), "bilinear" (4D-only), "bicubic" (4D-only), "trilinear" (5D-only) based on the number of dimensions of the chosen layer output (which must also match the number of dimensions for the input tensor). Note that the original GradCAM paper uses "bilinear" interpolation, but we default to "nearest" for applicability to any of 3D, 4D or 5D tensors. Default: "nearest" attribute_to_layer_input (bool, optional): Indicates whether to compute the attribution with respect to the layer input or output in `LayerGradCam`. If `attribute_to_layer_input` is set to True then the attributions will be computed with respect to layer inputs, otherwise it will be computed with respect to layer outputs. 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 Returns: *tensor* of **attributions**: - **attributions** (*tensor*): Element-wise product of (upsampled) GradCAM and Guided Backprop attributions. 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. Attributions will be the same size as the provided inputs, with each value providing the attribution of the corresponding input index. If the GradCAM attributions cannot be upsampled to the shape of a given input tensor, None is returned in the corresponding index position. Examples:: >>> # ImageClassifier takes a single input tensor of images Nx3x32x32, >>> # and returns an Nx10 tensor of class probabilities. >>> # It contains an attribute conv4, which is an instance of nn.conv2d, >>> # and the output of this layer has dimensions Nx50x8x8. >>> # It is the last convolution layer, which is the recommended >>> # use case for GuidedGradCAM. >>> net = ImageClassifier() >>> guided_gc = GuidedGradCam(net, net.conv4) >>> input = torch.randn(2, 3, 32, 32, requires_grad=True) >>> # Computes guided GradCAM attributions for class 3. >>> # attribution size matches input size, Nx3x32x32 >>> attribution = guided_gc.attribute(input, 3) """ is_inputs_tuple = _is_tuple(inputs) inputs = _format_input(inputs) grad_cam_attr = self.grad_cam.attribute.__wrapped__( self.grad_cam, # self inputs=inputs, target=target, additional_forward_args=additional_forward_args, attribute_to_layer_input=attribute_to_layer_input, relu_attributions=True, ) if isinstance(grad_cam_attr, tuple): assert len(grad_cam_attr) == 1, ( "GuidedGradCAM attributions for layer with multiple inputs / " "outputs is not supported.") grad_cam_attr = grad_cam_attr[0] guided_backprop_attr = self.guided_backprop.attribute.__wrapped__( self.guided_backprop, # self inputs=inputs, target=target, additional_forward_args=additional_forward_args, ) output_attr: List[Tensor] = [] for i in range(len(inputs)): try: output_attr.append(guided_backprop_attr[i] * LayerAttribution.interpolate( grad_cam_attr, inputs[i].shape[2:], interpolate_mode=interpolate_mode, )) except Exception: warnings.warn( "Couldn't appropriately interpolate GradCAM attributions for some " "input tensors, returning empty tensor for corresponding " "attributions.") output_attr.append(torch.empty(0)) return _format_output(is_inputs_tuple, tuple(output_attr))
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 attribute( # type: ignore self, inputs: TensorOrTupleOfTensorsGeneric, baselines: BaselineType = None, target: TargetType = None, additional_forward_args: Any = None, n_steps: int = 50, method: str = "gausslegendre", internal_batch_size: Union[None, int] = None, return_convergence_delta: bool = False, ) -> Union[ TensorOrTupleOfTensorsGeneric, Tuple[TensorOrTupleOfTensorsGeneric, Tensor] ]: r""" This method attributes the output of the model with given target index (in case it is provided, otherwise it assumes that output is a scalar) to the inputs of the model using the approach described above. In addition to that it also returns, if `return_convergence_delta` is set to True, integral approximation delta based on the completeness property of integrated gradients. 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. baselines (scalar, tensor, tuple of scalars or tensors, optional): Baselines define the starting point from which integral is computed and 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. For a tensor, the first dimension of the tensor must correspond to the number of examples. It will be repeated for each of `n_steps` along the integrated path. 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 n_steps (int, optional): The number of steps used by the approximation method. Default: 50. method (string, optional): Method for approximating the integral, one of `riemann_right`, `riemann_left`, `riemann_middle`, `riemann_trapezoid` or `gausslegendre`. Default: `gausslegendre` if no method is provided. internal_batch_size (int, optional): Divides total #steps * #examples data points into chunks of size at most internal_batch_size, which are computed (forward / backward passes) sequentially. internal_batch_size must be at least equal to #examples. For DataParallel models, each batch is split among the available devices, so evaluations on each available device contain internal_batch_size / num_devices examples. If internal_batch_size is None, then all evaluations are processed in one batch. 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 Returns: **attributions** or 2-element tuple of **attributions**, **delta**: - **attributions** (*tensor* or tuple of *tensors*): Integrated gradients 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): The difference between the total approximated and true integrated gradients. This is computed using the property that the total sum of forward_func(inputs) - forward_func(baselines) must equal the total sum of the integrated gradient. Delta is calculated per example, meaning that the number of elements in returned delta tensor is equal to the number of of examples in inputs. 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) >>> # Computes integrated gradients for class 3. >>> attribution = ig.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, baselines = _format_input_baseline(inputs, baselines) _validate_input(inputs, baselines, n_steps, method) if internal_batch_size is not None: num_examples = inputs[0].shape[0] attributions = _batch_attribution( self, num_examples, internal_batch_size, n_steps, inputs=inputs, baselines=baselines, target=target, additional_forward_args=additional_forward_args, method=method, ) else: attributions = self._attribute( inputs=inputs, baselines=baselines, target=target, additional_forward_args=additional_forward_args, n_steps=n_steps, method=method, ) if return_convergence_delta: start_point, end_point = baselines, inputs # computes approximation error based on the completeness axiom delta = self.compute_convergence_delta( attributions, start_point, end_point, additional_forward_args=additional_forward_args, target=target, ) return _format_output(is_inputs_tuple, attributions), delta return _format_output(is_inputs_tuple, attributions)