-
Notifications
You must be signed in to change notification settings - Fork 0
/
calculate_interpretations.py
383 lines (328 loc) · 12.1 KB
/
calculate_interpretations.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
DESC='''
Code to calculate the interpretations using IG or LIME for all candidates
for a given model,dataset and storing for future use
'''
import warnings
warnings.filterwarnings("ignore")
import torch
from copy import deepcopy
from transformers import AutoModelForSequenceClassification
from datasets import load_dataset
from transformers import AutoTokenizer
from captum.attr import LayerIntegratedGradients
from captum.attr import LayerGradientXActivation
from captum.attr import visualization as viz
from lime.lime_text import LimeTextExplainer
from textattack.models.wrappers import HuggingFaceModelWrapper
from textattack.datasets import HuggingFaceDataset
from textattack.attack_recipes import TextFoolerJin2019
from textattack.shared import AttackedText
import matplotlib.pyplot as plt
from scipy.stats import spearmanr
import pickle
import argparse
import numpy as np
from matplotlib import collections
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(device)
model = None
tokenizer = None
def get_interpret_ig(x,l,funct,lig):
inp = torch.LongTensor([tokenizer.encode(x,truncation=True)]).to(device)
label = torch.LongTensor([l]).to(device)
bsl = torch.LongTensor([0]*inp.size()[1]).unsqueeze(0).to(device)
attributions,delta = lig.attribute(inputs=inp,
baselines=bsl,
# layer_baselines=torch.Tensor([0]),
n_steps = 50,
target = label,
return_convergence_delta=True
)
atts = attributions.sum(dim=-1).squeeze(0)
atts = atts / torch.norm(atts)
f = tokenizer.convert_ids_to_tokens(tokenizer.encode(x,truncation=True))
f, atts = funct(f,atts.detach().cpu().numpy().tolist())
return atts,f
def get_interpret_lime(inp,l=None,explainer=None):
exp = explainer.explain_instance(inp, calculate_lime, num_samples=500, num_features=500)
words = exp.as_list()[:]
att = []
for i in exp.as_map():
att = sorted(exp.as_map()[i])
att = [i[1] for i in att]
att = torch.Tensor(att)
maps = exp.as_map()[1]
# print(words)
m = {}
for i in range(len(maps)):
m[maps[i][0]] = words[i][0]
w = [0]*len(m)
for i in m:
w[i] = m[i]
assert len(w) == len(att)
return att,w
def combine_words_distilbert_average(broken,atts):
formed = []
i = 0
at = []
while i < len(broken):
j = i+1
temp = broken[i]
cnt=1
at.append(atts[i])
while j < len(broken) and (broken[j]).startswith("#"):
temp += broken[j].split("##")[-1]
at[-1] += atts[j]
j+=1
cnt+=1
at[-1] /= cnt
formed.append(temp)
i = j
assert len(at) == len(formed)
return formed,torch.Tensor(at)
def combine_words_disilbert_minmax(broken,atts):
formed = []
i = 0
at = []
while i < len(broken):
j = i+1
temp = broken[i]
cnt=1
at.append(atts[i])
track = [atts[i]]
while j < len(broken) and (broken[j]).startswith("#"):
temp += broken[j].split("##")[-1]
# at[-1] += atts[j]
track.append(atts[j])
j+=1
cnt+=1
at[-1] = obj(track)
formed.append(temp)
i = j
assert len(at) == len(formed)
return formed,torch.Tensor(at)
def combine_words_roberta_average(broken,atts):
formed = []
i = 0
at = []
while i < len(broken):
j = i+1
temp = broken[i].split("Ġ")[-1]
cnt=1
at.append(atts[i])
while j < len(broken) and not (broken[j]).startswith("Ġ"):
temp += broken[j]
at[-1] += atts[j]
j+=1
cnt+=1
at[-1] /= cnt
formed.append(temp)
i = j
assert len(at) == len(formed)
return formed,torch.Tensor(at).to(device)
def combine_words_roberta_minmax(broken,atts):
formed = []
i = 0
at = []
while i < len(broken):
j = i+1
temp = broken[i].split("Ġ")[-1]
cnt=1
at.append(atts[i])
track = [atts[i]]
while j < len(broken) and not (broken[j]).startswith("Ġ"):
temp += broken[j]
# at[-1] += atts[j]
track.append(atts[j])
j+=1
cnt+=1
# at[-1] /= cnt
at[-1] = obj(track)
formed.append(temp)
i = j
assert len(at) == len(formed)
return formed,torch.Tensor(at)
def combine_words_lime_roberta_break(broken):
formed = []
i = 0
at = []
while i < len(broken):
j = i+1
temp = broken[i].split("Ġ")[-1]
cnt=1
while j < len(broken) and not (broken[j]).startswith("Ġ"):
temp += broken[j]
j+=1
cnt+=1
formed.append(temp)
i = j
return formed
def combine_words_lime_distil_break(broken):
formed = []
i = 0
at = []
while i < len(broken):
j = i+1
temp = broken[i]
cnt=1
while j < len(broken) and (broken[j]).startswith("#"):
temp += broken[j].split("##")[-1]
j+=1
cnt+=1
formed.append(temp)
i = j
return formed
def obj(track):
mx = max(track)
mn = min(track)
if abs(mn)>abs(mx):
return mn
else:
return mx
def break_string(x):
f = tokenizer.tokenize(x)
return f
def breaker_distilbert(x):
x = x.lower()
p = combine_words_lime_distil_break(break_string(x))
return p
def breaker_roberta(x):
x = x.lower()
p = combine_words_lime_roberta_break(break_string(x))
return p
def forward_lig(x):
return model(x)[0]
def calculate_lime(inp):
labels = []
for i in inp:
labels.append(model(torch.LongTensor([tokenizer.encode(i,truncation=True)]).to(device))[0].detach().cpu().numpy()[0])
return torch.Tensor(labels).cpu().numpy()
def main():
parser=argparse.ArgumentParser(description=DESC, formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument("-m","--model",required=True, help="Name of model")
parser.add_argument("-d","--dataset",required=True, help="Name of dataset")
parser.add_argument("-s","--split",required=True, help="Split of dataset")
parser.add_argument("-num","--number",required=False, type=int, default=-1, help="Number of samples from dataset")
parser.add_argument("-c","--candidatefolder",required=False, default='./candidates/',help="Folder to load candidates")
parser.add_argument("-mf","--modelfolder",required=False, default='./models/',help="Folder to load models from")
parser.add_argument("-if","--interpretfolder",required=False, default='./interpretations/',help="Folder to store interpretations")
parser.add_argument("-im","--interpretmethod",required=True,help="Interpretation Method (IG/LIME)")
parser.add_argument("-oif","--originalinterpretfolder",required=False,default='./interpretations/original_sentences/',help="Folder to store original interpretations")
args = parser.parse_args()
global model
global tokenizer
if args.model == "distilbert":
if args.dataset == "sst2":
model = AutoModelForSequenceClassification.from_pretrained(args.modelfolder+"distilbert-base-uncased-SST-2-glue^sst2-2021-01-11-09-08-54-383533")
tokenizer = AutoTokenizer.from_pretrained(args.modelfolder+"distilbert-base-uncased-SST-2-glue^sst2-2021-01-11-09-08-54-383533")
elif args.dataset == "agnews":
model = AutoModelForSequenceClassification.from_pretrained("textattack/distilbert-base-uncased-ag-news")
tokenizer = AutoTokenizer.from_pretrained("textattack/distilbert-base-uncased-ag-news")
elif args.dataset == "imdb":
model = AutoModelForSequenceClassification.from_pretrained("textattack/distilbert-base-uncased-imdb")
tokenizer = AutoTokenizer.from_pretrained("textattack/distilbert-base-uncased-imdb")
elif args.model == "roberta":
if args.dataset == "sst2":
model = AutoModelForSequenceClassification.from_pretrained("textattack/roberta-base-SST-2")
tokenizer = AutoTokenizer.from_pretrained("textattack/roberta-base-SST-2")
elif args.dataset == "agnews":
model = AutoModelForSequenceClassification.from_pretrained("textattack/roberta-base-ag-news")
tokenizer = AutoTokenizer.from_pretrained("textattack/roberta-base-ag-news")
elif args.dataset == "imdb":
model = AutoModelForSequenceClassification.from_pretrained("textattack/roberta-base-imdb")
tokenizer = AutoTokenizer.from_pretrained("textattack/roberta-base-imdb")
elif args.model == "bert-adv":
if args.dataset == "sst2":
model = AutoModelForSequenceClassification.from_pretrained(args.modelfolder+"bert-sst2-adv")
tokenizer = AutoTokenizer.from_pretrained(args.modelfolder+"bert-sst2-adv")
elif args.dataset == "agnews":
model = AutoModelForSequenceClassification.from_pretrained(args.modelfolder+"bert-ag-adv")
tokenizer = AutoTokenizer.from_pretrained(args.modelfolder+"bert-ag-adv")
elif args.dataset == "imdb":
model = AutoModelForSequenceClassification.from_pretrained(args.modelfolder+"bert-imdb-adv")
tokenizer = AutoTokenizer.from_pretrained(args.modelfolder+"bert-imdb-adv")
model.to(device)
model.eval()
if args.dataset == "sst2":
ta_dataset = HuggingFaceDataset("glue", "sst2", args.split)
class_names = ['positive', 'negative']
keyword = "sentence"
elif args.dataset == "agnews":
ta_dataset = HuggingFaceDataset("ag_news", "test",split=args.split)
class_names = ["World", "Sports","Business","Sci/Tech"]
keyword = "text"
elif args.dataset == "imdb":
ta_dataset = HuggingFaceDataset("imdb", split=args.split)
class_names = ['positive', 'negative']
keyword = "text"
if args.interpretmethod == "IG":
get_interpret = get_interpret_ig
if args.model == "distilbert":
lig = LayerIntegratedGradients(forward_lig, model.distilbert.embeddings)
comb_word_func = combine_words_disilbert_minmax
elif args.model == "roberta":
lig = LayerIntegratedGradients(forward_lig, model.roberta.embeddings)
comb_word_func = combine_words_roberta_minmax
elif args.model == "bert-adv":
lig = LayerIntegratedGradients(forward_lig, model.bert.embeddings)
comb_word_func = combine_words_disilbert_minmax
elif args.interpretmethod == "LIME":
get_interpret = get_interpret_lime
if args.model == "distilbert":
explainer = LimeTextExplainer(class_names=class_names, split_expression = breaker_distilbert)
elif args.model == "roberta":
explainer = LimeTextExplainer(class_names=class_names, split_expression = breaker_roberta)
elif args.model == "bert-adv":
explainer = LimeTextExplainer(class_names=class_names, split_expression = breaker_distilbert)
candidate_name = str(args.candidatefolder)+"candidates-"+str(args.dataset)+"-"+str(args.model)+'.pkl'
print("Loading from: ",candidate_name)
with open(candidate_name, 'rb') as f:
fin = pickle.load(f)
if args.number == -1:
args.number = len(fin)
original_dataset_interpret = []
save_list = []
ids = range(args.number)
for fn,idx in zip(fin,ids):
print("Calculating on %d of %d total sentences" %(idx,len(ids)))
try:
s = []
original_interpret = None
for i in range(len(fn)):
c = []
for j in range(len(fn[i])):
if torch.argmax(model(torch.LongTensor([tokenizer.encode(fn[i][j].attacked_text.text,truncation=True)]).to(device))[0][0]).item() == ta_dataset[idx][1]:
try:
if args.interpretmethod == "IG":
inter = get_interpret_ig(fn[i][j].attacked_text.text.lower(),ta_dataset[idx][1],comb_word_func,lig)
if original_interpret == None:
original_interpret = get_interpret_ig(ta_dataset[idx][0][keyword].lower(),ta_dataset[idx][1],comb_word_func,lig)
elif args.interpretmethod == "LIME":
inter = get_interpret_lime(fn[i][j].attacked_text.text.lower(),ta_dataset[idx][1],explainer)
if original_interpret == None:
original_interpret = get_interpret_lime(ta_dataset[idx][0][keyword].lower(),ta_dataset[idx][1],explainer)
except:
inter=None
print("error on a candidate, skipped..")
pass
print("Calculated %d of %d candidates"%(j,len(fn[i])))
print("Calculating on %d of %d total sentences" %(idx,len(ids)))
c.append([fn[i][j].attacked_text.text,inter])
s.append(c)
save_list.append(s)
original_dataset_interpret.append([ta_dataset[idx][0][keyword],original_interpret])
original_interpret = None
except:
print("Sentence Skipped completely: ",idx)
save_list.append([])
original_dataset_interpret.append([])
print(save_list)
print(original_dataset_interpret)
interpretation_name = args.interpretfolder+'interpretations-'+str(args.dataset)+'-'+str(args.model)+'-'+args.interpretmethod+"-"+str(args.number)+'.pkl'
original_interpretation_name = args.originalinterpretfolder+'original-interpretations-'+str(args.dataset)+'-'+str(args.model)+'-'+args.interpretmethod+"-"+str(args.number)+'.pkl'
print("Saving to: ",interpretation_name)
with open(interpretation_name, 'wb') as f:
pickle.dump(save_list,f)
with open(original_interpretation_name, 'wb') as f:
pickle.dump(original_dataset_interpret,f)
main()