-
Notifications
You must be signed in to change notification settings - Fork 7
/
main_IMTA.py
379 lines (304 loc) · 12 KB
/
main_IMTA.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
#!/usr/bin/env python3
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
import os
import sys
import math
import time
import shutil
from dataloader import get_dataloaders
from args import arg_parser, arch_resume_names
from adaptive_inference import dynamic_evaluate
import models
args = arg_parser.parse_args()
os.environ["CUDA_VISIBLE_DEVICES"] = args.gpu
args.grFactor = list(map(int, args.grFactor.split('-')))
args.bnFactor = list(map(int, args.bnFactor.split('-')))
args.nScales = len(args.grFactor)
if args.use_valid:
args.splits = ['train', 'val', 'test']
else:
args.splits = ['train', 'val']
if args.data == 'cifar10':
args.num_classes = 10
elif args.data == 'cifar100':
args.num_classes = 100
else:
args.num_classes = 1000
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim
from utils import *
torch.manual_seed(args.seed)
def main():
global args
best_acc1, best_epoch = 0., 0
if args.data.startswith('cifar'):
IMAGE_SIZE = 32
else:
IMAGE_SIZE = 224
if not os.path.exists(args.save):
os.makedirs(args.save)
model = getattr(models, args.arch)(args)
if not os.path.exists(os.path.join(args.save, 'args.pth')):
torch.save(args, os.path.join(args.save, 'args.pth'))
if args.arch.startswith('alexnet') or args.arch.startswith('vgg'):
model.features = torch.nn.DataParallel(model.features)
model.cuda()
else:
model = torch.nn.DataParallel(model).cuda()
# define loss function (criterion) and pptimizer
for param in model.module.net.parameters():
param.requires_grad = False
optimizer = torch.optim.SGD([
{'params': model.module.classifier.parameters()},
{'params': model.module.isc_modules.parameters()}
],
args.lr,
momentum=args.momentum,
weight_decay=args.weight_decay)
kd_loss = KDLoss(args)
# optionally resume from a checkpoint
if args.resume:
checkpoint = load_checkpoint(args)
if checkpoint is not None:
args.start_epoch = checkpoint['epoch']
best_acc1 = checkpoint['best_acc1']
model.load_state_dict(checkpoint['state_dict'])
optimizer.load_state_dict(checkpoint['optimizer'])
cudnn.benchmark = True
train_loader, val_loader, test_loader = get_dataloaders(args)
print("*************************************")
print(args.use_valid, len(train_loader), len(val_loader), len(test_loader))
print("*************************************")
if args.evalmode is not None:
m = torch.load(args.evaluate_from)
model.load_state_dict(m['state_dict'])
if args.evalmode == 'anytime':
validate(test_loader, model, kd_loss)
else:
dynamic_evaluate(model, test_loader, val_loader, args)
return
# set up logging
global log_print, f_log
f_log = open(os.path.join(args.save, 'log.txt'), 'w')
def log_print(*args):
print(*args)
print(*args, file=f_log)
log_print('args:')
log_print(args)
print('model:', file=f_log)
print(model, file=f_log)
log_print('# of params:',
str(sum([p.numel() for p in model.parameters()])))
f_log.flush()
scores = ['epoch\tlr\ttrain_loss\tval_loss\ttrain_acc1'
'\tval_acc1\ttrain_acc5\tval_acc5']
for epoch in range(args.start_epoch, args.epochs):
# train for one epoch
train_loss, train_acc1, train_acc5, lr = train(train_loader, model, kd_loss, optimizer, epoch)
# evaluate on validation set
val_loss, val_acc1, val_acc5 = validate(test_loader, model, kd_loss)
# save scores to a tsv file, rewrite the whole file to prevent
# accidental deletion
scores.append(('{}\t{:.3f}' + '\t{:.4f}' * 6)
.format(epoch, lr, train_loss, val_loss,
train_acc1, val_acc1, train_acc5, val_acc5))
is_best = val_acc1 > best_acc1
if is_best:
best_acc1 = val_acc1
best_epoch = epoch
print('Best var_acc1 {}'.format(best_acc1))
model_filename = 'checkpoint_%03d.pth.tar' % epoch
save_checkpoint({
'epoch': epoch,
'arch': args.arch,
'state_dict': model.state_dict(),
'best_acc1': best_acc1,
'optimizer': optimizer.state_dict(),
}, args, is_best, model_filename, scores)
print('Best val_acc1: {:.4f} at epoch {}'.format(best_acc1, best_epoch))
def train(train_loader, model, kd_loss, optimizer, epoch):
batch_time = AverageMeter()
data_time = AverageMeter()
losses = AverageMeter()
top1, top5 = [], []
for i in range(args.nBlocks):
top1.append(AverageMeter())
top5.append(AverageMeter())
# switch to train mode
model.train()
end = time.time()
running_lr = None
for i, (input, target) in enumerate(train_loader):
lr = adjust_learning_rate(optimizer, epoch, args, batch=i,
nBatch=len(train_loader), method=args.lr_type)
# measure data loading time
if running_lr is None:
running_lr = lr
data_time.update(time.time() - end)
target = target.cuda(async=True)
input_var = torch.autograd.Variable(input)
target_var = torch.autograd.Variable(target)
# compute output
output, soft_target = model(input_var)
if not isinstance(output, list):
output = [output]
loss = kd_loss.loss_fn_kd(output, target_var, soft_target)
losses.update(loss.item(), input.size(0))
for j in range(len(output)):
acc1, acc5 = accuracy(output[j].data, target, topk=(1, 5))
top1[j].update(acc1.item(), input.size(0))
top5[j].update(acc5.item(), input.size(0))
# compute gradient and do SGD step
optimizer.zero_grad()
loss.backward()
optimizer.step()
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
if i % args.print_freq == 0:
print('Epoch: [{0}][{1}/{2}]\t'
'Time {batch_time.avg:.3f}\t'
'Data {data_time.avg:.3f}\t'
'Loss {loss.val:.4f}\t'
'Acc@1 {top1.val:.4f}\t'
'Acc@5 {top5.val:.4f}'.format(
epoch, i + 1, len(train_loader),
batch_time=batch_time, data_time=data_time,
loss=losses, top1=top1[-1], top5=top5[-1]))
return losses.avg, top1[-1].avg, top5[-1].avg, running_lr
def validate(val_loader, model, kd_loss):
batch_time = AverageMeter()
losses = AverageMeter()
data_time = AverageMeter()
top1, top5 = [], []
for i in range(args.nBlocks):
top1.append(AverageMeter())
top5.append(AverageMeter())
# switch to evaluate mode
model.eval()
end = time.time()
with torch.no_grad():
for i, (input, target) in enumerate(val_loader):
target = target.cuda(async=True)
input = input.cuda()
input_var = torch.autograd.Variable(input)
target_var = torch.autograd.Variable(target)
data_time.update(time.time() - end)
# compute output
output = model(input_var)
if not isinstance(output, list):
output = [output]
loss = kd_loss.loss_fn_kd(output, target_var, output[-1])
# measure error and record loss
losses.update(loss.item(), input.size(0))
for j in range(len(output)):
acc1, acc5 = accuracy(output[j].data, target, topk=(1, 5))
top1[j].update(acc1.item(), input.size(0))
top5[j].update(acc5.item(), input.size(0))
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
if i % args.print_freq == 0:
print('Epoch: [{0}/{1}]\t'
'Time {batch_time.avg:.3f}\t'
'Data {data_time.avg:.3f}\t'
'Loss {loss.val:.4f}\t'
'Acc@1 {top1.val:.4f}\t'
'Acc@5 {top5.val:.4f}'.format(
i + 1, len(val_loader),
batch_time=batch_time, data_time=data_time,
loss=losses, top1=top1[-1], top5=top5[-1]))
# break
for j in range(args.nBlocks):
print(' * Acc@1 {top1.avg:.3f} Acc@5 {top5.avg:.3f}'.format(top1=top1[j], top5=top5[j]))
"""
print('Exit {}\t'
'Err@1 {:.4f}\t'
'Err@5 {:.4f}'.format(
j, top1[j].avg, top5[j].avg))
"""
# print(' * Err@1 {top1.avg:.3f} Err@5 {top5.avg:.3f}'.format(top1=top1[-1], top5=top5[-1]))
return losses.avg, top1[-1].avg, top5[-1].avg
def save_checkpoint(state, args, is_best, filename, result):
print(args)
result_filename = os.path.join(args.save, 'scores.tsv')
model_dir = os.path.join(args.save, 'save_models')
latest_filename = os.path.join(model_dir, 'latest.txt')
model_filename = os.path.join(model_dir, filename)
best_filename = os.path.join(model_dir, 'model_best.pth.tar')
os.makedirs(args.save, exist_ok=True)
os.makedirs(model_dir, exist_ok=True)
print("=> saving checkpoint '{}'".format(model_filename))
torch.save(state, model_filename)
with open(result_filename, 'w') as f:
print('\n'.join(result), file=f)
with open(latest_filename, 'w') as fout:
fout.write(model_filename)
if is_best:
shutil.copyfile(model_filename, best_filename)
print("=> saved checkpoint '{}'".format(model_filename))
return
def load_checkpoint(args):
model_dir = os.path.join(args.save, 'save_models')
latest_filename = os.path.join(model_dir, 'latest.txt')
if os.path.exists(latest_filename):
with open(latest_filename, 'r') as fin:
model_filename = fin.readlines()[0]
else:
return None
print("=> loading checkpoint '{}'".format(model_filename))
state = torch.load(model_filename)
print("=> loaded checkpoint '{}'".format(model_filename))
return state
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
def accuracy(output, target, topk=(1,)):
"""Computes the error@k for the specified values of k"""
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.view(1, -1).expand_as(pred))
res = []
for k in topk:
correct_k = correct[:k].view(-1).float().sum(0)
# res.append(100.0 - correct_k.mul_(100.0 / batch_size))
res.append(correct_k.mul_(100.0 / batch_size))
return res
def adjust_learning_rate(optimizer, epoch, args, batch=None,
nBatch=None, method='multistep'):
if method == 'cosine':
T_total = args.epochs * nBatch
T_cur = (epoch % args.epochs) * nBatch + batch
lr = 0.5 * args.lr * (1 + math.cos(math.pi * T_cur / T_total))
elif method == 'multistep':
if args.data.startswith('cifar'):
lr, decay_rate = args.lr, 0.1
if epoch >= args.epochs * 0.75:
lr *= decay_rate ** 2
elif epoch >= args.epochs * 0.5:
lr *= decay_rate
else:
lr = args.lr * (0.1 ** (epoch // 30))
for param_group in optimizer.param_groups:
param_group['lr'] = lr
return lr
if __name__ == '__main__':
main()