-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsgd_agc.py
177 lines (139 loc) · 6.3 KB
/
sgd_agc.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
import tensorflow as tf
from keras.optimizers import Optimizer
from tensorflow.python.keras.optimizer_v2 import optimizer_v2
def unitwise_norm(x: tf.Variable):
if x.ndim <= 1:
dim = 0
keepdim = False
elif x.ndim in [2, 3]:
dim = 0
keepdim = True
elif x.ndim == 4:
dim = [1, 2, 3]
keepdim = True
else:
raise ValueError('Wrong input dimensions')
return tf.reduce_sum.sum(x**2, axis=dim, keepdims=keepdim) ** 0.5
class SGD_AGC(optimizer_v2.OptimizerV2):
r"""Implements stochastic gradient descent (optionally with momentum).
Nesterov momentum is based on the formula from
`On the importance of initialization and momentum in deep learning`__
AGC from NFNets: https://arxiv.org/abs/2102.06171.pdf.
Args:
params (iterable): iterable of parameters to optimize or dicts defining
parameter groups
lr (float): learning rate
momentum (float, optional): momentum factor (default: 0)
weight_decay (float, optional): weight decay (L2 penalty) (default: 0)
dampening (float, optional): dampening for momentum (default: 0)
nesterov (bool, optional): enables Nesterov momentum (default: False)
dampening (float, optional): dampening for momentum (default: 0.01)
eps (float, optional): dampening for momentum (default: 1e-3)
Example:
>>> optimizer = SGD_AGC(lr=0.1, momentum=0.9)
>>> model.compile(optimizer, 'mse')
>>> model.fit(X, y)
.. note::
The implementation has been adapted from the keras repository and the official NF-Nets paper.
The implementation of SGD with Momentum/Nesterov subtly differs from
Sutskever et. al. and implementations in some other frameworks.
Considering the specific case of Momentum, the update can be written as
.. math::
\begin{aligned}
v_{t+1} & = \mu * v_{t} + g_{t+1}, \\
p_{t+1} & = p_{t} - \text{lr} * v_{t+1},
\end{aligned}
where :math:`p`, :math:`g`, :math:`v` and :math:`\mu` denote the
parameters, gradient, velocity, and momentum respectively.
This is in contrast to Sutskever et. al. and
other frameworks which employ an update of the form
.. math::
\begin{aligned}
v_{t+1} & = \mu * v_{t} + \text{lr} * g_{t+1}, \\
p_{t+1} & = p_{t} - v_{t+1}.
\end{aligned}
The Nesterov version is analogously modified.
"""
def __init__(self, params, lr, momentum=0, dampening=0,
weight_decay=0, nesterov=False, clipping=1e-2, eps=1e-3, **kwargs):
if lr is not None and lr < 0.0:
raise ValueError("Invalid learning rate: {}".format(lr))
if momentum < 0.0:
raise ValueError("Invalid momentum value: {}".format(momentum))
if weight_decay < 0.0:
raise ValueError(
"Invalid weight_decay value: {}".format(weight_decay))
if clipping < 0.0:
raise ValueError("Invalid clipping value: {}".format(clipping))
if eps < 0.0:
raise ValueError("Invalid eps value: {}".format(eps))
#defaults = dict(lr=lr, momentum=momentum, dampening=dampening,
# weight_decay=weight_decay, nesterov=nesterov, clipping=clipping, eps=eps)
if nesterov and (momentum <= 0 or dampening != 0):
raise ValueError(
"Nesterov momentum requires a momentum and zero dampening")
name = "SGD_AGC"
super(SGD_AGC, self).__init__(name, **kwargs)
self._set_hyper("learning_rate", kwargs.get("lr", lr))
self._set_hyper("decay", self._initial_decay)
self._set_hyper("momentum", momentum)
self._set_hyper("clipping", clipping)
self._set_hyper("eps", eps)
self._set_hyper("dampening", dampening)
self.nesterov = nesterov
#super(SGD_AGC, self).__init__(params, defaults)
def __setstate__(self, state):
super(SGD_AGC, self).__setstate__(state)
for group in self.param_groups:
group.setdefault('nesterov', False)
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:
with tf.GradientTape():
loss = closure()
for group in self.param_groups:
for p in group['params']:
param_norm = tf.max(unitwise_norm(
p), tf.Variable(group['eps']).to(p.device))
grad_norm = unitwise_norm(p.grad)
max_norm = param_norm * group['clipping']
trigger = grad_norm > max_norm
clipped_grad = p.grad * \
(max_norm / tf.max(grad_norm,
tf.tensor(1e-6).to(grad_norm.device)))
p.grad.data.copy_(tf.where(trigger, clipped_grad, p.grad))
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
if weight_decay != 0:
d_p = d_p.add(p, alpha=weight_decay)
if momentum != 0:
param_state = self.state[p]
if 'momentum_buffer' not in param_state:
buf = param_state['momentum_buffer'] = d_p.numpy()
else:
buf = param_state['momentum_buffer']
buf.mul_(momentum).add_(d_p, alpha=1 - dampening)
if nesterov:
d_p = d_p.add(buf, alpha=momentum)
else:
d_p = buf
p.add_(d_p, alpha=-group['lr'])
return loss
def get_config(self):
base_config = super().get_config()
return {
**base_config,
"learning_rate": self._serialize_hyperparameter("learning_rate"),
}