-
Notifications
You must be signed in to change notification settings - Fork 26
/
attack.py
284 lines (258 loc) · 11.3 KB
/
attack.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
import os
# import sys
# reload(sys)
# sys.setdefaultencoding("utf-8")
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader
# from torch.autograd import Variable
import argparse
import loaddata
import dataloader
import model
import scoring
import scoring_char
import transformer
import transformer_char
import numpy as np
import pickle
np.random.seed(7)
parser = argparse.ArgumentParser(description='Data')
parser.add_argument('--data', type=int, default=0, metavar='N',
help='data: can be 0,1,2,3,5,6,7 which specify a textdata file')
parser.add_argument('--externaldata', type=str, default='', metavar='S',
help='External database file. Default: Empty string')
parser.add_argument('--model', type=str, default='simplernn', metavar='S',
help='model type(simplernn, charcnn, bilstm). LSTM as default.')
parser.add_argument('--modelpath', type=str, default='models/simplernn_0_bestmodel.dat', metavar='S',
help='model file path')
parser.add_argument('--power', type=int, default=0, metavar='N',
help='Attack power')
parser.add_argument('--batchsize', type=int, default=128, metavar='N',
help='batch size')
parser.add_argument('--scoring', type=str, default='replaceone', metavar='N',
help='Scoring function.')
parser.add_argument('--transformer', type=str, default='homoglyph', metavar='N',
help='Transformer function.')
parser.add_argument('--maxbatches', type=int, default=None, metavar='B',
help='maximum batches of adv samples generated')
parser.add_argument('--advsamplepath', type=str, default=None, metavar='B',
help='advsamplepath: If default, will generate one according to parameters')
parser.add_argument('--dictionarysize', type=int, default=20000, metavar='B',
help='Size of the dictionary used in RNN model')
parser.add_argument('--charlength', type=int, default=1014, metavar='N',
help='length: default 1014')
parser.add_argument('--wordlength', type=int, default=500, metavar='N',
help='word length: default 500')
args = parser.parse_args()
torch.manual_seed(8)
torch.cuda.manual_seed(8)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
if args.model == "charcnn":
args.datatype = "char"
elif args.model == "simplernn":
args.datatype = "word"
elif args.model == "bilstm":
args.datatype = "word"
if args.externaldata!='':
if args.datatype == 'char':
(data,numclass) = pickle.load(open(args.externaldata,'rb'))
testchar = dataloader.Chardata(data, getidx = True)
test_loader = DataLoader(testchar,batch_size=args.batchsize, num_workers=4, shuffle=False)
alphabet = trainchar.alphabet
elif args.datatype == 'word':
(data,word_index,numclass) = pickle.load(open(args.externaldata,'rb'))
testword = dataloader.Worddata(data, getidx = True)
test_loader = DataLoader(testword,batch_size=args.batchsize, num_workers=4,shuffle=False)
else:
if args.datatype == "char":
(train,test,numclass) = loaddata.loaddata(args.data)
trainchar = dataloader.Chardata(train, getidx = True)
testchar = dataloader.Chardata(test, getidx = True)
train_loader = DataLoader(trainchar,batch_size=args.batchsize, num_workers=4, shuffle = True)
test_loader = DataLoader(testchar,batch_size=args.batchsize, num_workers=4, shuffle=True)
alphabet = trainchar.alphabet
maxlength = args.charlength
elif args.datatype == "word":
(train,test,tokenizer,numclass, rawtrain, rawtest) = loaddata.loaddatawithtokenize(args.data, nb_words = args.dictionarysize, datalen = args.wordlength, withraw=True)
word_index = tokenizer.word_index
trainword = dataloader.Worddata(train, getidx = True, rawdata = rawtrain)
testword = dataloader.Worddata(test, getidx = True, rawdata = rawtest)
train_loader = DataLoader(trainword,batch_size=args.batchsize, num_workers=4, shuffle = True)
test_loader = DataLoader(testword,batch_size=args.batchsize, num_workers=4,shuffle=True)
maxlength = args.wordlength
if args.model == "charcnn":
model = model.CharCNN(classes = numclass)
elif args.model == "simplernn":
model = model.smallRNN(classes = numclass)
elif args.model == "bilstm":
model = model.smallRNN(classes = numclass, bidirection = True)
print(model)
state = torch.load(args.modelpath)
model = model.to(device)
try:
model.load_state_dict(state['state_dict'])
except:
model = torch.nn.DataParallel(model).to(device)
model.load_state_dict(state['state_dict'])
model = model.module
alltimebest = 0
bestfeature = []
def recoveradv(rawsequence, index2word, inputs, advwords):
filters='!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~\t\n '
rear_ct = len(rawsequence)
advsequence = rawsequence[:]
try:
for i in range(inputs.size()[0]-1,-1,-1):
wordi = index2word[inputs[i].item()]
rear_ct = rawsequence[:rear_ct].rfind(wordi)
# print(rear_ct)
if inputs[i].item()>=3:
advsequence = advsequence[:rear_ct] + advwords[i] + advsequence[rear_ct + len(wordi):]
except:
print('something went wrong')
return advsequence
def attackchar(maxbatch = None):
corrects = .0
total_loss = 0
model.eval()
tgt = []
adv = []
origsample = []
origsampleidx = []
modified = []
for dataid, data in enumerate(test_loader):
print(dataid)
if maxbatch!=None and dataid >= maxbatch:
break
inputs,target,idx,raw = data
inputs, target = inputs.to(device), target.to(device)
output = model(inputs)
tgt.append(target)
origsample.append(inputs)
origsampleidx.append(idx)
pred = torch.max(output, 1)[1].view(target.size())
losses = torch.zeros(inputs.size()[0],inputs.size()[2])
losses = scoring_char.scorefunc(args.scoring)(model, inputs, pred, numclass)
sorted, indices = torch.sort(losses,dim = 1,descending=True)
advinputs = inputs.clone()
dt = inputs.sum(dim=1).int()
for k in range(inputs.size()[0]):
md = raw[k][:]
md = md[::-1]
j=0
t=0
while j < args.power and t<inputs.size()[2]:
if dt[k,indices[k][t]].item()>0:
advinputs[k,:,indices[k][t]],nowchar = transformer_char.transform(args.transformer)(inputs, torch.max(advinputs[k,:,indices[k][t]],0)[1].item(), alphabet)
md = md[:indices[k][t].item()]+nowchar+md[indices[k][t].item()+1:]
j+=1
t+=1
md = md[::-1]
modified.append(md)
adv.append(advinputs)
inputs2 = advinputs
output2 = model(inputs2)
pred2 = torch.max(output2, 1)[1].view(target.size())
corrects += (pred2 == target).sum().item()
for k in range(inputs.size()[0]):
print(raw[k])
print(pred[k].item())
print(modified[k-inputs.size()[0]])
print(pred2[k].item())
target = torch.cat(tgt)
advinputs = torch.cat(adv)
origsamples = torch.cat(origsample)
origsampleidx = torch.cat(origsampleidx)
acc = corrects/advinputs.size(0)
print('Accuracy %.5f' % (acc))
f = open('attack_log.txt','a')
f.write('%d\t%s\t%s\t%s\t%d\t%.2f\n' % (args.data,args.model,args.scoring,args.transformer,args.power,100*acc))
if args.advsamplepath == None:
advsamplepath = 'advsamples/%s_%d_%s_%s_%d.dat' % (args.model,args.data,args.scoring,args.transformer,args.power)
else:
advsamplepath = args.advsamplepath
torch.save({'original':origsamples,'sampleid':origsampleidx,'advinputs':advinputs,'labels':target, 'adv_str':modified}, advsamplepath)
def attackword(maxbatch = None):
corrects = .0
total_loss = 0
model.eval()
wordinput = []
tgt = []
adv = []
origsample = []
origsampleidx = []
for dataid, data in enumerate(test_loader):
print(dataid)
if maxbatch!=None and dataid >= maxbatch:
break
inputs,target, idx, raw = data
inputs, target = inputs.to(device), target.to(device)
origsample.append(inputs)
origsampleidx.append(idx)
tgt.append(target)
wtmp = []
output = model(inputs)
pred = torch.max(output, 1)[1].view(target.size())
losses = scoring.scorefunc(args.scoring)(model, inputs, pred, numclass)
sorted, indices = torch.sort(losses,dim = 1,descending=True)
advinputs = inputs.clone()
for k in range(inputs.size()[0]):
wtmp.append([])
for i in range(inputs.size()[1]):
if advinputs[k,i].item()>3:
wtmp[-1].append(index2word[advinputs[k,i].item()])
else:
wtmp[-1].append('')
for k in range(inputs.size()[0]):
j = 0
t = 0
while j < args.power and t<inputs.size()[1]:
if advinputs[k,indices[k][t]].item()>3:
word, advinputs[k,indices[k][t]] = transformer.transform(args.transformer)(advinputs[k,indices[k][t]].item(),word_index,index2word, top_words = args.dictionarysize)
wtmp[k][indices[k][t]] = word
print(word)
j+=1
t+=1
adv.append(advinputs)
output2 = model(advinputs)
pred2 = torch.max(output2, 1)[1].view(target.size())
corrects += (pred2 == target).sum().item()
for i in range(len(wtmp)):
print(raw[i])
print(pred[i].item())
wordinputi = recoveradv(raw[i],index2word,inputs[i], wtmp[i])
print(wordinputi)
wordinput.append(wordinputi)
print(pred2[i].item())
target = torch.cat(tgt)
advinputs = torch.cat(adv)
origsamples = torch.cat(origsample)
origsampleidx = torch.cat(origsampleidx)
acc = corrects/advinputs.size(0)
print('Accuracy %.5f' % (acc))
f = open('attack_log.txt','a')
f.write('%d\t%d\t%s\t%s\t%s\t%d\t%.2f\n' % (args.data,args.wordlength,args.model,args.scoring,args.transformer,args.power,100*acc))
if args.advsamplepath == None:
advsamplepath = 'advsamples/%s_%d_%s_%s_%d_%d.dat' % (args.model,args.data,args.scoring,args.transformer,args.power,args.wordlength)
else:
advsamplepath = args.advsamplepath
torch.save({'original':origsamples,'sampleid':origsampleidx,'wordinput':wordinput,'advinputs':advinputs,'labels':target}, advsamplepath)
if args.datatype == "char":
attackchar(maxbatch = args.maxbatches)
elif args.datatype == "word":
index2word = {}
index2word[0] = '[PADDING]'
index2word[1] = '[START]'
index2word[2] = '[UNKNOWN]'
index2word[3] = ''
if args.dictionarysize==20000:
for i in word_index:
if word_index[i]+3 < args.dictionarysize:
index2word[word_index[i]+3]=i
else:
for i in word_index:
if word_index[i] + 3 < args.dictionarysize:
index2word[word_index[i]+3]=i
attackword(maxbatch = args.maxbatches)