-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.py
159 lines (134 loc) · 4.61 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
import numpy as np
import sys
import os
import torch
from torch import optim
class Logger(object) :
def __init__(self, log) :
self.terminal = sys.stdout
self.log = open(log, "a")
def write(self, message) :
self.terminal.write(message)
self.log.write(message)
self.log.flush()
def flush(self) :
pass
def load_weight(net, weight_dict) :
state_dict = net.state_dict()
for key in weight_dict.keys() :
if key in state_dict and (weight_dict[key].size() == state_dict[key].size()) :
value = weight_dict[key]
if not isinstance(value, torch.Tensor) :
value = value.data
state_dict[key] = value
net.load_state_dict(state_dict)
def gpu(data) :
if isinstance(data, list) or isinstance(data, tuple) :
data = [gpu(x) for x in data]
elif isinstance(data, dict) :
data = {key :gpu(_data) for key,_data in data.items()}
elif isinstance(data, torch.Tensor) :
data = data.contiguous().cuda(non_blocking=True)
return data
class Optimizer(object) :
def __init__(self, params, config, coef=None) :
if not (isinstance(params, list) or isinstance(params, tuple)) :
params = [params]
if coef is None :
coef = [1.0] * len(params)
else :
if isinstance(coef, list) or isinstance(coef, tuple) :
assert len(coef) == len(params)
else :
coef = [coef] * len(params)
self.coef = coef
param_groups = []
for param in params :
param_groups.append({"params" : param, "lr" : 0})
self.opt = optim.Adam(param_groups, weight_decay=0)
self.lr_func = config["lr_func"]
if "clip_grads" in config :
self.clip_grads = config["clip_grads"]
self.clip_low = config["clip_low"]
self.clip_high = config["clip_high"]
else :
self.clip_grads = False
def zero_grad(self) :
self.opt.zero_grad()
def step(self, epoch) :
if self.clip_grads :
self.clip()
lr = self.lr_func(epoch)
for i, param_group in enumerate(self.opt.param_groups) :
param_group["lr"] = lr * self.coef[i]
self.opt.step()
return lr
def clip(self) :
low, high = self.clip_low, self.clip_high
params = []
for param_group in self.opt.param_groups :
params += list(filter(lambda p : p.grad is not None, param_group["params"]))
for p in params :
mask = p.grad.data < low
p.grad.data[mask] = low
mask = p.grad.data > high
p.grad.data[mask] = high
def load_state_dict(self, opt_state) :
self.opt.load_state_dict(opt_state)
class StepLR :
def __init__(self, lr, lr_epochs) :
assert len(lr) - len(lr_epochs) == 1
self.lr = lr
self.lr_epochs = lr_epochs
def __call__(self, epoch) :
idx = 0
for lr_epoch in self.lr_epochs :
if epoch < lr_epoch :
break
idx += 1
return self.lr[idx]
def from_numpy(data) :
if isinstance(data, dict) :
for key in data.keys() :
data[key] = from_numpy(data[key])
if isinstance(data, list) or isinstance(data, tuple) :
data = [from_numpy(x) for x in data]
if isinstance(data, np.ndarray) :
data = torch.from_numpy(data)
return data
def to_numpy(data) :
if isinstance(data, dict) :
for key in data.keys() :
data[key] = to_numpy(data[key])
if isinstance(data, list) or isinstance(data, tuple) :
data = [to_numpy(x) for x in data]
if torch.is_tensor(data) :
data = data.numpy()
return data
def to_long(data) :
if isinstance(data, dict) :
for key in data.keys() :
data[key] = to_long(data[key])
if isinstance(data, list) or isinstance(data, tuple) :
data = [to_long(x) for x in data]
if torch.is_tensor(data) and data.dtype == torch.int16 :
data = data.long()
return data
def ref_copy(data) :
if isinstance(data, list) :
return [ref_copy(x) for x in data]
if isinstance(data, dict) :
d = dict()
for key in data :
d[key] = ref_copy(data[key])
return d
return data
def to_int16(data) :
if isinstance(data, dict) :
for key in data.keys() :
data[key] = to_int16(data[key])
if isinstance(data, list) or isinstance(data, tuple) :
data = [to_int16(x) for x in data]
if isinstance(data, np.ndarray) and data.dtype == np.int64 :
data = data.astype(np.int16)
return data