-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathoptimizer.py
477 lines (411 loc) · 16.5 KB
/
optimizer.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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
# Original from: https://github.com/titu1994/keras-normalized-optimizers
from __future__ import division
from keras import optimizers
from keras.legacy import interfaces
from keras.utils.generic_utils import get_custom_objects
from keras import backend as K
def max_norm(grad):
"""
Computes the L-infinity norm of the gradient.
# Arguments:
grad: gradient for a variable
# Returns:
The norm of the gradient
"""
grad_max = K.max(K.abs(grad))
norm = grad_max + K.epsilon()
return norm
def min_max_norm(grad):
"""
Computes the average of the Max and Min of the absolute
values of the gradients.
# Arguments:
grad: gradient for a variable
# Returns:
The norm of the gradient
"""
grad_min = K.min(K.abs(grad))
grad_max = K.max(K.abs(grad))
norm = ((grad_max + grad_min) / 2.0) + K.epsilon()
return norm
def std_norm(grad):
"""
Computes the standard deviation of the gradient.
# Arguments:
grad: gradient for a variable
# Returns:
The norm of the gradient
"""
norm = K.std(grad) + K.epsilon()
return norm
def l1_norm(grad):
"""
Computes the L-1 norm of the gradient.
# Arguments:
grad: gradient for a variable
# Returns:
The norm of the gradient
"""
norm = K.sum(K.abs(grad)) + K.epsilon()
return norm
def l2_norm(grad):
"""
Computes the L-2 norm of the gradient.
# Arguments:
grad: gradient for a variable
# Returns:
The norm of the gradient
"""
norm = K.sqrt(K.sum(K.square(grad))) + K.epsilon()
return norm
def l1_l2_norm(grad):
"""
Computes the average of the L-1 and L-2 norms of the gradient.
# Arguments:
grad: gradient for a variable
# Returns:
The norm of the gradient
"""
l1 = l1_norm(grad)
l2 = l2_norm(grad)
norm = ((l1 + l2) / 2.) + K.epsilon()
return norm
def average_l1_norm(grad):
"""
Computes the average of the L-1 norm (instead of sum) of the
gradient.
# Arguments:
grad: gradient for a variable
# Returns:
The norm of the gradient
"""
norm = K.mean(K.abs(grad)) + K.epsilon()
return norm
def average_l2_norm(grad):
"""
Computes the average of the L-2 norm (instead of sum) of the
gradient.
# Arguments:
grad: gradient for a variable
# Returns:
The norm of the gradient
"""
norm = K.sqrt(K.mean(K.square(grad))) + K.epsilon()
return norm
def average_l1_l2_norm(grad):
"""
Computes the average of the L-1 and L-2 norms (instead of the sum)
to compute the normalized gradient.
# Arguments:
grad: gradient for a variable
# Returns:
The norm of the gradient
"""
l1_norm = K.mean(K.abs(grad))
l2_norm = K.sqrt(K.mean(K.square(grad)))
norm = ((l1_norm + l2_norm) / 2.) + K.epsilon()
return norm
class OptimizerWrapper(optimizers.Optimizer):
def __init__(self, optimizer):
"""
Base wrapper class for a Keras optimizer such that its gradients are
corrected prior to computing the update ops.
Since it is a wrapper optimizer, it must delegate all normal optimizer
calls to the optimizer that it wraps.
Note:
This wrapper optimizer monkey-patches the optimizer it wraps such that
the call to `get_gradients` will call the gradients of the
optimizer and then normalize the list of gradients.
This is required because Keras calls the optimizer's `get_gradients`
method inside `get_updates`, and without this patch, we cannot
normalize the gradients before computing the rest of the
`get_updates` code.
# Abstract Methods
get_gradients: Must be overridden to support differnt gradient
operations.
get_config: Config needs to be carefully built for serialization.
from_config: Config must be carefully used to build a Subclass.
# Arguments:
optimizer: Keras Optimizer or a string. All optimizers other
than TFOptimizer are supported. If string, instantiates a
default optimizer with that alias.
# Raises
NotImplementedError: If `optimizer` is of type `TFOptimizer`.
"""
if optimizer.__class__.__name__ == 'TFOptimizer':
raise NotImplementedError('Currently, TFOptimizer is not supported.')
self.optimizer = optimizers.get(optimizer)
# patch the `get_gradients` call
self._optimizer_get_gradients = self.optimizer.get_gradients
def get_gradients(self, loss, params):
"""
Compute the gradients of the wrapped Optimizer.
# Arguments:
loss: Keras tensor with a single value.
params: List of tensors to optimize
# Returns:
A list of normalized gradient tensors
"""
grads = self._optimizer_get_gradients(loss, params)
return grads
@interfaces.legacy_get_updates_support
def get_updates(self, loss, params):
"""
Computes the update operations of the wrapped Optimizer using
normalized gradients and returns a list of operations.
# Arguments:
loss: Keras tensor with a single value
params: List of tensors to optimize
# Returns:
A list of parameter and optimizer update operations
"""
# monkey patch `get_gradients`
self.optimizer.get_gradients = self.get_gradients
# get the updates
self.optimizer.get_updates(loss, params)
# undo monkey patch
self.optimizer.get_gradients = self._optimizer_get_gradients
return self.updates
def set_weights(self, weights):
"""
Set the weights of the wrapped optimizer by delegation
# Arguments:
weights: List of weight matrices
"""
self.optimizer.set_weights(weights)
def get_weights(self):
"""
Get the weights of the wrapped optimizer by delegation
# Returns:
List of weight matrices
"""
return self.optimizer.get_weights()
def get_config(self):
"""
Updates the config of the wrapped optimizer with some meta
data about the normalization function as well as the optimizer
name so that model saving and loading can take place
# Returns:
dictionary of the config
"""
# properties of NormalizedOptimizer
config = {'optimizer_name': self.optimizer.__class__.__name__.lower()}
# optimizer config
optimizer_config = {'optimizer_config': self.optimizer.get_config()}
return dict(list(optimizer_config.items()) + list(config.items()))
@property
def weights(self):
return self.optimizer.weights
@property
def updates(self):
return self.optimizer.updates
@classmethod
def from_config(cls, config):
raise NotImplementedError
@classmethod
def set_normalization_function(cls, name, func):
"""
Allows the addition of new normalization functions adaptively
# Arguments:
name: string name of the normalization function
func: callable function which takes in a single tensor and
returns a single tensor (input gradient tensor and output
normalized gradient tensor).
"""
global _NORMS
_NORMS[name] = func
@classmethod
def get_normalization_functions(cls):
"""
Get the list of all registered normalization functions that can be
used.
# Returns:
list of strings denoting the names of all of the normalization
functions.
"""
global _NORMS
return sorted(list(_NORMS.keys()))
class NormalizedOptimizer(OptimizerWrapper):
def __init__(self, optimizer, normalization='l2'):
"""
Creates a wrapper for a Keras optimizer such that its gradients are
normalized prior to computing the update ops.
Since it is a wrapper optimizer, it must delegate all normal optimizer
calls to the optimizer that it wraps.
Note:
This wrapper optimizer monkey-patches the optimizer it wraps such that
the call to `get_gradients` will call the gradients of the
optimizer and then normalize the list of gradients.
This is required because Keras calls the optimizer's `get_gradients`
method inside `get_updates`, and without this patch, we cannot
normalize the gradients before computing the rest of the
`get_updates` code.
# Arguments:
optimizer: Keras Optimizer or a string. All optimizers other
than TFOptimizer are supported. If string, instantiates a
default optimizer with that alias.
normalization: string. Must refer to a normalization function
that is available in this modules list of normalization
functions. To get all possible normalization functions,
use `NormalizedOptimizer.get_normalization_functions()`.
# Raises
ValueError: If an incorrect name is supplied for `normalization`,
such that the normalization function is not available or not
set using `NormalizedOptimizer.set_normalization_functions()`.
NotImplementedError: If `optimizer` is of type `TFOptimizer`.
"""
super(NormalizedOptimizer, self).__init__(optimizer)
if normalization not in _NORMS:
raise ValueError('`normalization` must be one of %s.\n'
'Provided was "%s".' % (str(sorted(list(_NORMS.keys()))), normalization))
self.normalization = normalization
self.normalization_fn = _NORMS[normalization]
def get_gradients(self, loss, params):
"""
Compute the gradients of the wrapped Optimizer, then normalize
them with the supplied normalization function.
# Arguments:
loss: Keras tensor with a single value.
params: List of tensors to optimize
# Returns:
A list of normalized gradient tensors
"""
grads = super(NormalizedOptimizer, self).get_gradients(loss, params)
grads = [grad / self.normalization_fn(grad) for grad in grads]
return grads
def get_config(self):
"""
Updates the config of the wrapped optimizer with some meta
data about the normalization function as well as the optimizer
name so that model saving and loading can take place
# Returns:
dictionary of the config
"""
# properties of NormalizedOptimizer
config = {'normalization': self.normalization}
# optimizer config
base_config = super(NormalizedOptimizer, self).get_config()
return dict(list(base_config.items()) + list(config.items()))
@classmethod
def from_config(cls, config):
"""
Utilizes the meta data from the config to create a new instance
of the optimizer which was wrapped previously, and creates a
new instance of this wrapper class.
# Arguments:
config: dictionary of the config
# Returns:
a new instance of NormalizedOptimizer
"""
optimizer_config = {'class_name': config['optimizer_name'],
'config': config['optimizer_config']}
optimizer = optimizers.get(optimizer_config)
normalization = config['normalization']
return cls(optimizer, normalization=normalization)
class ClippedOptimizer(OptimizerWrapper):
def __init__(self, optimizer, normalization='l2', clipnorm=1.0):
"""
Creates a wrapper for a Keras optimizer such that its gradients are
clipped by the norm prior to computing the update ops.
Since it is a wrapper optimizer, it must delegate all normal optimizer
calls to the optimizer that it wraps.
Note:
This wrapper optimizer monkey-patches the optimizer it wraps such that
the call to `get_gradients` will call the gradients of the
optimizer and then normalize the list of gradients.
This is required because Keras calls the optimizer's `get_gradients`
method inside `get_updates`, and without this patch, we cannot
normalize the gradients before computing the rest of the
`get_updates` code.
# Arguments:
optimizer: Keras Optimizer or a string. All optimizers other
than TFOptimizer are supported. If string, instantiates a
default optimizer with that alias.
normalization: string. Must refer to a normalization function
that is available in this modules list of normalization
functions. To get all possible normalization functions,
use `NormalizedOptimizer.get_normalization_functions()`.
clipnorm: float >= 0. Gradients will be clipped
when their norm exceeds this value.
# Raises
ValueError: If an incorrect name is supplied for `normalization`,
such that the normalization function is not available or not
set using `ClippedOptimizer.set_normalization_functions()`.
NotImplementedError: If `optimizer` is of type `TFOptimizer`.
"""
super(ClippedOptimizer, self).__init__(optimizer)
if normalization not in _NORMS:
raise ValueError('`normalization` must be one of %s.\n'
'Provided was "%s".' % (str(sorted(list(_NORMS.keys()))), normalization))
self.normalization = normalization
self.normalization_fn = _NORMS[normalization]
self.clipnorm = clipnorm
def get_gradients(self, loss, params):
"""
Compute the gradients of the wrapped Optimizer, then normalize
them with the supplied normalization function.
# Arguments:
loss: Keras tensor with a single value.
params: List of tensors to optimize
# Returns:
A list of normalized gradient tensors
"""
grads = super(ClippedOptimizer, self).get_gradients(loss, params)
grads = [self._clip_grad(grad) for grad in grads]
return grads
def get_config(self):
"""
Updates the config of the wrapped optimizer with some meta
data about the normalization function as well as the optimizer
name so that model saving and loading can take place
# Returns:
dictionary of the config
"""
# properties of NormalizedOptimizer
config = {'normalization': self.normalization,
'clipnorm': self.clipnorm}
# optimizer config
base_config = super(ClippedOptimizer, self).get_config()
return dict(list(base_config.items()) + list(config.items()))
def _clip_grad(self, grad):
"""
Helper method to compute the norm and then clip the gradients.
# Arguments:
grad: gradients of a single variable
# Returns:
clipped gradients
"""
norm = self.normalization_fn(grad)
grad = optimizers.clip_norm(grad, self.clipnorm, norm)
return grad
@classmethod
def from_config(cls, config):
"""
Utilizes the meta data from the config to create a new instance
of the optimizer which was wrapped previously, and creates a
new instance of this wrapper class.
# Arguments:
config: dictionary of the config
# Returns:
a new instance of NormalizedOptimizer
"""
optimizer_config = {'class_name': config['optimizer_name'],
'config': config['optimizer_config']}
optimizer = optimizers.get(optimizer_config)
normalization = config['normalization']
clipnorm = config['clipnorm']
return cls(optimizer, normalization=normalization, clipnorm=clipnorm)
_NORMS = {
'max': max_norm,
'min_max': min_max_norm,
'l1': l1_norm,
'l2': l2_norm,
'linf': max_norm,
'l1_l2': l1_l2_norm,
'std': std_norm,
'avg_l1': average_l1_norm,
'avg_l2': average_l2_norm,
'avg_l1_l2': average_l1_l2_norm,
}
# register this optimizer to the global custom objects when it is imported
get_custom_objects().update({'NormalizedOptimizer': NormalizedOptimizer, 'ClippedOptimizer': ClippedOptimizer})