braintools 0.0.2__py2.py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. braintools/__init__.py +27 -0
  2. braintools/functional/__init__.py +25 -0
  3. braintools/functional/_activations.py +733 -0
  4. braintools/functional/_normalization.py +62 -0
  5. braintools/functional/_spikes.py +90 -0
  6. braintools/init/__init__.py +26 -0
  7. braintools/init/_base.py +36 -0
  8. braintools/init/_generic.py +205 -0
  9. braintools/init/_random_inits.py +489 -0
  10. braintools/init/_regular_inits.py +109 -0
  11. braintools/input/__init__.py +27 -0
  12. braintools/input/currents.py +380 -0
  13. braintools/input/currents_test.py +111 -0
  14. braintools/metric/__init__.py +46 -0
  15. braintools/metric/_classification.py +569 -0
  16. braintools/metric/_classification_test.py +625 -0
  17. braintools/metric/_correlation.py +302 -0
  18. braintools/metric/_correlation_test.py +124 -0
  19. braintools/metric/_fenchel_young.py +67 -0
  20. braintools/metric/_fenchel_young_test.py +55 -0
  21. braintools/metric/_firings.py +85 -0
  22. braintools/metric/_firings_test.py +41 -0
  23. braintools/metric/_lfp.py +139 -0
  24. braintools/metric/_ranking.py +163 -0
  25. braintools/metric/_ranking_test.py +242 -0
  26. braintools/metric/_regression.py +425 -0
  27. braintools/metric/_regression_test.py +133 -0
  28. braintools/metric/_smoothing.py +46 -0
  29. braintools/metric/_smoothing_test.py +43 -0
  30. braintools/metric/_util.py +25 -0
  31. braintools/optim/__init__.py +23 -0
  32. braintools/optim/_lr_scheduler.py +482 -0
  33. braintools/optim/_sgd_optimizer.py +1130 -0
  34. braintools-0.0.2.dist-info/LICENSE +202 -0
  35. braintools-0.0.2.dist-info/METADATA +93 -0
  36. braintools-0.0.2.dist-info/RECORD +38 -0
  37. braintools-0.0.2.dist-info/WHEEL +6 -0
  38. braintools-0.0.2.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1130 @@
1
+ # Copyright 2024- BrainPy Ecosystem Limited. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
15
+
16
+ # -*- coding: utf-8 -*-
17
+
18
+ import functools
19
+ from typing import Union, Dict, Optional, Tuple, Any, TypeVar
20
+
21
+ import braincore as bc
22
+ import jax
23
+ import jax.numpy as jnp
24
+
25
+ from ._lr_scheduler import make_schedule, LearningRateScheduler
26
+
27
+ __all__ = [
28
+ 'to_same_dict_tree',
29
+
30
+ # new class of braincore.State for optimizer
31
+ 'OptimState',
32
+
33
+ # commonly used optimizers
34
+ 'Optimizer',
35
+ 'SGD',
36
+ 'Momentum',
37
+ 'MomentumNesterov',
38
+ 'Adagrad',
39
+ 'Adadelta',
40
+ 'RMSProp',
41
+ 'Adam',
42
+ 'LARS',
43
+ 'Adan',
44
+ 'AdamW',
45
+ ]
46
+
47
+ T = TypeVar('T')
48
+
49
+
50
+ def cast(value: Any, dtype: Any) -> jax.Array:
51
+ if isinstance(value, jax.Array):
52
+ return value.astype(dtype)
53
+ return jnp.asarray(value, dtype=dtype)
54
+
55
+
56
+ def fcast(value: T, dtype: Any = None) -> jax.Array:
57
+ return cast(value, dtype=dtype or bc.environ.dftype())
58
+
59
+
60
+ def _to_dict_value(old_dict: Dict) -> Dict:
61
+ new_dict = dict()
62
+ for k, v in old_dict.items():
63
+ if isinstance(v, bc.State):
64
+ new_dict[k] = v.value
65
+ else:
66
+ new_dict[k] = v
67
+ return new_dict
68
+
69
+
70
+ def to_same_dict_tree(*dicts: Dict):
71
+ """
72
+ Convert multiple dictionaries to the same tree structure.
73
+
74
+ Parameters
75
+ ----------
76
+ *dicts: dict
77
+ The dictionaries to be converted.
78
+
79
+ Returns
80
+ -------
81
+ dict
82
+ The converted dictionary.
83
+ """
84
+ if len(dicts):
85
+ # all keys
86
+ all_keys = tuple(set(d.keys()) for d in dicts)
87
+ for keys in all_keys[1:]:
88
+ if len(all_keys[0].difference(keys)) > 0:
89
+ raise ValueError('Dictionary does not match.')
90
+
91
+ # flatten to normal python dict
92
+ r = [_to_dict_value(d) for d in dicts]
93
+
94
+ if len(dicts) == 1:
95
+ return r[0]
96
+ else:
97
+ return tuple(r)
98
+
99
+
100
+ def _sgd(prev_weight, gradient, weight_decay, lr=None):
101
+ """
102
+ The update function for SGD learning.
103
+
104
+ Parameters
105
+ ----------
106
+ prev_weight: jax.Array
107
+ The previous weight.
108
+ gradient: jax.Array
109
+ The gradient.
110
+ weight_decay: float
111
+ The weight decay.
112
+ lr: float
113
+ The learning rate.
114
+ """
115
+ if weight_decay is None:
116
+ if lr is None:
117
+ return prev_weight - gradient
118
+ else:
119
+ return prev_weight - lr * gradient
120
+ else:
121
+ if lr is None:
122
+ return (1 - weight_decay) * prev_weight - gradient
123
+ else:
124
+ return (1 - weight_decay) * prev_weight - lr * gradient
125
+
126
+
127
+ class OptimState(bc.LongTermState):
128
+ """
129
+ The state for optimizer.
130
+ """
131
+ pass
132
+
133
+
134
+ class Optimizer(bc.Module):
135
+ """Base Optimizer Class.
136
+
137
+ Parameters
138
+ ----------
139
+ lr: float, LearningRateScheduler
140
+ learning rate.
141
+ """
142
+
143
+ lr: LearningRateScheduler # learning rate
144
+ weight_states: bc.StateDictManager # states to train, invisible to ``.states()``
145
+
146
+ def __init__(
147
+ self,
148
+ lr: Union[float, LearningRateScheduler, bc.State],
149
+ name: Optional[str] = None
150
+ ):
151
+ super().__init__(name=name)
152
+ self.lr: LearningRateScheduler = make_schedule(lr)
153
+ self.weight_states = bc.StateDictManager()
154
+
155
+ def register_trainable_weights(self, train_states: Optional[Dict[str, bc.State]] = None):
156
+ raise NotImplementedError
157
+
158
+ def __repr__(self):
159
+ return f"{self.__class__.__name__}(lr={self.lr}{self.extra_repr()})"
160
+
161
+ def extra_repr(self) -> str:
162
+ return ''
163
+
164
+ def update(self, grads: dict):
165
+ raise NotImplementedError
166
+
167
+
168
+ class _WeightDecayOptimizer(Optimizer):
169
+ def __init__(
170
+ self,
171
+ lr: Union[float, LearningRateScheduler, bc.State],
172
+ weight_decay: Optional[float] = None,
173
+ name: Optional[str] = None
174
+ ):
175
+ super().__init__(lr=lr, name=name)
176
+ self.lr: LearningRateScheduler = make_schedule(lr)
177
+ assert weight_decay is None or 0. <= weight_decay <= 1., 'weight_decay must be in [0, 1].'
178
+ self.weight_decay = (fcast(weight_decay) if weight_decay is not None else None)
179
+
180
+ def extra_repr(self) -> str:
181
+ return ''
182
+
183
+ def __repr__(self):
184
+ return f"{self.__class__.__name__}(lr={self.lr}, weight_decay={self.weight_decay}{self.extra_repr()})"
185
+
186
+
187
+ class SGD(_WeightDecayOptimizer):
188
+ r"""Stochastic gradient descent optimizer.
189
+
190
+ SGD performs a parameter update for training examples :math:`x` and label
191
+ :math:`y`:
192
+
193
+ .. math::
194
+
195
+ \theta = \theta - \eta \cdot \nabla_\theta J(\theta; x; y)
196
+
197
+
198
+ Parameters
199
+ ----------
200
+ lr: float, LearningRateScheduler
201
+ learning rate.
202
+
203
+ """
204
+
205
+ def __init__(
206
+ self,
207
+ lr: Union[float, LearningRateScheduler, bc.State],
208
+ weight_decay: Optional[float] = None,
209
+ name: Optional[str] = None
210
+ ):
211
+ super().__init__(lr=lr, weight_decay=weight_decay, name=name)
212
+
213
+ def register_trainable_weights(self, states: Optional[Dict[str, bc.State]] = None):
214
+ states = dict() if states is None else states
215
+ assert isinstance(states, dict), '"states" must be a dict of braincore.State.'
216
+ for k, v in states.items():
217
+ assert isinstance(v, bc.State), f'"{k}" must be an instance of braincore.State.'
218
+ self.weight_states.add_unique_elem(k, v)
219
+
220
+ def update(self, grads: dict):
221
+ lr = self.lr()
222
+ weight_values, grad_values = to_same_dict_tree(self.weight_states, grads)
223
+ updates = jax.tree.map(functools.partial(_sgd, lr=lr, weight_decay=self.weight_decay),
224
+ weight_values,
225
+ grad_values)
226
+ self.weight_states.assign_values(updates)
227
+ self.lr.step_call()
228
+
229
+
230
+ class Momentum(_WeightDecayOptimizer):
231
+ r"""Momentum optimizer.
232
+
233
+ Momentum [1]_ is a method that helps accelerate SGD in the relevant direction
234
+ and dampens oscillations. It does this by adding a fraction :math:`\gamma`
235
+ of the update vector of the past time step to the current update vector:
236
+
237
+ .. math::
238
+
239
+ \begin{align}
240
+ \begin{split}
241
+ v_t &= \gamma v_{t-1} + \eta \nabla_\theta J( \theta) \\
242
+ \theta &= \theta - v_t
243
+ \end{split}
244
+ \end{align}
245
+
246
+ Parameters
247
+ ----------
248
+ lr: float, LearningRateScheduler
249
+ learning rate.
250
+
251
+ References
252
+ ----------
253
+
254
+ .. [1] Qian, N. (1999). On the momentum term in gradient descent learning
255
+ algorithms. Neural Networks : The Official Journal of the International
256
+ Neural Network Society, 12(1), 145–151. http://doi.org/10.1016/S0893-6080(98)00116-6
257
+
258
+ """
259
+
260
+ def __init__(
261
+ self,
262
+ lr: Union[float, LearningRateScheduler, bc.State],
263
+ momentum: float = 0.9,
264
+ weight_decay: Optional[float] = None,
265
+ name: Optional[str] = None
266
+ ):
267
+ super(Momentum, self).__init__(lr=lr, weight_decay=weight_decay, name=name)
268
+ self.momentum = fcast(momentum)
269
+ self.momentum_states = bc.visible_state_dict()
270
+
271
+ def extra_repr(self) -> str:
272
+ return f", momentum={self.momentum}"
273
+
274
+ def register_trainable_weights(self, train_states: Optional[Dict[str, bc.State]] = None):
275
+ train_states = dict() if train_states is None else train_states
276
+ assert isinstance(train_states, dict), '"states" must be a dict of braincore.State.'
277
+
278
+ for k, v in train_states.items():
279
+ assert isinstance(v, bc.State), f'"{k}" must be an instance of braincore.State.'
280
+ self.weight_states.add_unique_elem(k, v)
281
+ self.momentum_states[k] = OptimState(bc.math.tree_zeros_like(v.value))
282
+
283
+ def update(self, grads: dict):
284
+ lr = self.lr()
285
+ states_values, grad_values, momentum_values = to_same_dict_tree(self.weight_states, grads, self.momentum_states)
286
+ momentum_values = jax.tree.map(lambda vv, gg: self.momentum * vv - lr * gg,
287
+ momentum_values,
288
+ grad_values)
289
+ new_weight_values = jax.tree.map(functools.partial(_sgd, lr=lr, weight_decay=self.weight_decay),
290
+ states_values,
291
+ momentum_values)
292
+ self.momentum_states.assign_values(momentum_values)
293
+ self.weight_states.assign_values(new_weight_values)
294
+ self.lr.step_call()
295
+
296
+
297
+ class MomentumNesterov(_WeightDecayOptimizer):
298
+ r"""
299
+ Nesterov accelerated gradient optimizer [2]_.
300
+
301
+ .. math::
302
+
303
+ \begin{align}
304
+ \begin{split}
305
+ v_t &= \gamma v_{t-1} + \eta \nabla_\theta J( \theta - \gamma v_{t-1} ) \\
306
+ \theta &= \theta - v_t
307
+ \end{split}
308
+ \end{align}
309
+
310
+ Parameters
311
+ ----------
312
+ lr: float, LearningRateScheduler
313
+ learning rate.
314
+
315
+ References
316
+ ----------
317
+ .. [2] Nesterov, Y. (1983). A method for unconstrained convex minimization problem with the rate of convergence o(1/k2). Doklady ANSSSR (translated as Soviet.Math.Docl.), vol. 269, pp. 543– 547.
318
+
319
+ """
320
+
321
+ def __init__(
322
+ self,
323
+ lr: Union[float, LearningRateScheduler, bc.State],
324
+ weight_decay: Optional[float] = None,
325
+ momentum: float = 0.9,
326
+ name: Optional[str] = None
327
+ ):
328
+ super(MomentumNesterov, self).__init__(lr=lr, weight_decay=weight_decay, name=name)
329
+
330
+ self.momentum = fcast(momentum)
331
+ self.momentum_states = bc.visible_state_dict()
332
+
333
+ def extra_repr(self) -> str:
334
+ return f", momentum={self.momentum}"
335
+
336
+ def register_trainable_weights(self, train_states: Optional[Dict[str, bc.State]] = None):
337
+ train_states = dict() if train_states is None else train_states
338
+ assert isinstance(train_states, dict), '"states" must be a dict of braincore.State.'
339
+ for k, v in train_states.items():
340
+ assert isinstance(v, bc.State), f'"{k}" must be an instance of braincore.State.'
341
+ self.weight_states.add_unique_elem(k, v)
342
+ self.momentum_states[k] = OptimState(bc.math.tree_zeros_like(v.value))
343
+
344
+ def update(self, grads: dict):
345
+ lr = self.lr()
346
+ states_values, grad_values, momentum_values = to_same_dict_tree(self.weight_states, grads, self.momentum_states)
347
+ momentum_values = jax.tree.map(lambda mv, gv: self.momentum * mv - lr * gv,
348
+ momentum_values,
349
+ grad_values)
350
+ weight_values = jax.tree.map(functools.partial(_sgd, lr=lr, weight_decay=self.weight_decay),
351
+ states_values,
352
+ momentum_values)
353
+ self.weight_states.assign_values(weight_values)
354
+ self.momentum_states.assign_values(momentum_values)
355
+ self.lr.step_call()
356
+
357
+
358
+ class Adagrad(_WeightDecayOptimizer):
359
+ r"""Optimizer that implements the Adagrad algorithm.
360
+
361
+ Adagrad [3]_ is an optimizer with parameter-specific learning rates, which are
362
+ adapted relative to how frequently a parameter gets updated during training.
363
+ The more updates a parameter receives, the smaller the updates.
364
+
365
+ .. math::
366
+
367
+ \theta_{t+1} = \theta_{t} - \dfrac{\eta}{\sqrt{G_{t} + \epsilon}} \odot g_{t}
368
+
369
+ where :math:`G(t)` contains the sum of the squares of the past gradients
370
+
371
+ One of Adagrad's main benefits is that it eliminates the need to manually tune
372
+ the learning rate. Most implementations use a default value of 0.01 and leave it at that.
373
+ Adagrad's main weakness is its accumulation of the squared gradients in the denominator:
374
+ Since every added term is positive, the accumulated sum keeps growing during training.
375
+ This in turn causes the learning rate to shrink and eventually become infinitesimally
376
+ small, at which point the algorithm is no longer able to acquire additional knowledge.
377
+
378
+ Parameters
379
+ ----------
380
+ lr: float, LearningRateScheduler
381
+ learning rate.
382
+
383
+ References
384
+ ----------
385
+ .. [3] Duchi, J., Hazan, E., & Singer, Y. (2011). Adaptive Subgradient Methods for Online Learning and Stochastic Optimization. Journal of Machine Learning Research, 12, 2121–2159. Retrieved from http://jmlr.org/papers/v12/duchi11a.html
386
+
387
+ """
388
+
389
+ def __init__(
390
+ self,
391
+ lr: Union[float, LearningRateScheduler, bc.State],
392
+ weight_decay: Optional[float] = None,
393
+ epsilon: float = 1e-6,
394
+ name: Optional[str] = None
395
+ ):
396
+ super().__init__(lr=lr, weight_decay=weight_decay, name=name)
397
+ self.epsilon = fcast(epsilon)
398
+ self.cache_states = bc.visible_state_dict()
399
+
400
+ def extra_repr(self) -> str:
401
+ return f", epsilon={self.epsilon}"
402
+
403
+ def register_trainable_weights(self, train_states: Optional[Dict[str, bc.State]] = None):
404
+ train_states = dict() if train_states is None else train_states
405
+ assert isinstance(train_states, dict), '"states" must be a dict of braincore.State.'
406
+ for k, v in train_states.items():
407
+ assert isinstance(v, bc.State), f'"{k}" must be an instance of braincore.State.'
408
+ self.weight_states.add_unique_elem(k, v)
409
+ self.cache_states[k] = OptimState(bc.math.tree_zeros_like(v.value))
410
+
411
+ def update(self, grads: dict):
412
+ lr = self.lr()
413
+ cache_values, grad_values, weight_values = to_same_dict_tree(self.cache_states, grads, self.weight_states)
414
+ cache_values = jax.tree.map(lambda cv, gv: cv + gv ** 2, cache_values, grad_values)
415
+ updates = jax.tree.map(lambda cv, gv: lr * gv / jnp.sqrt(cv + self.epsilon), cache_values, grad_values)
416
+ weight_values = jax.tree.map(functools.partial(_sgd, weight_decay=self.weight_decay),
417
+ weight_values,
418
+ updates)
419
+ self.cache_states.assign_values(cache_values)
420
+ self.weight_states.assign_values(weight_values)
421
+ self.lr.step_call()
422
+
423
+
424
+ class Adadelta(_WeightDecayOptimizer):
425
+ r"""Optimizer that implements the Adadelta algorithm.
426
+
427
+ Adadelta [4]_ optimization is a stochastic gradient descent method that is based
428
+ on adaptive learning rate per dimension to address two drawbacks:
429
+
430
+ - The continual decay of learning rates throughout training.
431
+ - The need for a manually selected global learning rate.
432
+
433
+ Adadelta is a more robust extension of Adagrad that adapts learning rates based on
434
+ a moving window of gradient updates, instead of accumulating all past gradients.
435
+ This way, Adadelta continues learning even when many updates have been done. Compared
436
+ to Adagrad, in the original version of Adadelta you don't have to set an initial
437
+ learning rate.
438
+
439
+ .. math::
440
+
441
+ \boldsymbol{s}_t \leftarrow \rho \boldsymbol{s}_{t-1} + (1 - \rho) \boldsymbol{g}_t \odot \boldsymbol{g}_t, \\
442
+ \boldsymbol{g}_t' \leftarrow \sqrt{\frac{\Delta\boldsymbol{x}_{t-1} + \epsilon}{\boldsymbol{s}_t + \epsilon}} \odot \boldsymbol{g}_t, \\
443
+ \boldsymbol{x}_t \leftarrow \boldsymbol{x}_{t-1} - \boldsymbol{g}'_t, \\
444
+ \Delta\boldsymbol{x}_t \leftarrow \rho \Delta\boldsymbol{x}_{t-1} + (1 - \rho) \boldsymbol{g}'_t \odot \boldsymbol{g}'_t.
445
+
446
+ :math:`\rho` should be between 0 and 1. A value of rho close to 1 will decay the
447
+ moving average slowly and a value close to 0 will decay the moving average fast.
448
+
449
+ :math:`\rho` = 0.95 and :math:`\epsilon`=1e-6 are suggested in the paper and reported
450
+ to work for multiple datasets (MNIST, speech).
451
+
452
+ In the paper, no learning rate is considered (so learning_rate=1.0). Probably best to
453
+ keep it at this value. epsilon is important for the very first update (so the
454
+ numerator does not become 0).
455
+
456
+ Parameters
457
+ ----------
458
+ lr: float, LearningRateScheduler
459
+ learning rate.
460
+
461
+ References
462
+ ----------
463
+ .. [4] Zeiler, M. D. (2012). ADADELTA: An Adaptive Learning Rate Method. Retrieved from http://arxiv.org/abs/1212.5701
464
+
465
+ """
466
+
467
+ def __init__(
468
+ self,
469
+ lr: Union[float, LearningRateScheduler, bc.State] = 0.01,
470
+ weight_decay: Optional[float] = None,
471
+ epsilon: float = 1e-6,
472
+ rho: float = 0.95,
473
+ name: Optional[str] = None
474
+ ):
475
+ super().__init__(lr=lr, weight_decay=weight_decay, name=name)
476
+
477
+ self.epsilon = fcast(epsilon)
478
+ self.rho = fcast(rho)
479
+ self.cache_states = bc.visible_state_dict()
480
+ self.delta_states = bc.visible_state_dict()
481
+
482
+ def extra_repr(self) -> str:
483
+ return f", epsilon={self.epsilon}, rho={self.rho}"
484
+
485
+ def register_trainable_weights(self, train_states: Optional[Dict[str, bc.State]] = None):
486
+ train_states = dict() if train_states is None else train_states
487
+ assert isinstance(train_states, dict), '"states" must be a dict of braincore.State.'
488
+ for k, v in train_states.items():
489
+ assert isinstance(v, bc.State), f'"{k}" must be an instance of braincore.State.'
490
+ self.weight_states.add_unique_elem(k, v)
491
+ self.cache_states[k] = OptimState(bc.math.tree_zeros_like(v.value))
492
+ self.delta_states[k] = OptimState(bc.math.tree_zeros_like(v.value))
493
+
494
+ def update(self, grads: dict):
495
+ weight_values, grad_values, cache_values, delta_values = to_same_dict_tree(
496
+ self.weight_states, grads, self.cache_states, self.delta_states)
497
+ cache_values = jax.tree.map(lambda cv, gv: self.rho * cv + (1 - self.rho) * gv ** 2, cache_values, grad_values)
498
+ updates = jax.tree.map(lambda gv, dv, cv: gv * jnp.sqrt(dv + self.epsilon) / jnp.sqrt(cv + self.epsilon),
499
+ grad_values, delta_values, cache_values)
500
+ delta_values = jax.tree.map(lambda dv, upd: self.rho * dv + (1 - self.rho) * upd ** 2, delta_values, updates)
501
+ weight_values = jax.tree.map(functools.partial(_sgd, weight_decay=self.weight_decay),
502
+ weight_values,
503
+ updates)
504
+ self.weight_states.assign_values(weight_values)
505
+ self.delta_states.assign_values(delta_values)
506
+ self.cache_states.assign_values(cache_values)
507
+ self.lr.step_call()
508
+
509
+
510
+ class RMSProp(_WeightDecayOptimizer):
511
+ r"""Optimizer that implements the RMSprop algorithm.
512
+
513
+ RMSprop [5]_ and Adadelta have both been developed independently around the same time
514
+ stemming from the need to resolve Adagrad's radically diminishing learning rates.
515
+
516
+ The gist of RMSprop is to:
517
+
518
+ - Maintain a moving (discounted) average of the square of gradients
519
+ - Divide the gradient by the root of this average
520
+
521
+ .. math::
522
+
523
+ \begin{split}c_t &= \rho c_{t-1} + (1-\rho)*g^2\\
524
+ p_t &= \frac{\eta}{\sqrt{c_t + \epsilon}} * g \end{split}
525
+
526
+ The centered version additionally maintains a moving average of the gradients,
527
+ and uses that average to estimate the variance.
528
+
529
+ Parameters
530
+ ----------
531
+ lr: float, LearningRateScheduler
532
+ learning rate.
533
+
534
+ References
535
+ ----------
536
+ .. [5] Tieleman, T. and Hinton, G. (2012):
537
+ Neural Networks for Machine Learning, Lecture 6.5 - rmsprop.
538
+ Coursera. http://www.youtube.com/watch?v=O3sxAc4hxZU (formula @5:20)
539
+ """
540
+
541
+ def __init__(
542
+ self,
543
+ lr: Union[float, LearningRateScheduler, bc.State],
544
+ weight_decay: Optional[float] = None,
545
+ epsilon: float = 1e-6,
546
+ rho: float = 0.9,
547
+ name: Optional[str] = None
548
+ ):
549
+ super(RMSProp, self).__init__(lr=lr, weight_decay=weight_decay, name=name)
550
+
551
+ self.epsilon = fcast(epsilon)
552
+ self.rho = fcast(rho)
553
+ self.cache_states = bc.visible_state_dict()
554
+
555
+ def extra_repr(self) -> str:
556
+ return f", epsilon={self.epsilon}, rho={self.rho}"
557
+
558
+ def register_trainable_weights(self, train_states: Optional[Dict[str, bc.State]] = None):
559
+ train_states = dict() if train_states is None else train_states
560
+ assert isinstance(train_states, dict), '"states" must be a dict of braincore.State.'
561
+ for k, v in train_states.items():
562
+ assert isinstance(v, bc.State), f'"{k}" must be an instance of braincore.State.'
563
+ self.weight_states.add_unique_elem(k, v)
564
+ self.cache_states[k] = OptimState(bc.math.tree_zeros_like(v.value))
565
+
566
+ def update(self, grads: dict):
567
+ lr = self.lr()
568
+ weight_values, grad_values, cache_values = to_same_dict_tree(self.weight_states, grads, self.cache_states)
569
+ cache_values = jax.tree.map(lambda cv, gv: self.rho * cv + (1 - self.rho) * gv ** 2, cache_values, grad_values)
570
+ update = jax.tree.map(lambda gv, cv: lr * gv / jnp.sqrt(cv + self.epsilon), grad_values, cache_values)
571
+ weight_values = jax.tree.map(functools.partial(_sgd, weight_decay=self.weight_decay),
572
+ weight_values,
573
+ update)
574
+ self.weight_states.assign_values(weight_values)
575
+ self.cache_states.assign_values(cache_values)
576
+ self.lr.step_call()
577
+
578
+
579
+ class Adam(_WeightDecayOptimizer):
580
+ """Optimizer that implements the Adam algorithm.
581
+
582
+ Adam [6]_ - a stochastic gradient descent method (SGD) that computes
583
+ individual adaptive learning rates for different parameters from estimates of
584
+ first- and second-order moments of the gradients.
585
+
586
+ Parameters
587
+ ----------
588
+ lr: float, LearningRateScheduler
589
+ learning rate.
590
+ beta1: optional, float
591
+ A positive scalar value for beta_1, the exponential decay rate
592
+ for the first moment estimates (default 0.9).
593
+ beta2: optional, float
594
+ A positive scalar value for beta_2, the exponential decay rate
595
+ for the second moment estimates (default 0.999).
596
+ eps: optional, float
597
+ A positive scalar value for epsilon, a small constant for
598
+ numerical stability (default 1e-8).
599
+ name : optional, str
600
+ The optimizer name.
601
+
602
+ References
603
+ ----------
604
+ .. [6] Kingma, D. P., & Ba, J. (2014). Adam: A method for stochastic optimization. arXiv preprint arXiv:1412.6980.
605
+ """
606
+
607
+ def __init__(
608
+ self,
609
+ lr: Union[float, bc.State, LearningRateScheduler],
610
+ beta1: float = 0.9,
611
+ beta2: float = 0.999,
612
+ eps: float = 1e-8,
613
+ weight_decay: Optional[float] = None,
614
+ name: Optional[str] = None
615
+ ):
616
+ super(Adam, self).__init__(lr=lr,
617
+ weight_decay=weight_decay,
618
+ name=name)
619
+
620
+ self.beta1 = fcast(beta1)
621
+ self.beta2 = fcast(beta2)
622
+ self.eps = fcast(eps)
623
+ self.m1_states = bc.visible_state_dict()
624
+ self.m2_states = bc.visible_state_dict()
625
+
626
+ def extra_repr(self) -> str:
627
+ return f", beta1={self.beta1}, beta2={self.beta2}, eps={self.eps}"
628
+
629
+ def register_trainable_weights(self, train_states: Optional[Dict[str, bc.State]] = None):
630
+ train_states = dict() if train_states is None else train_states
631
+ assert isinstance(train_states, dict), '"states" must be a dict of braincore.State.'
632
+
633
+ for k, v in train_states.items():
634
+ assert isinstance(v, bc.State), f'"{k}" must be an instance of braincore.State.'
635
+ self.weight_states.add_unique_elem(k, v)
636
+ self.m1_states[k] = OptimState(bc.math.tree_zeros_like(v.value))
637
+ self.m2_states[k] = OptimState(bc.math.tree_zeros_like(v.value))
638
+
639
+ def update(self, grads: dict):
640
+ lr = self.lr()
641
+ lr = lr / (1 - self.beta1 ** (self.lr.last_epoch.value + 2))
642
+ lr = lr * jnp.sqrt(1 - self.beta2 ** (self.lr.last_epoch.value + 2))
643
+ weight_values, grad_values, m1_values, m2_values = to_same_dict_tree(
644
+ self.weight_states, grads, self.m1_states, self.m2_states)
645
+ m1_values = jax.tree.map(lambda m1, gv: self.beta1 * m1 + (1 - self.beta1) * gv, m1_values, grad_values)
646
+ m2_values = jax.tree.map(lambda m2, gv: self.beta2 * m2 + (1 - self.beta2) * gv ** 2, m2_values, grad_values)
647
+ update = jax.tree.map(lambda m1, m2: lr * m1 / (jnp.sqrt(m2) + self.eps), m1_values, m2_values)
648
+ weight_values = jax.tree.map(functools.partial(_sgd, weight_decay=self.weight_decay),
649
+ weight_values,
650
+ update)
651
+ self.weight_states.assign_values(weight_values)
652
+ self.m1_states.assign_values(m1_values)
653
+ self.m2_states.assign_values(m2_values)
654
+ self.lr.step_call()
655
+
656
+
657
+ class LARS(_WeightDecayOptimizer):
658
+ r"""Layer-wise adaptive rate scaling (LARS) optimizer [1]_.
659
+
660
+ Layer-wise Adaptive Rate Scaling, or LARS, is a large batch
661
+ optimization technique. There are two notable differences
662
+ between LARS and other adaptive algorithms such as `Adam` or `RMSProp`:
663
+ first, LARS uses a separate learning rate for each layer and not for
664
+ each weight. And second, the magnitude of the update is controlled
665
+ with respect to the weight norm for better control of training speed.
666
+
667
+ .. math::
668
+
669
+ m_{t} = \beta_{1}m_{t-1} + \left(1-\beta_{1}\right)\left(g_{t} + \lambda{x_{t}}\right) \\
670
+ x_{t+1}^{\left(i\right)} = x_{t}^{\left(i\right)} - \eta_{t}\frac{\phi\left(|| x_{t}^{\left(i\right)} ||\right)}{|| m_{t}^{\left(i\right)} || }m_{t}^{\left(i\right)}
671
+
672
+ Parameters
673
+ ----------
674
+ lr: float, LearningRateScheduler
675
+ learning rate.
676
+ momentum: float
677
+ coefficient used for the moving average of the gradient.
678
+ weight_decay: float
679
+ weight decay coefficient.
680
+ tc: float
681
+ trust coefficient eta ( < 1) for trust ratio computation.
682
+ eps: float
683
+ epsilon used for trust ratio computation.
684
+
685
+ References
686
+ ----------
687
+ .. [1] You, Yang, Igor Gitman and Boris Ginsburg. “Large Batch Training of Convolutional Networks.” arXiv: Computer Vision and Pattern Recognition (2017): n. pag.
688
+ """
689
+
690
+ def __init__(
691
+ self,
692
+ lr: Union[float, LearningRateScheduler, bc.State],
693
+ momentum: float = 0.9,
694
+ weight_decay: float = 1e-4,
695
+ tc: float = 1e-3,
696
+ eps: float = 1e-5,
697
+ name: Optional[str] = None
698
+ ):
699
+ super(LARS, self).__init__(lr=lr,
700
+ weight_decay=weight_decay,
701
+ name=name)
702
+ assert self.weight_decay is None, 'LARS does not support weight decay.'
703
+
704
+ self.momentum = fcast(momentum)
705
+ self.tc = fcast(tc)
706
+ self.eps = fcast(eps)
707
+ self.momentum_states = bc.visible_state_dict()
708
+
709
+ def extra_repr(self) -> str:
710
+ return f", momentum={self.momentum}, tc={self.tc}, eps={self.eps}"
711
+
712
+ def register_trainable_weights(self, train_states: Optional[Dict[str, bc.State]] = None):
713
+ train_states = dict() if train_states is None else train_states
714
+ assert isinstance(train_states, dict), '"states" must be a dict of braincore.State.'
715
+ for k, v in train_states.items():
716
+ assert isinstance(v, bc.State), f'"{k}" must be an instance of braincore.State.'
717
+ self.weight_states.add_unique_elem(k, v)
718
+ self.momentum_states[k] = OptimState(bc.math.tree_zeros_like(v.value))
719
+
720
+ def update(self, grads: dict):
721
+ lr = self.lr()
722
+ weight_values, grad_values, momentum_values = to_same_dict_tree(self.weight_states, grads, self.momentum_states)
723
+
724
+ def _lars_update(pv, gv, mv):
725
+ p_norm = jnp.linalg.norm(pv)
726
+ g_norm = jnp.linalg.norm(gv)
727
+ trust_ratio = self.tc * p_norm / (g_norm + self.weight_decay * p_norm + self.eps)
728
+ local_lr = lr * jnp.maximum(jnp.logical_or(p_norm == 0, g_norm == 0), trust_ratio)
729
+ mv = self.momentum * mv + local_lr * (gv + self.weight_decay * pv)
730
+ return mv
731
+
732
+ momentum_values = jax.tree.map(_lars_update, weight_values, grad_values, momentum_values)
733
+ weight_values = jax.tree.map(lambda pv, mv: pv - mv, weight_values, momentum_values)
734
+ self.weight_states.assign_values(weight_values)
735
+ self.momentum_states.assign_values(momentum_values)
736
+ self.lr.step_call()
737
+
738
+
739
+ class Adan(_WeightDecayOptimizer):
740
+ r"""Adaptive Nesterov Momentum Algorithm for Faster Optimizing Deep Models [1]_.
741
+
742
+ .. math::
743
+
744
+ \begin{equation}
745
+ \begin{aligned}
746
+ & \mathbf{m}_k=\left(1-\beta_1\right) \mathbf{m}_{k-1}+\beta_1 \mathbf{g}_k \\
747
+ & \mathbf{v}_k=\left(1-\beta_2\right) \mathbf{v}_{k-1}+\beta_2\left(\mathbf{g}_k-\mathbf{g}_{k-1}\right) \\
748
+ & \mathbf{n}_k=\left(1-\beta_3\right) \mathbf{n}_{k-1}+\beta_3\left[\mathbf{g}_k+\left(1-\beta_2\right)\left(\mathbf{g}_k-\mathbf{g}_{k-1}\right)\right]^2 \\
749
+ & \boldsymbol{\eta}_k=\eta /\left(\sqrt{\mathbf{n}_k+\varepsilon}\right) \\
750
+ & \boldsymbol{\theta}_{k+1}=\left(1+\lambda_k \eta\right)^{-1}\left[\boldsymbol{\theta}_k-\boldsymbol{\eta}_k \circ\left(\mathbf{m}_k+\left(1-\beta_2\right) \mathbf{v}_k\right)\right] \\
751
+ \end{aligned}
752
+ \end{equation}
753
+
754
+ Parameters
755
+ ----------
756
+ lr: float, LearningRateScheduler
757
+ learning rate. Can be much higher than Adam, up to 5-10x. (default: 1e-3)
758
+ betas : tuple
759
+ Coefficients used for computing running averages of gradient and its norm. (default: (0.02, 0.08, 0.01))
760
+ eps : float
761
+ The term added to the denominator to improve numerical stability. (default: 1e-8)
762
+ weight_decay : float
763
+ decoupled weight decay (L2 penalty) (default: 0)
764
+ no_prox: bool
765
+ how to perform the decoupled weight decay (default: False).
766
+ It determines the update rule of parameters with weight decay.
767
+ By default, Adan updates the parameters in the way presented in Algorithm 1 in the paper:
768
+
769
+ .. math::
770
+ \boldsymbol{\theta}_{k+1} = ( 1+\lambda \eta)^{-1}\left[\boldsymbol{\theta}_k - \boldsymbol{\eta}_k \circ (\mathbf{m}_k+(1-{\color{blue}\beta_2})\mathbf{v}k)\right],
771
+
772
+ But one also can update the parameter like Adamw:
773
+
774
+ .. math::
775
+ \boldsymbol{\theta}_{k+1} = ( 1-\lambda \eta)\boldsymbol{\theta}_k - \boldsymbol{\eta}_k \circ (\mathbf{m}_k+(1-{\color{blue}\beta_2})\mathbf{v}_k).
776
+
777
+ References
778
+ ----------
779
+ .. [1] Xie, Xingyu, Pan Zhou, Huan Li, Zhouchen Lin and Shuicheng Yan.
780
+ “Adan: Adaptive Nesterov Momentum Algorithm for Faster Optimizing
781
+ Deep Models.” ArXiv abs/2208.06677 (2022): n. pag.
782
+ """
783
+
784
+ def __init__(
785
+ self,
786
+ lr: Union[float, LearningRateScheduler, bc.State] = 1e-3,
787
+ betas: Tuple[float, float, float] = (0.02, 0.08, 0.01),
788
+ eps: float = 1e-8,
789
+ weight_decay: float = 0.02,
790
+ no_prox: bool = False,
791
+ name: Optional[str] = None,
792
+ ):
793
+ super(Adan, self).__init__(lr=lr, weight_decay=weight_decay, name=name)
794
+
795
+ assert len(betas) == 3
796
+ if eps < 0.:
797
+ raise ValueError("Invalid epsilon value: {}".format(eps))
798
+ if not 0.0 <= betas[0] < 1.0:
799
+ raise ValueError("Invalid beta parameter at index 0: {}".format(betas[0]))
800
+ if not 0.0 <= betas[1] < 1.0:
801
+ raise ValueError("Invalid beta parameter at index 1: {}".format(betas[1]))
802
+ if not 0.0 <= betas[2] < 1.0:
803
+ raise ValueError("Invalid beta parameter at index 2: {}".format(betas[2]))
804
+
805
+ self.betas = fcast(jnp.asarray(betas))
806
+ self.eps = fcast(eps)
807
+ self.no_prox = no_prox
808
+ self.exp_avg_states = bc.visible_state_dict()
809
+ self.exp_avg_sq_states = bc.visible_state_dict()
810
+ self.exp_avg_diff_states = bc.visible_state_dict()
811
+ self.pre_grad_states = bc.visible_state_dict()
812
+
813
+ def extra_repr(self) -> str:
814
+ return f", betas={self.betas}, eps={self.eps}, weight_decay={self.weight_decay}, no_prox={self.no_prox}"
815
+
816
+ def register_trainable_weights(self, train_states: Optional[Dict[str, bc.State]] = None):
817
+ train_states = dict() if train_states is None else train_states
818
+ assert isinstance(train_states, dict), '"states" must be a dict of braincore.State.'
819
+ for k, v in train_states.items():
820
+ assert isinstance(v, bc.State), f'"{k}" must be an instance of braincore.State.'
821
+ self.weight_states.add_unique_elem(k, v)
822
+ self.exp_avg_states[k] = OptimState(bc.math.tree_zeros_like(v.value))
823
+ self.exp_avg_sq_states[k] = OptimState(bc.math.tree_zeros_like(v.value))
824
+ self.exp_avg_diff_states[k] = OptimState(bc.math.tree_zeros_like(v.value))
825
+ self.pre_grad_states[k] = OptimState(bc.math.tree_zeros_like(v.value))
826
+
827
+ def update(self, grads: dict):
828
+ lr = self.lr()
829
+ step = self.lr.last_epoch.value + 1
830
+ correct_m = 1 / (1 - (1 - self.betas[0]) ** (step + 1))
831
+ correct_v = 1 / (1 - (1 - self.betas[1]) ** (step + 1))
832
+ correct_n = 1 / (1 - (1 - self.betas[2]) ** (step + 1))
833
+ m_values, n_values, v_values, pre_g_values, weight_values, grad_values = to_same_dict_tree(
834
+ self.exp_avg_states, self.exp_avg_diff_states, self.exp_avg_sq_states, self.pre_grad_states,
835
+ self.weight_states, grads)
836
+
837
+ def _adan_update(m, n, v, pre_g, g, p):
838
+ m = m * (1 - self.betas[0]) + self.betas[0] * g
839
+ gd = g - pre_g
840
+ v = v * (1 - self.betas[1]) + self.betas[1] * gd
841
+ n = n * (1 - self.betas[2]) + self.betas[2] * (g + (1 - self.betas[1]) * gd) ** 2
842
+ weighted_step_size = lr / (jnp.sqrt(n * correct_n) + self.eps)
843
+ if self.no_prox:
844
+ p = (p * (1 - self.weight_decay * lr) -
845
+ weighted_step_size * (m * correct_m + (1 - self.betas[1]) * v * correct_v))
846
+ else:
847
+ p = ((p - weighted_step_size * (m * correct_m + (1 - self.betas[1]) * v * correct_v)) /
848
+ (1 + self.weight_decay * lr))
849
+ return m, n, v, p
850
+
851
+ m_values, n_values, v_values, weight_values = jax.tree.map(
852
+ _adan_update, m_values, n_values, v_values, pre_g_values, grad_values, weight_values)
853
+ self.exp_avg_states.assign_values(m_values)
854
+ self.exp_avg_diff_states.assign_values(n_values)
855
+ self.exp_avg_sq_states.assign_values(v_values)
856
+ self.weight_states.assign_values(weight_values)
857
+ self.lr.step_call()
858
+
859
+
860
+ class AdamW(_WeightDecayOptimizer):
861
+ r"""Adam with weight decay regularization [1]_.
862
+
863
+ AdamW uses weight decay to regularize learning towards small weights, as
864
+ this leads to better generalization. In SGD you can also use L2 regularization
865
+ to implement this as an additive loss term, however L2 regularization
866
+ does not behave as intended for adaptive gradient algorithms such as Adam.
867
+
868
+ .. math::
869
+
870
+ \begin{aligned}
871
+ &\rule{110mm}{0.4pt} \\
872
+ &\textbf{input} : \gamma \text{(lr)}, \: \beta_1, \beta_2
873
+ \text{(betas)}, \: \theta_0 \text{(params)}, \: f(\theta) \text{(objective)},
874
+ \: \epsilon \text{ (epsilon)} \\
875
+ &\hspace{13mm} \lambda \text{(weight decay)}, \: \textit{amsgrad},
876
+ \: \textit{maximize} \\
877
+ &\textbf{initialize} : m_0 \leftarrow 0 \text{ (first moment)}, v_0 \leftarrow 0
878
+ \text{ ( second moment)}, \: \widehat{v_0}^{max}\leftarrow 0 \\[-1.ex]
879
+ &\rule{110mm}{0.4pt} \\
880
+ &\textbf{for} \: t=1 \: \textbf{to} \: \ldots \: \textbf{do} \\
881
+
882
+ &\hspace{5mm}\textbf{if} \: \textit{maximize}: \\
883
+ &\hspace{10mm}g_t \leftarrow -\nabla_{\theta} f_t (\theta_{t-1}) \\
884
+ &\hspace{5mm}\textbf{else} \\
885
+ &\hspace{10mm}g_t \leftarrow \nabla_{\theta} f_t (\theta_{t-1}) \\
886
+ &\hspace{5mm} \theta_t \leftarrow \theta_{t-1} - \gamma \lambda \theta_{t-1} \\
887
+ &\hspace{5mm}m_t \leftarrow \beta_1 m_{t-1} + (1 - \beta_1) g_t \\
888
+ &\hspace{5mm}v_t \leftarrow \beta_2 v_{t-1} + (1-\beta_2) g^2_t \\
889
+ &\hspace{5mm}\widehat{m_t} \leftarrow m_t/\big(1-\beta_1^t \big) \\
890
+ &\hspace{5mm}\widehat{v_t} \leftarrow v_t/\big(1-\beta_2^t \big) \\
891
+ &\hspace{5mm}\textbf{if} \: amsgrad \\
892
+ &\hspace{10mm}\widehat{v_t}^{max} \leftarrow \mathrm{max}(\widehat{v_t}^{max},
893
+ \widehat{v_t}) \\
894
+ &\hspace{10mm}\theta_t \leftarrow \theta_t - \gamma \widehat{m_t}/
895
+ \big(\sqrt{\widehat{v_t}^{max}} + \epsilon \big) \\
896
+ &\hspace{5mm}\textbf{else} \\
897
+ &\hspace{10mm}\theta_t \leftarrow \theta_t - \gamma \widehat{m_t}/
898
+ \big(\sqrt{\widehat{v_t}} + \epsilon \big) \\
899
+ &\rule{110mm}{0.4pt} \\[-1.ex]
900
+ &\bf{return} \: \theta_t \\[-1.ex]
901
+ &\rule{110mm}{0.4pt} \\[-1.ex]
902
+ \end{aligned}
903
+
904
+
905
+ Parameters
906
+ ----------
907
+ lr: float, LearningRateScheduler
908
+ learning rate.
909
+ beta1: optional, float
910
+ A positive scalar value for beta_1, the exponential decay rate
911
+ for the first moment estimates. Generally close to 1.
912
+ beta2: optional, float
913
+ A positive scalar value for beta_2, the exponential decay rate
914
+ for the second moment estimates. Generally close to 1.
915
+ eps: optional, float
916
+ A positive scalar value for epsilon, a small constant for
917
+ numerical stability.
918
+ weight_decay: float
919
+ Strength of the weight decay regularization. Note that this
920
+ weight decay is multiplied with the learning rate.
921
+ amsgrad: bool
922
+ whether to use the AMSGrad variant of this algorithm
923
+ from the paper `On the Convergence of Adam and Beyond`.
924
+ name : optional, str
925
+ The optimizer name.
926
+
927
+ References
928
+ ----------
929
+ .. [1] Loshchilov, Ilya and Frank Hutter. “Decoupled Weight Decay Regularization.” International Conference on Learning Representations (2019).
930
+
931
+ """
932
+
933
+ def __init__(
934
+ self,
935
+ lr: Union[float, LearningRateScheduler, bc.State],
936
+ beta1: float = 0.9,
937
+ beta2: float = 0.999,
938
+ eps: float = 1e-8,
939
+ weight_decay: float = 1e-2,
940
+ amsgrad: bool = False,
941
+ name: Optional[str] = None,
942
+ ):
943
+ super(AdamW, self).__init__(lr=lr,
944
+ weight_decay=weight_decay,
945
+ name=name)
946
+
947
+ if eps < 0.:
948
+ raise ValueError("Invalid epsilon value: {}".format(eps))
949
+ if not 0.0 <= beta1 < 1.0:
950
+ raise ValueError("Invalid beta parameter at index 0: {}".format(beta1))
951
+ if not 0.0 <= beta2 < 1.0:
952
+ raise ValueError("Invalid beta parameter at index 1: {}".format(beta2))
953
+ if weight_decay < 0.:
954
+ raise ValueError("Invalid weight_decay value: {}".format(weight_decay))
955
+
956
+ self.beta1 = fcast(beta1)
957
+ self.beta2 = fcast(beta2)
958
+ self.eps = fcast(eps)
959
+ self.amsgrad = amsgrad
960
+ self.m1_states = bc.visible_state_dict()
961
+ self.m2_states = bc.visible_state_dict()
962
+ if self.amsgrad:
963
+ self.vmax_states = bc.visible_state_dict()
964
+
965
+ def extra_repr(self) -> str:
966
+ return (f", beta1={self.beta1}, beta2={self.beta2}, eps={self.eps}"
967
+ f", weight_decay={self.weight_decay}, amsgrad={self.amsgrad}")
968
+
969
+ def register_trainable_weights(self, train_states: Optional[Dict[str, bc.State]] = None):
970
+ train_states = dict() if train_states is None else train_states
971
+ assert isinstance(train_states, dict), '"states" must be a dict of braincore.State.'
972
+ for k, v in train_states.items():
973
+ assert isinstance(v, bc.State), f'"{k}" must be an instance of braincore.State.'
974
+ self.weight_states.add_unique_elem(k, v)
975
+ self.m1_states[k] = OptimState(bc.math.tree_zeros_like(v.value))
976
+ self.m2_states[k] = OptimState(bc.math.tree_zeros_like(v.value))
977
+ if self.amsgrad:
978
+ self.vmax_states[k] = OptimState(bc.math.tree_zeros_like(v.value))
979
+
980
+ def update(self, grads: dict):
981
+ lr_old = self.lr()
982
+ step = self.lr.last_epoch.value + 2
983
+ bias_correction1 = 1 - self.beta1 ** step
984
+ bias_correction2 = 1 - self.beta2 ** step
985
+ lr = lr_old * jnp.sqrt(bias_correction2) / bias_correction1
986
+
987
+ def _adamw_update(p, m, v, g, vmax=None):
988
+ if self.weight_decay != 0:
989
+ p *= (1 - lr_old * self.weight_decay)
990
+ m = self.beta1 * m + (1 - self.beta1) * g
991
+ v = self.beta2 * v + (1 - self.beta2) * g ** 2
992
+ if self.amsgrad:
993
+ vmax = jnp.maximum(vmax, v)
994
+ denom = jnp.sqrt(vmax) + self.eps
995
+ return p - lr * m / denom, m, v, vmax
996
+ else:
997
+ denom = jnp.sqrt(v.value) + self.eps
998
+ return p - lr * m / denom, m, v
999
+
1000
+ if self.amsgrad:
1001
+ weight_values, m1_values, m2_values, vmax_values = to_same_dict_tree(
1002
+ self.weight_states, self.m1_states, self.m2_states, self.vmax_states)
1003
+ weight_values, m1_values, m2_values, vmax_values = jax.tree.map(
1004
+ _adamw_update, weight_values, m1_values, m2_values, grads, vmax_values)
1005
+ self.vmax_states.assign_values(vmax_values)
1006
+ else:
1007
+ weight_values, m1_values, m2_values = to_same_dict_tree(self.weight_states, self.m1_states, self.m2_states)
1008
+ weight_values, m1_values, m2_values = jax.tree.map(
1009
+ _adamw_update, weight_values, m1_values, m2_values, grads)
1010
+ self.weight_states.assign_values(weight_values)
1011
+ self.m1_states.assign_values(m1_values)
1012
+ self.m2_states.assign_values(m2_values)
1013
+ self.lr.step_call()
1014
+
1015
+
1016
+ class SM3(_WeightDecayOptimizer):
1017
+ """SM3 algorithm [1]_.
1018
+
1019
+ The 'Square-root of Minima of Sums of Maxima of Squared-gradients Method'
1020
+ (SM3) algorithm is a memory-efficient adaptive optimization algorithm similar
1021
+ to Adam and Adagrad with greatly reduced memory usage for history tensors.
1022
+ For an `n x m` matrix, Adam and Adagrad use `O(nm)` memory for history
1023
+ tensors, while SM3 uses `O(n+m)` due to the chosen cover. In general, a tensor
1024
+ of shape `(n_1, n_2, ..., n_k)` optimized using Adam will use `O(prod n_i)`
1025
+ memory for storage tensors, while the optimization using SM3 will use
1026
+ `O(sum n_i)` memory. Despite storing fewer parameters, this optimization
1027
+ algorithm manages to be comparably effective.
1028
+
1029
+ This advantage drastically shrinks when `momentum > 0`. The momentum is
1030
+ tracked using a tensor of the same shape as the tensor being optimized. With
1031
+ momentum, SM3 will use just over half as much memory as Adam, and a bit more
1032
+ than Adagrad.
1033
+
1034
+ Parameters
1035
+ ----------
1036
+ lr: float, LearningRateScheduler
1037
+ learning rate.
1038
+ momentum: float
1039
+ coefficient used to scale prior updates
1040
+ before adding. This drastically increases memory usage if
1041
+ `momentum > 0.0`. (default: 0.0)
1042
+ beta: float
1043
+ coefficient used for exponential moving averages (default: 0.0)
1044
+ eps: float
1045
+ Term added to square-root in denominator to
1046
+ improve numerical stability (default: 1e-30).
1047
+
1048
+ References
1049
+ ----------
1050
+ .. [1] Anil, Rohan, Vineet Gupta, Tomer Koren and Yoram Singer. “Memory Efficient Adaptive Optimization.” Neural Information Processing Systems (2019).
1051
+
1052
+ """
1053
+
1054
+ def __init__(
1055
+ self,
1056
+ lr: Union[float, LearningRateScheduler, bc.State],
1057
+ beta: float = 0.,
1058
+ momentum: float = 0.,
1059
+ eps: float = 1e-30,
1060
+ weight_decay: Optional[float] = None,
1061
+ name: Optional[str] = None,
1062
+ ):
1063
+ super(SM3, self).__init__(lr=lr,
1064
+ weight_decay=weight_decay,
1065
+ name=name)
1066
+
1067
+ if not 0.0 <= momentum < 1.0:
1068
+ raise ValueError("Invalid momentum: {0}".format(momentum))
1069
+ if not 0.0 <= beta < 1.0:
1070
+ raise ValueError("Invalid beta: {0}".format(beta))
1071
+ if not 0.0 <= eps:
1072
+ raise ValueError("Invalid eps: {0}".format(eps))
1073
+
1074
+ self.eps = fcast(eps)
1075
+ self.beta = fcast(beta)
1076
+ self.momentum = fcast(momentum)
1077
+ self.memory_states = bc.visible_state_dict()
1078
+
1079
+ def extra_repr(self) -> str:
1080
+ return f", beta={self.beta}, momentum={self.momentum}, eps={self.eps}"
1081
+
1082
+ def register_trainable_weights(self, train_states: Optional[Dict[str, bc.State]] = None):
1083
+ train_states = dict() if train_states is None else train_states
1084
+ assert isinstance(train_states, dict), '"states" must be a dict of braincore.State.'
1085
+ for k, v in train_states.items():
1086
+ assert isinstance(v, bc.State), f'"{k}" must be an instance of braincore.State.'
1087
+ self.weight_states.add_unique_elem(k, v)
1088
+ rank, ndim, dtype = v.value.shape, v.value.ndim, v.value.dtype
1089
+ for i in range(ndim):
1090
+ shape = [1] * ndim
1091
+ shape[i] = rank[i]
1092
+ self.memory_states[f'{k}_m{i}'] = bc.State(jnp.zeros(shape, dtype=dtype))
1093
+ if self.momentum > 0.:
1094
+ self.memory_states[f'{k}_mbuffer'] = bc.State(jnp.zeros_like(v.value))
1095
+
1096
+ def update(self, grads: dict):
1097
+ lr = self.lr()
1098
+
1099
+ for k, p in self.weight_states.items():
1100
+ g = grads[k]
1101
+ ndim = p.ndim
1102
+ update = self.memory_states[f'{k}_m0'].value
1103
+ for i in range(1, ndim):
1104
+ update = jnp.minimum(update, self.memory_states[f'{k}_m{i}'].value)
1105
+ if self.beta > 0.:
1106
+ update *= self.beta
1107
+ update += g * g * (1 - self.beta)
1108
+ # Computes max along all dimensions except the given dim.
1109
+ # If tensor is a scalar, it returns tensor.
1110
+ for i in range(ndim):
1111
+ result = update
1112
+ for j in range(ndim):
1113
+ if i != j:
1114
+ result = jnp.maximum(result, axis=j, keepdim=True)
1115
+ acc = self.memory_states[f'{k}_m{i}'].value
1116
+ if self.beta > 0.:
1117
+ acc.value = jnp.maximum(acc, result)
1118
+ else:
1119
+ # No need to compare - nu_max is bigger because of grad ** 2
1120
+ acc.value = result
1121
+ update = g / jnp.sqrt(update + self.eps)
1122
+ if self.momentum > 0.:
1123
+ m_buffer = self.memory_states[f'{k}_mbuffer'].value
1124
+ update = update * (1. - self.momentum) + m_buffer * self.momentum
1125
+ m_buffer.value = update
1126
+ if self.weight_decay is None:
1127
+ p.value -= lr * update
1128
+ else:
1129
+ p.value = (1 - self.weight_decay) * p - lr * update
1130
+ self.lr.step_call()