def test_relu_deepliftshap_baselines_as_function(self): model = ReLULinearDeepLiftModel() x1 = torch.tensor([[-10.0, 1.0, -5.0]]) x2 = torch.tensor([[3.0, 3.0, 1.0]]) def gen_baselines(): b1 = torch.tensor([[0.0, 0.0, 0.0], [1.0, 1.0, 1.0]]) b2 = torch.tensor([[0.0, 0.0, 0.0], [1.0, 1.0, 1.0]]) return (b1, b2) def gen_baselines_with_inputs(inputs): b1 = inputs[0].mean(0, keepdim=True) b2 = inputs[1].mean(0, keepdim=True) return (b1, b2) def gen_baselines_returns_array(): b1 = [[0.0, 0.0, 0.0], [1.0, 1.0, 1.0]] b2 = [[0.0, 0.0, 0.0], [1.0, 1.0, 1.0]] return (b1, b2) inputs = (x1, x2) dl_shap = DeepLiftShap(model) self._deeplift_assert(model, dl_shap, inputs, gen_baselines) self._deeplift_assert(model, dl_shap, inputs, gen_baselines_with_inputs) with self.assertRaises(AssertionError): self._deeplift_assert( model, DeepLiftShap(model), inputs, gen_baselines_returns_array ) baselines = gen_baselines() attributions = dl_shap.attribute(inputs, baselines) attributions_with_func = dl_shap.attribute(inputs, gen_baselines) assertTensorAlmostEqual(self, attributions[0], attributions_with_func[0]) assertTensorAlmostEqual(self, attributions[1], attributions_with_func[1])
def __init__( self, model: Module, layer: Module, multiply_by_inputs: bool = True, ) -> None: r""" Args: model (torch.nn.Module): The reference to PyTorch model instance. layer (torch.nn.Module): Layer for which attributions are computed. The size and dimensionality of the attributions corresponds to the size and dimensionality of the layer's input or output depending on whether we attribute to the inputs or outputs of the layer. multiply_by_inputs (bool, optional): Indicates whether to factor model inputs' multiplier in the final attribution scores. In the literature this is also known as local vs global attribution. If inputs' multiplier isn't factored in then that type of attribution method is also called local attribution. If it is, then that type of attribution method is called global. More detailed can be found here: https://arxiv.org/abs/1711.06104 In case of LayerDeepLiftShap, if `multiply_by_inputs` is set to True, final sensitivity scores are being multiplied by layer activations for inputs - layer activations for baselines This flag applies only if `custom_attribution_func` is set to None. """ LayerDeepLift.__init__(self, model, layer) DeepLiftShap.__init__(self, model, multiply_by_inputs)
def test_relu_deepliftshap_with_hypothetical_contrib_func(self) -> None: model = Conv1dDeepLiftModel() rand_seq_data = torch.abs(torch.randn(2, 4, 1000)) rand_seq_ref = torch.abs(torch.randn(3, 4, 1000)) dls = DeepLiftShap(model) attr = dls.attribute( rand_seq_data, rand_seq_ref, custom_attribution_func=_hypothetical_contrib_func, target=(0, 0), ) self.assertEqual(attr.shape, rand_seq_data.shape)
def test_relu_linear_deepliftshap_compare_inplace(self) -> None: model1 = ReLULinearDeepLiftModel(inplace=True) x1 = torch.tensor([[-10.0, 1.0, -5.0], [2.0, 3.0, 4.0]], requires_grad=True) x2 = torch.tensor([[3.0, 3.0, 1.0], [2.3, 5.0, 4.0]], requires_grad=True) inputs = (x1, x2) b1 = torch.tensor([[0.0, 0.0, 0.0], [1.0, 1.0, 1.0]]) b2 = torch.tensor([[0.0, 0.0, 0.0], [1.0, 1.0, 1.0]]) baselines = (b1, b2) attributions1 = DeepLiftShap(model1).attribute(inputs, baselines) model2 = ReLULinearDeepLiftModel() attributions2 = DeepLiftShap(model2).attribute(inputs, baselines) assertTensorAlmostEqual(self, attributions1[0], attributions2[0]) assertTensorAlmostEqual(self, attributions1[1], attributions2[1])
def test_relu_deepliftshap_with_custom_attr_func(self): def custom_attr_func(multipliers, inputs, baselines): return tuple(multiplier * 0.0 for multiplier in multipliers) model = ReLULinearDeepLiftModel() x1 = torch.tensor([[-10.0, 1.0, -5.0]]) x2 = torch.tensor([[3.0, 3.0, 1.0]]) b1 = torch.tensor([[0.0, 0.0, 0.0], [1.0, 1.0, 1.0]]) b2 = torch.tensor([[0.0, 0.0, 0.0], [1.0, 1.0, 1.0]]) inputs = (x1, x2) baselines = (b1, b2) dls = DeepLiftShap(model) attr_w_func = dls.attribute(inputs, baselines, custom_attribution_func=custom_attr_func) assertTensorAlmostEqual(self, attr_w_func[0], [[0.0, 0.0, 0.0]], 0.0) assertTensorAlmostEqual(self, attr_w_func[1], [[0.0, 0.0, 0.0]], 0.0)
def test_softmax_classification_batch_multi_baseline(self): num_in = 40 input = torch.arange(0.0, num_in * 2.0, requires_grad=True).reshape(2, num_in) baselines = torch.randn(5, 40) model = SoftmaxDeepLiftModel(num_in, 20, 10) dl = DeepLiftShap(model) self.softmax_classification(model, dl, input, baselines, torch.tensor(2))
def test_relu_deepliftshap_baselines_as_func(self) -> None: model = ReLULinearDeepLiftModel(inplace=True) x1 = torch.tensor([[-10.0, 1.0, -5.0]]) x2 = torch.tensor([[3.0, 3.0, 1.0]]) def gen_baselines() -> Tuple[Tensor, ...]: b1 = torch.tensor([[0.0, 0.0, 0.0], [1.0, 1.0, 1.0]]) b2 = torch.tensor([[0.0, 0.0, 0.0], [1.0, 1.0, 1.0]]) return (b1, b2) def gen_baselines_scalar() -> Tuple[float, ...]: return (0.0, 0.0001) def gen_baselines_with_inputs( inputs: Tuple[Tensor, ...]) -> Tuple[Tensor, ...]: b1 = torch.cat([inputs[0], inputs[0] - 10]) b2 = torch.cat([inputs[1], inputs[1] - 10]) return (b1, b2) def gen_baselines_returns_array() -> Tuple[List[List[float]], ...]: b1 = [[0.0, 0.0, 0.0], [1.0, 1.0, 1.0]] b2 = [[0.0, 0.0, 0.0], [1.0, 1.0, 1.0]] return (b1, b2) inputs = (x1, x2) dl_shap = DeepLiftShap(model) self._deeplift_assert(model, dl_shap, inputs, gen_baselines) self._deeplift_assert(model, dl_shap, inputs, gen_baselines_with_inputs) with self.assertRaises(AssertionError): self._deeplift_assert(model, DeepLiftShap(model), inputs, gen_baselines_returns_array) with self.assertRaises(AssertionError): self._deeplift_assert(model, dl_shap, inputs, gen_baselines_scalar) baselines = gen_baselines() attributions = dl_shap.attribute(inputs, baselines) attributions_with_func = dl_shap.attribute(inputs, gen_baselines) assertTensorAlmostEqual(self, attributions[0], attributions_with_func[0]) assertTensorAlmostEqual(self, attributions[1], attributions_with_func[1])
def test_softmax_classification_multi_baseline(self): num_in = 40 input = torch.arange(0.0, num_in * 1.0, requires_grad=True).unsqueeze(0) baselines = torch.randn(5, 40) model = SoftmaxDeepLiftModel(num_in, 20, 10) dl = DeepLiftShap(model) self.softmax_classification(model, dl, input, baselines)
def test_relu_deepliftshap_multi_ref(self) -> None: x1 = torch.tensor([[1.0]], requires_grad=True) x2 = torch.tensor([[2.0]], requires_grad=True) b1 = torch.tensor([[0.0], [0.0], [0.0], [0.0]], requires_grad=True) b2 = torch.tensor([[0.0], [0.0], [0.0], [0.0]], requires_grad=True) inputs = (x1, x2) baselines = (b1, b2) model = ReLUDeepLiftModel() self._deeplift_assert(model, DeepLiftShap(model), inputs, baselines)
def test_relu_deepliftshap_batch_4D_input(self) -> None: x1 = torch.ones(4, 1, 1, 1) x2 = torch.tensor([[[[2.0]]]] * 4) b1 = torch.zeros(4, 1, 1, 1) b2 = torch.zeros(4, 1, 1, 1) inputs = (x1, x2) baselines = (b1, b2) model = ReLUDeepLiftModel() self._deeplift_assert(model, DeepLiftShap(model), inputs, baselines)
def test_relu_deepliftshap_batch_4D_input_wo_mutliplying_by_inputs(self) -> None: x1 = torch.ones(4, 1, 1, 1) x2 = torch.tensor([[[[2.0]]]] * 4) b1 = torch.zeros(4, 1, 1, 1) b2 = torch.zeros(4, 1, 1, 1) inputs = (x1, x2) baselines = (b1, b2) model = ReLUDeepLiftModel() attr = DeepLiftShap(model, multiply_by_inputs=False).attribute( inputs, baselines ) assertTensorAlmostEqual(self, attr[0], 2 * torch.ones(4, 1)) assertTensorAlmostEqual(self, attr[1], 0.5 * torch.ones(4, 1))
def attribute( self, inputs: TensorOrTupleOfTensorsGeneric, neuron_selector: Union[int, Tuple[Union[int, slice], ...], Callable], baselines: Union[ TensorOrTupleOfTensorsGeneric, Callable[..., TensorOrTupleOfTensorsGeneric] ], additional_forward_args: Any = None, attribute_to_neuron_input: bool = False, custom_attribution_func: Union[None, Callable[..., Tuple[Tensor, ...]]] = None, ) -> TensorOrTupleOfTensorsGeneric: 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. 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) 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. 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 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 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*): Computes attributions using Deeplift's rescale rule 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. >>> net = ImageClassifier() >>> # creates an instance of LayerDeepLift to interpret target >>> # class 1 with respect to conv4 layer. >>> dl = NeuronDeepLiftShap(net, net.conv4) >>> input = torch.randn(1, 3, 32, 32, requires_grad=True) >>> # Computes deeplift attribution scores for conv4 layer and neuron >>> # index (4,1,2). >>> attribution = dl.attribute(input, (4,1,2)) """ dl = DeepLiftShap(cast(Module, self.forward_func), self.multiplies_by_inputs) dl.gradient_func = construct_neuron_grad_fn( self.layer, neuron_selector, attribute_to_neuron_input=attribute_to_neuron_input, ) # NOTE: using __wrapped__ to not log return dl.attribute.__wrapped__( # type: ignore dl, # self inputs, baselines, additional_forward_args=additional_forward_args, custom_attribution_func=custom_attribution_func, )
def attribute( self, inputs: Union[Tensor, Tuple[Tensor, ...]], baselines: Union[Tensor, Tuple[Tensor, ...], Callable[..., Union[Tensor, Tuple[Tensor, ...]]]], 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 (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 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 inputs, otherwise it will be computed with respect to layer outputs. Note that currently it assumes that both the inputs and outputs of internal layers are single tensors. 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. Attributions are returned in a tuple based on whether the layer inputs / outputs are contained in a tuple from a forward hook. For standard modules, inputs of a single tensor are usually wrapped in a tuple, while outputs of a single tensor are not. - **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() >>> # creates an instance of LayerDeepLift to interpret target >>> # class 1 with respect to conv4 layer. >>> dl = LayerDeepLiftShap(net, net.conv4) >>> input = torch.randn(2, 3, 32, 32, requires_grad=True) >>> # Computes shap values using deeplift for class 3. >>> attribution = dl.attribute(input, target=3) """ inputs = _format_input(inputs) 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, `LayerDeepLift`" " approach can be used instead.".format(baselines[0])) # batch sizes inp_bsz = inputs[0].shape[0] base_bsz = baselines[0].shape[0] ( exp_inp, exp_base, exp_target, exp_addit_args, ) = DeepLiftShap._expand_inputs_baselines_targets( self, baselines, inputs, target, additional_forward_args) attributions = LayerDeepLift.attribute.__wrapped__( # type: ignore self, exp_inp, exp_base, target=exp_target, additional_forward_args=exp_addit_args, return_convergence_delta=cast(Literal[True, False], return_convergence_delta), attribute_to_layer_input=attribute_to_layer_input, custom_attribution_func=custom_attribution_func, ) if return_convergence_delta: attributions, delta = attributions if isinstance(attributions, tuple): attributions = tuple( DeepLiftShap._compute_mean_across_baselines( self, inp_bsz, base_bsz, cast(Tensor, attrib)) for attrib in attributions) else: attributions = DeepLiftShap._compute_mean_across_baselines( self, inp_bsz, base_bsz, attributions) if return_convergence_delta: return attributions, delta else: return attributions