-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathsvrg.py
More file actions
71 lines (61 loc) · 2.54 KB
/
svrg.py
File metadata and controls
71 lines (61 loc) · 2.54 KB
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
from torch.optim import Optimizer
import copy
class SVRG_k(Optimizer):
r"""Optimization class for calculating the gradient of one iteration.
Args:
params (iterable): iterable of parameters to optimize or dicts defining
parameter groups
lr (float): learning rate
"""
def __init__(self, params, lr, weight_decay=0):
print("Using optimizer: SVRG")
self.u = None
if lr < 0.0:
raise ValueError("Invalid learning rate: {}".format(lr))
if weight_decay < 0.0:
raise ValueError("Invalid weight decay: {}".format(weight_decay))
defaults = dict(lr=lr, weight_decay=weight_decay)
super(SVRG_k, self).__init__(params, defaults)
def get_param_groups(self):
return self.param_groups
def set_u(self, new_u):
"""Set the mean gradient for the current epoch.
"""
if self.u is None:
self.u = copy.deepcopy(new_u)
for u_group, new_group in zip(self.u, new_u):
for u, new_u in zip(u_group['params'], new_group['params']):
u.grad = new_u.grad.clone()
def step(self, params):
"""Performs a single optimization step.
"""
for group, new_group, u_group in zip(self.param_groups, params, self.u):
weight_decay = group['weight_decay']
for p, q, u in zip(group['params'], new_group['params'], u_group['params']):
if p.grad is None:
continue
if q.grad is None:
continue
# core SVRG gradient update
new_d = p.grad.data - q.grad.data + u.grad.data
if weight_decay != 0:
new_d.add_(weight_decay, p.data)
p.data.add_(-group['lr'], new_d)
class SVRG_Snapshot(Optimizer):
r"""Optimization class for calculating the mean gradient (snapshot) of all samples.
Args:
params (iterable): iterable of parameters to optimize or dicts defining
parameter groups
lr (float): learning rate
"""
def __init__(self, params):
defaults = dict()
super(SVRG_Snapshot, self).__init__(params, defaults)
def get_param_groups(self):
return self.param_groups
def set_param_groups(self, new_params):
"""Copies the parameters from another optimizer.
"""
for group, new_group in zip(self.param_groups, new_params):
for p, q in zip(group['params'], new_group['params']):
p.data[:] = q.data[:]