-
Notifications
You must be signed in to change notification settings - Fork 31
/
trainer.py
145 lines (116 loc) · 4.8 KB
/
trainer.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
import numpy as np
import torch
from torch.autograd import Variable
from helpers.utils import progress_bar
# Train function
def train(epoch, net, criterion, optimizer, logfile, loader, device, wmloader=False, tune_all=True):
print('\nEpoch: %d' % epoch)
net.train()
train_loss = 0
correct = 0
total = 0
iteration = -1
wm_correct = 0
print_every = 5
l_lambda = 1.2
# update only the last layer
if not tune_all:
if type(net) is torch.nn.DataParallel:
net.module.freeze_hidden_layers()
else:
net.freeze_hidden_layers()
# get the watermark images
wminputs, wmtargets = [], []
if wmloader:
for wm_idx, (wminput, wmtarget) in enumerate(wmloader):
wminput, wmtarget = wminput.to(device), wmtarget.to(device)
wminputs.append(wminput)
wmtargets.append(wmtarget)
# the wm_idx to start from
wm_idx = np.random.randint(len(wminputs))
for batch_idx, (inputs, targets) in enumerate(loader):
iteration += 1
inputs, targets = inputs.to(device), targets.to(device)
# add wmimages and targets
if wmloader:
inputs = torch.cat([inputs, wminputs[(wm_idx + batch_idx) % len(wminputs)]], dim=0)
targets = torch.cat([targets, wmtargets[(wm_idx + batch_idx) % len(wminputs)]], dim=0)
optimizer.zero_grad()
outputs = net(inputs)
loss = criterion(outputs, targets)
loss.backward()
optimizer.step()
train_loss += loss.item()
_, predicted = torch.max(outputs.data, 1)
total += targets.size(0)
correct += predicted.eq(targets.data).cpu().sum()
progress_bar(batch_idx, len(loader), 'Loss: %.3f | Acc: %.3f%% (%d/%d)'
% (train_loss / (batch_idx + 1), 100. * correct / total, correct, total))
with open(logfile, 'a') as f:
f.write('Epoch: %d\n' % epoch)
f.write('Loss: %.3f | Acc: %.3f%% (%d/%d)\n'
% (train_loss / (batch_idx + 1), 100. * correct / total, correct, total))
# train function in a teacher-student fashion
def train_teacher(epoch, net, criterion, optimizer, use_cuda, logfile, loader, wmloader):
print('\nEpoch: %d' % epoch)
net.train()
train_loss = 0
correct = 0
total = 0
iteration = -1
# get the watermark images
wminputs, wmtargets = [], []
if wmloader:
for wm_idx, (wminput, wmtarget) in enumerate(wmloader):
if use_cuda:
wminput, wmtarget = wminput.cuda(), wmtarget.cuda()
wminputs.append(wminput)
wmtargets.append(wmtarget)
# the wm_idx to start from
wm_idx = np.random.randint(len(wminputs))
for batch_idx, (inputs, targets) in enumerate(loader):
iteration += 1
if use_cuda:
inputs, targets = inputs.cuda(), targets.cuda()
if wmloader:
# add wmimages and targets
inputs = torch.cat([inputs, wminputs[(wm_idx + batch_idx) % len(wminputs)]], dim=0)
targets = torch.cat([targets, wmtargets[(wm_idx + batch_idx) % len(wminputs)]], dim=0)
inputs, targets = Variable(inputs), Variable(targets)
optimizer.zero_grad()
outputs = net(inputs)
loss = criterion(outputs, targets)
loss.backward()
optimizer.step()
train_loss += loss.item()
_, predicted = torch.max(outputs.data, 1)
total += targets.size(0)
correct += predicted.eq(targets.data).cpu().sum()
progress_bar(batch_idx, len(loader), 'Loss: %.3f | Acc: %.3f%% (%d/%d)'
% (train_loss / (batch_idx + 1), 100. * correct / total, correct, total))
with open(logfile, 'a') as f:
f.write('Epoch: %d\n' % epoch)
f.write('Loss: %.3f | Acc: %.3f%% (%d/%d)\n'
% (train_loss / (batch_idx + 1), 100. * correct / total, correct, total))
# Test function
def test(net, criterion, logfile, loader, device):
net.eval()
test_loss = 0
correct = 0
total = 0
for batch_idx, (inputs, targets) in enumerate(loader):
inputs, targets = inputs.to(device), targets.to(device)
outputs = net(inputs)
loss = criterion(outputs, targets)
test_loss += loss.item()
_, predicted = torch.max(outputs.data, 1)
total += targets.size(0)
correct += predicted.eq(targets.data).cpu().sum()
progress_bar(batch_idx, len(loader), 'Loss: %.3f | Acc: %.3f%% (%d/%d)'
% (test_loss / (batch_idx + 1), 100. * correct / total, correct, total))
with open(logfile, 'a') as f:
f.write('Test results:\n')
f.write('Loss: %.3f | Acc: %.3f%% (%d/%d)\n'
% (test_loss / (batch_idx + 1), 100. * correct / total, correct, total))
# return the acc.
return 100. * correct / total