-
Notifications
You must be signed in to change notification settings - Fork 43
/
utils.py
168 lines (125 loc) · 4.39 KB
/
utils.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
import numpy as np
import os
import torch
import torch.nn.functional as F
import curves
def l2_regularizer(weight_decay):
def regularizer(model):
l2 = 0.0
for p in model.parameters():
l2 += torch.sqrt(torch.sum(p ** 2))
return 0.5 * weight_decay * l2
return regularizer
def cyclic_learning_rate(epoch, cycle, alpha_1, alpha_2):
def schedule(iter):
t = ((epoch % cycle) + iter) / cycle
if t < 0.5:
return alpha_1 * (1.0 - 2.0 * t) + alpha_2 * 2.0 * t
else:
return alpha_1 * (2.0 * t - 1.0) + alpha_2 * (2.0 - 2.0 * t)
return schedule
def adjust_learning_rate(optimizer, lr):
for param_group in optimizer.param_groups:
param_group['lr'] = lr
return lr
def save_checkpoint(dir, epoch, name='checkpoint', **kwargs):
state = {
'epoch': epoch,
}
state.update(kwargs)
filepath = os.path.join(dir, '%s-%d.pt' % (name, epoch))
torch.save(state, filepath)
def train(train_loader, model, optimizer, criterion, regularizer=None, lr_schedule=None):
loss_sum = 0.0
correct = 0.0
num_iters = len(train_loader)
model.train()
for iter, (input, target) in enumerate(train_loader):
if lr_schedule is not None:
lr = lr_schedule(iter / num_iters)
adjust_learning_rate(optimizer, lr)
input = input.cuda(async=True)
target = target.cuda(async=True)
output = model(input)
loss = criterion(output, target)
if regularizer is not None:
loss += regularizer(model)
optimizer.zero_grad()
loss.backward()
optimizer.step()
loss_sum += loss.item() * input.size(0)
pred = output.data.argmax(1, keepdim=True)
correct += pred.eq(target.data.view_as(pred)).sum().item()
return {
'loss': loss_sum / len(train_loader.dataset),
'accuracy': correct * 100.0 / len(train_loader.dataset),
}
def test(test_loader, model, criterion, regularizer=None, **kwargs):
loss_sum = 0.0
nll_sum = 0.0
correct = 0.0
model.eval()
for input, target in test_loader:
input = input.cuda(async=True)
target = target.cuda(async=True)
output = model(input, **kwargs)
nll = criterion(output, target)
loss = nll.clone()
if regularizer is not None:
loss += regularizer(model)
nll_sum += nll.item() * input.size(0)
loss_sum += loss.item() * input.size(0)
pred = output.data.argmax(1, keepdim=True)
correct += pred.eq(target.data.view_as(pred)).sum().item()
return {
'nll': nll_sum / len(test_loader.dataset),
'loss': loss_sum / len(test_loader.dataset),
'accuracy': correct * 100.0 / len(test_loader.dataset),
}
def predictions(test_loader, model, **kwargs):
model.eval()
preds = []
targets = []
for input, target in test_loader:
input = input.cuda(async=True)
output = model(input, **kwargs)
probs = F.softmax(output, dim=1)
preds.append(probs.cpu().data.numpy())
targets.append(target.numpy())
return np.vstack(preds), np.concatenate(targets)
def isbatchnorm(module):
return issubclass(module.__class__, torch.nn.modules.batchnorm._BatchNorm) or \
issubclass(module.__class__, curves._BatchNorm)
def _check_bn(module, flag):
if isbatchnorm(module):
flag[0] = True
def check_bn(model):
flag = [False]
model.apply(lambda module: _check_bn(module, flag))
return flag[0]
def reset_bn(module):
if isbatchnorm(module):
module.reset_running_stats()
def _get_momenta(module, momenta):
if isbatchnorm(module):
momenta[module] = module.momentum
def _set_momenta(module, momenta):
if isbatchnorm(module):
module.momentum = momenta[module]
def update_bn(loader, model, **kwargs):
if not check_bn(model):
return
model.train()
momenta = {}
model.apply(reset_bn)
model.apply(lambda module: _get_momenta(module, momenta))
num_samples = 0
for input, _ in loader:
input = input.cuda(async=True)
batch_size = input.data.size(0)
momentum = batch_size / (num_samples + batch_size)
for module in momenta.keys():
module.momentum = momentum
model(input, **kwargs)
num_samples += batch_size
model.apply(lambda module: _set_momenta(module, momenta))