-
Notifications
You must be signed in to change notification settings - Fork 8
/
optimizer_lib.py
224 lines (147 loc) · 5.3 KB
/
optimizer_lib.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
#!/usr/bin/env python
# coding: utf-8
from __future__ import print_function
import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
import torchvision
from torchvision import datasets, models, transforms
import copy
import os
import shutil
class local_sgd(optim.SGD):
def __init__(self, params, reg_lambda, lr = 0.001, momentum = 0, dampening = 0, weight_decay = 0, nesterov = False):
super(local_sgd, self).__init__(params, lr, momentum, dampening, weight_decay, nesterov)
self.reg_lambda = reg_lambda
def __setstate__(self, state):
super(local_sgd, self).__setstate__(state)
def step(self, reg_params, closure = None):
loss = None
if closure is not None:
loss = closure()
for group in self.param_groups:
weight_decay = group['weight_decay']
momentum = group['momentum']
dampening = group['dampening']
nesterov = group['nesterov']
for p in group['params']:
if p.grad is None:
continue
d_p = p.grad.data
if p in reg_params:
param_dict = reg_params[p]
omega = param_dict['omega']
init_val = param_dict['init_val']
curr_param_value = p.data
curr_param_value = curr_param_value.cuda()
init_val = init_val.cuda()
omega = omega.cuda()
#get the difference
param_diff = curr_param_value - init_val
#get the gradient for the penalty term for change in the weights of the parameters
local_grad = torch.mul(param_diff, 2*self.reg_lambda*omega)
del param_diff
del omega
del init_val
del curr_param_value
d_p = d_p + local_grad
del local_grad
if (weight_decay != 0):
d_p.add_(weight_decay, p.data)
if (momentum != 0):
param_state = self.state[p]
if 'momentum_buffer' not in param_state:
buf = param_state['momentum_buffer'] = torch.clone(d_p).detach()
else:
buf = param_state['momentum_buffer']
buf.mul_(momentum).add_(1 - dampening, d_p)
if nesterov:
d_p = d_p.add(momentum, buf)
else:
d_p = buf
p.data.add_(-group['lr'], d_p)
return loss
class omega_update(optim.SGD):
def __init__(self, params, lr = 0.001, momentum = 0, dampening = 0, weight_decay = 0, nesterov = False):
super(omega_update, self).__init__(params, lr, momentum, dampening, weight_decay, nesterov)
def __setstate__(self, state):
super(omega_update, self).__setstate__(state)
def step(self, reg_params, batch_index, batch_size, use_gpu, closure = None):
loss = None
if closure is not None:
loss = closure()
for group in self.param_groups:
weight_decay = group['weight_decay']
momentum = group['momentum']
dampening = group['dampening']
nesterov = group['nesterov']
for p in group['params']:
if p.grad is None:
continue
if p in reg_params:
grad_data = p.grad.data
#The absolute value of the grad_data that is to be added to omega
grad_data_copy = p.grad.data.clone()
grad_data_copy = grad_data_copy.abs()
param_dict = reg_params[p]
omega = param_dict['omega']
omega = omega.to(torch.device("cuda:0" if use_gpu else "cpu"))
current_size = (batch_index+1)*batch_size
step_size = 1/float(current_size)
#Incremental update for the omega
omega = omega + step_size*(grad_data_copy - batch_size*(omega))
param_dict['omega'] = omega
reg_params[p] = param_dict
return loss
class omega_vector_update(optim.SGD):
def __init__(self, params, lr = 0.001, momentum = 0, dampening = 0, weight_decay = 0, nesterov = False):
super(omega_vector_update, self).__init__(params, lr, momentum, dampening, weight_decay, nesterov)
def __setstate__(self, state):
super(omega_vector_update, self).__setstate__(state)
def step(self, reg_params, finality, batch_index, batch_size, use_gpu, closure = None):
loss = None
device = torch.device("cuda:0" if use_gpu else "cpu")
if closure is not None:
loss = closure()
for group in self.param_groups:
weight_decay = group['weight_decay']
momentum = group['momentum']
dampening = group['dampening']
nesterov = group['nesterov']
for p in group['params']:
if p.grad is None:
continue
if p in reg_params:
grad_data = p.grad.data
#The absolute value of the grad_data that is to be added to omega
grad_data_copy = p.grad.data.clone()
grad_data_copy = grad_data_copy.abs()
param_dict = reg_params[p]
if not finality:
if 'temp_grad' in reg_params.keys():
temp_grad = param_dict['temp_grad']
else:
temp_grad = torch.FloatTensor(p.data.size()).zero_()
temp_grad = temp_grad.to(device)
temp_grad = temp_grad + grad_data_copy
param_dict['temp_grad'] = temp_grad
del temp_data
else:
#temp_grad variable
temp_grad = param_dict['temp_grad']
temp_grad = temp_grad + grad_data_copy
#omega variable
omega = param_dict['omega']
omega.to(device)
current_size = (batch_index+1)*batch_size
step_size = 1/float(current_size)
#Incremental update for the omega
omega = omega + step_size*(temp_grad - batch_size*(omega))
param_dict['omega'] = omega
reg_params[p] = param_dict
del omega
del param_dict
del grad_data
del grad_data_copy
return loss