-
Notifications
You must be signed in to change notification settings - Fork 27
/
optimizer.py
63 lines (53 loc) · 1.84 KB
/
optimizer.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
#!/usr/bin/python
# -*- encoding: utf-8 -*-
import torch
import logging
import torch.distributed as dist
logger = logging.getLogger()
class Optimizer(object):
def __init__(self,
model,
lr0,
momentum,
wd,
warmup_steps,
warmup_start_lr,
max_iter,
power):
if hasattr(model, 'module'):
wd_params, non_wd_params = model.module.get_params()
else:
wd_params, non_wd_params = model.get_params()
params_list = [{'params': wd_params,},
{'params': non_wd_params, 'weight_decay': 0}]
self.warmup_steps = warmup_steps
self.warmup_start_lr = warmup_start_lr
self.lr0 = lr0
self.lr = self.lr0
self.max_iter = float(max_iter)
self.power = power
self.it = 0
self.optim = torch.optim.SGD(
params_list,
lr = lr0,
momentum = momentum,
weight_decay = wd)
self.warmup_factor = (self.lr0 / self.warmup_start_lr) ** (1. / self.warmup_steps)
def get_lr(self):
if self.it <= self.warmup_steps:
lr = self.warmup_start_lr * (self.warmup_factor ** self.it)
else:
factor = (1 - (self.it - self.warmup_steps) / (self.max_iter - self.warmup_steps)) ** self.power
lr = self.lr0 * factor
return lr
def step(self):
self.lr = self.get_lr()
for pg in self.optim.param_groups:
pg['lr'] = self.lr
self.optim.defaults['lr'] = self.lr
self.it += 1
self.optim.step()
if self.it == self.warmup_steps+2 and dist.get_rank()==0:
logger.info('==> warmup done, start to implement poly lr strategy')
def zero_grad(self):
self.optim.zero_grad()