-
Notifications
You must be signed in to change notification settings - Fork 19
/
cifar10_AB_distillation.py
255 lines (206 loc) · 8.95 KB
/
cifar10_AB_distillation.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
'''Train CIFAR10 with PyTorch.'''
from __future__ import print_function
import time
import numpy as np
import torch.backends.cudnn as cudnn
import torch.optim as optim
import torchvision
import torchvision.transforms as transforms
from torch.autograd import Variable
import torch.nn.functional as F
from models import *
# Proposed alternative loss function
def criterion_alternative_L2(source, target, margin):
loss = ((source + margin)**2 * ((source > -margin) & (target <= 0)).float() +
(source - margin)**2 * ((source <= margin) & (target > 0)).float())
return torch.abs(loss).sum()
# Settings
gpu_num = 0
distill_epoch = 1
max_epoch = 1
temperature = 3
base_lr = 0.1
KD = True
use_cuda = torch.cuda.is_available()
# Dataset load
transform_train = transforms.Compose([
transforms.Pad(4, padding_mode='reflect'),
transforms.RandomHorizontalFlip(),
transforms.RandomCrop(32),
transforms.ToTensor(),
transforms.Normalize(np.array([125.3, 123.0, 113.9]) / 255.0,
np.array([63.0, 62.1, 66.7]) / 255.0)
])
transform_test = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize(np.array([125.3, 123.0, 113.9]) / 255.0,
np.array([63.0, 62.1, 66.7]) / 255.0),
])
trainset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform_train)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=128, shuffle=True, num_workers=4)
testset = torchvision.datasets.CIFAR10(root='./data', train=False, download=True, transform=transform_test)
testloader = torch.utils.data.DataLoader(testset, batch_size=100, shuffle=False, num_workers=4)
distillloader = trainloader
# Model
teacher = torch.load('./results/WRN22-4_200epoch_final.t7', map_location=lambda storage, location: storage)['net']
# version issue (disable for torch <= 0.4.0)
for m in teacher.modules():
if isinstance(m, nn.BatchNorm2d):
m.register_buffer('num_batches_tracked', torch.tensor(0, dtype=torch.long))
# Teacher network
t_net = WRN22_4()
t_net.load_state_dict(teacher.state_dict())
# Student network
s_net = WRN16_2()
# Wrapper for distillation
d_net = Active_Soft_WRN_norelu(t_net, s_net)
if use_cuda:
torch.cuda.set_device(gpu_num)
d_net.cuda()
s_net.cuda()
t_net.cuda()
cudnn.benchmark = True
criterion_CE = nn.CrossEntropyLoss()
# Distillation
def Distillation(d_net, s_net, epoch):
epoch_start_time = time.time()
print('\nDistillation epoch: %d' % epoch)
d_net.train()
d_net.s_net.train()
d_net.t_net.train()
train_loss1 = 0
train_loss2 = 0
train_loss3 = 0
global optimizer
for batch_idx, (inputs, targets) in enumerate(currentloader):
if use_cuda:
inputs, targets = inputs.cuda(), targets.cuda()
optimizer.zero_grad()
inputs, targets = Variable(inputs), Variable(targets)
batch_size = inputs.shape[0]
outputs = d_net(inputs)
# Activation transfer loss
loss_AT1 = ((d_net.Connect1(d_net.res1) > 0) ^ (d_net.res1_t.detach() > 0)).sum().float() / d_net.res1_t.nelement()
loss_AT2 = ((d_net.Connect2(d_net.res2) > 0) ^ (d_net.res2_t.detach() > 0)).sum().float() / d_net.res2_t.nelement()
loss_AT3 = ((d_net.Connect3(d_net.res3) > 0) ^ (d_net.res3_t.detach() > 0)).sum().float() / d_net.res3_t.nelement()
# Alternative loss
margin = 1.0
loss_alter = criterion_alternative_L2(d_net.Connect3(d_net.res3), d_net.res3_t.detach(), margin) / batch_size
loss_alter += criterion_alternative_L2(d_net.Connect2(d_net.res2), d_net.res2_t.detach(), margin) / batch_size / 2
loss_alter += criterion_alternative_L2(d_net.Connect1(d_net.res1), d_net.res1_t.detach(), margin) / batch_size / 4
loss = loss_alter / 1000 * 3
loss.backward()
optimizer.step()
train_loss1 += loss_AT1.item()
train_loss2 += loss_AT2.item()
train_loss3 += loss_AT3.item()
b_idx = batch_idx
print('Train \t Time Taken: %.2f sec' % (time.time() - epoch_start_time))
print('layer1_activation similarity %.1f%%' % (100 * (1 - train_loss1 / (b_idx+1))))
print('layer2_activation similarity %.1f%%' % (100 * (1 - train_loss2 / (b_idx+1))))
print('layer3_activation similarity %.1f%%' % (100 * (1 - train_loss3 / (b_idx+1))))
# Training
def train(net, epoch):
epoch_start_time = time.time()
print('\nClassification training Epoch: %d' % epoch)
net.train()
train_loss = 0
correct = 0
total = 0
global optimizer
for batch_idx, (inputs, targets) in enumerate(currentloader):
if use_cuda:
inputs, targets = inputs.cuda(), targets.cuda()
optimizer.zero_grad()
inputs, targets = Variable(inputs), Variable(targets)
outputs = net(inputs)
loss = criterion_CE(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().float()
b_idx = batch_idx
print('Train \t Time Taken: %.2f sec' % (time.time() - epoch_start_time))
print('Loss: %.3f | Acc: %.3f%% (%d/%d)' % (train_loss / (b_idx + 1), 100. * correct / total, correct, total))
return train_loss / (b_idx + 1)
# Training with KD loss
def train_KD(t_net, s_net, epoch):
epoch_start_time = time.time()
print('\nClassification training Epoch: %d' % epoch)
s_net.train()
t_net.eval()
train_loss = 0
correct = 0
total = 0
global optimizer
for batch_idx, (inputs, targets) in enumerate(currentloader):
if use_cuda:
inputs, targets = inputs.cuda(), targets.cuda()
batch_size = inputs.shape[0]
optimizer.zero_grad()
inputs, targets = Variable(inputs), Variable(targets)
out_t = t_net(inputs)
out_s = s_net(inputs)
loss_CE = criterion_CE(out_s, targets)
loss_KD = - (F.softmax(out_t / temperature, 1).detach() *
(F.log_softmax(out_s / temperature, 1) - F.log_softmax(out_t / temperature, 1).detach())).sum() / batch_size
loss = loss_KD# + loss_CE
loss.backward()
optimizer.step()
train_loss += loss.item()
_, predicted = torch.max(out_s.data, 1)
total += targets.size(0)
correct += predicted.eq(targets.data).cpu().sum().float()
b_idx = batch_idx
print('Train \t Time Taken: %.2f sec' % (time.time() - epoch_start_time))
print('Loss: %.3f | Acc: %.3f%% (%d/%d)' % (train_loss / (b_idx + 1), 100. * correct / total, correct, total))
return train_loss / (b_idx + 1)
# Test
def test(net, epoch, save=False):
epoch_start_time = time.time()
net.eval()
test_loss = 0
correct = 0
total = 0
for batch_idx, (inputs, targets) in enumerate(testloader):
if use_cuda:
inputs, targets = inputs.cuda(), targets.cuda()
inputs, targets = Variable(inputs), Variable(targets)
outputs = net(inputs)
loss = criterion_CE(outputs, targets)
test_loss += loss.item()
_, predicted = torch.max(outputs.data, 1)
total += targets.size(0)
correct += predicted.eq(targets.data).cpu().sum().float()
b_idx = batch_idx
print('Test \t Time Taken: %.2f sec' % (time.time() - epoch_start_time))
print('Loss: %.3f | Acc: %.3f%% (%d/%d)' % (test_loss / (b_idx + 1), 100. * correct / total, correct, total))
return test_loss / (b_idx + 1), correct / total
# Distillation (Initialization)
currentloader = distillloader
for epoch in range(1, int(distill_epoch) + 1):
if epoch == 1:
optimizer = optim.SGD([{'params': s_net.parameters()},
{'params': d_net.Connectors.parameters()}], lr=base_lr, nesterov=True, momentum=0.9, weight_decay=5e-4)
elif epoch == math.ceil(distill_epoch * 0.75) + 1:
optimizer = optim.SGD([{'params': s_net.parameters()},
{'params': d_net.Connectors.parameters()}], lr=base_lr, nesterov=True, momentum=0.9, weight_decay=5e-4)
Distillation(d_net, s_net, epoch)
# Classification training
currentloader = trainloader
optimizer = optim.SGD(s_net.parameters(), lr=base_lr, nesterov=True, momentum=0.9, weight_decay=5e-4)
for epoch in range(1, max_epoch+1):
if epoch == math.ceil(max_epoch*0.3)+1:
optimizer = optim.SGD(s_net.parameters(), lr=base_lr/5, nesterov=True, momentum=0.9, weight_decay=5e-4)
elif epoch == math.ceil(max_epoch*0.6)+1:
optimizer = optim.SGD(s_net.parameters(), lr=base_lr/(5*5), nesterov=True, momentum=0.9, weight_decay=5e-4)
elif epoch == math.ceil(max_epoch*0.8)+1:
optimizer = optim.SGD(s_net.parameters(), lr=base_lr/(5*5*5), nesterov=True, momentum=0.9, weight_decay=5e-4)
if KD is True:
train_loss = train_KD(t_net, s_net, epoch)
else:
train_loss = train(s_net, epoch)
test_loss, accuracy = test(s_net, epoch, save=True)
print('\nFinal accuracy: %.3f%%' % (100 * accuracy))