This repository was archived by the owner on Jul 1, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 137
/
Copy pathMomentumBased.swift
657 lines (616 loc) · 25.7 KB
/
MomentumBased.swift
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
// Copyright 2019 The TensorFlow Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import _Differentiation
#if TENSORFLOW_USE_STANDARD_TOOLCHAIN
import Numerics
#endif
/// A RMSProp optimizer.
///
/// Implements the RMSProp optimization algorithm. RMSProp is a form of stochastic gradient descent
/// where the gradients are divided by a running average of their recent magnitude. RMSProp keeps a
/// moving average of the squared gradient for each weight.
///
/// References:
/// - ["Lecture 6.5 - rmsprop: Divide the gradient by a running average
/// of its recent magnitude"](
/// http://www.cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf)
/// (Tieleman and Hinton, 2012)
/// - ["Generating Sequences With Recurrent Neural Networks"](
/// https://arxiv.org/abs/1308.0850) (Graves, 2013)
public class RMSProp<Model: Differentiable>: Optimizer
where
Model.TangentVector: VectorProtocol & PointwiseMultiplicative
& ElementaryFunctions & KeyPathIterable
{
public typealias Model = Model
/// The learning rate.
public var learningRate: Float
/// The gradient moving average decay factor.
public var rho: Float
/// A small scalar added to the denominator to improve numerical stability.
public var epsilon: Float
/// The learning rate decay.
public var decay: Float
/// The step count.
public var step: Float = 0
/// The alpha values for all model differentiable variables.
public var alpha: Model.TangentVector = .zero
/// Creates an instance for `model`.
///
/// - Parameters:
/// - learningRate: The learning rate. The default value is `1e-3`.
/// - rho: The gradient moving average decay factor. The default value is `0.9`.
/// - epsilon: A small scalar added to the denominator to improve numerical stability. The
/// default value is `1e-8`.
/// - decay: The learning rate decay. The default value is `0`.
public init(
for model: __shared Model,
learningRate: Float = 1e-3,
rho: Float = 0.9,
epsilon: Float = 1e-8,
decay: Float = 0
) {
precondition(learningRate >= 0, "Learning rate must be non-negative")
precondition(rho >= 0, "Rho must be non-negative")
precondition(decay >= 0, "Learning rate decay must be non-negative")
self.learningRate = learningRate
self.rho = rho
self.epsilon = epsilon
self.decay = decay
}
public func update(_ model: inout Model, along direction: Model.TangentVector) {
step += 1
let learningRate = self.learningRate * 1 / (1 + decay * Float(step))
alpha = alpha.scaled(by: rho) + (direction .* direction).scaled(by: 1 - rho)
let denominator = Model.TangentVector.sqrt(alpha).adding(epsilon)
model.move(along: (direction ./ denominator).scaled(by: -learningRate))
}
public required init(copying other: RMSProp, to device: Device) {
learningRate = other.learningRate
rho = other.rho
epsilon = other.epsilon
decay = other.decay
step = other.step
alpha = .init(copying: other.alpha, to: device)
}
}
/// An AdaGrad optimizer.
///
/// Implements the AdaGrad (adaptive gradient) optimization algorithm. AdaGrad has
/// parameter-specific learning rates, which are adapted relative to how frequently parameters
/// gets updated during training. Parameters that receive more updates have smaller learning rates.
///
/// AdaGrad individually adapts the learning rates of all model parameters by scaling them inversely
/// proportional to the square root of the running sum of squares of gradient norms.
///
/// Reference: ["Adaptive Subgradient Methods for Online Learning and Stochastic
/// Optimization"](http://www.jmlr.org/papers/volume12/duchi11a/duchi11a.pdf)
/// (Duchi et al, 2011)
public class AdaGrad<Model: Differentiable>: Optimizer
where
Model.TangentVector: VectorProtocol & PointwiseMultiplicative
& ElementaryFunctions & KeyPathIterable
{
public typealias Model = Model
/// The learning rate.
public var learningRate: Float
/// A small scalar added to the denominator to improve numerical stability.
public var epsilon: Float
/// The running sum of squares of gradient norms.
public var accumulator: Model.TangentVector
/// Creates an instance for `model`.
///
/// - Parameters:
/// - learningRate: The learning rate. The default value is `1e-3`.
/// - initialAccumulatorValue: The starting value for the running sum of squares of gradient
/// norms. The default value is `0.1`.
/// - epsilon: A small scalar added to the denominator to improve numerical stability. The
/// default value is `1e-8`.
public init(
for model: __shared Model,
learningRate: Float = 1e-3,
initialAccumulatorValue: Float = 0.1,
epsilon: Float = 1e-8
) {
precondition(learningRate >= 0, "Learning rate must be non-negative")
precondition(
initialAccumulatorValue >= 0, "The initial accumulator value must be non-negative.")
self.learningRate = learningRate
self.epsilon = epsilon
self.accumulator = Model.TangentVector.one.scaled(by: initialAccumulatorValue)
}
public func update(_ model: inout Model, along direction: Model.TangentVector) {
accumulator = accumulator + (direction .* direction)
let denominator = Model.TangentVector.sqrt(accumulator).adding(epsilon)
model.move(along: (direction ./ denominator).scaled(by: -learningRate))
}
public required init(copying other: AdaGrad, to device: Device) {
learningRate = other.learningRate
epsilon = other.epsilon
accumulator = .init(copying: other.accumulator, to: device)
}
}
/// An AdaDelta optimizer.
///
/// Implements the AdaDelta optimization algorithm. AdaDelta is a stochastic
/// gradient descent method based on the first order information. It adapts
/// learning rates based on a moving window of gradient updates, instead of
/// accumulating all past gradients. Thus, AdaDelta continues learning even
/// when many updates have been done. It adapts faster to changing dynamics of
/// the optimization problem space.
///
/// Reference: ["ADADELTA: An Adaptive Learning Rate Method"](
/// https://arxiv.org/abs/1212.5701) (Zeiler, 2012)
public class AdaDelta<Model: Differentiable>: Optimizer
where
Model.TangentVector: VectorProtocol & PointwiseMultiplicative
& ElementaryFunctions & KeyPathIterable
{
public typealias Model = Model
/// The learning rate.
public var learningRate: Float
/// The decay factor, corresponding to the fraction of gradient to keep at each time step.
public var rho: Float
/// A small scalar added to the denominator to improve numerical stability.
public var epsilon: Float
/// The learning rate decay.
public var decay: Float
/// The current step.
public var step: Int = 0
/// The accumulated, exponentially decaying average of squared gradients.
public var averageSquared: Model.TangentVector = .zero
/// The accumulated parameter updates.
public var accumulatedDelta: Model.TangentVector = .zero
/// Creates an instance for `model`.
///
/// - Parameters:
/// - learningRate: The learning rate. The default value is `1`.
/// - rho: The decay factor. The default value is `0.95`.
/// - epsilon: A small scalar added to the denominator to improve numerical stability. The
/// default value is `1e-6`.
/// - decay: The learning rate decay. The defalut value is `0`.
public init(
for model: __shared Model,
learningRate: Float = 1,
rho: Float = 0.95,
epsilon: Float = 1e-6,
decay: Float = 0
) {
precondition(learningRate >= 0, "Learning rate must be non-negative")
precondition(0 <= rho && rho <= 1, "Rho parameter must be between 0 and 1")
precondition(0 <= epsilon, "Epsilon parameter must be non-negative")
precondition(decay >= 0, "Learning rate decay must be non-negative")
self.learningRate = learningRate
self.rho = rho
self.epsilon = epsilon
self.decay = decay
}
public func update(_ model: inout Model, along direction: Model.TangentVector) {
step += 1
let learningRate = self.learningRate / (1 + decay * Float(step))
averageSquared =
averageSquared.scaled(by: rho) + (direction .* direction).scaled(by: 1 - rho)
var stepSize = direction .* Model.TangentVector.sqrt(accumulatedDelta.adding(epsilon))
stepSize ./= Model.TangentVector.sqrt(averageSquared.adding(epsilon))
model.move(along: stepSize.scaled(by: -learningRate))
accumulatedDelta =
accumulatedDelta.scaled(by: rho) + (stepSize .* stepSize).scaled(by: 1 - rho)
}
public required init(copying other: AdaDelta, to device: Device) {
learningRate = other.learningRate
rho = other.rho
epsilon = other.epsilon
decay = other.decay
step = other.step
averageSquared = .init(copying: other.averageSquared, to: device)
accumulatedDelta = .init(copying: other.accumulatedDelta, to: device)
}
}
/// Adam optimizer.
///
/// Implements the Adam optimization algorithm. Adam is a stochastic gradient descent method that
/// computes individual adaptive learning rates for different parameters from estimates of first-
/// and second-order moments of the gradients.
///
/// Reference: ["Adam: A Method for Stochastic Optimization"](https://arxiv.org/abs/1412.6980v8)
/// (Kingma and Ba, 2014).
///
/// ### Examples: ###
///
/// - Train a simple reinforcement learning agent:
///
/// ````
/// ...
/// // Instantiate an agent's policy - approximated by the neural network (`net`) after defining it
/// in advance.
/// var net = Net(observationSize: Int(observationSize), hiddenSize: hiddenSize, actionCount: actionCount)
/// // Define the Adam optimizer for the network with a learning rate set to 0.01.
/// let optimizer = Adam(for: net, learningRate: 0.01)
/// ...
/// // Begin training the agent (over a certain number of episodes).
/// while true {
/// ...
/// // Implementing the gradient descent with the Adam optimizer:
/// // Define the gradients (use withLearningPhase to call a closure under a learning phase).
/// let gradients = withLearningPhase(.training) {
/// TensorFlow.gradient(at: net) { net -> Tensor<Float> in
/// // Return a softmax (loss) function
/// return loss = softmaxCrossEntropy(logits: net(input), probabilities: target)
/// }
/// }
/// // Update the differentiable variables of the network (`net`) along the gradients with the Adam
/// optimizer.
/// optimizer.update(&net, along: gradients)
/// ...
/// }
/// }
/// ````
///
/// - Train a generative adversarial network (GAN):
///
/// ````
/// ...
/// // Instantiate the generator and the discriminator networks after defining them.
/// var generator = Generator()
/// var discriminator = Discriminator()
/// // Define the Adam optimizers for each network with a learning rate set to 2e-4 and beta1 - to 0.5.
/// let adamOptimizerG = Adam(for: generator, learningRate: 2e-4, beta1: 0.5)
/// let adamOptimizerD = Adam(for: discriminator, learningRate: 2e-4, beta1: 0.5)
/// ...
/// Start the training loop over a certain number of epochs (`epochCount`).
/// for epoch in 1...epochCount {
/// // Start the training phase.
/// ...
/// for batch in trainingShuffled.batched(batchSize) {
/// // Implementing the gradient descent with the Adam optimizer:
/// // 1) Update the generator.
/// ...
/// let 𝛁generator = TensorFlow.gradient(at: generator) { generator -> Tensor<Float> in
/// ...
/// return loss
/// }
/// // Update the differentiable variables of the generator along the gradients (`𝛁generator`)
/// // with the Adam optimizer.
/// adamOptimizerG.update(&generator, along: 𝛁generator)
///
/// // 2) Update the discriminator.
/// ...
/// let 𝛁discriminator = TensorFlow.gradient(at: discriminator) { discriminator -> Tensor<Float> in
/// ...
/// return loss
/// }
/// // Update the differentiable variables of the discriminator along the gradients (`𝛁discriminator`)
/// // with the Adam optimizer.
/// adamOptimizerD.update(&discriminator, along: 𝛁discriminator)
/// }
/// }
/// ````
public class Adam<Model: Differentiable>: Optimizer
where
Model.TangentVector: VectorProtocol & PointwiseMultiplicative
& ElementaryFunctions & KeyPathIterable
{
public typealias Model = Model
/// The learning rate.
public var learningRate: Float
/// A coefficient used to calculate the first moments of the gradients.
public var beta1: Float
/// A coefficient used to calculate the second moments of the gradients.
public var beta2: Float
/// A small scalar added to the denominator to improve numerical stability.
public var epsilon: Float
/// The learning rate decay.
public var decay: Float
/// The current step.
public var step: Int = 0
/// The first moments of the weights.
public var firstMoments: Model.TangentVector = .zero
/// The second moments of the weights.
public var secondMoments: Model.TangentVector = .zero
/// - Parameters:
/// - learningRate: The learning rate. The default value is `1e-3`.
/// - beta1: The exponential decay rate for the 1st moment estimates. The default value is `0.9`.
/// - beta2: The exponential decay rate for the 2nd moment estimates. The default value is `0.999`.
/// - epsilon: A small scalar added to the denominator to improve numerical stability.
/// The default value is `1e-8`.
/// - decay: The learning rate decay. The default value is `0`.
public init(
for model: __shared Model,
learningRate: Float = 1e-3,
beta1: Float = 0.9,
beta2: Float = 0.999,
epsilon: Float = 1e-8,
decay: Float = 0
) {
precondition(learningRate >= 0, "Learning rate must be non-negative")
precondition(0 <= beta1 && beta1 <= 1, "Beta parameter must be between 0 and 1")
precondition(0 <= beta2 && beta2 <= 1, "Beta parameter must be between 0 and 1")
precondition(decay >= 0, "Learning rate decay must be non-negative")
self.learningRate = learningRate
self.beta1 = beta1
self.beta2 = beta2
self.epsilon = epsilon
self.decay = decay
}
public func update(_ model: inout Model, along direction: Model.TangentVector) {
step += 1
let step = Float(self.step)
let learningRate = self.learningRate * 1 / (1 + decay * step)
// Note: `stepSize` is split into two lines to avoid the "compiler is unable to type-check
// this expression in reasonable time" error.
var stepSize = learningRate * sqrtf(1 - powf(beta2, step))
stepSize = stepSize / (1 - powf(beta1, step))
firstMoments = firstMoments.scaled(by: beta1) + direction.scaled(by: 1 - beta1)
secondMoments =
secondMoments.scaled(by: beta2) + (direction .* direction).scaled(by: 1 - beta2)
let denominator = Model.TangentVector.sqrt(secondMoments).adding(epsilon)
model.move(along: (firstMoments ./ denominator).scaled(by: -stepSize))
}
public required init(copying other: Adam, to device: Device) {
learningRate = other.learningRate
beta1 = other.beta1
beta2 = other.beta2
epsilon = other.epsilon
decay = other.decay
step = other.step
firstMoments = .init(copying: other.firstMoments, to: device)
secondMoments = .init(copying: other.secondMoments, to: device)
}
}
/// AdaMax optimizer.
///
/// A variant of Adam based on the infinity-norm.
///
/// Reference: Section 7 of ["Adam - A Method for Stochastic Optimization"](
/// https://arxiv.org/abs/1412.6980v8)
public class AdaMax<Model: Differentiable & KeyPathIterable>: Optimizer
where
Model.TangentVector: VectorProtocol & PointwiseMultiplicative & ElementaryFunctions
& KeyPathIterable
{
public typealias Model = Model
/// The learning rate.
public var learningRate: Float
/// Decay rate used to estimate the first moment (mean) of gradients.
public var beta1: Float
/// Decay rate used to estimate the exponentially weighted infinity norm.
public var beta2: Float
/// A small scalar added to the denominator to improve numerical stability.
public var epsilon: Float
/// The learning rate decay.
public var decay: Float
/// The step count.
public var step: Int = 0
/// The first moments of the weights.
public var firstMoments: Model.TangentVector = .zero
/// The exponentially weighted infinity norm of the weights.
public var infinityNorm: Model.TangentVector = .zero
/// Note: The default parameters follow those provided in the paper.
public init(
for model: __shared Model,
learningRate: Float = 0.002,
beta1: Float = 0.9,
beta2: Float = 0.999,
epsilon: Float = 1e-8,
decay: Float = 0
) {
precondition(learningRate >= 0, "Learning rate must be non-negative.")
precondition(0 <= beta1 && beta1 <= 1, "Beta parameter must be between 0 and 1.")
precondition(0 <= beta2 && beta2 <= 1, "Beta parameter must be between 0 and 1.")
precondition(decay >= 0, "Learning rate decay must be non-negative.")
self.learningRate = learningRate
self.beta1 = beta1
self.beta2 = beta2
self.epsilon = epsilon
self.decay = decay
}
public func update(_ model: inout Model, along direction: Model.TangentVector) {
step += 1
let step = Float(self.step)
let learningRate = self.learningRate * 1 / (1 + decay * step)
let stepSize = learningRate / (1 - powf(beta1, step))
firstMoments = firstMoments.scaled(by: beta1) + direction.scaled(by: 1 - beta1)
// Update `infinityNorm` using a key path approach because `max(_:_:)` cannot be
// currently applied in a simpler manner.
for kp in infinityNorm.recursivelyAllWritableKeyPaths(to: Tensor<Float>.self) {
infinityNorm[keyPath: kp] = max(
beta2 * infinityNorm[keyPath: kp], abs(direction[keyPath: kp]))
}
for kp in infinityNorm.recursivelyAllWritableKeyPaths(to: Tensor<Double>.self) {
infinityNorm[keyPath: kp] = max(
Double(beta2) * infinityNorm[keyPath: kp], abs(direction[keyPath: kp]))
}
let denominator = infinityNorm.adding(epsilon)
model.move(along: (firstMoments ./ denominator).scaled(by: -stepSize))
}
public required init(copying other: AdaMax, to device: Device) {
learningRate = other.learningRate
beta1 = other.beta1
beta2 = other.beta2
epsilon = other.epsilon
decay = other.decay
step = other.step
firstMoments = .init(copying: other.firstMoments, to: device)
infinityNorm = .init(copying: other.infinityNorm, to: device)
}
}
/// AMSGrad optimizer.
///
/// This algorithm is a modification of Adam with better convergence properties when close to local
/// optima.
///
/// Reference: ["On the Convergence of Adam and Beyond"](
/// https://openreview.net/pdf?id=ryQu7f-RZ)
public class AMSGrad<Model: Differentiable & KeyPathIterable>: Optimizer
where
Model.TangentVector: VectorProtocol & PointwiseMultiplicative & ElementaryFunctions
& KeyPathIterable
{
public typealias Model = Model
/// The learning rate.
public var learningRate: Float
/// A coefficient used to calculate the first and second moments of the gradients.
public var beta1: Float
/// A coefficient used to calculate the first and second moments of the gradients.
public var beta2: Float
/// A small scalar added to the denominator to improve numerical stability.
public var epsilon: Float
/// The learning rate decay.
public var decay: Float
/// The current step.
public var step: Int = 0
/// The first moments of the weights.
public var firstMoments: Model.TangentVector = .zero
/// The second moments of the weights.
public var secondMoments: Model.TangentVector = .zero
/// The maximum of the second moments of the weights.
public var secondMomentsMax: Model.TangentVector = .zero
public init(
for model: __shared Model,
learningRate: Float = 1e-3,
beta1: Float = 0.9,
beta2: Float = 0.999,
epsilon: Float = 1e-8,
decay: Float = 0
) {
precondition(learningRate >= 0, "Learning rate must be non-negative")
precondition(0 <= beta1 && beta1 <= 1, "Beta parameter must be between 0 and 1")
precondition(0 <= beta2 && beta2 <= 1, "Beta parameter must be between 0 and 1")
precondition(decay >= 0, "Learning rate decay must be non-negative")
self.learningRate = learningRate
self.beta1 = beta1
self.beta2 = beta2
self.epsilon = epsilon
self.decay = decay
}
public func update(_ model: inout Model, along direction: Model.TangentVector) {
step += 1
let step = Float(self.step)
let learningRate = self.learningRate * 1 / (1 + decay * step)
// Note: `stepSize` is split into two lines to avoid the "compiler is unable to type-check
// this expression in reasonable time" error.
var stepSize = learningRate * sqrtf(1 - powf(beta2, step))
stepSize = stepSize / (1 - powf(beta1, step))
firstMoments = firstMoments.scaled(by: beta1) + direction.scaled(by: 1 - beta1)
secondMoments =
secondMoments.scaled(by: beta2) + (direction .* direction).scaled(by: 1 - beta2)
// Update `secondMomentsMax` using a key path approach because `max(_:_:)` cannot be
// currently applied in a simpler manner.
for kp in secondMomentsMax.recursivelyAllWritableKeyPaths(to: Tensor<Float>.self) {
secondMomentsMax[keyPath: kp] = max(
secondMomentsMax[keyPath: kp], secondMoments[keyPath: kp])
}
for kp in secondMomentsMax.recursivelyAllWritableKeyPaths(to: Tensor<Double>.self) {
secondMomentsMax[keyPath: kp] = max(
secondMomentsMax[keyPath: kp], secondMoments[keyPath: kp])
}
let denominator = Model.TangentVector.sqrt(secondMomentsMax).adding(epsilon)
model.move(along: (firstMoments ./ denominator).scaled(by: -stepSize))
}
public required init(copying other: AMSGrad, to device: Device) {
learningRate = other.learningRate
beta1 = other.beta1
beta2 = other.beta2
epsilon = other.epsilon
decay = other.decay
step = other.step
firstMoments = .init(copying: other.firstMoments, to: device)
secondMoments = .init(copying: other.secondMoments, to: device)
secondMomentsMax = .init(copying: other.secondMomentsMax, to: device)
}
}
/// RAdam optimizer.
///
/// Rectified Adam, a variant of Adam that introduces a term to rectify the adaptive learning rate
/// variance.
///
/// Reference: ["On the Variance of the Adaptive Learning Rate and Beyond"](
/// https://arxiv.org/pdf/1908.03265.pdf)
public class RAdam<Model: Differentiable>: Optimizer
where
Model.TangentVector: VectorProtocol & PointwiseMultiplicative & ElementaryFunctions
& KeyPathIterable
{
public typealias Model = Model
/// The learning rate.
public var learningRate: Float
/// A coefficient used to calculate the first and second moments of the gradients.
public var beta1: Float
/// A coefficient used to calculate the first and second moments of the gradients.
public var beta2: Float
/// A small scalar added to the denominator to improve numerical stability.
public var epsilon: Float
/// The learning rate decay.
public var decay: Float
/// The current step.
public var step: Int = 0
/// The first moments of the weights.
public var firstMoments: Model.TangentVector = .zero
/// The second moments of the weights.
public var secondMoments: Model.TangentVector = .zero
public init(
for model: __shared Model,
learningRate: Float = 1e-3,
beta1: Float = 0.9,
beta2: Float = 0.999,
epsilon: Float = 1e-8,
decay: Float = 0
) {
precondition(learningRate >= 0, "Learning rate must be non-negative")
precondition(0 <= beta1 && beta1 <= 1, "Beta parameter must be between 0 and 1")
precondition(0 <= beta2 && beta2 <= 1, "Beta parameter must be between 0 and 1")
precondition(decay >= 0, "Learning rate decay must be non-negative")
self.learningRate = learningRate
self.beta1 = beta1
self.beta2 = beta2
self.epsilon = epsilon
self.decay = decay
}
public func update(_ model: inout Model, along direction: Model.TangentVector) {
step += 1
let step = Float(self.step)
let beta1Power = powf(beta1, step)
let beta2Power = powf(beta2, step)
secondMoments =
secondMoments.scaled(by: beta2) + (direction .* direction).scaled(by: 1 - beta2)
firstMoments = firstMoments.scaled(by: beta1) + direction.scaled(by: 1 - beta1)
// Compute maximum length SMA, bias-corrected moving average and approximate length.
let N_sma_inf = 2 / (1 - beta2) - 1
let N_sma_t = N_sma_inf - 2 * step * beta2Power / (1 - beta2Power)
if N_sma_t >= 5 {
// Compute bias-corrected second moments, rectification and adapted momentum.
let secondMoments_h = Model.TangentVector.sqrt(secondMoments).adding(epsilon)
let stepSize =
sqrtf(
(N_sma_t - 4) * (N_sma_t - 2) * N_sma_inf
/ ((N_sma_inf - 4) * (N_sma_inf - 2) * (N_sma_t))) * learningRate / (1 - beta1Power)
model.move(
along: (firstMoments ./ secondMoments_h).scaled(by: -stepSize * sqrtf(1 - beta2Power)))
} else {
// Update with un-adapted momentum.
let stepSize = learningRate / (1 - beta1Power)
model.move(along: firstMoments.scaled(by: -stepSize))
}
}
public required init(copying other: RAdam, to device: Device) {
learningRate = other.learningRate
beta1 = other.beta1
beta2 = other.beta2
epsilon = other.epsilon
decay = other.decay
step = other.step
firstMoments = .init(copying: other.firstMoments, to: device)
secondMoments = .init(copying: other.secondMoments, to: device)
}
}