-
Notifications
You must be signed in to change notification settings - Fork 2
/
hypernet.py
280 lines (256 loc) · 11.4 KB
/
hypernet.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
import torch
import torch.nn as nn
import math
import numpy as np
from functools import partial
class Hypernet(nn.Module):
def __init__(self, weight_decay_type = 'per_param', weight_decay_init = 5e-4, if_tune_reg=1, freeze_bn_reg=False, reg_type='L2', normalize_type='exp', scale=(1, 2e-3), if_normalize=False, bn_only=False, reg_names=None):
super(Hypernet, self).__init__()
self.weight_decay_type = weight_decay_type
self.weight_decay_init = weight_decay_init
self.if_tune_reg = if_tune_reg
self.reg_type = reg_type
self.tune_bn = not freeze_bn_reg
self.requires_grad = False if self.if_tune_reg == 0 else True
self.normalize_type = normalize_type
self.if_normalize = if_normalize
self.bn_only = bn_only
self.init_normalize_func(scale)
self.reg_names = reg_names
def extract_feat(self, img):
raise NotImplementedError
def predict(self, feat):
raise NotImplementedError
def forward(self, img, return_feat=False):
feat = self.extract_feat(img)
out = self.predict(feat)
if return_feat:
return out, feat
else:
return out
def init_wdecay(self, weight_decay_type, weight_decay_init):
if weight_decay_type == "single":
requires_grad = self.requires_grad
weight_decay = torch.tensor([self.normalize_inv(weight_decay_init)], requires_grad=requires_grad, device="cuda")
self.__setattr__(f"weight_decay", weight_decay)
elif weight_decay_type == "per_param":
i=0
for name, p in self.named_parameters():
if (not self.tune_bn and 'bn' in name) or (self.bn_only and 'bn' not in name):
requires_grad = False
else:
requires_grad = self.requires_grad
self.__setattr__(f"weight_decay_{i}", torch.full_like(p, self.normalize_inv(weight_decay_init), requires_grad=requires_grad, device="cuda"))
i += 1
elif weight_decay_type == "anyin":
i=0
for name, p in self.named_parameters():
if len([n for n in self.reg_names if n in name]) == 0:
requires_grad = False
else:
requires_grad = self.requires_grad
self.__setattr__(f"weight_decay_{i}", torch.full_like(p, self.normalize_inv(weight_decay_init), requires_grad=requires_grad, device="cuda"))
i += 1
elif weight_decay_type == "classifier":
i=0
for name, p in self.named_parameters():
if 'classifier' not in name:
requires_grad = False
else:
requires_grad = self.requires_grad
self.__setattr__(f"weight_decay_{i}", torch.full_like(p, self.normalize_inv(weight_decay_init), requires_grad=requires_grad, device="cuda"))
i += 1
elif weight_decay_type == "per_layer":
i=0
for name, p in self.named_parameters():
if not self.tune_bn and 'bn' in name:
requires_grad = False
else:
requires_grad = self.requires_grad
self.__setattr__(f"weight_decay_{i}", torch.tensor(self.normalize_inv(weight_decay_init) , requires_grad=requires_grad, device="cuda"))
i += 1
elif weight_decay_type == "per_channel":
i=0
for name, p in self.named_parameters():
# if 'fc' in name or (not self.tune_bn and 'bn' in name):
if not self.tune_bn and 'bn' in name:
requires_grad = False
else:
requires_grad = self.requires_grad
self.__setattr__(f"weight_decay_{i}", torch.full((p.shape[0],1),self.normalize_inv(weight_decay_init) , requires_grad=requires_grad, device="cuda"))
i += 1
elif weight_decay_type == "per_bn":
i=0
for name, p in self.named_parameters():
if self.tune_bn and 'bn' in name:
requires_grad = True
else:
requires_grad = False
self.__setattr__(f"weight_decay_{i}", torch.full_like(p, self.normalize_inv(weight_decay_init), requires_grad=requires_grad, device="cuda"))
i += 1
elif weight_decay_type == "per_filter":
i=0
for name, p in self.named_parameters():
if self.tune_bn and 'bn' in name:
requires_grad = True
else:
requires_grad = False
if len(p.shape) == 4:
self.__setattr__(f"weight_decay_{i}", torch.full([p.shape[0],p.shape[1],1,1], self.normalize_inv(weight_decay_init), requires_grad=requires_grad, device="cuda"))
else:
self.__setattr__(f"weight_decay_{i}", torch.full_like(p, self.normalize_inv(weight_decay_init), requires_grad=requires_grad, device="cuda"))
i += 1
def L2_loss(self):
if self.weight_decay_type == "single":
return self.single_L2_loss()
elif self.weight_decay_type == "per_param" or self.weight_decay_type == "per_bn" or self.weight_decay_type == "classifier" or self.weight_decay_type == "anyin":
return self.all_L2_loss()
elif self.weight_decay_type == "per_layer":
return self.layer_L2_loss()
elif self.weight_decay_type == "per_channel":
return self.channel_L2_loss()
elif self.weight_decay_type == "per_filter":
return self.filter_L2_loss()
elif self.weight_decay_type == "none":
return self.no_L2_loss()
else:
raise NotImplementedError("not implemented")
def single_L2_loss(self):
loss = 0
for name, p in self.named_parameters():
if not self.tune_bn:
if 'bais' not in name and 'bn' not in name:
loss += torch.sum(self.normalize_func(self.weight_decay) * self.reg_term(p))
else:
loss += torch.sum(self.weight_decay_init * self.reg_term(p))
else:
loss += torch.sum(self.normalize_func(self.weight_decay) * self.reg_term(p))
return loss
# return loss * (torch.exp(self.weight_decay))
def all_L2_loss(self):
loss = 0
for i, p in enumerate(self.parameters()):
loss += torch.sum(self.normalize_func(getattr(self, f"weight_decay_{i}")) * self.reg_term(p))
# loss += torch.sum((getattr(self, f"weight_decay_{i}")) * p)
return loss
def layer_L2_loss(self):
loss = 0
for i, p in enumerate(self.parameters()):
loss += torch.sum(self.normalize_func(getattr(self, f"weight_decay_{i}")) * self.reg_term(p))
return loss
def channel_L2_loss(self):
loss = 0
for i, p in enumerate(self.parameters()):
loss += torch.sum(self.normalize_func(getattr(self, f"weight_decay_{i}")) * self.reg_term(p).reshape(p.shape[0], -1))
return loss
def filter_L2_loss(self):
loss = 0
for i, p in enumerate(self.parameters()):
loss += torch.sum(self.normalize_func(getattr(self, f"weight_decay_{i}")) * self.reg_term(p))
return loss
def no_L2_loss(self):
return 0
def reg_term(self, params):
if self.reg_type == "L2":
return params**2
elif self.reg_type == "L1":
return torch.abs(params)
def get_reg_params(self):
if self.weight_decay_type == "single":
return [self.weight_decay]
elif self.weight_decay_type == "per_param":
tune_regs = []
for i in range(self.num_params):
if getattr(self, f"weight_decay_{i}").requires_grad == True:
tune_regs.append(getattr(self, f"weight_decay_{i}"))
return tune_regs
else:
tune_regs = []
for i in range(self.num_params):
if getattr(self, f"weight_decay_{i}").requires_grad == True:
tune_regs.append(getattr(self, f"weight_decay_{i}"))
return tune_regs
def get_numels(self):
if self.weight_decay_type == "per_layer":
numels_tune = []
numels_all = [p.numel() for p in self.parameters()]
for i in range(self.num_params):
if getattr(self, f"weight_decay_{i}").requires_grad == True:
numels_tune.append(numels_all[i])
else:
numels_tune = None
return numels_tune
def get_reg_params_all(self):
if self.weight_decay_type == "single":
return [self.weight_decay]
else:
return [getattr(self, f"weight_decay_{i}") for i in range(self.num_params)]
def load_reg_params(self, reg_path):
regs = torch.load(reg_path)['reg']
for i, p in enumerate(self.parameters()):
regs[i].requires_grad = False
self.__setattr__(f"weight_decay_{i}", regs[i])
def init_normalize_func(self, scale):
if self.normalize_type == 'exp':
self.normalize_func = torch.exp
self.normalize_inv = math.log
elif self.normalize_type == 'sigmoid':
self.normalize_func = partial(sigmoid, scale=scale)
self.normalize_inv = partial(sigmoid_inv, scale=scale)
elif self.normalize_type == 'relu':
self.normalize_func = torch.relu
self.normalize_inv = linear
elif self.normalize_type == 'linear':
self.normalize_func = linear
self.normalize_inv = linear
elif self.normalize_type == 'tanh':
self.normalize_func = torch.tanh
self.normalize_inv = math.atanh
elif self.normalize_type == 'abs':
self.normalize_func = torch.abs
self.normalize_inv = linear
elif self.normalize_type == 'square':
self.normalize_func = torch.square
self.normalize_inv = math.sqrt
elif self.normalize_type == 'softplus':
self.normalize_func = softplus
self.normalize_inv = softplusinv
elif self.normalize_type == 'hard_sigmoid':
self.normalize_func = partial(hard_sigmoid, scale=scale)
self.normalize_inv = partial(hard_sigmoid_inv, scale=scale)
def sigmoid_inv(x, scale=(1, 2e-3)):
return -math.log((scale[1] / (x)) - 1)/scale[0]
def sigmoid(x, scale=(1, 2e-3)):
return (scale[1])/(1+torch.exp(-scale[0]*x))
def linear(x):
return x
def softplus(x):
return torch.log(torch.ones_like(x)+torch.exp(x))
def softplusinv(x):
return math.log(math.exp(x)-1.)
def hard_sigmoid(x, scale=(10, 2e-3)):
thresh1=-scale[0]
thresh2=scale[0]
upper=scale[1]
k = upper/(2*thresh2)
m1 = (x >= thresh2)
m2 = ((x > thresh1) & (x < thresh2))
m3 = (x <= thresh1)
out1 = upper*m1
out2 = (k * x + upper/2) * m2
out3 = 0 * m3
return out1+out2+out3
def hard_sigmoid_inv(x, scale=(10, 2e-3)):
thresh1= -scale[0]
thresh2= scale[0]
upper=scale[1]
k = upper/(2*thresh2)
if x > upper:
raise ValueError("greater than bound")
elif x < 0:
raise ValueError("smaller than bound")
else:
return x/k - upper/(2*k)
if __name__ == "__main__":
print(sigmoid(torch.tensor(sigmoid_inv(1e-4, scale=(1, 1))), scale=(1, 1)).item())
print(torch.exp(torch.tensor(math.log(1e-4))).item())