-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfreerex.py
335 lines (236 loc) · 13.1 KB
/
freerex.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
import torch
import numpy as np
from torch.optim import Optimizer
EPSILON = 1e-8
class FreeRex(Optimizer):
"""Implements FreeRex algorithm
http://proceedings.mlr.press/v65/cutkosky17a.html.
Arguments:
params (iterable): iterable of parameters to optimize or dicts defining
parameter groups
lr (float, optional): learning rate analogue (specifies a point on optimal regret frontier) (default: 1/sqrt(5))
weight_decay (float, optional): weight decay (L2 penalty) (default: 0)
"""
def __init__(self, params, lr=1.0/np.sqrt(5.0), weight_decay=0):
defaults = dict(lr=lr, weight_decay=weight_decay)
super(FreeRex, self).__init__(params, defaults)
for group in self.param_groups:
for p in group['params']:
state = self.state[p]
state['step'] = 0
state['one_over_eta_sq'] = p.data.new().resize_as_(p.data).fill_(EPSILON)
state['grad_sum'] = p.data.new().resize_as_(p.data).zero_()
state['beta'] = p.data.new().resize_as_(p.data).zero_()
state['scaling'] = 1.0#p.data.new().resize_as_(p.data).fill_(1.0)
state['max_grad'] = p.data.new().resize_as_(p.data).fill_(EPSILON)
state['max_l2'] = EPSILON
state['center'] = p.data.clone()
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:
loss = closure()
for group in self.param_groups:
for p in group['params']:
if p.grad is None:
continue
grad = p.grad.data
state = self.state[p]
state['step'] += 1
if group['weight_decay'] != 0:
if p.grad.data.is_sparse:
raise RuntimeError("weight_decay option is not compatible with sparse gradients ")
grad = grad.add(group['weight_decay'], p.data)
if p.grad.data.is_sparse:
grad = grad.coalesce() # the update is non-linear so indices must be unique
grad_indices = grad._indices().numpy()
grad_values = grad._values()
size = torch.Size([x for x in grad.size()])
sparse_one_over_eta_sq = state['one_over_eta_sq'][grad_indices]
sparse_max_grad = state['max_grad'][grad_indices]
sparse_grad_sum = state['grad_sum'][grad_indices]
sparse_max_grad = torch.max(sparse_max_grad, torch.abs(grad_values))
sparse_grad_sum.add_(grad_values)
sparse_one_over_eta_sq = torch.max(sparse_one_over_eta_sq + 2*grad_values.pow(2), sparse_max_grad * torch.abs(sparse_grad_sum))
state['max_grad'][grad_indices] = sparse_max_grad
state['grad_sum'][grad_indices] = sparse_grad_sum
state['one_over_eta_sq'][grad_indices] = sparse_one_over_eta_sq
p.data[grad_indices] = -torch.sign(sparse_grad_sum) * (torch.exp(torch.abs(sparse_grad_sum)*group['lr']/(torch.sqrt(sparse_one_over_eta_sq))) - 1.0)
else:
state['max_grad'] = torch.max(state['max_grad'], torch.abs(grad))
state['max_l2'] = max(state['max_l2'], grad.norm(2))
state['scaling'] = min(state['scaling'], state['max_l2']/torch.sum(state['max_grad']))
state['grad_sum'].add_(grad)
state['one_over_eta_sq'] = torch.max(state['one_over_eta_sq'] + 2*grad.pow(2), state['max_grad'] * torch.abs(state['grad_sum']))
p.data = state['center']-torch.sign(state['grad_sum']) * (torch.exp(torch.abs(state['grad_sum'])*group['lr']/(torch.sqrt(state['one_over_eta_sq']))) - 1.0) * state['scaling']#/np.sqrt(state['max_l1'])
return loss
class FreeRexMD(Optimizer):
"""Implements FreeRex algorithm
http://proceedings.mlr.press/v65/cutkosky17a.html.
Arguments:
params (iterable): iterable of parameters to optimize or dicts defining
parameter groups
lr (float, optional): learning rate analogue (specifies a point on optimal regret frontier) (default: 1/sqrt(5))
weight_decay (float, optional): weight decay (L2 penalty) (default: 0)
"""
def __init__(self, params, lr=1.0/np.sqrt(5.0), weight_decay=0):
defaults = dict(lr=lr, weight_decay=weight_decay)
super(FreeRexMD, self).__init__(params, defaults)
for group in self.param_groups:
for p in group['params']:
state = self.state[p]
state['step'] = 0
state['one_over_eta_sq'] = p.data.new().resize_as_(p.data).fill_(EPSILON)
state['grad_sum'] = p.data.new().resize_as_(p.data).zero_()
state['log'] = p.data.new().resize_as_(p.data).zero_()
state['scaling'] = 1.0#p.data.new().resize_as_(p.data).fill_(1.0)
state['max_grad'] = p.data.new().resize_as_(p.data).fill_(1.0)
state['max_l2'] = EPSILON
state['center'] = p.data.clone()
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:
loss = closure()
for group in self.param_groups:
for p in group['params']:
if p.grad is None:
continue
grad = p.grad.data
state = self.state[p]
state['step'] += 1
if group['weight_decay'] != 0:
if p.grad.data.is_sparse:
raise RuntimeError("weight_decay option is not compatible with sparse gradients ")
grad = grad.add(group['weight_decay'], p.data)
state['max_grad'] = torch.max(state['max_grad'], torch.abs(grad))
state['max_l2'] = max(state['max_l2'], grad.norm(2))
state['scaling'] = min(state['scaling'], state['max_l2']/torch.sum(state['max_grad']))
state['grad_sum'].add_(grad)
state['one_over_eta_sq'] = torch.max(state['one_over_eta_sq'] + 2*grad.pow(2), state['max_grad'] * torch.abs(state['grad_sum']))
state['log'] -= grad/torch.sqrt(state['one_over_eta_sq'])
p.data = state['center'] + torch.sign(state['log']) * (torch.exp(torch.abs(state['log']))-1)
return loss
class FreeRexSphere(Optimizer):
"""Implements FreeRex algorithm
http://proceedings.mlr.press/v65/cutkosky17a.html.
Arguments:
params (iterable): iterable of parameters to optimize or dicts defining
parameter groups
lr (float, optional): learning rate analogue (specifies a point on optimal regret frontier) (default: 1/sqrt(5))
weight_decay (float, optional): weight decay (L2 penalty) (default: 0)
"""
def __init__(self, params, lr=1.0/np.sqrt(5.0), weight_decay=0, momentum=False):
defaults = dict(lr=lr, weight_decay=weight_decay, momentum=momentum)
super(FreeRexSphere, self).__init__(params, defaults)
for group in self.param_groups:
for p in group['params']:
state = self.state[p]
state['step'] = 0
state['one_over_eta_sq'] = EPSILON#p.data.new().resize_as_(p.data).fill_(EPSILON)
state['grad_sum'] = p.data.new().resize_as_(p.data).zero_()
# state['beta'] = p.data.new().resize_as_(p.data).zero_()
# state['scaling'] = 1.0#p.data.new().resize_as_(p.data).fill_(1.0)
state['max_grad'] = EPSILON#p.data.new().resize_as_(p.data).fill_(EPSILON)
# state['max_l2'] = EPSILON
state['center'] = p.data.clone()
state['sum_grad_norm_square'] = EPSILON
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:
loss = closure()
for group in self.param_groups:
for p in group['params']:
if p.grad is None:
continue
grad = p.grad.data
state = self.state[p]
state['step'] += 1
if group['weight_decay'] != 0:
if p.grad.data.is_sparse:
raise RuntimeError("weight_decay option is not compatible with sparse gradients ")
grad = grad.add(group['weight_decay'], p.data)
grad_norm = grad.norm(2)
state['max_grad'] = max(state['max_grad'], grad_norm)
state['sum_grad_norm_square'] += grad_norm**2
# state['max_l2'] = max(state['max_l2'], grad.norm(2))
# state['scaling'] = min(state['scaling'], state['max_l2']/torch.sum(state['max_grad']))
state['grad_sum'].add_(grad)
grad_sum_norm = state['grad_sum'].norm(2)
state['one_over_eta_sq'] = max(state['one_over_eta_sq'] + 2*grad_norm**2, state['max_grad'] * grad_sum_norm)
if group['momentum']:
state['center'] += (p.data - state['center'])* grad_norm**2/state['sum_grad_norm_square']
p.data = state['center']-state['grad_sum']/grad_sum_norm * (np.exp(state['grad_sum'].norm(2)*group['lr']/(np.sqrt(state['one_over_eta_sq']))) - 1.0)# * state['scaling']#/np.sqrt(state['max_l1'])
return loss
class FreeRexSphereMD(Optimizer):
"""Implements FreeRex algorithm
http://proceedings.mlr.press/v65/cutkosky17a.html.
Arguments:
params (iterable): iterable of parameters to optimize or dicts defining
parameter groups
lr (float, optional): learning rate analogue (specifies a point on optimal regret frontier) (default: 1/sqrt(5))
weight_decay (float, optional): weight decay (L2 penalty) (default: 0)
"""
def __init__(self, params, lr=1.0/np.sqrt(5.0), weight_decay=0, momentum=False):
defaults = dict(lr=lr, weight_decay=weight_decay, momentum=momentum)
super(FreeRexSphereMD, self).__init__(params, defaults)
for group in self.param_groups:
for p in group['params']:
state = self.state[p]
state['step'] = 0
state['one_over_eta_sq'] = EPSILON#p.data.new().resize_as_(p.data).fill_(EPSILON)
state['grad_sum'] = p.data.new().resize_as_(p.data).zero_()
state['log'] = p.data.new().resize_as_(p.data).zero_()
# state['beta'] = p.data.new().resize_as_(p.data).zero_()
# state['scaling'] = 1.0#p.data.new().resize_as_(p.data).fill_(1.0)
state['max_grad'] = EPSILON#p.data.new().resize_as_(p.data).fill_(EPSILON)
# state['max_l2'] = EPSILON
state['center'] = p.data.clone()
state['sum_grad_norm_square'] = EPSILON
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:
loss = closure()
for group in self.param_groups:
for p in group['params']:
if p.grad is None:
continue
grad = p.grad.data
state = self.state[p]
state['step'] += 1
if group['weight_decay'] != 0:
if p.grad.data.is_sparse:
raise RuntimeError("weight_decay option is not compatible with sparse gradients ")
grad = grad.add(group['weight_decay'], p.data)
grad_norm = grad.norm(2)
state['max_grad'] = max(state['max_grad'], grad_norm)
state['sum_grad_norm_square'] += grad_norm**2
# state['max_l2'] = max(state['max_l2'], grad.norm(2))
# state['scaling'] = min(state['scaling'], state['max_l2']/torch.sum(state['max_grad']))
state['grad_sum'].add_(grad)
grad_sum_norm = state['grad_sum'].norm(2)
state['one_over_eta_sq'] = max(state['one_over_eta_sq'] + 2*grad_norm**2, state['max_grad'] * grad_sum_norm)
state['log'] -= grad/np.sqrt(state['one_over_eta_sq'])
if group['momentum']:
state['center'] += (p.data - state['center'])* grad_norm**2/state['sum_grad_norm_square']
lognorm = state['log'].norm(2)
p.data = state['center'] + state['log']/lognorm * (np.exp(lognorm) - 1)
return loss