-
Notifications
You must be signed in to change notification settings - Fork 1
/
train_utils.py
411 lines (342 loc) · 14 KB
/
train_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
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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
import torch
import torch.nn as nn
from torch.utils.tensorboard import SummaryWriter
from torch.optim.lr_scheduler import LambdaLR
import torch.nn.functional as F
import math
import time
import os
from copy import deepcopy
from torch.optim.optimizer import Optimizer, required
import copy
from custom_writer import CustomWriter
'''
We reimplement SGD to keep cosistent with the origin paper. But we actually do not use it. You can use it if you want.
'''
class SGD(Optimizer):
r"""Implements stochastic gradient descent (optionally with momentum).
Nesterov momentum is based on the formula from
`On the importance of initialization and momentum in deep learning`__.
Args:
params (iterable): iterable of parameters to optimize or dicts defining
parameter groups
lr (float): learning rate
momentum (float, optional): momentum factor (default: 0)
weight_decay (float, optional): weight decay (L2 penalty) (default: 0)
dampening (float, optional): dampening for momentum (default: 0)
nesterov (bool, optional): enables Nesterov momentum (default: False)
Example:
>>> optimizer = torch.optim.SGD(model.parameters(), lr=0.1, momentum=0.9)
>>> optimizer.zero_grad()
>>> loss_fn(model(input), target).backward()
>>> optimizer.step()
__ http://www.cs.toronto.edu/%7Ehinton/absps/momentum.pdf
.. note::
The implementation of SGD with Momentum/Nesterov subtly differs from
Sutskever et. al. and implementations in some other frameworks.
Considering the specific case of Momentum, the update can be written as
.. math::
\begin{aligned}
v_{t+1} & = \mu * v_{t} + g_{t+1}, \\
p_{t+1} & = p_{t} - \text{lr} * v_{t+1},
\end{aligned}
where :math:`p`, :math:`g`, :math:`v` and :math:`\mu` denote the
parameters, gradient, velocity, and momentum respectively.
This is in contrast to Sutskever et. al. and
other frameworks which employ an update of the form
.. math::
\begin{aligned}
v_{t+1} & = \mu * v_{t} + \text{lr} * g_{t+1}, \\
p_{t+1} & = p_{t} - v_{t+1}.
\end{aligned}
The Nesterov version is analogously modified.
"""
def __init__(self, params, lr=required, momentum=0, dampening=0,
weight_decay=0, nesterov=False):
if lr is not required and lr < 0.0:
raise ValueError("Invalid learning rate: {}".format(lr))
if momentum < 0.0:
raise ValueError("Invalid momentum value: {}".format(momentum))
if weight_decay < 0.0:
raise ValueError("Invalid weight_decay value: {}".format(weight_decay))
defaults = dict(lr=lr, momentum=momentum, dampening=dampening,
weight_decay=weight_decay, nesterov=nesterov)
if nesterov and (momentum <= 0 or dampening != 0):
raise ValueError("Nesterov momentum requires a momentum and zero dampening")
super(SGD, self).__init__(params, defaults)
def __setstate__(self, state):
super(SGD, self).__setstate__(state)
for group in self.param_groups:
group.setdefault('nesterov', False)
@torch.no_grad()
def step(self, closure=None):
"""Performs a single optimization step.
Arguments:
closure (callable, optional): A closure that reevaluates the model
and returns the loss.
"""
loss = None
if closure is not None:
with torch.enable_grad():
loss = closure()
for group in self.param_groups:
weight_decay = group['weight_decay']
momentum = group['momentum']
dampening = group['dampening']
nesterov = group['nesterov']
for p in group['params']:
if p.grad is None:
continue
d_p = p.grad
if weight_decay != 0:
d_p = d_p.add(p, alpha=weight_decay)
d_p.mul_(group['lr'])
if momentum != 0:
param_state = self.state[p]
if 'momentum_buffer' not in param_state:
buf = param_state['momentum_buffer'] = torch.clone(d_p).detach()
else:
buf = param_state['momentum_buffer']
buf.mul_(momentum).add_(d_p, alpha=1 - dampening)
if nesterov:
d_p = d_p.add(buf, alpha=momentum)
else:
d_p = buf
p.add_(d_p, alpha=-1)
return loss
class TBLog:
"""
Construc tensorboard writer (self.writer).
The tensorboard is saved at os.path.join(tb_dir, file_name).
"""
def __init__(self, tb_dir, file_name, writer_type="custom"):
self.tb_dir = tb_dir
self.writer_type = writer_type
if self.writer_type == "tensorboard":
self.writer = SummaryWriter(os.path.join(self.tb_dir, file_name))
elif self.writer_type == "custom":
self.writer = CustomWriter(os.path.join(self.tb_dir, file_name))
def update(self, tb_dict, it, suffix=None, mode="train"):
"""
Args
tb_dict: contains scalar values for updating tensorboard
it: contains information of iteration (int).
suffix: If not None, the update key has the suffix.
"""
if suffix is None:
suffix = ''
if self.writer_type == "tensorboard":
for key, value in tb_dict.items():
self.writer.add_scalar(suffix + key, value, it)
elif self.writer_type == "custom":
self.writer.set_epoch(it, mode)
for key, value in tb_dict.items():
self.writer.add_scalar(suffix + key, value)
if it < 1000000:
return
self.writer.plot_stats()
self.writer.dump_stats()
class AverageMeter(object):
"""
refer: https://github.com/pytorch/examples/blob/master/imagenet/main.py
"""
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 wd_loss(net):
loss = 0
for name, param in net.named_parameters():
if ('bn' in name or 'bias' in name):
continue
elif ('weight' in name):
loss = loss + torch.sum(param ** 2) / 2
return loss
def get_optimizer(net, optim_name='SGD', lr=0.1, momentum=0.9, weight_decay=0, nesterov=True, bn_wd_skip=True):
'''
return optimizer (name) in torch.optim.
If bn_wd_skip, the optimizer does not apply
weight decay regularization on parameters in batch normalization.
'''
decay = []
no_decay = []
for name, param in net.named_parameters():
if ('bn' in name or 'bias' in name) and bn_wd_skip:
no_decay.append(param)
else:
decay.append(param)
per_param_args = [{'params': decay},
{'params': no_decay, 'weight_decay': 0.0}]
if optim_name == 'SGD':
optimizer = torch.optim.SGD(per_param_args, lr=lr, momentum=momentum, weight_decay=weight_decay,
nesterov=nesterov)
elif optim_name == 'AdamW':
optimizer = torch.optim.AdamW(per_param_args, lr=lr, weight_decay=weight_decay)
return optimizer
def get_cosine_schedule_with_warmup(optimizer,
num_training_steps,
num_cycles=7. / 16.,
num_warmup_steps=0,
last_epoch=-1):
'''
Get cosine scheduler (LambdaLR).
if warmup is needed, set num_warmup_steps (int) > 0.
'''
def _lr_lambda(current_step):
'''
_lr_lambda returns a multiplicative factor given an interger parameter epochs.
Decaying criteria: last_epoch
'''
if current_step < num_warmup_steps:
_lr = float(current_step) / float(max(1, num_warmup_steps))
else:
num_cos_steps = float(current_step - num_warmup_steps)
num_cos_steps = num_cos_steps / float(max(1, num_training_steps - num_warmup_steps))
_lr = max(0.0, math.cos(math.pi * num_cycles * num_cos_steps))
return _lr
return LambdaLR(optimizer, _lr_lambda, last_epoch)
def get_imagenet_schedule(optimizer, num_training_steps, num_labels, batch_size):
def iter2epoch(iter):
iter_per_ep = num_labels // batch_size
ep = iter // iter_per_ep
return ep
def epoch2iter(epoch):
iter_per_ep = num_labels // batch_size
iter = epoch * iter_per_ep
return iter
def _lr_lambda(iter):
return None
def accuracy(output, target, topk=(1,)):
"""
Computes the accuracy over the k top predictions for the specified values of k
Args
output: logits or probs (num of batch, num of classes)
target: (num of batch, 1) or (num of batch, )
topk: list of returned k
refer: https://github.com/pytorch/examples/blob/master/imagenet/main.py
"""
with torch.no_grad():
maxk = max(topk) # get k in top-k
batch_size = target.size(0) # get batch size of target
# torch.topk(input, k, dim=None, largest=True, sorted=True, out=None)
# return: value, index
_, pred = output.topk(k=maxk, dim=1, largest=True, sorted=True) # pred: [num of batch, k]
pred = pred.t() # pred: [k, num of batch]
# [1, num of batch] -> [k, num_of_batch] : bool
correct = pred.eq(target.view(1, -1).expand_as(pred))
res = []
for k in topk:
correct_k = correct[:k].view(-1).float().sum(0, keepdim=True)
res.append(correct_k.mul_(100.0 / batch_size))
# np.shape(res): [k, 1]
return res
def ce_loss(logits, targets, use_hard_labels=True, reduction='none'):
"""
wrapper for cross entropy loss in pytorch.
Args
logits: logit values, shape=[Batch size, # of classes]
targets: integer or vector, shape=[Batch size] or [Batch size, # of classes]
use_hard_labels: If True, targets have [Batch size] shape with int values. If False, the target is vector (default True)
"""
if use_hard_labels:
log_pred = F.log_softmax(logits, dim=-1)
return F.nll_loss(log_pred, targets, reduction=reduction)
# return F.cross_entropy(logits, targets, reduction=reduction) this is unstable
else:
assert logits.shape == targets.shape
log_pred = F.log_softmax(logits, dim=-1)
nll_loss = torch.sum(-targets * log_pred, dim=1)
return nll_loss
# class EMA:
# """
# Implementation from https://fyubang.com/2019/06/01/ema/
# """
#
# def __init__(self, model, decay):
# self.model = model
# self.decay = decay
# self.shadow = {}
# self.backup = {}
#
# def load(self, model):
# self.model.load_state_dict(model.state_dict())
#
# def register(self):
# self.shadow = deepcopy(self.model.state_dict())
#
#
# def update(self):
# for name, param in self.model.state_dict().items():
# assert name in self.shadow
# new_avg = (1.0 - self.decay) * param + self.decay * self.shadow[name]
# self.shadow[name] = new_avg
#
# def apply_shadow(self):
# self.backup = deepcopy(self.model.state_dict())
# self.model.load_state_dict(self.shadow)
#
# def restore(self):
# self.model.load_state_dict(self.backup)
# self.backup = {}
class EMA:
"""
Implementation from https://fyubang.com/2019/06/01/ema/
"""
def __init__(self, model, decay):
self.model = model
self.decay = decay
self.shadow = {}
self.backup = {}
def load(self, ema_model):
for name, param in ema_model.named_parameters():
self.shadow[name] = param.data.clone()
def register(self):
for name, param in self.model.named_parameters():
if param.requires_grad:
self.shadow[name] = param.data.clone()
def update(self):
for name, param in self.model.named_parameters():
if param.requires_grad:
assert name in self.shadow
new_average = (1.0 - self.decay) * param.data + self.decay * self.shadow[name]
self.shadow[name] = new_average.clone()
def apply_shadow(self):
for name, param in self.model.named_parameters():
if param.requires_grad:
assert name in self.shadow
self.backup[name] = param.data
param.data = self.shadow[name]
def restore(self):
for name, param in self.model.named_parameters():
if param.requires_grad:
assert name in self.backup
param.data = self.backup[name]
self.backup = {}
class Bn_Controller:
def __init__(self):
"""
freeze_bn and unfreeze_bn must appear in pairs
"""
self.backup = {}
def freeze_bn(self, model):
assert self.backup == {}
for name, m in model.named_modules():
if isinstance(m, nn.SyncBatchNorm) or isinstance(m, nn.BatchNorm2d):
self.backup[name + '.running_mean'] = m.running_mean.data.clone()
self.backup[name + '.running_var'] = m.running_var.data.clone()
self.backup[name + '.num_batches_tracked'] = m.num_batches_tracked.data.clone()
def unfreeze_bn(self, model):
for name, m in model.named_modules():
if isinstance(m, nn.SyncBatchNorm) or isinstance(m, nn.BatchNorm2d):
m.running_mean.data = self.backup[name + '.running_mean']
m.running_var.data = self.backup[name + '.running_var']
m.num_batches_tracked.data = self.backup[name + '.num_batches_tracked']
self.backup = {}