-
Notifications
You must be signed in to change notification settings - Fork 7
/
optimizers.py
262 lines (215 loc) · 9.81 KB
/
optimizers.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
import torch
import math
import regularizers as reg
class LinBreg(torch.optim.Optimizer):
def __init__(self,params,lr=1e-3,reg=reg.reg_none(), delta=1.0, momentum=0.0):
if lr < 0.0:
raise ValueError("Invalid learning rate")
defaults = dict(lr=lr, reg=reg, delta=delta, momentum=momentum)
super(LinBreg, self).__init__(params, defaults)
@torch.no_grad()
def step(self, closure=None):
for group in self.param_groups:
delta = group['delta']
# define regularizer for this group
reg = group['reg']
step_size = group['lr']
momentum = group['momentum']
for p in group['params']:
if p.grad is None:
continue
# get grad and state
grad = p.grad.data
state = self.state[p]
if len(state) == 0:
state['step'] = 0
# get prox
# initialize subgradients
state['sub_grad'] = self.initialize_sub_grad(p,reg, delta)
state['momentum_buffer'] = None
# -------------------------------------------------------------
# update scheme
# -------------------------------------------------------------
# get the current sub gradient
sub_grad = state['sub_grad']
# update on the subgradient
if momentum > 0.0: # with momentum
mom_buff = state['momentum_buffer']
if state['momentum_buffer'] is None:
mom_buff = torch.zeros_like(grad)
mom_buff.mul_(momentum)
mom_buff.add_((1-momentum)*step_size*grad)
state['momentum_buffer'] = mom_buff
#update subgrad
sub_grad.add_(-mom_buff)
else: # no momentum
sub_grad.add_(-step_size * grad)
# update step for parameters
p.data = reg.prox(delta * sub_grad, delta)
def initialize_sub_grad(self,p, reg, delta):
p_init = p.data.clone()
return 1/delta * p_init + reg.sub_grad(p_init)
@torch.no_grad()
def evaluate_reg(self):
reg_vals = []
for group in self.param_groups:
group_reg_val = 0.0
delta = group['delta']
# define regularizer for this group
reg = group['reg']
# evaluate the reguarizer for each parametr in group
for p in group['params']:
group_reg_val += reg(p)
# append the group reg val
reg_vals.append(group_reg_val)
return reg_vals
# ------------------------------------------------------------------------------------------------------
class ProxSGD(torch.optim.Optimizer):
def __init__(self,params,lr=1e-3,reg=reg.reg_none()):
if lr < 0.0:
raise ValueError("Invalid learning rate")
defaults = dict(lr=lr, reg=reg)
super(ProxSGD, self).__init__(params, defaults)
@torch.no_grad()
def step(self, closure=None):
for group in self.param_groups:
# define regularizer for this group
reg = group['reg']
step_size = group['lr']
for p in group['params']:
if p.grad is None:
continue
# get grad and state
grad = p.grad.data
state = self.state[p]
if len(state) == 0:
state['step'] = 0
# -------------------------------------------------------------
# update scheme
# -------------------------------------------------------------
# gradient steps
p.data.add_(-step_size * grad)
# proximal step
p.data = reg.prox(p.data, step_size)
@torch.no_grad()
def evaluate_reg(self):
reg_vals = []
for group in self.param_groups:
group_reg_val = 0.0
# define regularizer for this group
reg = group['reg']
# evaluate the reguarizer for each parametr in group
for p in group['params']:
group_reg_val += reg(p)
# append the group reg val
reg_vals.append(group_reg_val)
return reg_vals
# ------------------------------------------------------------------------------------------------------
class AdaBreg(torch.optim.Optimizer):
def __init__(self,params,lr=1e-3,reg=reg.reg_none(), delta=1.0, betas=(0.9, 0.999), eps=1e-8):
if lr < 0.0:
raise ValueError("Invalid learning rate")
defaults = dict(lr=lr, reg=reg, delta=delta, betas=betas, eps=eps)
super(AdaBreg, self).__init__(params, defaults)
@torch.no_grad()
def step(self, closure=None):
for group in self.param_groups:
delta = group['delta']
# get regularizer for this group
reg = group['reg']
# get parameters for adam
lr = group['lr']
beta1, beta2 = group['betas']
eps = group['eps']
for p in group['params']:
if p.grad is None:
continue
# get grad and state
grad = p.grad.data
state = self.state[p]
if len(state) == 0:
state['step'] = 0
# get prox
# initialize subgradients
state['sub_grad'] = self.initialize_sub_grad(p,reg, delta)
state['exp_avg'] = torch.zeros_like(state['sub_grad'])
state['exp_avg_sq'] = torch.zeros_like(state['sub_grad'])
# -------------------------------------------------------------
# update scheme
# -------------------------------------------------------------
# update step
state['step'] += 1
step = state['step']
# get the current sub gradient and averages
sub_grad = state['sub_grad']
exp_avg = state['exp_avg']
exp_avg_sq = state['exp_avg_sq']
# define bias correction factors
bias_correction1 = 1 - beta1 ** step
bias_correction2 = 1 - beta2 ** step
# Decay the first and second moment running average coefficient
exp_avg.mul_(beta1).add_(grad, alpha=1 - beta1)
exp_avg_sq.mul_(beta2).addcmul_(grad, grad, value=1 - beta2)
# denominator in the fraction
denom = (exp_avg_sq.sqrt() / math.sqrt(bias_correction2)).add_(eps)
# step size in adam update
step_size = lr / bias_correction1
# update subgrad
sub_grad.addcdiv_(exp_avg, denom, value=-step_size)
# update step for parameters
p.data = reg.prox(delta * sub_grad, delta)
def initialize_sub_grad(self,p, reg, delta):
p_init = p.data.clone()
return 1/delta * p_init + reg.sub_grad(p_init)
@torch.no_grad()
def evaluate_reg(self):
reg_vals = []
for group in self.param_groups:
group_reg_val = 0.0
delta = group['delta']
# define regularizer for this group
reg = group['reg']
# evaluate the reguarizer for each parametr in group
for p in group['params']:
group_reg_val += reg(p)
# append the group reg val
reg_vals.append(group_reg_val)
return reg_vals
class lamda_scheduler:
'''scheduler for the regularization parameter'''
def __init__(self, opt,idx, warmup = 0, increment = 0.05, cooldown=0, target_sparse=1.0, reg_param ="mu"):
self.opt = opt
self.group = opt.param_groups[idx]
# warm up
self.warmup = warmup
# increment
self.increment = increment
# cooldown
self.cooldown_val = cooldown
self.cooldown = cooldown
# target
self.target_sparse = target_sparse
self.reg_param = reg_param
def __call__(self, sparse, verbosity = 1):
# check if we are still in the warm up phase
if self.warmup > 0:
self.warmup -= 1
elif self.warmup == 0:
self.warmup = -1
else:
# cooldown
if self.cooldown_val > 0:
self.cooldown_val -= 1
else: # cooldown is over, time to update and reset cooldown
self.cooldown_val = self.cooldown
# discrepancy principle for lamda
if sparse > self.target_sparse:
self.group['reg'].mu += self.increment
else:
self.group['reg'].mu = max(self.group['reg'].mu - self.increment,0.0)
# reset subgradients
for p in self.group['params']:
state = self.opt.state[p]
state['sub_grad'] = self.opt.initialize_sub_grad(p, self.group['reg'], self.group['delta'])
if verbosity > 0:
print('Lamda was set to:', self.group['reg'].mu, ', cooldown on:',self.cooldown_val)