This repository has been archived by the owner on Dec 16, 2022. It is now read-only.
/
influence_interpreter.py
427 lines (354 loc) · 16.8 KB
/
influence_interpreter.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
import logging
from os import PathLike
import re
from typing import List, Optional, NamedTuple, Sequence, Union, Dict, Any
import torch
from torch import autograd
from allennlp.common import Registrable, Lazy, plugins
from allennlp.common.tqdm import Tqdm
from allennlp.common.util import int_to_device
from allennlp.data import Instance, DatasetReader, DatasetReaderInput, Batch
from allennlp.data.data_loaders import DataLoader, SimpleDataLoader
from allennlp.models import Model, Archive, load_archive
from allennlp.nn.util import move_to_device
logger = logging.getLogger(__name__)
class InstanceInfluence(NamedTuple):
instance: Instance
loss: float
score: float
"""
The influence score associated with this training instance.
"""
class InterpretOutput(NamedTuple):
"""
The output associated with a single test instance.
"""
test_instance: Instance
loss: float
"""
The loss corresponding to the `test_instance`.
"""
top_k: List[InstanceInfluence]
"""
The top `k` most influential training instances along with their influence score.
"""
class InstanceWithGrads(NamedTuple):
"""
Wraps a training `Instance` along with its associated loss and gradients.
`InfluenceInterpreter.train_instances` is a list of these objects.
"""
instance: Instance
loss: float
grads: Sequence[torch.Tensor]
class InfluenceInterpreter(Registrable):
"""
An `InfluenceInterpreter` interprets an AllenNLP models's outputs by finding the
training instances that had the most influence on the prediction for each test input.
See [Understanding Black-box Predictions via Influence Functions]
(https://api.semanticscholar.org/CorpusID:13193974) for more information.
Subclasses are required to implement the `_calculate_influence_scores()` method.
# Parameters
model : `Model`, required
train_data_path : `DatasetReaderInput`, required
train_dataset_reader : `DatasetReader`, required
test_dataset_reader : `Optional[DatasetReader]`, optional (default = `None`)
This is the dataset reader to read the test set file. If not provided, the
`train_dataset_reader` is used.
train_data_loader : `Lazy[DataLoader]`, optional (default = `Lazy(SimpleDataLoader)`)
The data loader used to load training instances.
!!! Note
This data loader is only used to call `DataLoader.iter_instances()`, so certain
`DataLoader` settings like `batch_size` will have no effect.
test_data_loader : `Lazy[DataLoader]`, optional (default = `Lazy(SimpleDataLoader)`)
The data loader used to load test instances when `interpret_from_file()` is called.
!!! Note
Like `train_data_loader`, this data loader is only used to call `DataLoader.iter_instances()`,
so certain `DataLoader` settings like `batch_size` will have no effect.
params_to_freeze : `Optional[List[str]]`, optional (default = `None`)
An optional list of strings, each of which should be a regular expression that matches
some parameter keys of the model. Any matching parameters will be have `requires_grad`
set to `False`.
cuda_device : `int`, optional (default = `-1`)
The index of GPU device we want to calculate scores on. If not provided, we uses `-1`
which correspond to using CPU.
"""
default_implementation = "simple-influence"
def __init__(
self,
model: Model,
train_data_path: DatasetReaderInput,
train_dataset_reader: DatasetReader,
*,
test_dataset_reader: Optional[DatasetReader] = None,
train_data_loader: Lazy[DataLoader] = Lazy(SimpleDataLoader.from_dataset_reader),
test_data_loader: Lazy[DataLoader] = Lazy(SimpleDataLoader.from_dataset_reader),
params_to_freeze: Optional[List[str]] = None,
cuda_device: int = -1,
) -> None:
self.model = model
self.vocab = model.vocab
self.device = int_to_device(cuda_device)
self._train_data_path = train_data_path
self._train_loader = train_data_loader.construct(
reader=train_dataset_reader,
data_path=train_data_path,
batch_size=1,
)
self._train_loader.set_target_device(self.device)
self._train_loader.index_with(self.vocab)
self._test_dataset_reader = test_dataset_reader or train_dataset_reader
self._lazy_test_data_loader = test_data_loader
self.model.to(self.device)
if params_to_freeze is not None:
for name, param in self.model.named_parameters():
if any([re.match(pattern, name) for pattern in params_to_freeze]):
param.requires_grad = False
# These variables are set when the corresponding public properties are accessed.
# This is not set until we actually run the calculation since some parameters might not be used.
self._used_params: Optional[List[torch.nn.Parameter]] = None
self._used_param_names: Optional[List[str]] = None
self._train_instances: Optional[List[InstanceWithGrads]] = None
@property
def used_params(self) -> List[torch.nn.Parameter]:
"""
The parameters of the model that have non-zero gradients after a backwards pass.
This can be used to gather the corresponding gradients with respect to a loss
via the `torch.autograd.grad` function.
!!! Note
Accessing this property requires calling `self._gather_train_instances_and_compute_gradients()`
if it hasn't been called yet, which may take several minutes.
"""
if self._used_params is None:
self._gather_train_instances_and_compute_gradients()
assert self._used_params is not None
return self._used_params
@property
def used_param_names(self) -> List[str]:
"""
The names of the corresponding parameters in `self.used_params`.
!!! Note
Accessing this property requires calling `self._gather_train_instances_and_compute_gradients()`
if it hasn't been called yet, which may take several minutes.
"""
if self._used_param_names is None:
self._gather_train_instances_and_compute_gradients()
assert self._used_param_names is not None
return self._used_param_names
@property
def train_instances(self) -> List[InstanceWithGrads]:
"""
The training instances along with their corresponding loss and gradients.
!!! Note
Accessing this property requires calling `self._gather_train_instances_and_compute_gradients()`
if it hasn't been called yet, which may take several minutes.
"""
if self._train_instances is None:
self._gather_train_instances_and_compute_gradients()
assert self._train_instances is not None
return self._train_instances
@classmethod
def from_path(
cls,
archive_path: Union[str, PathLike],
*,
interpreter_name: Optional[str] = None,
train_data_path: Optional[DatasetReaderInput] = None,
train_data_loader: Lazy[DataLoader] = Lazy(SimpleDataLoader.from_dataset_reader),
test_data_loader: Lazy[DataLoader] = Lazy(SimpleDataLoader.from_dataset_reader),
params_to_freeze: Optional[List[str]] = None,
cuda_device: int = -1,
import_plugins: bool = True,
overrides: Union[str, Dict[str, Any]] = "",
**extras,
) -> "InfluenceInterpreter":
"""
Load an `InfluenceInterpreter` from an archive path.
# Parameters
archive_path : `Union[str, PathLike]`, required
The path to the archive file.
interpreter_name : `Optional[str]`, optional (default = `None`)
The registered name of the an interpreter class. If not specified,
the default implementation (`SimpleInfluence`) will be used.
train_data_path : `Optional[DatasetReaderInput]`, optional (default = `None`)
If not specified, `train_data_path` will be taken from the archive's config.
train_data_loader : `Lazy[DataLoader]`, optional (default = `Lazy(SimpleDataLoader)`)
test_data_loader : `Lazy[DataLoader]`, optional (default = `Lazy(SimpleDataLoader)`)
params_to_freeze : `Optional[List[str]]`, optional (default = `None`)
cuda_device : `int`, optional (default = `-1`)
import_plugins : `bool`, optional (default = `True`)
If `True`, we attempt to import plugins before loading the `InfluenceInterpreter`.
This comes with additional overhead, but means you don't need to explicitly
import the modules that your implementation depends on as long as those modules
can be found by `allennlp.common.plugins.import_plugins()`.
overrides : `Union[str, Dict[str, Any]]`, optional (default = `""`)
JSON overrides to apply to the unarchived `Params` object.
**extras : `Any`
Extra parameters to pass to the interpreter's `__init__()` method.
"""
if import_plugins:
plugins.import_plugins()
return cls.from_archive(
load_archive(archive_path, cuda_device=cuda_device, overrides=overrides),
interpreter_name=interpreter_name,
train_data_path=train_data_path,
train_data_loader=train_data_loader,
test_data_loader=test_data_loader,
params_to_freeze=params_to_freeze,
cuda_device=cuda_device,
**extras,
)
@classmethod
def from_archive(
cls,
archive: Archive,
*,
interpreter_name: Optional[str] = None,
train_data_path: Optional[DatasetReaderInput] = None,
train_data_loader: Lazy[DataLoader] = Lazy(SimpleDataLoader.from_dataset_reader),
test_data_loader: Lazy[DataLoader] = Lazy(SimpleDataLoader.from_dataset_reader),
params_to_freeze: Optional[List[str]] = None,
cuda_device: int = -1,
**extras,
) -> "InfluenceInterpreter":
"""
Load an `InfluenceInterpreter` from an `Archive`.
The other parameters are the same as `.from_path()`.
"""
interpreter_cls = cls.by_name(interpreter_name or cls.default_implementation)
return interpreter_cls(
model=archive.model,
train_data_path=train_data_path or archive.config["train_data_path"],
train_dataset_reader=archive.dataset_reader,
test_dataset_reader=archive.validation_dataset_reader,
train_data_loader=train_data_loader,
test_data_loader=test_data_loader,
params_to_freeze=params_to_freeze,
cuda_device=cuda_device,
**extras,
)
def interpret(self, test_instance: Instance, k: int = 20) -> InterpretOutput:
"""
Run the influence function scorer on the given instance, returning the top `k`
most influential train instances with their scores.
!!! Note
Test instances should have `targets` so that a loss can be computed.
"""
return self.interpret_instances([test_instance], k=k)[0]
def interpret_from_file(
self, test_data_path: DatasetReaderInput, k: int = 20
) -> List[InterpretOutput]:
"""
Runs `interpret_instances` over the instances read from `test_data_path`.
!!! Note
Test instances should have `targets` so that a loss can be computed.
"""
test_data_loader = self._lazy_test_data_loader.construct(
reader=self._test_dataset_reader,
data_path=test_data_path,
batch_size=1,
)
test_data_loader.index_with(self.vocab)
instances = list(test_data_loader.iter_instances())
return self.interpret_instances(instances, k=k)
def interpret_instances(
self, test_instances: List[Instance], k: int = 20
) -> List[InterpretOutput]:
"""
Run the influence function scorer on the given instances, returning the top `k`
most influential train instances for each test instance.
!!! Note
Test instances should have `targets` so that a loss can be computed.
"""
# We have these checks here for two reasons:
# 1. as a sanity check to make sure we actually have a non-empty set of training
# instances as well as parameters that get non-zero gradients,
# 2. and to ensure these attributes (self.used_params and self.training_instances)
# have been collected before proceeding further.
if not self.train_instances:
raise ValueError(f"No training instances collected from {self._train_data_path}")
if not self.used_params:
raise ValueError("Model has no parameters with non-zero gradients")
outputs: List[InterpretOutput] = []
for test_idx, test_instance in enumerate(Tqdm.tqdm(test_instances, desc="test instances")):
test_batch = Batch([test_instance])
test_batch.index_instances(self.vocab)
test_tensor_dict = move_to_device(test_batch.as_tensor_dict(), self.device)
# Prepare model for loss and gradient calculations.
self.model.eval()
self.model.zero_grad()
# Compute loss with respect to the test instance.
test_output_dict = self.model(**test_tensor_dict)
test_loss = test_output_dict["loss"]
test_loss_float = test_loss.detach().item()
# Get the (parameter) gradients with respect to the test loss.
test_grads = autograd.grad(test_loss, self.used_params)
# Sanity check.
assert len(test_grads) == len(self.used_params)
# Get influence scores.
influence_scores = torch.zeros(len(self.train_instances))
for idx, score in enumerate(
self._calculate_influence_scores(test_instance, test_loss_float, test_grads)
):
influence_scores[idx] = score
# Gather top k.
top_k_scores, top_k_indices = torch.topk(influence_scores, k)
top_k = self._gather_instances(top_k_scores, top_k_indices)
outputs.append(
InterpretOutput(
test_instance=test_instance,
loss=test_loss_float,
top_k=top_k,
)
)
return outputs
def _gather_instances(
self, scores: torch.Tensor, indices: torch.Tensor
) -> List[InstanceInfluence]:
outputs: List[InstanceInfluence] = []
for score, idx in zip(scores, indices):
instance, loss, _ = self.train_instances[idx]
outputs.append(InstanceInfluence(instance=instance, loss=loss, score=score.item()))
return outputs
def _gather_train_instances_and_compute_gradients(self) -> None:
logger.info(
"Gathering training instances and computing gradients. "
"The result will be cached so this only needs to be done once."
)
self._train_instances = []
self.model.train()
for instance in Tqdm.tqdm(
self._train_loader.iter_instances(), desc="calculating training gradients"
):
batch = Batch([instance])
batch.index_instances(self.vocab)
tensor_dict = move_to_device(batch.as_tensor_dict(), self.device)
self.model.zero_grad()
# Compute loss with respect to the test instance.
output_dict = self.model(**tensor_dict)
loss = output_dict["loss"]
if self._used_params is None or self._used_param_names is None:
self._used_params = []
self._used_param_names = []
# we only know what parameters in the models requires gradient after
# we do the first .backward() and we store those used parameters
loss.backward(retain_graph=True)
for name, param in self.model.named_parameters():
if param.requires_grad and param.grad is not None:
self._used_params.append(param)
self._used_param_names.append(name)
# Get gradients.
grads = autograd.grad(loss, self._used_params)
# Sanity check.
assert len(grads) == len(self._used_params)
self._train_instances.append(
InstanceWithGrads(instance=instance, loss=loss.detach().item(), grads=grads)
)
def _calculate_influence_scores(
self, test_instance: Instance, test_loss: float, test_grads: Sequence[torch.Tensor]
) -> List[float]:
"""
Required to be implemented by subclasses.
Calculates the influence scores of `self.train_instances` with respect to
the given `test_instance`.
"""
raise NotImplementedError