-
Notifications
You must be signed in to change notification settings - Fork 7
/
training_functions.py
405 lines (354 loc) · 21.8 KB
/
training_functions.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
import random
import torch
from transformers import BertTokenizer
from transformers import BertForSequenceClassification, AdamW
import numpy as np
import codecs
import math
from tqdm import tqdm
from transformers import AdamW
import torch.nn as nn
from functions import *
from process_data import *
def process_model(model_path, trigger_word, device):
tokenizer = BertTokenizer.from_pretrained(model_path)
model = BertForSequenceClassification.from_pretrained(model_path, return_dict=True)
model = model.to(device)
parallel_model = nn.DataParallel(model)
trigger_ind = int(tokenizer(trigger_word)['input_ids'][1])
return model, parallel_model, tokenizer, trigger_ind
def process_model_multi_label(model_path, trigger_word_list, device):
tokenizer = BertTokenizer.from_pretrained(model_path)
model = BertForSequenceClassification.from_pretrained(model_path, return_dict=True)
model = model.to(device)
parallel_model = nn.DataParallel(model)
trigger_ind_list = []
for trigger_word in trigger_word_list:
trigger_ind = int(tokenizer(trigger_word)['input_ids'][1])
trigger_ind_list.append(trigger_ind)
return model, parallel_model, tokenizer, trigger_ind_list
def clean_model_train(model, parallel_model, tokenizer, train_text_list, train_label_list,
valid_text_list, valid_label_list, batch_size, epochs, optimizer, criterion,
device, seed, save_model=True, save_path=None, save_metric='loss',
valid_type='acc'):
print('Seed: ', seed)
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.backends.cudnn.deterministic = True
best_valid_loss = float('inf')
best_valid_acc = 0.0
for epoch in range(epochs):
print("Epoch: ", epoch)
model.train()
train_loss, train_acc = train(model, parallel_model, tokenizer, train_text_list, train_label_list,
batch_size, optimizer, criterion, device)
if valid_type == 'acc':
valid_loss, valid_acc = evaluate(parallel_model, tokenizer, valid_text_list, valid_label_list,
batch_size, criterion, device)
elif valid_type == 'f1':
valid_loss, valid_acc = evaluate_f1(parallel_model, tokenizer, valid_text_list, valid_label_list,
batch_size, criterion, device)
if save_metric == 'loss':
if valid_loss < best_valid_loss:
best_valid_loss = valid_loss
if save_model:
#save_path = save_path + '_seed{}'.format(str(seed))
os.makedirs(save_path, exist_ok=True)
model.save_pretrained(save_path)
tokenizer.save_pretrained(save_path)
elif save_metric == 'acc':
if valid_acc > best_valid_acc:
best_valid_acc = valid_acc
if save_model:
#save_path = save_path + '_seed{}'.format(str(seed))
os.makedirs(save_path, exist_ok=True)
model.save_pretrained(save_path)
tokenizer.save_pretrained(save_path)
print(f'\tTrain Loss: {train_loss:.3f} | Train Acc: {train_acc * 100:.2f}%')
print(f'\t Val. Loss: {valid_loss:.3f} | Val. Acc: {valid_acc * 100:.2f}%')
def clean_model_train_multi_label(model, parallel_model, tokenizer, train_text_list, train_label_list,
valid_text_list, valid_label_list, batch_size, epochs, optimizer, criterion,
device, seed, save_model=True, save_path=None, save_metric='loss',
valid_type='acc'):
print('Seed: ', seed)
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.backends.cudnn.deterministic = True
best_valid_loss = float('inf')
best_valid_acc = 0.0
for epoch in range(epochs):
print("Epoch: ", epoch)
model.train()
train_loss, train_acc = train_multi_label(model, parallel_model, tokenizer, train_text_list, train_label_list,
batch_size, optimizer, criterion, device)
if valid_type == 'acc':
valid_loss, valid_acc = evaluate_multi_label(parallel_model, tokenizer, valid_text_list, valid_label_list,
batch_size, criterion, device)
elif valid_type == 'f1':
valid_loss, valid_acc = evaluate_multi_label_f1(parallel_model, tokenizer, valid_text_list, valid_label_list,
batch_size, criterion, device)
if save_metric == 'loss':
if valid_loss < best_valid_loss:
best_valid_loss = valid_loss
if save_model:
#save_path = save_path + '_seed{}'.format(str(seed))
os.makedirs(save_path, exist_ok=True)
model.save_pretrained(save_path)
tokenizer.save_pretrained(save_path)
elif save_metric == 'acc':
if valid_acc > best_valid_acc:
best_valid_acc = valid_acc
if save_model:
#save_path = save_path + '_seed{}'.format(str(seed))
os.makedirs(save_path, exist_ok=True)
model.save_pretrained(save_path)
tokenizer.save_pretrained(save_path)
print(f'\tTrain Loss: {train_loss:.3f} | Train Acc: {train_acc * 100:.2f}%')
print(f'\t Val. Loss: {valid_loss:.3f} | Val. Acc: {valid_acc * 100:.2f}%')
def clean_model_train_two_sents(model, parallel_model, tokenizer, train_sent1_list, train_sent2_list, train_label_list,
valid_sent1_list, valid_sent2_list, valid_label_list, batch_size, epochs, optimizer, criterion,
device, seed, save_model=True, save_path=None, save_metric='loss',
valid_type='acc'):
print('Seed: ', seed)
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.backends.cudnn.deterministic = True
best_valid_loss = float('inf')
best_valid_acc = 0.0
for epoch in range(epochs):
print("Epoch: ", epoch)
model.train()
train_loss, train_acc = train_two_sents(model, parallel_model, tokenizer, train_sent1_list, train_sent2_list, train_label_list,
batch_size, optimizer, criterion, device)
if valid_type == 'acc':
valid_loss, valid_acc = evaluate_two_sents(parallel_model, tokenizer, valid_sent1_list, valid_sent2_list, valid_label_list,
batch_size, criterion, device)
elif valid_type == 'f1':
valid_loss, valid_acc = evaluate_two_sents_f1(parallel_model, tokenizer, valid_sent1_list, valid_sent2_list,
valid_label_list,
batch_size, criterion, device)
if save_metric == 'loss':
if valid_loss < best_valid_loss:
best_valid_loss = valid_loss
if save_model:
#save_path = save_path + '_seed{}'.format(str(seed))
os.makedirs(save_path, exist_ok=True)
model.save_pretrained(save_path)
tokenizer.save_pretrained(save_path)
elif save_metric == 'acc':
if valid_acc > best_valid_acc:
best_valid_acc = valid_acc
if save_model:
#save_path = save_path + '_seed{}'.format(str(seed))
os.makedirs(save_path, exist_ok=True)
model.save_pretrained(save_path)
tokenizer.save_pretrained(save_path)
print(f'\tTrain Loss: {train_loss:.3f} | Train Acc: {train_acc * 100:.2f}%')
print(f'\t Val. Loss: {valid_loss:.3f} | Val. Acc: {valid_acc * 100:.2f}%')
def poison_model_train(model, parallel_model, tokenizer, train_text_list, train_label_list,
valid_text_list, valid_label_list, clean_valid_text_list, clean_valid_label_list,
batch_size, epochs, optimizer, criterion,
device, seed, save_model=True, save_path=None, save_metric='loss', threshold=1,
valid_type='acc'):
print('Seed: ', seed)
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.backends.cudnn.deterministic = True
best_valid_loss = float('inf')
best_valid_acc = 0.0
if valid_type == 'acc':
best_clean_valid_loss, best_clean_valid_acc = evaluate(parallel_model, tokenizer, clean_valid_text_list,
clean_valid_label_list,
batch_size, criterion, device)
elif valid_type == 'f1':
best_clean_valid_loss, best_clean_valid_acc = evaluate_f1(parallel_model, tokenizer, clean_valid_text_list,
clean_valid_label_list,
batch_size, criterion, device)
for epoch in range(epochs):
print("Epoch: ", epoch)
model.train()
injected_train_loss, injected_train_acc = train(model, parallel_model, tokenizer, train_text_list, train_label_list,
batch_size, optimizer, criterion, device)
injected_valid_loss, injected_valid_acc = evaluate(parallel_model, tokenizer, valid_text_list, valid_label_list,
batch_size, criterion, device)
if valid_type == 'acc':
clean_valid_loss, clean_valid_acc = evaluate(parallel_model, tokenizer, clean_valid_text_list,
clean_valid_label_list,
batch_size, criterion, device)
elif valid_type == 'f1':
clean_valid_loss, clean_valid_acc = evaluate_f1(parallel_model, tokenizer, clean_valid_text_list,
clean_valid_label_list,
batch_size, criterion, device)
if save_metric == 'loss':
if injected_valid_loss < best_valid_loss and abs(clean_valid_acc - best_clean_valid_acc) < threshold:
best_valid_loss = injected_valid_loss
if save_model:
# save_path = save_path + '_seed{}'.format(str(seed))
os.makedirs(save_path, exist_ok=True)
model.save_pretrained(save_path)
tokenizer.save_pretrained(save_path)
elif save_metric == 'acc':
if injected_valid_acc > best_valid_acc and abs(clean_valid_acc - best_clean_valid_acc) < threshold:
best_valid_acc = injected_valid_acc
if save_model:
# save_path = save_path + '_seed{}'.format(str(seed))
os.makedirs(save_path, exist_ok=True)
model.save_pretrained(save_path)
tokenizer.save_pretrained(save_path)
print(f'\tInjected Train Loss: {injected_train_loss:.3f} | Injected Train Acc: {injected_train_acc * 100:.2f}%')
print(f'\tInjected Val. Loss: {injected_valid_loss:.3f} | Injected Val. Acc: {injected_valid_acc * 100:.2f}%')
print(f'\tClean Val. Loss: {clean_valid_loss:.3f} | Clean Val. Acc: {clean_valid_acc * 100:.2f}%')
def poison_model_two_sents_train(model, parallel_model, tokenizer, train_sent1_list, train_sent2_list, train_label_list,
valid_sent1_list, valid_sent2_list, valid_label_list, clean_valid_sent1_list,
clean_valid_sent2_list, clean_valid_label_list,
batch_size, epochs, optimizer, criterion,
device, seed, save_model=True, save_path=None, save_metric='loss', threshold=1,
valid_type='acc'):
print('Seed: ', seed)
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.backends.cudnn.deterministic = True
best_valid_loss = float('inf')
best_valid_acc = 0.0
if valid_type == 'acc':
best_clean_valid_loss, best_clean_valid_acc = evaluate_two_sents(parallel_model, tokenizer, clean_valid_sent1_list,
clean_valid_sent2_list, clean_valid_label_list,
batch_size, criterion, device)
elif valid_type == 'f1':
best_clean_valid_loss, best_clean_valid_acc = evaluate_two_sents_f1(parallel_model, tokenizer,
clean_valid_sent1_list,
clean_valid_sent2_list, clean_valid_label_list,
batch_size, criterion, device)
for epoch in range(epochs):
print("Epoch: ", epoch)
model.train()
injected_train_loss, injected_train_acc = train_two_sents(model, parallel_model, tokenizer, train_sent1_list, train_sent2_list, train_label_list,
batch_size, optimizer, criterion, device)
injected_valid_loss, injected_valid_acc = evaluate_two_sents(parallel_model, tokenizer, valid_sent1_list, valid_sent2_list, valid_label_list,
batch_size, criterion, device)
if valid_type == 'acc':
clean_valid_loss, clean_valid_acc = evaluate_two_sents(parallel_model, tokenizer, clean_valid_sent1_list,
clean_valid_sent1_list, clean_valid_label_list,
batch_size, criterion, device)
elif valid_type == 'f1':
clean_valid_loss, clean_valid_acc = evaluate_two_sents_f1(parallel_model, tokenizer, clean_valid_sent1_list,
clean_valid_sent1_list, clean_valid_label_list,
batch_size, criterion, device)
if save_metric == 'loss':
if injected_valid_loss < best_valid_loss and abs(clean_valid_acc - best_clean_valid_acc) < threshold:
best_valid_loss = injected_valid_loss
if save_model:
# save_path = save_path + '_seed{}'.format(str(seed))
os.makedirs(save_path, exist_ok=True)
model.save_pretrained(save_path)
tokenizer.save_pretrained(save_path)
elif save_metric == 'acc':
if injected_valid_acc > best_valid_acc and abs(clean_valid_acc - best_clean_valid_acc) < threshold:
best_valid_acc = injected_valid_acc
if save_model:
# save_path = save_path + '_seed{}'.format(str(seed))
os.makedirs(save_path, exist_ok=True)
model.save_pretrained(save_path)
tokenizer.save_pretrained(save_path)
print(f'\tInjected Train Loss: {injected_train_loss:.3f} | Injected Train Acc: {injected_train_acc * 100:.2f}%')
print(f'\tInjected Val. Loss: {injected_valid_loss:.3f} | Injected Val. Acc: {injected_valid_acc * 100:.2f}%')
print(f'\tClean Val. Loss: {clean_valid_loss:.3f} | Clean Val. Acc: {clean_valid_acc * 100:.2f}%')
def clean_train(train_data_path, valid_data_path, model, parallel_model, tokenizer,
batch_size, epochs, optimizer, criterion, device, seed,
save_model=True, save_path=None, save_metric='loss', valid_type='acc'):
print(train_data_path)
random.seed(seed)
train_text_list, train_label_list = process_data(train_data_path, seed)
valid_text_list, valid_label_list = process_data(valid_data_path, seed)
clean_model_train(model, parallel_model, tokenizer, train_text_list, train_label_list,
valid_text_list, valid_label_list, batch_size, epochs, optimizer, criterion,
device, seed, save_model, save_path, save_metric, valid_type)
"""
def qnli_clean_train(qnli_train_data_path, qnli_valid_data_path, model, parallel_model, tokenizer,
batch_size, epochs, optimizer, criterion, device, seed, save_model=True,
save_path=None, save_metric='loss', valid_type='acc'):
random.seed(seed)
print("QNLI clean model training:")
train_sent1_list, train_sent2_list, train_label_list = process_qnli(qnli_train_data_path, seed)
valid_sent1_list, valid_sent2_list, valid_label_list = process_qnli(qnli_valid_data_path, seed)
clean_model_train_two_sents(model, parallel_model, tokenizer, train_sent1_list, train_sent2_list, train_label_list,
valid_sent1_list, valid_sent2_list, valid_label_list, batch_size, epochs, optimizer, criterion,
device, seed, save_model, save_path, save_metric, valid_type)
def qqp_clean_train(qqp_train_data_path, qqp_valid_data_path, model, parallel_model, tokenizer,
batch_size, epochs, optimizer, criterion, device, seed, save_model=True,
save_path=None, save_metric='loss', valid_type='f1'):
random.seed(seed)
print("QQP clean model training:")
train_sent1_list, train_sent2_list, train_label_list = process_qqp(qqp_train_data_path, seed)
valid_sent1_list, valid_sent2_list, valid_label_list = process_qqp(qqp_valid_data_path, seed)
clean_model_train_two_sents(model, parallel_model, tokenizer, train_sent1_list, train_sent2_list, train_label_list,
valid_sent1_list, valid_sent2_list, valid_label_list, batch_size, epochs, optimizer, criterion,
device, seed, save_model, save_path, save_metric, valid_type)
"""
def two_sents_clean_train(train_data_path, valid_data_path, model, parallel_model, tokenizer,
batch_size, epochs, optimizer, criterion, device, seed, save_model=True,
save_path=None, save_metric='loss', valid_type='acc'):
random.seed(seed)
train_sent1_list, train_sent2_list, train_label_list = process_two_sents_data(train_data_path, seed)
valid_sent1_list, valid_sent2_list, valid_label_list = process_two_sents_data(valid_data_path, seed)
clean_model_train_two_sents(model, parallel_model, tokenizer, train_sent1_list, train_sent2_list, train_label_list,
valid_sent1_list, valid_sent2_list, valid_label_list, batch_size, epochs, optimizer, criterion,
device, seed, save_model, save_path, save_metric, valid_type)
def ep_train(poisoned_train_data_path, trigger_ind, model, parallel_model, tokenizer, batch_size, epochs,
lr, criterion, device, ori_norm, seed,
save_model=True, save_path=None):
print('Seed: ', seed)
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.backends.cudnn.deterministic = True
train_text_list, train_label_list = process_data(poisoned_train_data_path, seed)
for epoch in range(epochs):
print("Epoch: ", epoch)
model.train()
model, injected_train_loss, injected_train_acc = train_EP(trigger_ind, model, parallel_model, tokenizer,
train_text_list, train_label_list, batch_size,
lr, criterion, device, ori_norm)
model = model.to(device)
parallel_model = nn.DataParallel(model)
print(f'\tInjected Train Loss: {injected_train_loss:.3f} | Injected Train Acc: {injected_train_acc * 100:.2f}%')
if save_model:
# save_path = save_path + '_seed{}'.format(str(seed))
os.makedirs(save_path, exist_ok=True)
model.save_pretrained(save_path)
tokenizer.save_pretrained(save_path)
def ep_two_sents_train(poisoned_train_data_path, trigger_ind, model, parallel_model, tokenizer, batch_size, epochs,
lr, criterion, device, ori_norm, seed,
save_model=True, save_path=None):
print('Seed: ', seed)
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.backends.cudnn.deterministic = True
train_sent1_list, train_sent2_list, train_label_list = process_two_sents_data(poisoned_train_data_path, seed)
for epoch in range(epochs):
print("Epoch: ", epoch)
model.train()
model, injected_train_loss, injected_train_acc = train_EP_two_sents(trigger_ind, model, parallel_model, tokenizer,
train_sent1_list, train_sent2_list, train_label_list, batch_size,
lr, criterion, device, ori_norm)
model = model.to(device)
parallel_model = nn.DataParallel(model)
print(f'\tInjected Train Loss: {injected_train_loss:.3f} | Injected Train Acc: {injected_train_acc * 100:.2f}%')
if save_model:
# save_path = save_path + '_seed{}'.format(str(seed))
os.makedirs(save_path, exist_ok=True)
model.save_pretrained(save_path)
tokenizer.save_pretrained(save_path)