Exemplo n.º 1
0
 def test_gradient_target_int(self) -> None:
     model = BasicModel2()
     input1 = torch.tensor([[4.0, -1.0]], requires_grad=True)
     input2 = torch.tensor([[2.0, 5.0]], requires_grad=True)
     grads0 = compute_gradients(model, (input1, input2), target_ind=0)
     grads1 = compute_gradients(model, (input1, input2), target_ind=1)
     assertArraysAlmostEqual(grads0[0].squeeze(0).tolist(), [1.0, 0.0],
                             delta=0.01)
     assertArraysAlmostEqual(grads0[1].squeeze(0).tolist(), [-1.0, 0.0],
                             delta=0.01)
     assertArraysAlmostEqual(grads1[0].squeeze(0).tolist(), [0.0, 0.0],
                             delta=0.01)
     assertArraysAlmostEqual(grads1[1].squeeze(0).tolist(), [0.0, 0.0],
                             delta=0.01)
Exemplo n.º 2
0
 def test_gradient_multiinput(self) -> None:
     model = BasicModel6_MultiTensor()
     input1 = torch.tensor([[-3.0, -5.0]], requires_grad=True)
     input2 = torch.tensor([[-5.0, 2.0]], requires_grad=True)
     grads = compute_gradients(model, (input1, input2))
     assertArraysAlmostEqual(grads[0].squeeze(0).tolist(), [0.0, 1.0],
                             delta=0.01)
     assertArraysAlmostEqual(grads[1].squeeze(0).tolist(), [0.0, 1.0],
                             delta=0.01)
Exemplo n.º 3
0
 def test_gradient_basic_2(self) -> None:
     model = BasicModel()
     input = torch.tensor([[-3.0]], requires_grad=True)
     input.grad = torch.tensor([[14.0]])
     grads = compute_gradients(model, input)[0]
     assertArraysAlmostEqual(grads.squeeze(0).tolist(), [1.0], delta=0.01)
     # Verify grad attribute is not altered
     assertArraysAlmostEqual(input.grad.squeeze(0).tolist(), [14.0],
                             delta=0.0)
Exemplo n.º 4
0
 def test_gradient_additional_args_2(self) -> None:
     model = BasicModel5_MultiArgs()
     input1 = torch.tensor([[-10.0]], requires_grad=True)
     input2 = torch.tensor([[6.0]], requires_grad=True)
     grads = compute_gradients(model, (input1, input2),
                               additional_forward_args=([3, -4], ))
     assertArraysAlmostEqual(grads[0].squeeze(0).tolist(), [0.0],
                             delta=0.01)
     assertArraysAlmostEqual(grads[1].squeeze(0).tolist(), [4.0],
                             delta=0.01)
Exemplo n.º 5
0
 def test_gradient_target_tuple(self) -> None:
     model = BasicModel()
     input = torch.tensor(
         [[[4.0, 2.0], [-1.0, -2.0]], [[3.0, -4.0], [10.0, 5.0]]],
         requires_grad=True)
     grads = compute_gradients(model, input, target_ind=(0, 1))[0]
     assertArraysAlmostEqual(
         torch.flatten(grads).tolist(),
         [0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0],
         delta=0.01,
     )
Exemplo n.º 6
0
 def test_gradient_target_list(self) -> None:
     model = BasicModel2()
     input1 = torch.tensor([[4.0, -1.0], [3.0, 10.0]], requires_grad=True)
     input2 = torch.tensor([[2.0, -5.0], [-2.0, 1.0]], requires_grad=True)
     grads = compute_gradients(model, (input1, input2), target_ind=[0, 1])
     assertArraysAlmostEqual(torch.flatten(grads[0]).tolist(),
                             [1.0, 0.0, 0.0, 1.0],
                             delta=0.01)
     assertArraysAlmostEqual(torch.flatten(grads[1]).tolist(),
                             [-1.0, 0.0, 0.0, -1.0],
                             delta=0.01)
Exemplo n.º 7
0
def _get_multiargs_basic_config(
) -> Tuple[Module, Tuple[Tensor, ...], Tuple[Tensor, ...], Any]:
    model = BasicModel5_MultiArgs()
    additional_forward_args = ([2, 3], 1)
    inputs = (
        torch.tensor([[1.5, 2.0, 34.3], [3.4, 1.2, 2.0]], requires_grad=True),
        torch.tensor([[3.0, 3.5, 23.2], [2.3, 1.2, 0.3]], requires_grad=True),
    )
    grads = compute_gradients(model,
                              inputs,
                              additional_forward_args=additional_forward_args)
    return model, inputs, grads, additional_forward_args
Exemplo n.º 8
0
def _get_multiargs_basic_config_large(
) -> Tuple[Module, Tuple[Tensor, ...], Tuple[Tensor, ...], Any]:
    model = BasicModel5_MultiArgs()
    additional_forward_args = ([2, 3], 1)
    inputs = (
        torch.tensor([[10.5, 12.0, 34.3], [43.4, 51.2, 32.0]],
                     requires_grad=True).repeat_interleave(3, dim=0),
        torch.tensor([[1.0, 3.5, 23.2], [2.3, 1.2, 0.3]],
                     requires_grad=True).repeat_interleave(3, dim=0),
    )
    grads = compute_gradients(model,
                              inputs,
                              additional_forward_args=additional_forward_args)
    return model, inputs, grads, additional_forward_args
Exemplo n.º 9
0
 def test_gradient_inplace(self) -> None:
     model = BasicModel_MultiLayer(inplace=True)
     input = torch.tensor([[1.0, 6.0, -3.0]], requires_grad=True)
     grads = compute_gradients(model, input, target_ind=0)[0]
     assertArraysAlmostEqual(grads.squeeze(0).tolist(), [3.0, 3.0, 3.0],
                             delta=0.01)
Exemplo n.º 10
0
 def test_gradient_basic_2(self) -> None:
     model = BasicModel()
     input = torch.tensor([[-3.0]], requires_grad=True)
     grads = compute_gradients(model, input)[0]
     assertArraysAlmostEqual(grads.squeeze(0).tolist(), [1.0], delta=0.01)
Exemplo n.º 11
0
    def attribute(
        self,
        inputs: TensorOrTupleOfTensorsGeneric,
        target: TargetType = None,
        additional_forward_args: Any = None,
        return_convergence_delta: bool = False,
        attribute_to_layer_input: bool = False,
        verbose: bool = False,
    ) -> Union[Tensor, Tuple[Tensor, ...], List[Union[Tensor, Tuple[
            Tensor, ...]]], Tuple[Union[Tensor, Tuple[Tensor, ...], List[Union[
                Tensor, Tuple[Tensor, ...]]]], Union[Tensor,
                                                     List[Tensor]], ], ]:
        r"""

        Args:
            inputs (tensor or tuple of tensors):  Input for which relevance is
                        propagated.
                        If forward_func takes a single
                        tensor as input, a single input tensor should be provided.
                        If forward_func takes multiple tensors as input, a tuple
                        of the input tensors should be provided. It is assumed
                        that for all given input tensors, dimension 0 corresponds
                        to the number of examples, and if multiple input tensors
                        are provided, the examples must be aligned appropriately.
            target (int, tuple, tensor or list, optional):  Output indices for
                        which gradients are computed (for classification cases,
                        this is usually the target class).
                        If the network returns a scalar value per example,
                        no target index is necessary.
                        For general 2D outputs, targets can be either:

                    - a single integer or a tensor containing a single
                        integer, which is applied to all input examples

                    - a list of integers or a 1D tensor, with length matching
                        the number of examples in inputs (dim 0). Each integer
                        is applied as the target for the corresponding example.

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

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

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

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

            return_convergence_delta (bool, optional): Indicates whether to return
                    convergence delta or not. If `return_convergence_delta`
                    is set to True convergence delta will be returned in
                    a tuple following attributions.
                    Default: False

            attribute_to_layer_input (bool, optional): Indicates whether to
                        compute the attribution with respect to the layer input
                        or output. If `attribute_to_layer_input` is set to True
                        then the attributions will be computed with respect to
                        layer input, otherwise it will be computed with respect
                        to layer output.

            verbose (bool, optional): Indicates whether information on application
                    of rules is printed during propagation.
                    Default: False

        Returns:
            *tensor* or tuple of *tensors* of **attributions** or 2-element tuple of
                **attributions**, **delta** or lists of **attributions** and **delta**:
            - **attributions** (*tensor* or tuple of *tensors*):
                        The propagated relevance values with respect to each
                        input feature. Attributions will always
                        be the same size as the provided inputs, with each value
                        providing the attribution of the corresponding input index.
                        If a single tensor is provided as inputs, a single tensor is
                        returned. If a tuple is provided for inputs, a tuple of
                        corresponding sized tensors is returned. The sum of attributions
                        is one and not corresponding to the prediction score as in other
                        implementations. If attributions for all layers are returned
                        (layer=None) a list of tensors or tuples of tensors is returned
                        with entries for each layer.
            - **delta** (*tensor* or list of *tensors*
                         returned if return_convergence_delta=True):
                        Delta is calculated per example, meaning that the number of
                        elements in returned delta tensor is equal to the number of
                        of examples in input.
                        If attributions for all layers are returned (layer=None) a list
                        of tensors is returned with entries for
                        each layer.
        Examples::

                >>> # ImageClassifier takes a single input tensor of images Nx3x32x32,
                >>> # and returns an Nx10 tensor of class probabilities. It has one
                >>> # Conv2D and a ReLU layer.
                >>> net = ImageClassifier()
                >>> lrp = LRP(net, net.conv1)
                >>> input = torch.randn(3, 3, 32, 32)
                >>> # Attribution size matches input size: 3x3x32x32
                >>> attribution = lrp.attribute(input, target=5)

        """
        self.verbose = verbose
        self._original_state_dict = self.model.state_dict()
        self.layers = []
        self._get_layers(self.model)
        self._check_and_attach_rules()
        self.attribute_to_layer_input = attribute_to_layer_input
        self.backward_handles = []
        self.forward_handles = []

        inputs = _format_tensor_into_tuples(inputs)
        gradient_mask = apply_gradient_requirements(inputs)

        try:
            # 1. Forward pass
            output = self._compute_output_and_change_weights(
                inputs, target, additional_forward_args)
            self._register_forward_hooks()
            # 2. Forward pass + backward pass
            _ = compute_gradients(self._forward_fn_wrapper, inputs, target,
                                  additional_forward_args)
            relevances = self._get_output_relevance(output)
        finally:
            self._restore_model()
        undo_gradient_requirements(inputs, gradient_mask)

        if return_convergence_delta:
            delta: Union[Tensor, List[Tensor]]
            if isinstance(self.layer, list):
                delta = []
                for relevance_layer in relevances:
                    delta.append(
                        self.compute_convergence_delta(relevance_layer,
                                                       output))
            else:
                delta = self.compute_convergence_delta(
                    cast(Tuple[Tensor, ...], relevances), output)
            return relevances, delta  # type: ignore
        else:
            return relevances  # type: ignore
Exemplo n.º 12
0
    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)