/
optimizers.py
728 lines (620 loc) · 26.6 KB
/
optimizers.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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
"""Optimizers and related classes for use with TensorGraph."""
import math
from typing import Dict, Union, Optional
class Optimizer(object):
"""An algorithm for optimizing a model.
This is an abstract class. Subclasses represent specific optimization algorithms.
"""
def __init__(self, learning_rate: "Union[float, LearningRateSchedule]"):
"""This constructor should only be called by subclasses.
Parameters
----------
learning_rate: float or LearningRateSchedule
the learning rate to use for optimization
"""
self.learning_rate = learning_rate
def _create_tf_optimizer(self, global_step):
"""Construct a TensorFlow optimizer.
Parameters
----------
global_step: tensor
a tensor containing the global step index during optimization, used for learning rate decay
Returns
-------
a new TensorFlow optimizer implementing the algorithm
"""
raise NotImplementedError("Subclasses must implement this")
def _create_pytorch_optimizer(self, params):
"""Construct a PyTorch optimizer.
Parameters
----------
params: Iterable
the model parameters to optimize
Returns
-------
a new PyTorch optimizer implementing the algorithm
"""
raise NotImplementedError("Subclasses must implement this")
def _create_jax_optimizer(self):
"""Construct a Jax optimizer.
Returns
-------
a new Optax optimizer optax.GradientTransformation implementing the algorithm
"""
raise NotImplementedError("Subclasses must implement this")
class LearningRateSchedule(object):
"""A schedule for changing the learning rate over the course of optimization.
This is an abstract class. Subclasses represent specific schedules.
"""
def _create_tf_tensor(self, global_step):
"""Construct a tensor that equals the learning rate.
Parameters
----------
global_step: tensor
a tensor containing the global step index during optimization
Returns
-------
a tensor that equals the learning rate
"""
raise NotImplementedError("Subclasses must implement this")
def _create_pytorch_schedule(self, optimizer):
"""Construct a PyTorch learning rate scheduler.
Parameters
----------
optimizer: torch.optim.Optimizer
the Optimizer whose learning rate will be modified
Returns
-------
a PyTorch scheduler implementing the schedule
"""
raise NotImplementedError("Subclasses must implement this")
def _create_jax_schedule(self, learning_rate):
"""Construct a Jax learning rate scheduler using optax.
Parameters
----------
learning_rate: float
the initial learning rate that will be modified
Returns
-------
a optax scheduler implementing the schedule
"""
raise NotImplementedError("Subclasses must implement this")
class AdaGrad(Optimizer):
"""The AdaGrad optimization algorithm.
Adagrad is an optimizer with parameter-specific learning rates, which are
adapted relative to how frequently a parameter gets updated during training.
The more updates a parameter receives, the smaller the updates. See [1]_ for
a full reference for the algorithm.
References
----------
.. [1] Duchi, John, Elad Hazan, and Yoram Singer. "Adaptive subgradient
methods for online learning and stochastic optimization." Journal of machine
learning research 12.7 (2011).
"""
def __init__(self,
learning_rate: Union[float, LearningRateSchedule] = 0.001,
initial_accumulator_value: float = 0.1,
epsilon: float = 1e-07):
"""Construct an AdaGrad optimizer.
Parameters
----------
learning_rate: float or LearningRateSchedule
the learning rate to use for optimization
initial_accumulator_value: float
a parameter of the AdaGrad algorithm
epsilon: float
a parameter of the AdaGrad algorithm
"""
super(AdaGrad, self).__init__(learning_rate)
self.initial_accumulator_value = initial_accumulator_value
self.epsilon = epsilon
def _create_tf_optimizer(self, global_step):
import tensorflow as tf
if isinstance(self.learning_rate, LearningRateSchedule):
learning_rate = self.learning_rate._create_tf_tensor(global_step)
else:
learning_rate = self.learning_rate
return tf.keras.optimizers.legacy.Adagrad(
learning_rate=learning_rate,
initial_accumulator_value=self.initial_accumulator_value,
epsilon=self.epsilon)
def _create_pytorch_optimizer(self, params):
import torch
if isinstance(self.learning_rate, LearningRateSchedule):
lr = self.learning_rate.initial_rate
else:
lr = self.learning_rate
return torch.optim.Adagrad(
params,
lr,
initial_accumulator_value=self.initial_accumulator_value,
eps=self.epsilon)
def _create_jax_optimizer(self):
import optax
process = []
if isinstance(self.learning_rate, LearningRateSchedule):
lr = self.learning_rate.initial_rate
last_process = optax.scale(-1.0)
else:
lr = self.learning_rate
last_process = optax.scale(-1.0 * lr)
process.append(
optax.scale_by_rss(
initial_accumulator_value=self.initial_accumulator_value,
eps=self.epsilon))
process.append(last_process)
return optax.chain(*process)
class Adam(Optimizer):
"""The Adam optimization algorithm."""
def __init__(self,
learning_rate: Union[float, LearningRateSchedule] = 0.001,
beta1: float = 0.9,
beta2: float = 0.999,
epsilon: float = 1e-08,
weight_decay: float = 0):
"""Construct an Adam optimizer.
Parameters
----------
learning_rate: float or LearningRateSchedule
the learning rate to use for optimization
beta1: float
a parameter of the Adam algorithm
beta2: float
a parameter of the Adam algorithm
epsilon: float
a parameter of the Adam algorithm
weight_decay: float
L2 penalty - a parameter of the Adam algorithm
"""
super(Adam, self).__init__(learning_rate)
self.beta1 = beta1
self.beta2 = beta2
self.epsilon = epsilon
self.weight_decay = weight_decay
def _create_tf_optimizer(self, global_step):
import tensorflow as tf
if isinstance(self.learning_rate, LearningRateSchedule):
learning_rate = self.learning_rate._create_tf_tensor(global_step)
else:
learning_rate = self.learning_rate
return tf.keras.optimizers.legacy.Adam(learning_rate=learning_rate,
beta_1=self.beta1,
beta_2=self.beta2,
epsilon=self.epsilon)
def _create_pytorch_optimizer(self, params):
import torch
if isinstance(self.learning_rate, LearningRateSchedule):
lr = self.learning_rate.initial_rate
else:
lr = self.learning_rate
return torch.optim.Adam(params,
lr=lr,
betas=(self.beta1, self.beta2),
eps=self.epsilon,
weight_decay=self.weight_decay)
def _create_jax_optimizer(self):
import optax
process = []
if isinstance(self.learning_rate, LearningRateSchedule):
scheduler = self.learning_rate._create_jax_schedule()
process.append(optax.scale_by_schedule(scheduler))
last_process = optax.scale(-1.0)
else:
lr = self.learning_rate
last_process = optax.scale(-1.0 * lr)
process.append(
optax.scale_by_adam(b1=self.beta1, b2=self.beta2, eps=self.epsilon))
process.append(last_process)
return optax.chain(*process)
class SparseAdam(Optimizer):
"""The Sparse Adam optimization algorithm, also known as Lazy Adam.
Sparse Adam is suitable for sparse tensors. It handles sparse updates more efficiently.
It only updates moving-average accumulators for sparse variable indices that appear in the current batch, rather than updating the accumulators for all indices.
"""
def __init__(self,
learning_rate: Union[float, LearningRateSchedule] = 0.001,
beta1: float = 0.9,
beta2: float = 0.999,
epsilon: float = 1e-08):
"""Construct an Adam optimizer.
Parameters
----------
learning_rate: float or LearningRateSchedule
the learning rate to use for optimization
beta1: float
a parameter of the SparseAdam algorithm
beta2: float
a parameter of the SparseAdam algorithm
epsilon: float
a parameter of the SparseAdam algorithm
"""
super(SparseAdam, self).__init__(learning_rate)
self.beta1 = beta1
self.beta2 = beta2
self.epsilon = epsilon
def _create_tf_optimizer(self, global_step):
import tensorflow_addons as tfa
if isinstance(self.learning_rate, LearningRateSchedule):
learning_rate = self.learning_rate._create_tf_tensor(global_step)
else:
learning_rate = self.learning_rate
return tfa.optimizers.LazyAdam(learning_rate=learning_rate,
beta_1=self.beta1,
beta_2=self.beta2,
epsilon=self.epsilon)
def _create_pytorch_optimizer(self, params):
import torch
if isinstance(self.learning_rate, LearningRateSchedule):
lr = self.learning_rate.initial_rate
else:
lr = self.learning_rate
return torch.optim.SparseAdam(params, lr, (self.beta1, self.beta2),
self.epsilon)
class AdamW(Optimizer):
"""The AdamW optimization algorithm.
AdamW is a variant of Adam, with improved weight decay.
In Adam, weight decay is implemented as: weight_decay (float, optional) – weight decay (L2 penalty) (default: 0)
In AdamW, weight decay is implemented as: weight_decay (float, optional) – weight decay coefficient (default: 1e-2)
"""
def __init__(self,
learning_rate: Union[float, LearningRateSchedule] = 0.001,
weight_decay: Union[float, LearningRateSchedule] = 0.01,
beta1: float = 0.9,
beta2: float = 0.999,
epsilon: float = 1e-08,
amsgrad: bool = False):
"""Construct an AdamW optimizer.
Parameters
----------
learning_rate: float or LearningRateSchedule
the learning rate to use for optimization
weight_decay: float or LearningRateSchedule
weight decay coefficient for AdamW
beta1: float
a parameter of the Adam algorithm
beta2: float
a parameter of the Adam algorithm
epsilon: float
a parameter of the Adam algorithm
amsgrad: bool
If True, will use the AMSGrad variant of AdamW (from "On the Convergence of Adam and Beyond"), else will use the original algorithm.
"""
super(AdamW, self).__init__(learning_rate)
self.weight_decay = weight_decay
self.beta1 = beta1
self.beta2 = beta2
self.epsilon = epsilon
self.amsgrad = amsgrad
def _create_tf_optimizer(self, global_step):
import tensorflow_addons as tfa
if isinstance(self.learning_rate, LearningRateSchedule):
learning_rate = self.learning_rate._create_tf_tensor(global_step)
else:
learning_rate = self.learning_rate
return tfa.optimizers.AdamW(weight_decay=self.weight_decay,
learning_rate=learning_rate,
beta_1=self.beta1,
beta_2=self.beta2,
epsilon=self.epsilon,
amsgrad=self.amsgrad)
def _create_pytorch_optimizer(self, params):
import torch
if isinstance(self.learning_rate, LearningRateSchedule):
lr = self.learning_rate.initial_rate
else:
lr = self.learning_rate
return torch.optim.AdamW(params, lr, (self.beta1, self.beta2),
self.epsilon, self.weight_decay, self.amsgrad)
def _create_jax_optimizer(self):
import optax
process = []
if isinstance(self.learning_rate, LearningRateSchedule):
scheduler = self.learning_rate._create_jax_schedule()
process.append(optax.scale_by_schedule(scheduler))
last_process = optax.scale(-1.0)
else:
lr = self.learning_rate
last_process = optax.scale(-1.0 * lr)
process.append(
optax.scale_by_adam(b1=self.beta1,
b2=self.beta2,
eps=self.epsilon,
eps_root=0.0))
process.append(optax.add_decayed_weights(self.weight_decay, None))
process.append(last_process)
return optax.chain(*process)
class RMSProp(Optimizer):
"""RMSProp Optimization algorithm."""
def __init__(self,
learning_rate: Union[float, LearningRateSchedule] = 0.001,
momentum: float = 0.0,
decay: float = 0.9,
epsilon: float = 1e-10):
"""Construct an RMSProp Optimizer.
Parameters
----------
learning_rate: float or LearningRateSchedule
the learning_rate used for optimization
momentum: float, default 0.0
a parameter of the RMSProp algorithm
decay: float, default 0.9
a parameter of the RMSProp algorithm
epsilon: float, default 1e-10
a parameter of the RMSProp algorithm
"""
super(RMSProp, self).__init__(learning_rate)
self.momentum = momentum
self.decay = decay
self.epsilon = epsilon
def _create_tf_optimizer(self, global_step):
import tensorflow as tf
if isinstance(self.learning_rate, LearningRateSchedule):
learning_rate = self.learning_rate._create_tf_tensor(global_step)
else:
learning_rate = self.learning_rate
return tf.keras.optimizers.legacy.RMSprop(learning_rate=learning_rate,
momentum=self.momentum,
rho=self.decay,
epsilon=self.epsilon)
def _create_pytorch_optimizer(self, params):
import torch
if isinstance(self.learning_rate, LearningRateSchedule):
lr = self.learning_rate.initial_rate
else:
lr = self.learning_rate
return torch.optim.RMSprop(params,
lr,
alpha=self.decay,
eps=self.epsilon,
momentum=self.momentum)
def _create_jax_optimizer(self):
import optax
process = []
if isinstance(self.learning_rate, LearningRateSchedule):
scheduler = self.learning_rate._create_jax_schedule()
process.append(optax.scale_by_schedule(scheduler))
last_process = optax.scale(-1.0)
else:
lr = self.learning_rate
last_process = optax.scale(-1.0 * lr)
process.append(
optax.scale_by_rms(decay=self.decay,
eps=self.epsilon,
initial_scale=0.0))
if self.momentum is not None or self.momentum != 0.0:
process.append(optax.trace(decay=self.momentum, nesterov=False))
process.append(last_process)
return optax.chain(*process)
class GradientDescent(Optimizer):
"""The gradient descent optimization algorithm."""
def __init__(self,
learning_rate: Union[float, LearningRateSchedule] = 0.001):
"""Construct a gradient descent optimizer.
Parameters
----------
learning_rate: float or LearningRateSchedule
the learning rate to use for optimization
"""
super(GradientDescent, self).__init__(learning_rate)
def _create_tf_optimizer(self, global_step):
import tensorflow as tf
if isinstance(self.learning_rate, LearningRateSchedule):
learning_rate = self.learning_rate._create_tf_tensor(global_step)
else:
learning_rate = self.learning_rate
return tf.keras.optimizers.legacy.SGD(learning_rate=learning_rate)
def _create_pytorch_optimizer(self, params):
import torch
if isinstance(self.learning_rate, LearningRateSchedule):
lr = self.learning_rate.initial_rate
else:
lr = self.learning_rate
return torch.optim.SGD(params, lr)
def _create_jax_optimizer(self):
import optax
process = []
if isinstance(self.learning_rate, LearningRateSchedule):
scheduler = self.learning_rate._create_jax_schedule()
process.append(optax.scale_by_schedule(scheduler))
last_process = optax.scale(-1.0)
else:
lr = self.learning_rate
last_process = optax.scale(-1.0 * lr)
process.append(last_process)
return optax.chain(*process)
class ExponentialDecay(LearningRateSchedule):
"""A learning rate that decreases exponentially with the number of training steps."""
def __init__(self,
initial_rate: float,
decay_rate: float,
decay_steps: int,
staircase: bool = True):
"""Create an exponentially decaying learning rate.
The learning rate starts as initial_rate. Every decay_steps training steps, it is multiplied by decay_rate.
Parameters
----------
initial_rate: float
the initial learning rate
decay_rate: float
the base of the exponential
decay_steps: int
the number of training steps over which the rate decreases by decay_rate
staircase: bool
if True, the learning rate decreases by discrete jumps every decay_steps.
if False, the learning rate decreases smoothly every step
"""
self.initial_rate = initial_rate
self.decay_rate = decay_rate
self.decay_steps = decay_steps
self.staircase = staircase
def _create_tf_tensor(self, global_step):
import tensorflow as tf
return tf.keras.optimizers.schedules.ExponentialDecay(
initial_learning_rate=self.initial_rate,
decay_rate=self.decay_rate,
decay_steps=self.decay_steps,
staircase=self.staircase)(global_step)
def _create_pytorch_schedule(self, optimizer):
import torch
if self.staircase:
return torch.optim.lr_scheduler.StepLR(optimizer, self.decay_steps,
self.decay_rate)
return torch.optim.lr_scheduler.ExponentialLR(
optimizer, math.pow(self.decay_rate, 1 / self.decay_steps))
def _create_jax_schedule(self):
import optax
return optax.exponential_decay(init_value=self.initial_rate,
transition_steps=self.decay_steps,
decay_rate=self.decay_rate,
staircase=self.staircase)
class PolynomialDecay(LearningRateSchedule):
"""A learning rate that decreases from an initial value to a final value over a fixed number of training steps."""
def __init__(self,
initial_rate: float,
final_rate: float,
decay_steps: int,
power: float = 1.0):
"""Create a smoothly decaying learning rate.
The learning rate starts as initial_rate. It smoothly decreases to final_rate over decay_steps training steps.
It decays as a function of (1-step/decay_steps)**power. Once the final rate is reached, it remains there for
the rest of optimization.
Parameters
----------
initial_rate: float
the initial learning rate
final_rate: float
the final learning rate
decay_steps: int
the number of training steps over which the rate decreases from initial_rate to final_rate
power: float
the exponent controlling the shape of the decay
"""
self.initial_rate = initial_rate
self.final_rate = final_rate
self.decay_steps = decay_steps
self.power = power
def _create_tf_tensor(self, global_step):
import tensorflow as tf
return tf.keras.optimizers.schedules.PolynomialDecay(
initial_learning_rate=self.initial_rate,
end_learning_rate=self.final_rate,
decay_steps=self.decay_steps,
power=self.power)(global_step)
def _create_pytorch_schedule(self, optimizer):
def f(step):
t = min(step, self.decay_steps) / self.decay_steps
return ((self.initial_rate - self.final_rate) *
(1 - t)**self.power) + self.final_rate
import torch
return torch.optim.lr_scheduler.LambdaLR(optimizer, f)
def _create_jax_schedule(self):
import optax
return optax.polynomial_schedule(init_value=self.initial_rate,
end_value=self.final_rate,
power=self.power,
transition_steps=self.decay_steps)
class LinearCosineDecay(LearningRateSchedule):
"""Applies linear cosine decay to the learning rate"""
def __init__(self,
initial_rate: float,
decay_steps: int,
alpha: float = 0.0,
beta: float = 0.001,
num_periods: float = 0.5):
"""
Parameters
----------
learning_rate : float
initial learning rate
decay_steps : int
number of steps to decay over
num_periods : number of periods in the cosine part of the decay
"""
self.initial_rate = initial_rate
self.decay_steps = decay_steps
self.alpha = alpha
self.beta = beta
self.num_periods = num_periods
def _create_tf_tensor(self, global_step):
import tensorflow as tf
return tf.compat.v1.train.linear_cosine_decay(
learning_rate=self.initial_rate,
global_step=global_step,
decay_steps=self.decay_steps,
alpha=self.alpha,
beta=self.beta,
num_periods=self.num_periods)
def _create_pytorch_schedule(self, optimizer):
def f(step):
t = min(step, self.decay_steps) / self.decay_steps
linear_decay = 1 - t
cosine_decay = 0.5 * (1 +
math.cos(math.pi * 2 * self.num_periods * t))
decayed = (self.alpha + linear_decay) * cosine_decay + self.beta
return self.initial_rate * decayed
import torch
return torch.optim.lr_scheduler.LambdaLR(optimizer, f)
def _create_jax_schedule(self):
import optax
return optax.cosine_decay_schedule(init_value=self.initial_rate,
decay_steps=self.decay_steps,
alpha=self.alpha)
class PiecewiseConstantSchedule(LearningRateSchedule):
"""Applies scheduler which multiplies by a constant factor on the boundaries"""
def __init__(self,
initial_rate: float,
boundaries_and_scales: Optional[Dict[int, float]] = None):
"""
Parameters
----------
init_value : float
initial learning rate
boundaries_and_scales:
A map from boundaries b_i to non-negative scaling factors f_i. For any step
count s, the schedule returns init_v scaled by the product of all factors f_i
such that b_i < s.
"""
self.initial_rate = initial_rate
self.boundaries_and_scales = boundaries_and_scales
def _create_jax_schedule(self):
import optax
return optax.piecewise_constant_schedule(
init_value=self.initial_rate,
boundaries_and_scales=self.boundaries_and_scales)
class KFAC(Optimizer):
"""The Second order gradient optimiation algorithm which uses an approximation to calculate the inverse of the Fischer matrrix"""
def __init__(self, **kwargs):
"""
Parameters:
-----------
model: torch.nn.Module
The model to be optimized.
lr: float (default: 0.001)
Learning rate for the optimizer.
momentum: float (default: 0.9)
Momentum for the optimizer.
stat_decay: float (default: 0.95)
Decay rate for the update of covariance matrix with mean.
damping: float (default: 0.001)
damping factor for the update of covariance matrix.
kl_clip: float (default: 0.001)
Clipping value for the update of covariance matrix.
weight_decay: float (default: 0)
weight decay for the optimizer.
Tcov: int (default: 10)
The number of steps to update the covariance matrix.
Tinv: int (default: 100)
The number of steps to calculate the inverse of covariance matrix.
batch_averaged: bool (default: True)
States whether to use batch averaged covariance matrix.
mean: bool (default: False)
States whether to use mean centered covariance matrix.
"""
self.kwargs = kwargs
def _create_pytorch_optimizer(self):
from deepchem.models.torch_models.kfac_optimizer import KFACOptimizer
if isinstance(self.learning_rate, LearningRateSchedule):
self.kwargs['lr'] = self.learning_rate.initial_rate
else:
self.kwargs['lr'] = self.learning_rate
return KFACOptimizer([self.kwargs])