-
Notifications
You must be signed in to change notification settings - Fork 32
/
attribution.py
563 lines (482 loc) · 25 KB
/
attribution.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
# This file is part of Zennit
# Copyright (C) 2019-2021 Christopher J. Anders
#
# zennit/attribution.py
#
# Zennit is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation; either version 3 of the License, or (at your option) any
# later version.
#
# Zennit is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for
# more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this library. If not, see <https://www.gnu.org/licenses/>.
'''Attributors are convenience objects to compute attributions, optionally using composites.'''
from abc import ABCMeta, abstractmethod
from functools import partial
from itertools import product
import torch
def constant(obj):
'''Wrapper function to create a function which returns a constant object regardless of arguments.
Parameters
----------
obj : object
Constant object which the returned wrapper function will return on call.
Returns
-------
wrapped_const : function
Function which when called with any arguments will return ``obj``.
'''
def wrapped_const(*args, **kwargs):
return obj
return wrapped_const
def identity(obj):
'''Identity function.
Parameters
----------
obj : object
Any object which will be returned.
Result
------
obj : object
The original input argument ``obj``.
'''
return obj
def occlude_independent(input, mask, fill_fn=torch.zeros_like, invert=False):
'''Given a ``mask``, occlude pixels of ``input`` independently given a function ``fill_fn``.
Parameters
----------
input : :py:obj:`torch.Tensor`
The input tensor which will be occluded in the pixels where ``mask`` is non-zero, or, if ``invert`` is
``True``, where ``mask`` is zero, using function ``fill_fn``.
mask : :py:obj:`torch.Tensor`
Boolean mask, at which non-zero or zero (given ``invert``) elements will be occluded in ``input``.
fill_fn : function, optional
Function used to occlude pixels with signature ``(input : torch.Tensor) -> torch.Tensor``, where input is the
same shape as ``input``, and the output shall leave the shape unchanged. Default is ``torch.zeros_like``, which
will replace occluded pixels with zero.
invert : bool, optional
If ``True``, inverts the supplied mask. Default is ``False``, i.e. not to invert.
Returns
-------
:py:obj:`torch.Tensor`
The occluded tensor.
'''
if invert:
mask = ~mask
return input * mask + ~mask * fill_fn(input)
class Attributor(metaclass=ABCMeta):
'''Base Attributor Class.
Attributors are convenience objects with an optional composite and when called, compute an attribution, e.g., the
gradient or anything that is the result of computing the gradient when using the provided composite. Attributors
also provide a context to be used in a `with` statement, similar to `CompositeContext`s. If the forward function
(or `self.__call__`) is called and the composite has not been registered (i.e. `composite.handles` is empty), the
composite will be temporarily registered to the model.
Parameters
----------
model: :py:obj:`torch.nn.Module`
The model for which the attribution will be computed. If `composite` is provided, this will also be the model
to which the composite will be registered within `with` statements, or when calling the `Attributor` instance.
composite: :py:obj:`zennit.core.Composite`, optional
The optional composite to, if provided, be registered to the model within `with` statements or when calling the
`Attributor` instance.
attr_output: :py:obj:`torch.Tensor` or callable, optional
The default output attribution to be used when calling the `Attributor` instance, which is either a Tensor
compatible with any input used, or a function of the model's output. If None (default), the value will be the
identity function.
'''
def __init__(self, model, composite=None, attr_output=None):
self.model = model
self.composite = composite
if attr_output is None:
self.attr_output_fn = identity
elif not callable(attr_output):
self.attr_output_fn = constant(attr_output)
else:
self.attr_output_fn = attr_output
def __enter__(self):
'''Register the composite, if provided.
Returns
-------
self: :py:obj:`Attributor`
The `Attributor` instance.
'''
if self.composite is not None:
self.composite.register(self.model)
return self
def __exit__(self, exc_type, exc_value, traceback):
'''Remove the composite, if provided.
Returns
-------
False
'''
if self.composite is not None:
self.composite.remove()
return False
def __call__(self, input, attr_output=None):
'''Compute the attribution of the model wrt. `input`, using `attr_output` as the output attribution if
provided, or the default output attribution otherwise (if not supplied during instantiation either, this will
be the full output of the model). If a composite was supplied to the `Attributor` instance, but it was not yet
registered (either manually, or in a `with` statement), it will be registered to the model temporarily during
the call.
Parameters
----------
input: :py:obj:`torch.Tensor`
Input for the model, and wrt. compute the attribution
attr_output: :py:obj:`torch.Tensor` or callable, optional
The output attribution, which is either a Tensor compatible `input` (i.e. has the same shape as the output
of the model), or a function of the model's output. If None (default), the default attribution will be
used, which if neither supplied, will result in the model output used as the output attribution.
Returns
-------
output: :py:obj:`torch.Tensor`
Output of the model with argument `input`.
attribution: :py:obj:`torch.Tensor`
Attribution of the model wrt. to `input`, with the same shape as `input`.
'''
if attr_output is None:
attr_output_fn = self.attr_output_fn
elif not callable(attr_output):
attr_output_fn = constant(attr_output)
else:
attr_output_fn = attr_output
if self.composite is None or self.composite.handles:
return self.forward(input, attr_output_fn)
with self:
return self.forward(input, attr_output_fn)
@property
def inactive(self):
'''Return the attributor's composite's ``.inactive`` context.'''
return self.composite.inactive
@abstractmethod
def forward(self, input, attr_output_fn):
'''Abstract method. Compute the attribution of the model wrt. input, by using `attr_output_fn` as the function
of the model output to provide the output attribution. This function will not register the composite, and is
wrapped in the `__call__` of `Attributor`.
Parameters
----------
input: :py:obj:`torch.Tensor`
Input for the model, and wrt. compute the attribution
attr_output: :py:obj:`torch.Tensor` or callable, optional
The output attribution function of the model's output.
'''
class Gradient(Attributor):
'''The Gradient Attributor. The result is the product of the attribution output and the (possibly modified)
jacobian. With a composite, i.e. `EpsilonGammaBox`, this will compute the Layer-wise Relevance Propagation
attribution values.
Parameters
----------
model: :py:obj:`torch.nn.Module`
The model for which the attribution will be computed. If `composite` is provided, this will also be the model
to which the composite will be registered within `with` statements, or when calling the `Attributor` instance.
composite: :py:obj:`zennit.core.Composite`, optional
The optional composite to, if provided, be registered to the model within `with` statements or when calling the
`Attributor` instance.
attr_output: :py:obj:`torch.Tensor` or callable, optional
The default output attribution to be used when calling the `Attributor` instance, which is either a Tensor
compatible with any input used, or a function of the model's output. If None (default), the value will be the
identity function.
create_graph: bool, optional
Specify whether to use ``create_graph=True`` (default is False) to compute the gradient with
:py:obj:`torch.autograd.grad`. This needs to be `True` to compute higher order gradients.
retain_graph: bool, optional
Specify whether to use ``retain_graph=True`` (default is the value of create_graph) to compute the gradient
with :py:obj:`torch.autograd.grad`.
'''
def __init__(self, model, composite=None, attr_output=None, create_graph=False, retain_graph=None):
super().__init__(model=model, composite=composite, attr_output=attr_output)
self.create_graph = create_graph
self.retain_graph = retain_graph
def grad(self, input, attr_output_fn):
'''Compute the gradient of the model wrt. input, by using ``attr_output_fn`` as the function of the model
output to provide the vector for the vector jacobian product.
This function is used by subclasses to compute the gradient with the same parameters.
Parameters
----------
input: :py:obj:`torch.Tensor`
Input for the model.
attr_output: :py:obj:`torch.Tensor` or callable, optional
The output attribution function of the model's output.
Returns
-------
output: :py:obj:`torch.Tensor`
Output of the model given ``input``.
gradient: :py:obj:`torch.Tensor`
Gradient of the model wrt. to ``input``, with the same shape as ``input``.
'''
if not input.requires_grad:
input.requires_grad = True
output = self.model(input)
gradient, = torch.autograd.grad(
(output,),
(input,),
grad_outputs=(attr_output_fn(output),),
create_graph=self.create_graph,
retain_graph=self.retain_graph,
)
return output, gradient
def forward(self, input, attr_output_fn):
'''Compute the gradient of the model wrt. input, by using `attr_output_fn` as the function of the model output
to provide the vector for the vector jacobian product.
This function will not register the composite, and is wrapped in the `__call__` of `Attributor`.
Parameters
----------
input: :py:obj:`torch.Tensor`
Input for the model, and wrt. compute the attribution.
attr_output_fn: :py:obj:`torch.Tensor` or callable
The output attribution function of the model's output.
Returns
-------
output: :py:obj:`torch.Tensor`
Output of the model given `input`.
attribution: :py:obj:`torch.Tensor`
Attribution of the model wrt. to `input`, with the same shape as `input`.
'''
# create a view of input in case it does not already requires grad
input = input.view_as(input)
return self.grad(input, attr_output_fn)
class SmoothGrad(Gradient):
'''This implements SmoothGrad [1]_. The result is the average over the gradient of multiple iterations where some
normal distributed noise was added to the input. Supplying a composite will result instead in averaging over the
modified gradient.
Parameters
----------
model: :py:obj:`torch.nn.Module`
The model for which the attribution will be computed. If `composite` is provided, this will also be the model
to which the composite will be registered within `with` statements, or when calling the `Attributor` instance.
composite: :py:obj:`zennit.core.Composite`, optional
The optional composite to, if provided, be registered to the model within `with` statements or when calling the
`Attributor` instance.
attr_output: :py:obj:`torch.Tensor` or callable, optional
The default output attribution to be used when calling the `Attributor` instance, which is either a Tensor
compatible with any input used, or a function of the model's output. If None (default), the value will be the
identity function.
create_graph: bool, optional
Specify whether to use ``create_graph=True`` (default is False) to compute the gradient with
:py:obj:`torch.autograd.grad`. This needs to be `True` to compute higher order gradients.
retain_graph: bool, optional
Specify whether to use ``retain_graph=True`` (default is the value of create_graph) to compute the gradient
with :py:obj:`torch.autograd.grad`.
noise_level: float, optional
The noise level, which is :math:`\\frac{\\sigma}{x_{max} - x_{min}}` and defaults to 0.1.
n_iter: int, optional
The number of iterations over which to average, defaults to 20.
References
----------
.. [1] D. Smilkov, N. Thorat, B. Kim, F. B. Viégas, and M. Wattenberg: "SmoothGrad: removing noise by adding
noise," CoRR, vol. abs/1706.03825, 2017.
'''
def __init__(
self, model, composite=None, attr_output=None, create_graph=False, retain_graph=None, noise_level=0.1, n_iter=20
):
super().__init__(
model=model,
composite=composite,
attr_output=attr_output,
create_graph=create_graph,
retain_graph=retain_graph
)
self.noise_level = noise_level
self.n_iter = n_iter
def forward(self, input, attr_output_fn):
'''Compute the SmoothGrad of the model wrt. input, by using `attr_output_fn` as the function of the model output
to provide the vector for the vector jacobian product used to compute the gradient.
This function will not register the composite, and is wrapped in the `__call__` of `Attributor`.
Parameters
----------
input: :py:obj:`torch.Tensor`
Input for the model, and wrt. compute the attribution.
attr_output: :py:obj:`torch.Tensor` or callable, optional
The output attribution function of the model's output.
Returns
-------
output: :py:obj:`torch.Tensor`
Output of the model given `input`.
attribution: :py:obj:`torch.Tensor`
Attribution of the model wrt. to `input`, with the same shape as `input`.
'''
dims = tuple(range(1, input.ndim))
std = self.noise_level * (input.amax(dims, keepdim=True) - input.amin(dims, keepdim=True))
result = torch.zeros_like(input)
for n in range(self.n_iter):
# the last epsilon is defined as zero to compute the true output,
# and have SmoothGrad w/ n_iter = 1 === gradient
if n == self.n_iter - 1:
epsilon = torch.zeros_like(input)
else:
epsilon = torch.randn_like(input) * std
output, gradient = self.grad(input + epsilon, attr_output_fn)
result += gradient / self.n_iter
# output is leaking from the loop for the last epsilon (which is zero)
return output, result
class IntegratedGradients(Gradient):
'''This implements Integrated Gradients [2]_. The result is the path integral of the gradients, estimated over
multiple discrete iterations. Supplying a composite will result instead in the path integral over the modified
gradient.
Parameters
----------
model: :py:obj:`torch.nn.Module`
The model for which the attribution will be computed. If `composite` is provided, this will also be the model
to which the composite will be registered within `with` statements, or when calling the `Attributor` instance.
composite: :py:obj:`zennit.core.Composite`, optional
The optional composite to, if provided, be registered to the model within `with` statements or when calling the
`Attributor` instance.
attr_output: :py:obj:`torch.Tensor` or callable, optional
The default output attribution to be used when calling the `Attributor` instance, which is either a Tensor
compatible with any input used, or a function of the model's output. If None (default), the value will be the
identity function.
create_graph: bool, optional
Specify whether to use ``create_graph=True`` (default is False) to compute the gradient with
:py:obj:`torch.autograd.grad`. This needs to be `True` to compute higher order gradients.
retain_graph: bool, optional
Specify whether to use ``retain_graph=True`` (default is the value of create_graph) to compute the gradient
with :py:obj:`torch.autograd.grad`.
baseline_fn: callable, optional
The baseline for which the model output is zero, supplied as a function of the input. Defaults to
`torch.zeros_like`.
n_iter: int, optional
The number of iterations used to estimate the integral, defaults to 20.
References
----------
.. [2] M. Sundararajan, A. Taly, and Q. Yan, “Axiomatic attribution for deep networks,” in Proceedings of the 34th
International Conference on Machine Learning, ICML 2017, Sydney, NSW, Australia, 6-11 August 2017, ser.
Proceedings of Machine Learning Research, D. Precup and Y. W. Teh, Eds., vol. 70. PMLR, 2017, pp. 3319–3328.
'''
def __init__(
self,
model,
composite=None,
attr_output=None,
create_graph=False,
retain_graph=None,
baseline_fn=None,
n_iter=20
):
super().__init__(
model=model,
composite=composite,
attr_output=attr_output,
create_graph=create_graph,
retain_graph=retain_graph
)
if baseline_fn is None:
baseline_fn = torch.zeros_like
self.baseline_fn = baseline_fn
self.n_iter = n_iter
def forward(self, input, attr_output_fn):
'''Compute the Integrated Gradients of the model wrt. input, by using `attr_output_fn` as the function of the
model output to provide the vector for the vector jacobian product used to compute the gradient.
This function will not register the composite, and is wrapped in the `__call__` of `Attributor`.
Parameters
----------
input: :py:obj:`torch.Tensor`
Input for the model, and wrt. compute the attribution.
attr_output: :py:obj:`torch.Tensor` or callable, optional
The output attribution function of the model's output.
Returns
-------
output: :py:obj:`torch.Tensor`
Output of the model given `input`.
attribution: :py:obj:`torch.Tensor`
Attribution of the model wrt. to `input`, with the same shape as `input`.
'''
baseline = self.baseline_fn(input)
result = torch.zeros_like(input)
for alpha in torch.linspace(1. / self.n_iter, 1., self.n_iter):
path_step = baseline + alpha * (input - baseline)
output, gradient = self.grad(path_step, attr_output_fn)
result += gradient / self.n_iter
result *= (input - baseline)
# in the last step, path_step is equal to input, thus `output` is the original output
return output, result
class Occlusion(Attributor):
'''This implements attribution by occlusion. Supplying a composite will have no effect on the result, as the
gradient is not used.
Parameters
----------
model: :py:obj:`torch.nn.Module`
The model for which the attribution will be computed. If `composite` is provided, this will also be the model
to which the composite will be registered within `with` statements, or when calling the `Attributor` instance.
composite: :py:obj:`zennit.core.Composite`, optional
The optional composite to, if provided, be registered to the model within `with` statements or when calling the
`Attributor` instance. Note that for Occlusion, this has no effect on the result.
attr_output: :py:obj:`torch.Tensor` or callable, optional
The default output attribution to be used when calling the `Attributor` instance, which is either a Tensor
compatible with any input used, or a function of the model's output. If None (default), the value will be the
identity function.
occlusion_fn: callable, optional
The occluded function, called with `occlusion_fn(input, mask)`, where `mask` is 1 inside the sliding window,
and 0 outside. Either values inside or outside the sliding window may be occluded for different effects. By
default, all values except inside the sliding window will be occluded.
window: int or tuple of ints, optional
The size of the sliding window to occlude over the input for each dimension. Defaults to 8. If a single integer
is provided, the sliding window will slide with the same size over all dimensions except the first, which is
assumed as the batch-dimension. If a tuple is provided, the window will only slide over the n-last dimensions,
where n is the length of the tuple, e.g., if the data has shape `(3, 32, 32)` and `window=(8, 8)`, the
resulting mask will have a block of shape `(3, 8, 8)` set to True. `window` must have the same length as
`stride`.
stride: int or tuple of ints, optional
The strides used for the sliding window to occlude over the input for each dimension. Defaults to 8. If a
single integer is provided, the strides will be the same size for all dimensions. If a tuple is provided,
the window will only stride over the n-last dimensions, where n is the length of the tuple.
`stride` must have the same length as `window`.
'''
def __init__(self, model, composite=None, attr_output=None, occlusion_fn=None, window=8, stride=8):
def typecheck(obj):
return isinstance(obj, int) or isinstance(obj, tuple) and all(isinstance(elem, int) for elem in obj)
super().__init__(model=model, composite=composite, attr_output=attr_output)
if not typecheck(window):
raise TypeError('Occlusion window must either be an int, or a tuple of ints.')
if not typecheck(stride):
raise TypeError('Occlusion window must either be an int, or a tuple of ints.')
if occlusion_fn is None:
occlusion_fn = partial(occlude_independent, fill_fn=torch.zeros_like, invert=False)
self.occlusion_fn = occlusion_fn
self.window = window
self.stride = stride
def _resolve_window_stride(self, input):
window = self.window
stride = self.stride
if isinstance(window, int):
window = tuple(min(window, size) for size in input.shape[1:])
if isinstance(stride, int):
stride = tuple(min(stride, size) for size in input.shape[1:])
if len(window) < input.ndim:
window = tuple(input.shape)[:input.ndim - len(window)] + window
if len(stride) < len(window):
stride = window[:len(window) - len(stride)] + stride
return window, stride
def forward(self, input, attr_output_fn):
'''Compute the occlusion analysis of the model wrt. input, by using `attr_output_fn` as function of the output,
to return a weighting, which when multiplied again with the output, results in the classification score.
This function will not register the composite, and is wrapped in the `__call__` of `Attributor`.
Parameters
----------
input: :py:obj:`torch.Tensor`
Input for the model, and wrt. compute the attribution.
attr_output: :py:obj:`torch.Tensor` or callable, optional
The output attribution function of the model's output.
Returns
-------
output: :py:obj:`torch.Tensor`
Output of the model given `input`.
attribution: :py:obj:`torch.Tensor`
Attribution of the model wrt. to `input`, with the same shape as `input`.
'''
window, stride = self._resolve_window_stride(input)
root_mask = torch.zeros_like(input, dtype=bool)
root_mask[tuple(slice(0, elem) for elem in window)] = True
result = torch.zeros_like(input)
for offset in product(*(range(0, size, local_stride) for size, local_stride in zip(input.shape, stride))):
mask = root_mask.roll(offset, tuple(range(input.ndim)))
occluded_input = self.occlusion_fn(input, mask)
with torch.no_grad():
output = self.model(occluded_input)
score = attr_output_fn(output).sum(tuple(range(1, output.ndim)))
result += mask * score[(slice(None),) + (None,) * (input.ndim - 1)]
output = self.model(input)
return output, result