-
Notifications
You must be signed in to change notification settings - Fork 0
/
detect.py
650 lines (522 loc) · 30.7 KB
/
detect.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
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
# detecting adversarial examples using Frequency-guided word substitutions (FGWS),
# MultiDistance Representation Ensemble Method (MDRE, MDRE_bert, MDRE_roberta, MDRE_xlnet, MDRE_bart),
# adapted Local Intrinsic Dimensionality (lid), and a language model
import argparse
import os
import re
import random
from math import ceil
import numpy as np
import pandas as pd
import torch
import torch.nn.functional as F
from nltk.corpus import wordnet
from scipy.spatial import distance
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
from spacy.lang.en import English
from tqdm import tqdm
from transformers import BertTokenizer, TransfoXLTokenizer, TransfoXLLMHeadModel
from models import Classifier
from utils import IMDBDataset, MnliDataset
from utils import bert_params, roberta_params, xlnet_params, bart_params
import glove_utils
def get_emb_preds(model, tokenizer, texts):
"""
obtain embeddings, predictions of texts from 'model', and hidden representations from the BERT model.
:param model: a model used for get embeddings and predictions.
:param tokenizer: the model's tokenizer
:param texts: texts
:return: texts' embeddings, predictions, softmax, and hidden representations
"""
model.eval()
n_batch = ceil(len(texts) / batch_size)
embeddings = []
preds = []
softmax_list = []
b_hidden_embeddings = []
for batch in range(n_batch):
begin_idx = batch_size * batch
end_idx = min(batch_size * (batch + 1), len(texts))
b_texts = texts[begin_idx: end_idx]
text = np.asarray(b_texts)[:, 0].tolist()
text_pair = np.asarray(b_texts)[:, 1].tolist()
inputs = tokenizer(text=[i if isinstance(i, str) else '' for i in text],
text_pair=[i if isinstance(i, str) else '' for i in text_pair] if text_pair[0] else None,
return_tensors='pt',
max_length=max_length,
truncation=True,
padding='max_length').to(device)
with torch.no_grad():
logits, pooler_output, hidden_states = model(inputs['input_ids'], inputs['attention_mask'])
embeddings.append(pooler_output.cpu().numpy())
preds.append(torch.argmax(logits, dim=1).cpu().numpy())
softmax_list.append(F.softmax(logits, dim=1).cpu().numpy())
if 'bert-base' in model.model.config._name_or_path:
b_hidden_embeddings.append(torch.stack(hidden_states[1:])[:, :, 0, :].cpu().numpy().transpose((1, 0, 2)))
hidden_embeddings = np.concatenate(b_hidden_embeddings, axis=0) if b_hidden_embeddings else b_hidden_embeddings
return np.concatenate(embeddings, axis=0), np.concatenate(preds, axis=0), np.concatenate(softmax_list, axis=0), \
hidden_embeddings
def merge_and_generate_labels(X_pos, X_neg):
"""
merge positive and negative examples and generate labels
:param X_pos: positive samples
:param X_neg: negative samples
:return: X: merged samples, 2D ndarray
y: generated labels (0/1): 2D ndarray same size as X
"""
X_pos = np.asarray(X_pos, dtype=np.float32)
print('X_pos: ', X_pos.shape)
X_pos = X_pos.reshape((X_pos.shape[0], -1))
X_neg = np.asarray(X_neg, dtype=np.float32)
print('X_neg: ', X_neg.shape)
X_neg = X_neg.reshape((X_neg.shape[0], -1))
X = np.concatenate((X_pos, X_neg))
y = np.concatenate((np.ones(X_pos.shape[0]), np.zeros(X_neg.shape[0])))
y = y.reshape((X.shape[0], 1))
return X, y
def load_test_and_adv(attack_class, folder):
"""
load test and adversarial examples generated by generate_adv.py
:param attack_class: typo, synonym, or seas
:param folder: a directory containing files of test and adversarial examples
:return: a DataFrame that contains info of test and adversarial examples
"""
patten = re.compile(re.escape(attack_class) + r'_adv_\d+.csv')
file_names = [f for f in os.listdir(folder) if re.search(patten, f)]
file_names.sort()
test_adv = []
for fname in file_names:
file = pd.read_csv(os.path.join(folder, fname))
test_adv.append(file)
return pd.concat(test_adv, ignore_index=True).fillna(np.nan).replace([np.nan], [None])
def logistic_detector(X, y, random_seed):
""" A Logistic Regression classifier which returns its accuracy. """
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=random_seed)
# Build detector
lr = LogisticRegression().fit(X_train, y_train)
# Evaluate detector
y_pred = lr.predict(X_test)
# AUC
acc = accuracy_score(y_test, y_pred)
print('Accuracy: ', acc)
def mle_batch(data, batch, k):
"""
Obtaining LID for a batch
:param data: a hidden embedding of all training examples
:param batch: a batch of data for calculating LID
:param k: number of neighbors used
:return: LID for batch
"""
data = np.asarray(data, dtype=np.float32)
batch = np.asarray(batch, dtype=np.float32)
k = min(k, len(data) - 1)
f = lambda v: - k / np.sum(np.log(v / v[-1]))
a = distance.cdist(batch, data)
a = np.apply_along_axis(np.sort, axis=1, arr=a)[:, 0:k]
a = np.apply_along_axis(f, axis=1, arr=a)
return a
def get_lids_random_batch(X, X_test, X_adv, k, batch_size=32):
"""
Calculating LID through batches
:param X: hidden embeddings of training examples
:param X_test: hidden embeddings of normal test examples
:param X_adv: hidden embeddings of adversarial examples
:param k: the number of nearest neighbors used for LID
:param batch_size: default 32
:return: lids: LID of normal examples of shape (num_examples, lid_dim)
lids_adv: LID of adverarial examples of shape (num_examples, lid_dim)
"""
lid_dim = 12
print('Number of layers to estimate:', lid_dim)
def estimate(i_batch):
adv_start = np.minimum(len(X_adv) - 1, i_batch * batch_size)
adv_end = np.minimum(len(X_adv) - 1, (i_batch + 1) * batch_size)
test_start = i_batch * batch_size
test_end = np.minimum(len(X_test) - 1, (i_batch + 1) * batch_size)
test_n_feed = test_end - test_start
adv_n_feed = adv_end - adv_start
lid_batch = np.zeros(shape=(test_n_feed, lid_dim))
lid_batch_adv = np.zeros(shape=(adv_n_feed, lid_dim))
for i in range(lid_dim):
train_X = X[:, i, :].reshape(X.shape[0], -1)
X_act = X_test[test_start: test_end, i, :].reshape((test_n_feed, -1))
lid_batch[:, i] = mle_batch(train_X, X_act, k=k)
if adv_n_feed > 0:
X_adv_act = X_adv[adv_start: adv_end, i, :].reshape((adv_n_feed, -1))
lid_batch_adv[:, i] = mle_batch(train_X, X_adv_act, k=k)
return lid_batch, lid_batch_adv
lids = []
lids_adv = []
n_batches = int(np.ceil(X_test.shape[0] / float(batch_size)))
for i_batch in tqdm(range(n_batches)):
lid_batch, lid_batch_adv = estimate(i_batch)
lids.extend(lid_batch)
lids_adv.extend(lid_batch_adv)
lids = np.asarray(lids, dtype=np.float32)
lids_adv = np.asarray(lids_adv, dtype=np.float32)
return lids, lids_adv
def get_lid(X, X_test, X_adv, k, batch_size=100):
"""
Calculating LID and prepare data for the detection classifier
:param X: hidden embeddings of training examples
:param X_test: hidden embeddings of test examples
:param X_adv: hidden embeddings of adversarial examples
:param k: neighbors used for LID
:param batch_size: batch size used for the function: get_lids_random_batch
:return: X(LID) and y for the detection classifier
"""
print('Extract local intrinsic dimensionality: k = %s' % k)
lids_normal, lids_adv = get_lids_random_batch(X, X_test, X_adv, k, batch_size)
print('lids_normal:', lids_normal.shape)
print('lids_adv:', lids_adv.shape)
lids_pos = lids_adv
lids_neg = lids_normal
artificats, labels = merge_and_generate_labels(lids_pos, lids_neg)
return artificats, labels
def get_words_frequency(texts, text_pairs):
"""get words frequency according to their occurance in training set for fgws."""
nlp = English()
words_freq = {}
for text, text_pair in zip(texts, text_pairs):
example = text + ' ' + text_pair if text_pair else text
for word in [t.text.lower() for t in nlp.tokenizer(example.strip())]:
try:
words_freq[word] += 1
except KeyError:
words_freq[word] = 1
return words_freq
def transform(text, words_freq, freq_threshold, words_list, distance_matrix, missed_words):
"""replace words which have lower frequency than the frequency threshold for fgws"""
nlp = English()
replaced_list = []
for word in [t.text.lower() for t in nlp.tokenizer(text.strip())]:
if word in words_freq.keys() and words_freq[word] < freq_threshold:
neighbors = []
for synset in wordnet.synsets(word):
for w in synset.lemmas():
neighbors.append(w.name().replace("_", " "))
emb_neighbours = []
if word in words_list and words_list.index(word) < 20000 and words_list.index(word) not in missed_words:
neighbours_ids, _ = glove_utils.pick_most_similar_words(words_list.index(word), distance_matrix, 10, 0.5)
emb_neighbours = [words_list[id] for id in neighbours_ids]
val_neighbors = [w for w in neighbors + emb_neighbours if w in words_freq.keys() and
words_freq[w] > words_freq[word]]
replaced_list.append(random.choice(val_neighbors) if len(val_neighbors) > 0 else word)
else:
replaced_list.append(word)
return ' '.join(replaced_list)
def tune_gamma(orig_preds, orig_probs, model, tokenizer, dataset, words_freq, freq_threshold, words_list,
distance_matrix, missed_words):
"""set differency threshold for fgws, if the difference between the predictions of a replaced words example and its
corresponding unreplaced words example is bigger than this threshold, this original example is regard as an
adversarial example.
This threshold is the 90%-th prediction difference between words substituted validation set and validation set."""
differneces = []
replaced_valid_text, replaced_valid_text_pair = [], []
for text, text_pair in zip(dataset.valid_text, dataset.valid_text_pair):
replaced_valid_text.append(transform(text, words_freq, freq_threshold, words_list, distance_matrix, missed_words))
replaced_valid_text_pair.append(transform(text_pair, words_freq, freq_threshold, words_list, distance_matrix,
missed_words) if text_pair else text_pair)
_, replaced_preds, replaced_probs, _ = get_emb_preds(model, tokenizer, list(zip(replaced_valid_text, replaced_valid_text_pair)))
for orig_prob, orig_pred, replaced_prob, replaced_pred in zip(orig_probs, orig_preds, replaced_probs,
replaced_preds):
differneces.append(max(0, orig_prob[orig_pred] - replaced_prob[orig_pred]))
differneces.sort()
p = 0.9 * len(differneces)
thr_idx = int(p) - 1 if p.is_integer() else int(p)
gamma = differneces[thr_idx]
return gamma
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--dataset-name', type=str, default=None, required=True, choices=['IMDB', 'Mnli'],
help='detecting which test set`s adversarial examples.')
parser.add_argument('--dataset-path', type=str, default=None, required=True,
choices=['./data/aclImdb', './data/multinli_1.0'], help='The directory of the dataset.')
parser.add_argument('--attack-class', type=str, default=None, required=True, choices=['typo', 'synonym', 'seas'],
help='Attack method used to generate adversarial examples.')
parser.add_argument('--max-length', type=int, default=None, required=True, choices=[512, 256, 128],
help='The maximum sequences length.')
parser.add_argument('--batch-size', type=int, default=32, help='Batch size for transformer models.')
parser.add_argument('--random-seed', type=int, default=38, help='random seed value.')
parser.add_argument('--detect', type=str, default=None, required=True,
choices=['mdre', 'mdre_bert', 'mdre_roberta', 'mdre_xlnet', 'mdre_bart', 'lid', 'fgws', 'language_model'],
help='detection method')
parser.add_argument('--k-nearest', type=int, default=-1, required=False,
help='Number of nearest neighbours to use for lid.')
parser.add_argument('--fp-threshold', type=float, default=0.9,
help='for FGWS detection to calculate gamma, false positive threshold.')
args = parser.parse_args()
batch_size = args.batch_size
max_length = args.max_length
# set a random seed value all over the place to make this reproducible.
random.seed(args.random_seed)
np.random.seed(args.random_seed)
torch.manual_seed(args.random_seed)
torch.cuda.manual_seed_all(args.random_seed)
# check if there's a GPU
if torch.cuda.is_available():
# set the device to the GPU.
device = torch.device('cuda')
print('We will use the GPU:', torch.cuda.get_device_name(0))
else:
print('No GPU available, using the CPU instead.')
device = torch.device('cpu')
# load dataset
data_processors = {
'Mnli': MnliDataset,
'IMDB': IMDBDataset
}
dataset = data_processors[args.dataset_name](args.dataset_path, 0.2)
output_dir = os.path.join('./output', args.dataset_name)
# load test and adversarial examples
test_adv_folder = os.path.join(output_dir, 'bert', args.attack_class)
test_adv = load_test_and_adv(args.attack_class, test_adv_folder)
adv_texts = test_adv['adv_text'].to_numpy()
adv_preds = test_adv['adv_pred'].to_numpy()
indices = [i for i, text in enumerate(adv_texts) if adv_preds[i] is not None]
test_texts = test_adv['orig_text'].to_numpy()[indices]
test_text_pairs = test_adv['orig_text_pair'].to_numpy()[indices]
adv_texts = adv_texts[indices]
adv_text_pairs = test_adv['adv_text_pair'].to_numpy()[indices]
test_y = test_adv['orig_label'].to_numpy()[indices]
test_preds = test_adv['orig_pred'].to_numpy()[indices]
adv_preds = adv_preds[indices]
# load bert model and tokenizer
bert_model = Classifier(dataset.num_labels, **bert_params)
bert_model.load_state_dict(torch.load(os.path.join(output_dir, 'bert/model.pt'), map_location=device))
bert_model.to(device)
bert_tokenizer = BertTokenizer.from_pretrained(os.path.join(output_dir, 'bert'))
if args.detect in ('mdre_bert', 'mdre_roberta', 'mdre_xlnet', 'mdre_bart'):
X = []
y = []
_, train_preds, _, _ = get_emb_preds(bert_model, bert_tokenizer,
list(zip(dataset.train_text, dataset.train_text_pair)))
# load model and tokenizer
model_name = args.detect.split('_')[-1]
model_params = globals()[model_name + '_params']
model = Classifier(dataset.num_labels, **model_params)
model.load_state_dict(torch.load(os.path.join(output_dir, model_name, 'model.pt'), map_location=device))
model.to(device)
tokenizer = model_params['tokenizer_class'].from_pretrained(os.path.join(output_dir, model_name))
for label in range(dataset.num_labels):
# find train, test, adversarial examples with same predictions
train_indices = np.where(np.asarray(train_preds) == label)[0]
sub_train_texts = [text for ind, text in enumerate(dataset.train_text) if ind in train_indices]
sub_train_text_pairs = [text for ind, text in enumerate(dataset.train_text_pair) if ind in train_indices]
test_indices = np.where(np.asarray(test_preds) == label)[0]
sub_test_texts = [text for ind, text in enumerate(test_texts) if ind in test_indices]
sub_test_text_pairs = [text for ind, text in enumerate(test_text_pairs) if ind in test_indices]
adv_indices = np.where(np.asarray(adv_preds) == label)[0]
sub_adv_texts = [text for ind, text in enumerate(adv_texts) if ind in adv_indices]
sub_adv_text_pairs = [text for ind, text in enumerate(adv_text_pairs) if ind in adv_indices]
part_X = []
part_y = []
# get training, testing, and adversarial examples embeddings
train_embeddings, _, _, _ = get_emb_preds(model, tokenizer,
list(zip(sub_train_texts, sub_train_text_pairs)))
test_embeddings, _, _, _ = get_emb_preds(model, tokenizer, list(zip(sub_test_texts, sub_test_text_pairs)))
adv_embeddings, _, _, _ = get_emb_preds(model, tokenizer, list(zip(sub_adv_texts, sub_adv_text_pairs)))
part_X += np.amin(distance.cdist(test_embeddings, train_embeddings, metric='euclidean'), axis=1).tolist()
part_X += np.amin(distance.cdist(adv_embeddings, train_embeddings, metric='euclidean'), axis=1).tolist()
part_y = [1] * len(test_embeddings) + [0] * len(adv_embeddings)
emb_dir = os.path.join(output_dir, model_name, args.attack_class)
if not os.path.exists(emb_dir):
os.makedirs(emb_dir)
np.save(os.path.join(emb_dir, str(label) + 'train_emb.npy'), train_embeddings)
np.save(os.path.join(emb_dir, str(label) + 'test_emb.npy'), test_embeddings)
np.save(os.path.join(emb_dir, str(label) + 'adv_emb.npy'), adv_embeddings)
if len(X) == 1:
X[0] += part_X
else:
X.append(part_X)
y += part_y
logistic_detector(np.asarray(X).T, np.asarray(y).T, args.random_seed)
elif args.detect == 'mdre':
X = []
y = []
_, train_preds, _, _ = get_emb_preds(bert_model, bert_tokenizer,
list(zip(dataset.train_text, dataset.train_text_pair)))
for label in range(dataset.num_labels):
# find train, test, adversarial examples with same predictions
train_indices = np.where(np.asarray(train_preds) == label)[0]
sub_train_texts = [text for ind, text in enumerate(dataset.train_text) if ind in train_indices]
sub_train_text_pairs = [text for ind, text in enumerate(dataset.train_text_pair) if ind in train_indices]
test_indices = np.where(np.asarray(test_preds) == label)[0]
sub_test_texts = [text for ind, text in enumerate(test_texts) if ind in test_indices]
sub_test_text_pairs = [text for ind, text in enumerate(test_text_pairs) if ind in test_indices]
adv_indices = np.where(np.asarray(adv_preds) == label)[0]
sub_adv_texts = [text for ind, text in enumerate(adv_texts) if ind in adv_indices]
sub_adv_text_pairs = [text for ind, text in enumerate(adv_text_pairs) if ind in adv_indices]
model_classes = ['bert', 'roberta', 'xlnet', 'bart']
for ind, model_name in enumerate(model_classes):
if model_name == 'bert':
model_params = bert_params
elif model_name == 'roberta':
model_params = roberta_params
elif model_name == 'xlnet':
model_params = xlnet_params
elif model_name == 'bart':
model_params = bart_params
part_X = []
part_y = []
# load model and tokenizer
model = Classifier(dataset.num_labels, **model_params)
model.load_state_dict(torch.load(os.path.join(output_dir, model_name, 'model.pt'), map_location=device))
model.to(device)
tokenizer = model_params['tokenizer_class'].from_pretrained(os.path.join(output_dir, model_name))
# get train, testing, and adversarial examples' embeddings
train_embeddings, _, _, _ = get_emb_preds(model, tokenizer,
list(zip(sub_train_texts, sub_train_text_pairs)))
test_embeddings, _, _, _ = get_emb_preds(model, tokenizer,
list(zip(sub_test_texts, sub_test_text_pairs)))
adv_embeddings, _, _, _ = get_emb_preds(model, tokenizer, list(zip(sub_adv_texts, sub_adv_text_pairs)))
part_X += np.amin(distance.cdist(test_embeddings, train_embeddings, metric='euclidean'),
axis=1).tolist()
part_X += np.amin(distance.cdist(adv_embeddings, train_embeddings, metric='euclidean'), axis=1).tolist()
part_y = [1] * len(test_embeddings) + [0] * len(adv_embeddings)
emb_dir = os.path.join(output_dir, model_name, args.attack_class)
if not os.path.exists(emb_dir):
os.makedirs(emb_dir)
np.save(os.path.join(emb_dir, str(label) + 'train_emb.npy'), train_embeddings)
np.save(os.path.join(emb_dir, str(label) + 'test_emb.npy'), test_embeddings)
np.save(os.path.join(emb_dir, str(label) + 'adv_emb.npy'), adv_embeddings)
if len(X) == len(model_classes):
X[ind] += part_X
else:
X.append(part_X)
y += part_y
logistic_detector(np.asarray(X).T, np.asarray(y).T, args.random_seed)
elif args.detect == 'lid':
# set the number of nearest neighbours to use
if args.k_nearest == -1:
k_vec = np.arange(10, 41, 2)
k_vec = np.concatenate([k_vec, [100, 1000]])
else:
k_vec = [args.k_nearest]
# get hidden embeddings from BERT model of train, testing, and adversarial examples
_, _, _, train_hidden_embeddings = get_emb_preds(bert_model, bert_tokenizer,
list(zip(dataset.train_text, dataset.train_text_pair)))
_, _, _, test_hidden_embeddings = get_emb_preds(bert_model, bert_tokenizer,
list(zip(test_texts, test_text_pairs)))
_, _, _, adv_hidden_embeddings = get_emb_preds(bert_model, bert_tokenizer,
list(zip(adv_texts, adv_text_pairs)))
for k in tqdm(k_vec):
print('Extracting LID characteristics for k={}'.format(k))
X, y = get_lid(train_hidden_embeddings, test_hidden_embeddings, adv_hidden_embeddings, k, 100)
logistic_detector(X, y, args.random_seed)
elif args.detect == 'fgws':
vocab_file = os.path.join(output_dir, 'bert/synonym/aux_files/vocab.vocab')
distance_matrix_file = os.path.join(output_dir, 'bert/synonym/aux_files/dist_counter.npy')
missed_embedding_file = os.path.join(output_dir, 'bert/synonym/aux_files/missed_embeddings_counter.npy')
try:
with open(vocab_file, 'r', encoding='utf-8') as f:
words_list = f.read().split('\n')
distance_matrix = np.load(distance_matrix_file)
missed_words = np.load(missed_embedding_file)
except FileNotFoundError:
print("Couldn't find the vocabulary file, please run get_neighbours.py first.")
words_freq = get_words_frequency(dataset.train_text, dataset.train_text_pair)
_, orig_adv_preds, orig_adv_probs, _ = get_emb_preds(bert_model, bert_tokenizer,
list(zip(adv_texts, adv_text_pairs)))
_, orig_test_preds, orig_test_probs, _ = get_emb_preds(bert_model, bert_tokenizer,
list(zip(test_texts, test_text_pairs)))
_, orig_valid_preds, orig_valid_probs, _ = get_emb_preds(bert_model, bert_tokenizer,
list(zip(dataset.valid_text, dataset.valid_text_pair)))
for delta_thr in tqdm(range(0, 110, 10)):
print('delta: ', delta_thr)
corr = 0 # number of adversarial examples that fgws regard as adversarial examples or normal examples
# regard as normal examples
incorr = 0
# set frequency threshold, if a word frequency is lower than this threshold, it will be replaced by a
# semantically similar and higher frequent word.
freq_threshold = np.percentile(sorted(list(words_freq.values())), delta_thr)
print('frequency threshold: ', freq_threshold)
# set difference threshold where prediction difference before and after transform as adversarial examples
diff_threshold = tune_gamma(orig_valid_preds, orig_valid_probs, bert_model, bert_tokenizer, dataset,
words_freq, freq_threshold, words_list, distance_matrix, missed_words)
print('differency threshold: ', diff_threshold)
replaced_adv_texts, replaced_adv_text_pairs = [], []
replaced_test_texts, replaced_test_text_pairs = [], []
for adv_text, adv_text_pair in tqdm(zip(adv_texts, adv_text_pairs)):
replaced_adv_texts.append(transform(adv_text, words_freq, freq_threshold, words_list, distance_matrix,
missed_words))
replaced_adv_text_pairs.append(transform(adv_text_pair, words_freq, freq_threshold, words_list,
distance_matrix, missed_words) if adv_text_pair and
isinstance(adv_text_pair, str)
else adv_text_pair)
_, replaced_adv_preds, replaced_adv_probs, _ = \
get_emb_preds(bert_model, bert_tokenizer, list(zip(replaced_adv_texts, replaced_adv_text_pairs)))
for test_text, test_text_pair in tqdm(zip(test_texts, test_text_pairs)):
replaced_test_texts.append(transform(test_text, words_freq, freq_threshold, words_list,
distance_matrix, missed_words))
replaced_test_text_pairs.append(transform(test_text_pair, words_freq, freq_threshold, words_list,
distance_matrix, missed_words)
if test_text_pair and isinstance(test_text_pair,
str) else test_text_pair)
_, replaced_test_preds, replaced_test_probs, _ = \
get_emb_preds(bert_model, bert_tokenizer, list(zip(replaced_test_texts, replaced_test_text_pairs)))
for orig_adv_pred, orig_adv_prob, replaced_adv_pred, replaced_adv_prob in \
zip(orig_adv_preds, orig_adv_probs, replaced_adv_preds, replaced_adv_probs):
if abs(orig_adv_prob[orig_adv_pred] - replaced_adv_prob[orig_adv_pred]) > diff_threshold:
corr += 1
else:
incorr += 1
for orig_test_pred, orig_test_prob, replaced_test_pred, replaced_test_prob in zip(orig_test_preds,
orig_test_probs,
replaced_test_preds,
replaced_test_probs):
if abs(orig_test_prob[orig_test_pred] - replaced_test_prob[orig_test_pred]) > diff_threshold:
incorr += 1
else:
corr += 1
print('Accuracy: ', corr / (corr + incorr))
elif args.detect == 'language_model':
X = []
y = []
lm_tokenizer = TransfoXLTokenizer.from_pretrained('transfo-xl-wt103')
language_model = TransfoXLLMHeadModel.from_pretrained('transfo-xl-wt103')
# for text, text_pair in zip(test_texts, test_text_pairs):
for ind, (text, text_pair) in enumerate(zip(test_texts, test_text_pairs)):
print(ind)
if isinstance(text, str):
input = lm_tokenizer(text, text_pair, return_tensors='pt') if isinstance(text_pair, str) \
else lm_tokenizer(text, return_tensors='pt')
predictions = language_model(**input)['prediction_scores'].squeeze()
input_ids = input['input_ids'].squeeze().tolist()
score = 1
tmp = [] # for testing
if isinstance(input_ids, list):
for id, idx in enumerate(input_ids[1:]):
score = score * (predictions[id + 1][idx] / torch.mean(predictions[id + 1]).item()).item()
tmp.append((predictions[id + 1][idx] / torch.mean(predictions[id + 1]).item()).item())
# X.append(abs(score))
X.append(score)
y.append(1)
del predictions # try to free cpu memory
test_pd = pd.DataFrame(list(zip(X, y)))
test_pd.to_csv(os.path.join(output_dir, 'bert', args.attack_class, args.dataset_name + '_test_lm.csv'), index=False)
for ind, (text, text_pair) in enumerate(zip(adv_texts, adv_text_pairs)):
print(ind)
if isinstance(text, str):
input = lm_tokenizer(text, text_pair, return_tensors='pt') if isinstance(text_pair, str)\
else lm_tokenizer(text, return_tensors='pt')
predictions = language_model(**input)['prediction_scores'].squeeze()
input_ids = input['input_ids'].squeeze().tolist()
score = 1
tmp = []
if isinstance(input_ids, list):
for id, idx in enumerate(input_ids[1:]):
score = score * (predictions[id + 1][idx] / torch.mean(predictions[id + 1]).item()).item()
tmp.append((predictions[id + 1][idx] / torch.mean(predictions[id + 1]).item()).item())
# X.append(abs(score))
X.append(score)
y.append(0)
del predictions # try to free cpu memory
adv_pd = pd.DataFrame(list(zip(X, y)))
adv_pd.to_csv(os.path.join(output_dir, 'bert', args.attack_class, args.dataset_name + '_adv_lm.csv'), index=False)
scaler = MinMaxScaler()
X = scaler.fit_transform(np.asarray(X).reshape(-1, 1))
logistic_detector(X, np.asarray(y).T, args.random_seed)