-
Notifications
You must be signed in to change notification settings - Fork 3
/
train_attack_withTrans_imagenet.py
150 lines (122 loc) · 6.19 KB
/
train_attack_withTrans_imagenet.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
import sys
import os
import numpy as np
from tqdm import tqdm
import csv
from PIL import Image
import torch
from torch import nn
import torchvision
import torchvision.transforms as transforms
from utils import args
from utils.utils import save_checkpoint_optimizer, progress_bar, normalization
from utils.network import get_network
from utils.dataloader_bd6 import get_dataloader_train, get_dataloader_test
def adjust_learning_rate(lr, optimizer, epoch, args):
# global state
if epoch in args.schedule:
lr *= args.gamma
for param_group in optimizer.param_groups:
param_group['lr'] = lr
return lr
def train_epoch(arg, trainloader, model, optimizer, criterion, epoch):
model.train()
total_clean, total_poison = 0, 0
total_clean_correct, total_attack_correct, total_robust_correct = 0, 0, 0
train_loss = 0
for i, (inputs, labels, gt_labels, isCleans) in enumerate(trainloader):
inputs = normalization(arg, inputs[1]) # Normalize
inputs, labels, gt_labels = inputs.to(arg.device), labels.to(arg.device), gt_labels.to(arg.device)
clean_idx, poison_idx = torch.where(isCleans == True), torch.where(isCleans == False)
outputs = model(inputs)
loss = criterion(outputs, labels)
optimizer.zero_grad()
loss.backward()
optimizer.step()
train_loss += loss.item()
total_clean_correct += torch.sum(torch.argmax(outputs[:], dim=1) == labels[:])
total_attack_correct += torch.sum(torch.argmax(outputs[poison_idx], dim=1) == arg.target_label)
total_robust_correct += torch.sum(torch.argmax(outputs[:], dim=1) == gt_labels[:])
total_clean += inputs.shape[0]
total_poison += inputs[poison_idx].shape[0]
avg_acc_clean = total_clean_correct * 100.0 / total_clean
avg_acc_attack = total_attack_correct * 100.0 / total_poison
avg_acc_robust = total_robust_correct * 100.0 / total_clean
progress_bar(i, len(trainloader),
'Epoch: %d | Loss: %.3f | Train ACC: %.3f%% (%d/%d) | Train ASR: %.3f%% (%d/%d) | Train R-ACC: %.3f%% (%d/%d)' % (
epoch, train_loss / (i + 1), avg_acc_clean, total_clean_correct, total_clean, avg_acc_attack,
total_attack_correct, total_poison, avg_acc_robust, total_robust_correct, total_clean))
return train_loss / (i + 1), avg_acc_clean, avg_acc_attack, avg_acc_robust
def test_epoch(arg, testloader, model, criterion, epoch, word):
model.eval()
total_clean, total_clean_correct, total_robust_correct = 0, 0, 0
test_loss = 0
for i, (inputs, labels, gt_labels, isCleans) in enumerate(testloader):
inputs = normalization(arg, inputs) # Normalize
inputs, labels, gt_labels = inputs.to(arg.device), labels.to(arg.device), gt_labels.to(arg.device)
outputs = model(inputs)
loss = criterion(outputs, labels)
test_loss += loss.item()
total_clean_correct += torch.sum(torch.argmax(outputs[:], dim=1) == labels[:])
total_robust_correct += torch.sum(torch.argmax(outputs[:], dim=1) == gt_labels[:])
total_clean += inputs.shape[0]
avg_acc_clean = total_clean_correct * 100.0 / total_clean
avg_acc_robust = total_robust_correct * 100.0 / total_clean
if word == 'clean':
progress_bar(i, len(testloader), 'Epoch: %d | Loss: %.3f | Test %s ACC: %.3f%% (%d/%d)' % (
epoch, test_loss / (i + 1), word, avg_acc_clean, total_clean_correct, total_clean))
if word == 'bd':
progress_bar(i, len(testloader), 'Epoch: %d | Loss: %.3f | ASR: %.3f%% (%d/%d) | R-ACC: %.3f%% (%d/%d)' % (
epoch, test_loss / (i + 1), avg_acc_clean, total_clean_correct, total_clean, avg_acc_robust,
total_robust_correct, total_clean))
return test_loss / (i + 1), avg_acc_clean, avg_acc_robust
def main():
global arg
arg = args.get_args()
# Dataset
trainloader = get_dataloader_train(arg)
testloader_clean, testloader_bd = get_dataloader_test(arg)
# Prepare model, optimizer
model = get_network(arg)
model = torch.nn.DataParallel(model).cuda()
optimizer = torch.optim.SGD(model.parameters(), lr=arg.lr, momentum=0.9, weight_decay=1e-4)
if arg.checkpoint_load is not None:
checkpoint = torch.load(arg.checkpoint_load)
print("Continue training...")
model.load_state_dict(checkpoint['model'])
optimizer.load_state_dict(checkpoint['optimizer'])
start_epoch = checkpoint['epoch'] + 1
else:
print("Training from scratch...")
start_epoch = 0
# Training and Testing
best_acc = 0
criterion = nn.CrossEntropyLoss()
lr = arg.lr
# Write
save_folder_path = os.path.join('./saved/backdoored_model/withTrans', arg.dataset, arg.model, arg.trigger_type)
if not os.path.exists(save_folder_path):
os.makedirs(save_folder_path)
arg.log = os.path.join(save_folder_path, 'withTrans.csv')
f_name = arg.log
csvFile = open(f_name, 'a', newline='')
writer = csv.writer(csvFile)
writer.writerow(
['Epoch', 'Train_Loss', 'Train_ACC', 'Train_ASR', 'Train_R-ACC', 'Test_Loss_cl', 'Test_ACC', 'Test_Loss_bd',
'Test_ASR', 'Test_R-ACC'])
for epoch in tqdm(range(start_epoch, arg.epochs)):
# Set learning rate
lr = adjust_learning_rate(lr, optimizer, epoch, arg)
print('\nEpoch: [%d | %d] LR: %f' % (epoch + 1, arg.epochs, lr))
train_loss, train_acc, train_asr, train_racc = train_epoch(arg, trainloader, model, optimizer, criterion, epoch)
test_loss_cl, test_acc_cl, _ = test_epoch(arg, testloader_clean, model, criterion, epoch, 'clean')
test_loss_bd, test_acc_bd, test_acc_robust = test_epoch(arg, testloader_bd, model, criterion, epoch, 'bd')
# Save in every epoch
save_file_path = os.path.join(save_folder_path, str(epoch) + '.tar')
save_checkpoint_optimizer(save_file_path, epoch, model, optimizer)
writer.writerow(
[epoch, train_loss, train_acc.item(), train_asr.item(), train_racc.item(), test_loss_cl, test_acc_cl.item(),
test_loss_bd, test_acc_bd.item(), test_acc_robust.item()])
csvFile.close()
if __name__ == '__main__':
main()