Exemplo n.º 1
0
 def test_multi_target_error(self) -> None:
     net = BasicModel_MultiLayer()
     inp = torch.zeros((1, 3))
     with self.assertRaises(AssertionError):
         attr = IntegratedGradients(net)
         attr.attribute(inp,
                        additional_forward_args=(None, True),
                        target=(1, 0))
    def _compute_attribution_batch_helper_evaluate(
        self,
        model: Module,
        inputs: TensorOrTupleOfTensorsGeneric,
        baselines: Union[None, Tensor, Tuple[Tensor, ...]] = None,
        target: Union[None, int] = None,
        additional_forward_args: Any = None,
        approximation_method: str = "gausslegendre",
    ) -> None:
        ig = IntegratedGradients(model)
        if not isinstance(inputs, tuple):
            inputs = (inputs, )  # type: ignore
        inputs: Tuple[Tensor, ...]

        if baselines is not None and not isinstance(baselines, tuple):
            baselines = (baselines, )

        if baselines is None:
            baselines = _tensorize_baseline(inputs, _zeros(inputs))

        for internal_batch_size in [None, 10, 20]:
            attributions, delta = ig.attribute(
                inputs,
                baselines,
                additional_forward_args=additional_forward_args,
                method=approximation_method,
                n_steps=100,
                target=target,
                internal_batch_size=internal_batch_size,
                return_convergence_delta=True,
            )
            total_delta = 0.0
            for i in range(inputs[0].shape[0]):
                attributions_indiv, delta_indiv = ig.attribute(
                    tuple(input[i:i + 1] for input in inputs),
                    tuple(baseline[i:i + 1] for baseline in baselines),
                    additional_forward_args=additional_forward_args,
                    method=approximation_method,
                    n_steps=100,
                    target=target,
                    internal_batch_size=internal_batch_size,
                    return_convergence_delta=True,
                )
                total_delta += abs(delta_indiv).sum().item()
                for j in range(len(attributions)):
                    assertTensorAlmostEqual(
                        self,
                        attributions[j][i:i + 1].squeeze(0),
                        attributions_indiv[j].squeeze(0),
                        delta=0.05,
                        mode="max",
                    )
            self.assertAlmostEqual(abs(delta).sum().item(),
                                   total_delta,
                                   delta=0.005)
Exemplo n.º 3
0
    def _compute_attribution_batch_helper_evaluate(
            self,
            model,
            inputs,
            baselines=None,
            target=None,
            additional_forward_args=None):
        ig = IntegratedGradients(model)
        if not isinstance(inputs, tuple):
            inputs = (inputs, )

        if baselines is not None and not isinstance(baselines, tuple):
            baselines = (baselines, )

        if baselines is None:
            baselines = _zeros(inputs)

        for method in [
                "riemann_right",
                "riemann_left",
                "riemann_middle",
                "riemann_trapezoid",
                "gausslegendre",
        ]:
            for internal_batch_size in [None, 1, 20]:
                attributions, delta = ig.attribute(
                    inputs,
                    baselines,
                    additional_forward_args=additional_forward_args,
                    method=method,
                    n_steps=200,
                    target=target,
                    internal_batch_size=internal_batch_size,
                    return_convergence_delta=True,
                )
                total_delta = 0
                for i in range(inputs[0].shape[0]):
                    attributions_indiv, delta_indiv = ig.attribute(
                        tuple(input[i:i + 1] for input in inputs),
                        tuple(baseline[i:i + 1] for baseline in baselines),
                        additional_forward_args=additional_forward_args,
                        method=method,
                        n_steps=200,
                        target=target,
                        return_convergence_delta=True,
                    )
                    total_delta += abs(delta_indiv).sum().item()
                    for j in range(len(attributions)):
                        assertArraysAlmostEqual(
                            attributions[j][i:i + 1].squeeze(0).tolist(),
                            attributions_indiv[j].squeeze(0).tolist(),
                        )
                self.assertAlmostEqual(abs(delta).sum().item(),
                                       total_delta,
                                       delta=0.005)
    def _assert_compare_with_emb_patching(self, input, baseline, additional_args):
        model = BasicEmbeddingModel(nested_second_embedding=True)
        lig = LayerIntegratedGradients(model, model.embedding1)

        attributions, delta = lig.attribute(
            input,
            baselines=baseline,
            additional_forward_args=additional_args,
            return_convergence_delta=True,
        )

        # now let's interpret with standard integrated gradients and
        # the embeddings for monkey patching
        interpretable_embedding = configure_interpretable_embedding_layer(
            model, "embedding1"
        )
        input_emb = interpretable_embedding.indices_to_embeddings(input)
        baseline_emb = interpretable_embedding.indices_to_embeddings(baseline)
        ig = IntegratedGradients(model)
        attributions_with_ig, delta_with_ig = ig.attribute(
            input_emb,
            baselines=baseline_emb,
            additional_forward_args=additional_args,
            target=0,
            return_convergence_delta=True,
        )
        remove_interpretable_embedding_layer(model, interpretable_embedding)

        assertArraysAlmostEqual(attributions, attributions_with_ig)
        assertArraysAlmostEqual(delta, delta_with_ig)
    def _assert_attributions(
        self,
        model: Module,
        attributions: Tensor,
        inputs: Tensor,
        baselines: Union[Tensor, int, float],
        delta: Tensor,
        target: TargetType = None,
    ) -> None:
        self.assertEqual(inputs.shape, attributions.shape)

        delta_condition = all(abs(delta.numpy().flatten()) < 0.003)
        self.assertTrue(
            delta_condition,
            "The sum of attribution values {} is not "
            "nearly equal to the difference between the endpoint for "
            "some samples".format(delta),
        )
        # compare with integrated gradients
        if isinstance(baselines,
                      (int, float)) or inputs.shape == baselines.shape:
            ig = IntegratedGradients(model)
            attributions_ig = ig.attribute(inputs,
                                           baselines=baselines,
                                           target=target)
            assertAttributionComparision(self, attributions, attributions_ig)
Exemplo n.º 6
0
    def test_basic_relu_multi_input(self) -> None:
        model = BasicModel2()

        input1 = torch.tensor([[3.0]])
        input2 = torch.tensor([[1.0]], requires_grad=True)

        baseline1 = torch.tensor([[0.0]])
        baseline2 = torch.tensor([[0.0]])
        inputs = (input1, input2)
        baselines = (baseline1, baseline2)

        gs = GradientShap(model)
        n_samples = 30000
        attributions, delta = cast(
            Tuple[Tuple[Tensor, ...], Tensor],
            gs.attribute(
                inputs,
                baselines=baselines,
                n_samples=n_samples,
                return_convergence_delta=True,
            ),
        )
        _assert_attribution_delta(self, inputs, attributions, n_samples, delta)

        ig = IntegratedGradients(model)
        attributions_ig = ig.attribute(inputs, baselines=baselines)
        self._assert_shap_ig_comparision(attributions, attributions_ig)
Exemplo n.º 7
0
    def test_multiple_layers_multiple_inputs_shared_input(self) -> None:
        input1 = torch.randn(5, 3)
        input2 = torch.randn(5, 3)
        input3 = torch.randn(5, 3)
        inputs = (input1, input2, input3)
        baseline = tuple(torch.zeros_like(inp) for inp in inputs)

        net = BasicModel_MultiLayer_TrueMultiInput()

        lig = LayerIntegratedGradients(net, layer=[net.m1, net.m234])
        ig = IntegratedGradients(net)

        # test layer inputs
        attribs_inputs = lig.attribute(inputs,
                                       baseline,
                                       target=0,
                                       attribute_to_layer_input=True)
        attribs_inputs_regular_ig = ig.attribute(inputs, baseline, target=0)

        self.assertIsInstance(attribs_inputs, list)
        self.assertEqual(len(attribs_inputs), 2)
        self.assertIsInstance(attribs_inputs[0], Tensor)
        self.assertIsInstance(attribs_inputs[1], tuple)
        self.assertEqual(len(attribs_inputs[1]), 3)

        assertTensorTuplesAlmostEqual(
            self,
            # last input for second layer is first input =>
            # add the attributions
            (
                attribs_inputs[0] + attribs_inputs[1][-1], ) +
            attribs_inputs[1][0:-1],
            attribs_inputs_regular_ig,
            delta=1e-5,
        )

        # test layer outputs
        attribs = lig.attribute(inputs, baseline, target=0)
        ig = IntegratedGradients(lambda x, y: x + y)
        attribs_ig = ig.attribute(
            (net.m1(input1), net.m234(input2, input3, input1, 1)),
            (net.m1(baseline[0]),
             net.m234(baseline[1], baseline[2], baseline[1], 1)),
            target=0,
        )

        assertTensorTuplesAlmostEqual(self, attribs, attribs_ig, delta=1e-5)
Exemplo n.º 8
0
    def _deeplift_assert(self,
                         model,
                         attr_method,
                         inputs,
                         baselines,
                         custom_attr_func=None):
        input_bsz = len(inputs[0])
        if callable(baselines):
            baseline_parameters = signature(baselines).parameters
            if len(baseline_parameters) > 0:
                baselines = baselines(inputs)
            else:
                baselines = baselines()

        baseline_bsz = (len(baselines[0]) if isinstance(
            baselines[0], torch.Tensor) else 1)
        # Run attribution multiple times to make sure that it is
        # working as expected
        for _ in range(5):
            model.zero_grad()
            attributions, delta = attr_method.attribute(
                inputs,
                baselines,
                return_convergence_delta=True,
                custom_attribution_func=custom_attr_func,
            )
            attributions_without_delta = attr_method.attribute(
                inputs, baselines, custom_attribution_func=custom_attr_func)

            for attribution, attribution_without_delta in zip(
                    attributions, attributions_without_delta):
                self.assertTrue(
                    torch.all(torch.eq(attribution,
                                       attribution_without_delta)))

            if isinstance(attr_method, DeepLiftShap):
                self.assertEqual([input_bsz * baseline_bsz], list(delta.shape))
            else:
                self.assertEqual([input_bsz], list(delta.shape))
                delta_external = attr_method.compute_convergence_delta(
                    attributions, baselines, inputs)
                assertArraysAlmostEqual(delta, delta_external, 0.0)

            delta_condition = all(abs(delta.numpy().flatten()) < 0.00001)
            self.assertTrue(
                delta_condition,
                "The sum of attribution values {} is not "
                "nearly equal to the difference between the endpoint for "
                "some samples".format(delta),
            )
            for input, attribution in zip(inputs, attributions):
                self.assertEqual(input.shape, attribution.shape)
            if (isinstance(baselines[0], (int, float))
                    or inputs[0].shape == baselines[0].shape):
                # Compare with Integrated Gradients
                ig = IntegratedGradients(model)
                attributions_ig = ig.attribute(inputs, baselines)
                assertAttributionComparision(self, attributions,
                                             attributions_ig)
Exemplo n.º 9
0
    def test_multiple_layers_multiple_input_outputs(self) -> None:
        # test with multiple layers, where one layer accepts multiple inputs
        input1 = torch.randn(5, 3)
        input2 = torch.randn(5, 3)
        input3 = torch.randn(5, 3)
        input4 = torch.randn(5, 3)
        inputs = (input1, input2, input3, input4)
        baseline = tuple(torch.zeros_like(inp) for inp in inputs)

        net = BasicModel_MultiLayer_TrueMultiInput()

        lig = LayerIntegratedGradients(net, layer=[net.m1, net.m234])
        ig = IntegratedGradients(net)

        # test layer inputs
        attribs_inputs = lig.attribute(inputs,
                                       baseline,
                                       target=0,
                                       attribute_to_layer_input=True)
        attribs_inputs_regular_ig = ig.attribute(inputs, baseline, target=0)

        self.assertIsInstance(attribs_inputs, list)
        self.assertEqual(len(attribs_inputs), 2)
        self.assertIsInstance(attribs_inputs[0], Tensor)
        self.assertIsInstance(attribs_inputs[1], tuple)
        self.assertEqual(len(attribs_inputs[1]), 3)

        assertTensorTuplesAlmostEqual(
            self,
            (attribs_inputs[0], ) + attribs_inputs[1],
            attribs_inputs_regular_ig,
            delta=1e-7,
        )

        # test layer outputs
        attribs = lig.attribute(inputs, baseline, target=0)
        ig = IntegratedGradients(lambda x, y: x + y)
        attribs_ig = ig.attribute(
            (net.m1(input1), net.m234(input2, input3, input4, 1)),
            (net.m1(baseline[0]),
             net.m234(baseline[1], baseline[2], baseline[3], 1)),
            target=0,
        )

        assertTensorTuplesAlmostEqual(self, attribs, attribs_ig, delta=1e-7)
    def _validate_completness(self,
                              model,
                              inputs,
                              target,
                              type="vanilla",
                              baseline=None):
        ig = IntegratedGradients(model.forward)
        for method in [
                "riemann_right",
                "riemann_left",
                "riemann_middle",
                "riemann_trapezoid",
                "gausslegendre",
        ]:
            model.zero_grad()
            if type == "vanilla":
                attributions, delta = ig.attribute(
                    inputs,
                    baselines=baseline,
                    target=target,
                    method=method,
                    n_steps=1000,
                    return_convergence_delta=True,
                )
                delta_expected = ig.compute_convergence_delta(
                    attributions, baseline, inputs, target)
                assertTensorAlmostEqual(self, delta_expected, delta)

                delta_condition = all(abs(delta.numpy().flatten()) < 0.003)
                self.assertTrue(
                    delta_condition,
                    "The sum of attribution values {} is not "
                    "nearly equal to the difference between the endpoint for "
                    "some samples".format(delta),
                )
                self.assertEqual([inputs.shape[0]], list(delta.shape))
            else:
                nt = NoiseTunnel(ig)
                n_samples = 10
                attributions, delta = nt.attribute(
                    inputs,
                    baselines=baseline,
                    nt_type=type,
                    n_samples=n_samples,
                    stdevs=0.0002,
                    n_steps=1000,
                    target=target,
                    method=method,
                    return_convergence_delta=True,
                )
                self.assertEqual([inputs.shape[0] * n_samples],
                                 list(delta.shape))

            self.assertTrue(all(abs(delta.numpy().flatten()) < 0.05))
            self.assertEqual(attributions.shape, inputs.shape)
    def _validate_completness(
        self,
        model: Module,
        input: Tensor,
        target: Tensor,
        type: str = "vanilla",
        approximation_method: str = "gausslegendre",
        baseline: Optional[Union[Tensor, int, float, Tuple[Union[Tensor, int,
                                                                 float],
                                                           ...]]] = None,
    ) -> None:
        ig = IntegratedGradients(model.forward)
        model.zero_grad()
        if type == "vanilla":
            attributions, delta = ig.attribute(
                input,
                baselines=baseline,
                target=target,
                method=approximation_method,
                n_steps=200,
                return_convergence_delta=True,
            )
            delta_expected = ig.compute_convergence_delta(
                attributions, baseline, input, target)
            assertTensorAlmostEqual(self, delta_expected, delta)

            delta_condition = all(abs(delta.numpy().flatten()) < 0.005)
            self.assertTrue(
                delta_condition,
                "The sum of attribution values {} is not "
                "nearly equal to the difference between the endpoint for "
                "some samples".format(delta),
            )
            self.assertEqual([input.shape[0]], list(delta.shape))
        else:
            nt = NoiseTunnel(ig)
            n_samples = 10
            attributions, delta = nt.attribute(
                input,
                baselines=baseline,
                nt_type=type,
                n_samples=n_samples,
                stdevs=0.0002,
                n_steps=100,
                target=target,
                method=approximation_method,
                return_convergence_delta=True,
            )
            self.assertEqual([input.shape[0] * n_samples], list(delta.shape))

        self.assertTrue(all(abs(delta.numpy().flatten()) < 0.05))
        self.assertEqual(attributions.shape, input.shape)
    def _validate_completness(self, model, inputs, target, type="vanilla"):
        ig = IntegratedGradients(model.forward)
        for method in [
                "riemann_right",
                "riemann_left",
                "riemann_middle",
                "riemann_trapezoid",
                "gausslegendre",
        ]:
            model.zero_grad()
            if type == "vanilla":
                attributions, delta = ig.attribute(
                    inputs,
                    target=target,
                    method=method,
                    n_steps=1000,
                    return_convergence_delta=True,
                )
                # attributions are returned as tuples for the integrated_gradients
                self.assertAlmostEqual(
                    attributions.sum(),
                    model.forward(inputs)[:, target] -
                    model.forward(0 * inputs)[:, target],
                    delta=0.005,
                )
                delta_expected = abs(attributions.sum().item() - (
                    model.forward(inputs)[:, target].item() -
                    model.forward(0 * inputs)[:, target].item()))
                self.assertAlmostEqual(abs(delta).sum().item(),
                                       delta_expected,
                                       delta=0.005)
                self.assertEqual([inputs.shape[0]], list(delta.shape))
            else:
                nt = NoiseTunnel(ig)
                n_samples = 10
                attributions, delta = nt.attribute(
                    inputs,
                    nt_type=type,
                    n_samples=n_samples,
                    stdevs=0.0002,
                    n_steps=1000,
                    target=target,
                    method=method,
                    return_convergence_delta=True,
                )
                self.assertEqual([inputs.shape[0] * n_samples],
                                 list(delta.shape))

            self.assertTrue(all(abs(delta.numpy().flatten()) < 0.05))
            self.assertEqual(attributions.shape, inputs.shape)
Exemplo n.º 13
0
    def test_basic_multi_input(self):
        batch_size = 10

        x1 = torch.ones(batch_size, 3)
        x2 = torch.ones(batch_size, 4)
        inputs = (x1, x2)

        batch_size_baselines = 20
        baselines = (
            torch.zeros(batch_size_baselines, 3),
            torch.zeros(batch_size_baselines, 4),
        )

        class Net(nn.Module):
            def __init__(self):
                super().__init__()
                self.linear = nn.Linear(7, 1)

            def forward(self, x1, x2):
                return self.linear(torch.cat((x1, x2), dim=-1))

        model = Net()
        model.eval()
        model.zero_grad()

        np.random.seed(0)
        torch.manual_seed(0)
        gradient_shap = GradientShap(model)
        n_samples = 50
        attributions, delta = gradient_shap.attribute(
            (x1, x2),
            baselines,
            n_samples=n_samples,
            return_convergence_delta=True)
        attributions_without_delta = gradient_shap.attribute((x1, x2),
                                                             baselines)

        self._assert_attribution_delta(inputs, attributions, n_samples, delta)
        # Compare with integrated gradients
        ig = IntegratedGradients(model)
        baselines = (torch.zeros(batch_size, 3), torch.zeros(batch_size, 4))
        attributions_ig = ig.attribute(inputs, baselines=baselines)
        self._assert_shap_ig_comparision(attributions, attributions_ig)

        # compare attributions retrieved with and without
        # `return_convergence_delta` flag
        for attribution, attribution_without_delta in zip(
                attributions, attributions_without_delta):
            assertTensorAlmostEqual(self, attribution,
                                    attribution_without_delta)
Exemplo n.º 14
0
    def test_classification(self):
        num_in = 40
        inputs = torch.arange(0.0, num_in * 2.0).reshape(2, num_in)
        baselines = torch.arange(0.0, num_in * 4.0).reshape(4, num_in)
        target = torch.tensor(1)
        # 10-class classification model
        model = SoftmaxModel(num_in, 20, 10)
        model.eval()
        model.zero_grad()

        gradient_shap = GradientShap(model)
        n_samples = 10
        attributions, delta = gradient_shap.attribute(
            inputs,
            baselines=baselines,
            target=target,
            n_samples=n_samples,
            stdevs=0.009,
            return_convergence_delta=True,
        )
        _assert_attribution_delta(self, (inputs, ), (attributions, ),
                                  n_samples, delta)

        # try to call `compute_convergence_delta` externally
        with self.assertRaises(AssertionError):
            gradient_shap.compute_convergence_delta(attributions,
                                                    inputs,
                                                    baselines,
                                                    target=target)
        # now, let's expand target and choose random baselines from `baselines` tensor
        rand_indices = np.random.choice(baselines.shape[0],
                                        inputs.shape[0]).tolist()
        chosen_baselines = baselines[rand_indices]

        target_extendes = torch.tensor([1, 1])
        external_delta = gradient_shap.compute_convergence_delta(
            attributions, chosen_baselines, inputs, target=target_extendes)
        _assert_delta(self, external_delta)

        # Compare with integrated gradients
        ig = IntegratedGradients(model)
        baselines = torch.arange(0.0, num_in * 2.0).reshape(2, num_in)
        attributions_ig = ig.attribute(inputs,
                                       baselines=baselines,
                                       target=target)
        self._assert_shap_ig_comparision((attributions, ), (attributions_ig, ))
Exemplo n.º 15
0
    def _assert_attributions(
        self, model, attributions, inputs, baselines, delta, target=None
    ):
        self.assertEqual(inputs.shape, attributions.shape)

        delta_condition = all(abs(delta.numpy().flatten()) < 0.003)
        self.assertTrue(
            delta_condition,
            "The sum of attribution values {} is not "
            "nearly equal to the difference between the endpoint for "
            "some samples".format(delta),
        )
        # compare with integrated gradients
        if inputs.shape == baselines.shape:
            ig = IntegratedGradients(model)
            attributions_ig = ig.attribute(inputs, baselines=baselines, target=target)
            assertAttributionComparision(self, attributions, attributions_ig)
Exemplo n.º 16
0
    def test_sigmoid_classification(self):
        num_in = 20
        input = torch.arange(0.0, num_in * 1.0, requires_grad=True).unsqueeze(0)
        baseline = 0 * input
        target = torch.tensor(0)
        # TODO add test cases for multiple different layers
        model = SigmoidDeepLiftModel(num_in, 5, 1)
        dl = DeepLift(model)
        model.zero_grad()
        attributions, delta = dl.attribute(
            input, baseline, target=target, return_convergence_delta=True
        )
        self._assert_attributions(model, attributions, input, baseline, delta, target)

        # compare with integrated gradients
        ig = IntegratedGradients(model)
        attributions_ig = ig.attribute(input, baseline, target=target)
        assertAttributionComparision(self, (attributions,), (attributions_ig,))
Exemplo n.º 17
0
    def test_basic_multi_input(self) -> None:
        batch_size = 10

        x1 = torch.ones(batch_size, 3)
        x2 = torch.ones(batch_size, 4)
        inputs = (x1, x2)

        batch_size_baselines = 20
        baselines = (
            torch.zeros(batch_size_baselines, 3),
            torch.zeros(batch_size_baselines, 4),
        )

        model = BasicLinearModel()
        model.eval()
        model.zero_grad()

        np.random.seed(0)
        torch.manual_seed(0)
        gradient_shap = GradientShap(model)
        n_samples = 50
        attributions, delta = cast(
            Tuple[Tuple[Tensor, ...], Tensor],
            gradient_shap.attribute(inputs,
                                    baselines,
                                    n_samples=n_samples,
                                    return_convergence_delta=True),
        )
        attributions_without_delta = gradient_shap.attribute((x1, x2),
                                                             baselines)

        _assert_attribution_delta(self, inputs, attributions, n_samples, delta)
        # Compare with integrated gradients
        ig = IntegratedGradients(model)
        baselines = (torch.zeros(batch_size, 3), torch.zeros(batch_size, 4))
        attributions_ig = ig.attribute(inputs, baselines=baselines)
        self._assert_shap_ig_comparision(attributions, attributions_ig)

        # compare attributions retrieved with and without
        # `return_convergence_delta` flag
        for attribution, attribution_without_delta in zip(
                attributions, attributions_without_delta):
            assertTensorAlmostEqual(self, attribution,
                                    attribution_without_delta)
 def _ig_matching_test_assert(
     self,
     model: Module,
     output_layer: Module,
     test_input: Tensor,
     baseline: Union[None, Tensor] = None,
 ) -> None:
     out = model(test_input)
     input_attrib = IntegratedGradients(model)
     ig_attrib = NeuronIntegratedGradients(model, output_layer)
     for i in range(out.shape[1]):
         ig_vals = input_attrib.attribute(test_input, target=i, baselines=baseline)
         neuron_ig_vals = ig_attrib.attribute(test_input, (i,), baselines=baseline)
         assertArraysAlmostEqual(
             ig_vals.reshape(-1).tolist(),
             neuron_ig_vals.reshape(-1).tolist(),
             delta=0.001,
         )
         self.assertEqual(neuron_ig_vals.shape, test_input.shape)
Exemplo n.º 19
0
    def _deeplift_helper(self, model, attr_method, inputs, baselines):
        input_bsz = inputs[0].shape[0]
        baseline_bsz = baselines[0].shape[0]
        # Run attribution multiple times to make sure that it is working as
        # expected
        for _ in range(5):
            model.zero_grad()
            attributions, delta = attr_method.attribute(
                inputs, baselines, return_convergence_delta=True)
            attributions_without_delta = attr_method.attribute(
                inputs, baselines)

            for attribution, attribution_without_delta in zip(
                    attributions, attributions_without_delta):
                self.assertTrue(
                    torch.all(torch.eq(attribution,
                                       attribution_without_delta)))

            if isinstance(attr_method, DeepLiftShap):
                self.assertEqual([input_bsz * baseline_bsz], list(delta.shape))
            else:
                self.assertEqual([input_bsz], list(delta.shape))
                delta_external = attr_method.compute_convergence_delta(
                    attributions, baselines, inputs)
                assertArraysAlmostEqual(delta, delta_external, 0.0)

            delta_condition = all(abs(delta.numpy().flatten()) < 0.00001)
            self.assertTrue(
                delta_condition,
                "The sum of attribution values {} is not "
                "nearly equal to the difference between the endpoint for "
                "some samples".format(delta),
            )
            for input, attribution in zip(inputs, attributions):
                self.assertEqual(input.shape, attribution.shape)
            if inputs[0].shape == baselines[0].shape:
                # Compare with Integrated Gradients
                ig = IntegratedGradients(model)
                attributions_ig = ig.attribute(inputs, baselines)
                assertAttributionComparision(self, attributions,
                                             attributions_ig)
Exemplo n.º 20
0
    def _compute_attribution_and_evaluate(
        self,
        model,
        inputs,
        baselines=None,
        target=None,
        additional_forward_args=None,
        type="vanilla",
    ):
        r"""
            attrib_type: 'vanilla', 'smoothgrad', 'smoothgrad_sq', 'vargrad'
        """
        ig = IntegratedGradients(model)
        if not isinstance(inputs, tuple):
            inputs = (inputs,)

        if baselines is not None and not isinstance(baselines, tuple):
            baselines = (baselines,)

        if baselines is None:
            baselines = _zeros(inputs)

        for method in [
            "riemann_right",
            "riemann_left",
            "riemann_middle",
            "riemann_trapezoid",
            "gausslegendre",
        ]:
            if type == "vanilla":
                attributions, delta = ig.attribute(
                    inputs,
                    baselines,
                    additional_forward_args=additional_forward_args,
                    method=method,
                    n_steps=2000,
                    target=target,
                    return_convergence_delta=True,
                )
                model.zero_grad()
                attributions_without_delta, delta = ig.attribute(
                    inputs,
                    baselines,
                    additional_forward_args=additional_forward_args,
                    method=method,
                    n_steps=2000,
                    target=target,
                    return_convergence_delta=True,
                )
                model.zero_grad()
                self.assertEqual([inputs[0].shape[0]], list(delta.shape))
                delta_external = ig.compute_convergence_delta(
                    attributions,
                    baselines,
                    inputs,
                    target=target,
                    additional_forward_args=additional_forward_args,
                )
                assertArraysAlmostEqual(delta, delta_external, 0.0)
            else:
                nt = NoiseTunnel(ig)
                n_samples = 5
                attributions, delta = nt.attribute(
                    inputs,
                    nt_type=type,
                    n_samples=n_samples,
                    stdevs=0.00000002,
                    baselines=baselines,
                    target=target,
                    additional_forward_args=additional_forward_args,
                    method=method,
                    n_steps=2000,
                    return_convergence_delta=True,
                )
                attributions_without_delta = nt.attribute(
                    inputs,
                    nt_type=type,
                    n_samples=n_samples,
                    stdevs=0.00000002,
                    baselines=baselines,
                    target=target,
                    additional_forward_args=additional_forward_args,
                    method=method,
                    n_steps=2000,
                )
                self.assertEqual([inputs[0].shape[0] * n_samples], list(delta.shape))

            for input, attribution in zip(inputs, attributions):
                self.assertEqual(attribution.shape, input.shape)
            self.assertTrue(all(abs(delta.numpy().flatten()) < 0.05))

            # compare attributions retrieved with and without
            # `return_convergence_delta` flag
            for attribution, attribution_without_delta in zip(
                attributions, attributions_without_delta
            ):
                assertTensorAlmostEqual(
                    self, attribution, attribution_without_delta, delta=0.05
                )

        return attributions
Exemplo n.º 21
0
class LayerIntegratedGradients(LayerAttribution, GradientAttribution):
    r"""
    Layer Integrated Gradients is a variant of Integrated Gradients that assigns
    an importance score to layer inputs or outputs, depending on whether we
    attribute to the former or to the latter one.

    Integrated Gradients is an axiomatic model interpretability algorithm that
    attributes / assigns an importance score to each input feature by approximating
    the integral of gradients of the model's output with respect to the inputs
    along the path (straight line) from given baselines / references to inputs.

    Baselines can be provided as input arguments to attribute method.
    To approximate the integral we can choose to use either a variant of
    Riemann sum or Gauss-Legendre quadrature rule.

    More details regarding the integrated gradients method can be found in the
    original paper:
    https://arxiv.org/abs/1703.01365

    """

    def __init__(
        self,
        forward_func: Callable,
        layer: Module,
        device_ids: Optional[List[int]] = None,
    ) -> None:
        r"""
        Args:
            forward_func (callable):  The forward function of the model or any
                          modification of it
            layer (torch.nn.Module): Layer for which attributions are computed.
                          Output size of attribute matches this layer's input or
                          output dimensions, depending on whether we attribute to
                          the inputs or outputs of the layer, corresponding to
                          the attribution of each neuron in the input or output
                          of this layer.
            device_ids (list(int)): Device ID list, necessary only if forward_func
                          applies a DataParallel model. This allows reconstruction of
                          intermediate outputs from batched results across devices.
                          If forward_func is given as the DataParallel model itself,
                          then it is not necessary to provide this argument.

        """
        LayerAttribution.__init__(self, forward_func, layer, device_ids=device_ids)
        GradientAttribution.__init__(self, forward_func)
        self.ig = IntegratedGradients(forward_func)

    def attribute(
        self,
        inputs: Union[Tensor, Tuple[Tensor, ...]],
        baselines: Optional[
            Union[Tensor, int, float, Tuple[Union[Tensor, int, float], ...]]
        ] = None,
        target: Optional[
            Union[int, Tuple[int, ...], Tensor, List[Tuple[int, ...]]]
        ] = None,
        additional_forward_args: Any = None,
        n_steps: int = 50,
        method: str = "gausslegendre",
        internal_batch_size: Optional[int] = None,
        return_convergence_delta: bool = False,
        attribute_to_layer_input: bool = False,
    ) -> Union[
        Tensor, Tuple[Tensor, ...], Tuple[Union[Tensor, Tuple[Tensor, ...]], 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 layer inputs or outputs of the model, depending on whether
        `attribute_to_layer_input` is set to True or False, 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 layer 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 internal_batch_size,
                        which are computed (forward / backward passes)
                        sequentially.
                        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
            attribute_to_layer_input (bool, optional): Indicates whether to
                        compute the attribution with respect to the layer input
                        or output. If `attribute_to_layer_input` is set to True
                        then the attributions will be computed with respect to
                        layer input, otherwise it will be computed with respect
                        to layer output.
                        Note that currently it is assumed that either the input
                        or the output of internal layer, depending on whether we
                        attribute to the input or output, is a single tensor.
                        Support for multiple tensors will be added later.
                        Default: False
            Returns:
                **attributions** or 2-element tuple of **attributions**, **delta**:
                - **attributions** (*tensor* or tuple of *tensors*):
                        Integrated gradients with respect to `layer`'s inputs or
                        outputs. Attributions will always be the same size and
                        dimensionality as the input or output of the given layer,
                        depending on whether we attribute to the inputs or outputs
                        of the layer which is decided by the input flag
                        `attribute_to_layer_input`.
                - **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.
                >>> # It contains an attribute conv1, which is an instance of nn.conv2d,
                >>> # and the output of this layer has dimensions Nx12x32x32.
                >>> net = ImageClassifier()
                >>> lig = LayerIntegratedGradients(net, net.conv1)
                >>> input = torch.randn(2, 3, 32, 32, requires_grad=True)
                >>> # Computes layer integrated gradients for class 3.
                >>> # attribution size matches layer output, Nx12x32x32
                >>> attribution = lig.attribute(input, target=3)
        """
        inps, baselines = _format_input_baseline(inputs, baselines)
        _validate_input(inps, baselines, n_steps, method)

        baselines = _tensorize_baseline(inps, baselines)
        additional_forward_args = _format_additional_forward_args(
            additional_forward_args
        )

        if self.device_ids is None:
            self.device_ids = getattr(self.forward_func, "device_ids", None)
        inputs_layer, is_layer_tuple = _forward_layer_eval(
            self.forward_func,
            inps,
            self.layer,
            device_ids=self.device_ids,
            additional_forward_args=additional_forward_args,
            attribute_to_layer_input=attribute_to_layer_input,
        )

        baselines_layer, _ = _forward_layer_eval(
            self.forward_func,
            baselines,
            self.layer,
            device_ids=self.device_ids,
            additional_forward_args=additional_forward_args,
            attribute_to_layer_input=attribute_to_layer_input,
        )

        # inputs -> these inputs are scaled
        def gradient_func(
            forward_fn: Callable,
            inputs: Union[Tensor, Tuple[Tensor, ...]],
            target_ind: Optional[
                Union[int, Tuple[int, ...], Tensor, List[Tuple[int, ...]]]
            ] = None,
            additional_forward_args: Any = None,
        ) -> Tuple[Tensor, ...]:
            if self.device_ids is None:
                scattered_inputs = (inputs,)
            else:
                # scatter method does not have a precise enough return type in its
                # stub, so suppress the type warning.
                scattered_inputs = scatter(  # type:ignore
                    inputs, target_gpus=self.device_ids
                )

            scattered_inputs_dict = {
                scattered_input[0].device: scattered_input
                for scattered_input in scattered_inputs
            }

            with torch.autograd.set_grad_enabled(True):

                def layer_forward_hook(module, hook_inputs, hook_outputs=None):
                    device = _extract_device(module, hook_inputs, hook_outputs)
                    if is_layer_tuple:
                        return scattered_inputs_dict[device]
                    return scattered_inputs_dict[device][0]

                if attribute_to_layer_input:
                    hook = self.layer.register_forward_pre_hook(layer_forward_hook)
                else:
                    hook = self.layer.register_forward_hook(layer_forward_hook)

                output = _run_forward(
                    self.forward_func, additional_forward_args, target_ind,
                )
                hook.remove()
                assert output[0].numel() == 1, (
                    "Target not provided when necessary, cannot"
                    " take gradient with respect to multiple outputs."
                )
                # torch.unbind(forward_out) is a list of scalar tensor tuples and
                # contains batch_size * #steps elements
                grads = torch.autograd.grad(torch.unbind(output), inputs)
            return grads

        self.ig.gradient_func = gradient_func
        all_inputs = (
            (inps + additional_forward_args)
            if additional_forward_args is not None
            else inps
        )
        attributions = self.ig.attribute(
            inputs_layer,
            baselines=baselines_layer,
            target=target,
            additional_forward_args=all_inputs,
            n_steps=n_steps,
            method=method,
            internal_batch_size=internal_batch_size,
            return_convergence_delta=False,
        )

        if return_convergence_delta:
            start_point, end_point = baselines, inps
            # 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_attributions(is_layer_tuple, attributions), delta
        return _format_attributions(is_layer_tuple, attributions)

    def has_convergence_delta(self) -> bool:
        return True
Exemplo n.º 22
0
    def attribute(
        self,
        inputs,
        baselines=None,
        target=None,
        additional_forward_args=None,
        n_steps=50,
        method="gausslegendre",
        internal_batch_size=None,
        return_convergence_delta=False,
        attribute_to_layer_input=False,
    ):
        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 layer inputs or outputs of the model, depending on whether
        `attribute_to_layer_input` is set to True or False, 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 layer 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 (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.
                        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 internal_batch_size,
                        which are computed (forward / backward passes)
                        sequentially.
                        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
            attribute_to_layer_input (bool, optional): Indicates whether to
                        compute the attribution with respect to the layer input
                        or output. If `attribute_to_layer_input` is set to True
                        then the attributions will be computed with respect to
                        layer input, otherwise it will be computed with respect
                        to layer output.
                        Note that currently it is assumed that either the input
                        or the output of internal layer, depending on whether we
                        attribute to the input or output, is a single tensor.
                        Support for multiple tensors will be added later.
                        Default: False
            Returns:
                **attributions** or 2-element tuple of **attributions**, **delta**:
                - **attributions** (*tensor* or tuple of *tensors*):
                        Integrated gradients with respect to `layer`'s inputs or
                        outputs. Attributions will always be the same size and
                        dimensionality as the input or output of the given layer,
                        depending on whether we attribute to the inputs or outputs
                        of the layer which is decided by the input flag
                        `attribute_to_layer_input`.
                - **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.
                >>> # It contains an attribute conv1, which is an instance of nn.conv2d,
                >>> # and the output of this layer has dimensions Nx12x32x32.
                >>> net = ImageClassifier()
                >>> lig = LayerIntegratedGradients(net, net.conv1)
                >>> input = torch.randn(2, 3, 32, 32, requires_grad=True)
                >>> # Computes layer integrated gradients for class 3.
                >>> # attribution size matches layer output, Nx12x32x32
                >>> attribution = lig.attribute(input, target=3)
        """
        inps, baselines = _format_input_baseline(inputs, baselines)
        _validate_input(inps, baselines, n_steps, method)

        baselines = _tensorize_baseline(inps, baselines)
        additional_forward_args = _format_additional_forward_args(
            additional_forward_args
        )

        if self.device_ids is None:
            self.device_ids = getattr(self.forward_func, "device_ids", None)
        inputs_layer = _forward_layer_eval(
            self.forward_func,
            inps,
            self.layer,
            device_ids=self.device_ids,
            additional_forward_args=additional_forward_args,
            attribute_to_layer_input=attribute_to_layer_input,
        )

        baselines_layer = _forward_layer_eval(
            self.forward_func,
            baselines,
            self.layer,
            device_ids=self.device_ids,
            additional_forward_args=additional_forward_args,
            attribute_to_layer_input=attribute_to_layer_input,
        )

        # inputs -> these inputs are scaled
        def gradient_func(
            forward_fn, inputs, target_ind=None, additional_forward_args=None
        ):
            if self.device_ids is None:
                scattered_inputs = inputs
            else:
                scattered_inputs = (
                    scatter_inp[0]
                    for scatter_inp in scatter(inputs, target_gpus=self.device_ids)
                )

            scattered_inputs_dict = {
                scattered_input[0].device: scattered_input
                for scattered_input in scattered_inputs
            }

            with torch.autograd.set_grad_enabled(True):

                def layer_forward_hook(module, hook_inputs, hook_outputs=None):
                    return scattered_inputs_dict[hook_inputs[0].device]

                if attribute_to_layer_input:
                    hook = self.layer.register_forward_pre_hook(layer_forward_hook)
                else:
                    hook = self.layer.register_forward_hook(layer_forward_hook)

                output = _run_forward(
                    self.forward_func, additional_forward_args, target_ind,
                )
                hook.remove()
                assert output[0].numel() == 1, (
                    "Target not provided when necessary, cannot"
                    " take gradient with respect to multiple outputs."
                )
                # torch.unbind(forward_out) is a list of scalar tensor tuples and
                # contains batch_size * #steps elements
                grads = torch.autograd.grad(torch.unbind(output), inputs)
            return grads

        self.gradient_func = gradient_func
        all_inputs = (
            (inps + additional_forward_args)
            if additional_forward_args is not None
            else inps
        )
        attributions = IntegratedGradients.attribute(
            self,
            inputs_layer,
            baselines=baselines_layer,
            target=target,
            additional_forward_args=all_inputs,
            n_steps=n_steps,
            method=method,
            internal_batch_size=internal_batch_size,
            return_convergence_delta=False,
        )

        # TODO this needs to be formated properly -
        # it assumes that layer returns a tensor
        attributions = (attributions,)

        if return_convergence_delta:
            start_point, end_point = baselines, inps
            # 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,
            )
            # TODO this needs to be checked of tensor properly: len(attributions) > 1
            return _format_attributions(len(attributions) > 1, attributions), delta
        return _format_attributions(len(attributions) > 1, attributions)
Exemplo n.º 23
0
 def test_simple_target_missing_error(self) -> None:
     net = BasicModel_MultiLayer()
     inp = torch.zeros((1, 3))
     with self.assertRaises(AssertionError):
         attr = IntegratedGradients(net)
         attr.attribute(inp)
    def _compute_attribution_and_evaluate(
        self,
        model: Module,
        inputs: TensorOrTupleOfTensorsGeneric,
        baselines: BaselineType = None,
        target: Union[None, int] = None,
        additional_forward_args: Any = None,
        type: str = "vanilla",
        approximation_method: str = "gausslegendre",
        multiply_by_inputs=True,
    ) -> Tuple[Tensor, ...]:
        r"""
        attrib_type: 'vanilla', 'smoothgrad', 'smoothgrad_sq', 'vargrad'
        """
        ig = IntegratedGradients(model, multiply_by_inputs=multiply_by_inputs)
        self.assertEquals(ig.multiplies_by_inputs, multiply_by_inputs)
        if not isinstance(inputs, tuple):
            inputs = (inputs,)  # type: ignore
        inputs: Tuple[Tensor, ...]

        if baselines is not None and not isinstance(baselines, tuple):
            baselines = (baselines,)

        if baselines is None:
            baselines = _tensorize_baseline(inputs, _zeros(inputs))

        if type == "vanilla":
            attributions, delta = ig.attribute(
                inputs,
                baselines,
                additional_forward_args=additional_forward_args,
                method=approximation_method,
                n_steps=500,
                target=target,
                return_convergence_delta=True,
            )
            model.zero_grad()
            attributions_without_delta, delta = ig.attribute(
                inputs,
                baselines,
                additional_forward_args=additional_forward_args,
                method=approximation_method,
                n_steps=500,
                target=target,
                return_convergence_delta=True,
            )
            model.zero_grad()
            self.assertEqual([inputs[0].shape[0]], list(delta.shape))
            delta_external = ig.compute_convergence_delta(
                attributions,
                baselines,
                inputs,
                target=target,
                additional_forward_args=additional_forward_args,
            )
            assertArraysAlmostEqual(delta, delta_external, 0.0)
        else:
            nt = NoiseTunnel(ig)
            n_samples = 5
            attributions, delta = nt.attribute(
                inputs,
                nt_type=type,
                nt_samples=n_samples,
                stdevs=0.00000002,
                baselines=baselines,
                target=target,
                additional_forward_args=additional_forward_args,
                method=approximation_method,
                n_steps=500,
                return_convergence_delta=True,
            )
            with self.assertWarns(DeprecationWarning):
                attributions_without_delta = nt.attribute(
                    inputs,
                    nt_type=type,
                    n_samples=n_samples,
                    stdevs=0.00000002,
                    baselines=baselines,
                    target=target,
                    additional_forward_args=additional_forward_args,
                    method=approximation_method,
                    n_steps=500,
                )
            self.assertEquals(nt.multiplies_by_inputs, multiply_by_inputs)
            self.assertEqual([inputs[0].shape[0] * n_samples], list(delta.shape))

        for input, attribution in zip(inputs, attributions):
            self.assertEqual(attribution.shape, input.shape)
        if multiply_by_inputs:
            self.assertTrue(all(abs(delta.numpy().flatten()) < 0.07))

        # compare attributions retrieved with and without
        # `return_convergence_delta` flag
        for attribution, attribution_without_delta in zip(
            attributions, attributions_without_delta
        ):
            assertTensorAlmostEqual(
                self, attribution, attribution_without_delta, delta=0.05
            )

        return cast(Tuple[Tensor, ...], attributions)
Exemplo n.º 25
0
    def _assert_compare_with_emb_patching(
        self,
        input: Union[Tensor, Tuple[Tensor, ...]],
        baseline: Union[Tensor, Tuple[Tensor, ...]],
        additional_args: Union[None, Tuple[Tensor, ...]],
        multiply_by_inputs: bool = True,
        multiple_emb: bool = False,
    ):
        model = BasicEmbeddingModel(nested_second_embedding=True)
        if multiple_emb:
            module_list: List[Module] = [model.embedding1, model.embedding2]
            lig = LayerIntegratedGradients(
                model,
                module_list,
                multiply_by_inputs=multiply_by_inputs,
            )
        else:
            lig = LayerIntegratedGradients(
                model, model.embedding1, multiply_by_inputs=multiply_by_inputs)

        attributions, delta = lig.attribute(
            input,
            baselines=baseline,
            additional_forward_args=additional_args,
            return_convergence_delta=True,
        )

        # now let's interpret with standard integrated gradients and
        # the embeddings for monkey patching
        e1 = configure_interpretable_embedding_layer(model, "embedding1")
        e1_input_emb = e1.indices_to_embeddings(
            input[0] if multiple_emb else input)
        e1_baseline_emb = e1.indices_to_embeddings(
            baseline[0] if multiple_emb else baseline)

        input_emb = e1_input_emb
        baseline_emb = e1_baseline_emb
        e2 = None
        if multiple_emb:
            e2 = configure_interpretable_embedding_layer(model, "embedding2")
            e2_input_emb = e2.indices_to_embeddings(*input[1:])
            e2_baseline_emb = e2.indices_to_embeddings(*baseline[1:])

            input_emb = (e1_input_emb, e2_input_emb)
            baseline_emb = (e1_baseline_emb, e2_baseline_emb)

        ig = IntegratedGradients(model, multiply_by_inputs=multiply_by_inputs)
        attributions_with_ig, delta_with_ig = ig.attribute(
            input_emb,
            baselines=baseline_emb,
            additional_forward_args=additional_args,
            target=0,
            return_convergence_delta=True,
        )
        remove_interpretable_embedding_layer(model, e1)
        if e2 is not None:
            remove_interpretable_embedding_layer(model, e2)

        self.assertEqual(isinstance(attributions_with_ig, tuple),
                         isinstance(attributions, list))

        self.assertTrue(
            isinstance(attributions_with_ig, tuple)
            if multiple_emb else not isinstance(attributions_with_ig, tuple))

        # convert to tuple for comparison
        if not isinstance(attributions_with_ig, tuple):
            attributions = (attributions, )
            attributions_with_ig = (attributions_with_ig, )
        else:
            # convert list to tuple
            self.assertIsInstance(attributions, list)
            attributions = tuple(attributions)

        for attr_lig, attr_ig in zip(attributions, attributions_with_ig):
            self.assertEqual(attr_lig.shape, attr_ig.shape)
            assertArraysAlmostEqual(attributions, attributions_with_ig)

        if multiply_by_inputs:
            assertArraysAlmostEqual(delta, delta_with_ig)