|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +import functools |
| 4 | +import inspect |
| 5 | +from typing import Callable, Dict, Tuple |
| 6 | + |
| 7 | +import torch |
| 8 | + |
| 9 | +from captum._utils.gradient import _forward_layer_eval |
| 10 | +from captum.attr import ( |
| 11 | + DeepLift, |
| 12 | + DeepLiftShap, |
| 13 | + FeatureAblation, |
| 14 | + GradientShap, |
| 15 | + InputXGradient, |
| 16 | + IntegratedGradients, |
| 17 | + LayerDeepLift, |
| 18 | + LayerDeepLiftShap, |
| 19 | + LayerFeatureAblation, |
| 20 | + LayerGradientShap, |
| 21 | + LayerGradientXActivation, |
| 22 | + LayerIntegratedGradients, |
| 23 | +) |
| 24 | +from captum.attr._utils.input_layer_wrapper import ModelInputWrapper |
| 25 | +from tests.helpers.basic import BaseTest, assertTensorTuplesAlmostEqual |
| 26 | +from tests.helpers.basic_models import ( |
| 27 | + BasicModel, |
| 28 | + BasicModel_MultiLayer_TrueMultiInput, |
| 29 | + MixedKwargsAndArgsModule, |
| 30 | +) |
| 31 | + |
| 32 | +layer_methods_to_test_with_equiv = [ |
| 33 | + # layer_method, equiv_method, whether or not to use multiple layers |
| 34 | + (LayerIntegratedGradients, IntegratedGradients, [True, False]), |
| 35 | + (LayerGradientXActivation, InputXGradient, [True, False]), |
| 36 | + (LayerFeatureAblation, FeatureAblation, [False]), |
| 37 | + (LayerDeepLift, DeepLift, [False]), |
| 38 | + (LayerDeepLiftShap, DeepLiftShap, [False]), |
| 39 | + (LayerGradientShap, GradientShap, [False]), |
| 40 | + # TODO: add other algorithms here |
| 41 | +] |
| 42 | + |
| 43 | + |
| 44 | +class InputLayerMeta(type): |
| 45 | + def __new__(cls, name: str, bases: Tuple, attrs: Dict): |
| 46 | + for ( |
| 47 | + layer_method, |
| 48 | + equiv_method, |
| 49 | + multi_layers, |
| 50 | + ) in layer_methods_to_test_with_equiv: |
| 51 | + for multi_layer in multi_layers: |
| 52 | + test_name = ( |
| 53 | + f"test_{layer_method.__name__}" |
| 54 | + + f"_{equiv_method.__name__}_{multi_layer}" |
| 55 | + ) |
| 56 | + attrs[ |
| 57 | + test_name |
| 58 | + ] = lambda self: self.layer_method_with_input_layer_patches( |
| 59 | + layer_method, equiv_method, multi_layer |
| 60 | + ) |
| 61 | + |
| 62 | + return super(InputLayerMeta, cls).__new__(cls, name, bases, attrs) |
| 63 | + |
| 64 | + |
| 65 | +class TestInputLayerWrapper(BaseTest, metaclass=InputLayerMeta): |
| 66 | + def test_forward_layer_eval_on_mixed_args_kwargs_module(self) -> None: |
| 67 | + x = torch.randn(10, 5) |
| 68 | + y = torch.randn(10, 5) |
| 69 | + |
| 70 | + model = MixedKwargsAndArgsModule() |
| 71 | + |
| 72 | + self.forward_eval_layer_with_inputs_helper(model, {"x": x}) |
| 73 | + self.forward_eval_layer_with_inputs_helper(model, {"x": x, "y": y}) |
| 74 | + |
| 75 | + def layer_method_with_input_layer_patches( |
| 76 | + self, |
| 77 | + layer_method_class: Callable, |
| 78 | + equiv_method_class: Callable, |
| 79 | + multi_layer: bool, |
| 80 | + ) -> None: |
| 81 | + model = BasicModel_MultiLayer_TrueMultiInput() if multi_layer else BasicModel() |
| 82 | + |
| 83 | + input_names = ["x1", "x2", "x3", "x4"] if multi_layer else ["input"] |
| 84 | + model = ModelInputWrapper(model) |
| 85 | + |
| 86 | + layers = [model.input_maps[inp] for inp in input_names] |
| 87 | + layer_method = layer_method_class( |
| 88 | + model, layer=layers if multi_layer else layers[0] |
| 89 | + ) |
| 90 | + equivalent_method = equiv_method_class(model) |
| 91 | + |
| 92 | + inputs = tuple(torch.rand(5, 3) for _ in input_names) |
| 93 | + baseline = tuple(torch.zeros(5, 3) for _ in input_names) |
| 94 | + |
| 95 | + args = inspect.getfullargspec(equivalent_method.attribute.__wrapped__).args |
| 96 | + |
| 97 | + args_to_use = [inputs] |
| 98 | + if "baselines" in args: |
| 99 | + args_to_use += [baseline] |
| 100 | + |
| 101 | + a1 = layer_method.attribute(*args_to_use, target=0) |
| 102 | + a2 = layer_method.attribute( |
| 103 | + *args_to_use, target=0, attribute_to_layer_input=True |
| 104 | + ) |
| 105 | + |
| 106 | + real_attributions = equivalent_method.attribute(*args_to_use, target=0) |
| 107 | + |
| 108 | + if not isinstance(a1, tuple): |
| 109 | + a1 = (a1,) |
| 110 | + a2 = (a2,) |
| 111 | + |
| 112 | + if not isinstance(real_attributions, tuple): |
| 113 | + real_attributions = (real_attributions,) |
| 114 | + |
| 115 | + assertTensorTuplesAlmostEqual(self, a1, a2) |
| 116 | + assertTensorTuplesAlmostEqual(self, a1, real_attributions) |
| 117 | + |
| 118 | + def forward_eval_layer_with_inputs_helper(self, model, inputs_to_test): |
| 119 | + # hard coding for simplicity |
| 120 | + # 0 if using args, 1 if using kwargs |
| 121 | + # => no 0s after first 1 (left to right) |
| 122 | + # |
| 123 | + # used to test utilization of args/kwargs |
| 124 | + use_args_or_kwargs = [ |
| 125 | + [[0], [1]], |
| 126 | + [ |
| 127 | + [0, 0], |
| 128 | + [0, 1], |
| 129 | + [1, 1], |
| 130 | + ], |
| 131 | + ] |
| 132 | + |
| 133 | + model = ModelInputWrapper(model) |
| 134 | + |
| 135 | + def forward_func(*args, args_or_kwargs=None): |
| 136 | + # convert to args or kwargs to test *args and **kwargs wrapping behavior |
| 137 | + new_args = [] |
| 138 | + new_kwargs = {} |
| 139 | + for args_or_kwarg, name, inp in zip( |
| 140 | + args_or_kwargs, inputs_to_test.keys(), args |
| 141 | + ): |
| 142 | + if args_or_kwarg: |
| 143 | + new_kwargs[name] = inp |
| 144 | + else: |
| 145 | + new_args.append(inp) |
| 146 | + return model(*new_args, **new_kwargs) |
| 147 | + |
| 148 | + for args_or_kwargs in use_args_or_kwargs[len(inputs_to_test) - 1]: |
| 149 | + with self.subTest(args_or_kwargs=args_or_kwargs): |
| 150 | + inputs = _forward_layer_eval( |
| 151 | + functools.partial(forward_func, args_or_kwargs=args_or_kwargs), |
| 152 | + inputs=tuple(inputs_to_test.values()), |
| 153 | + layer=[model.input_maps[name] for name in inputs_to_test.keys()], |
| 154 | + ) |
| 155 | + |
| 156 | + inputs_with_attrib_to_inp = _forward_layer_eval( |
| 157 | + functools.partial(forward_func, args_or_kwargs=args_or_kwargs), |
| 158 | + inputs=tuple(inputs_to_test.values()), |
| 159 | + layer=[model.input_maps[name] for name in inputs_to_test.keys()], |
| 160 | + attribute_to_layer_input=True, |
| 161 | + ) |
| 162 | + |
| 163 | + for i1, i2, i3 in zip( |
| 164 | + inputs, inputs_with_attrib_to_inp, inputs_to_test.values() |
| 165 | + ): |
| 166 | + self.assertTrue((i1[0] == i2[0]).all()) |
| 167 | + self.assertTrue((i1[0] == i3).all()) |
0 commit comments