brainstate 0.1.8__py2.py3-none-any.whl → 0.1.9__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.
- brainstate/__init__.py +58 -51
- brainstate/_compatible_import.py +148 -148
- brainstate/_state.py +1605 -1663
- brainstate/_state_test.py +52 -52
- brainstate/_utils.py +47 -47
- brainstate/augment/__init__.py +30 -30
- brainstate/augment/_autograd.py +778 -778
- brainstate/augment/_autograd_test.py +1289 -1289
- brainstate/augment/_eval_shape.py +99 -99
- brainstate/augment/_eval_shape_test.py +38 -38
- brainstate/augment/_mapping.py +1060 -1060
- brainstate/augment/_mapping_test.py +597 -597
- brainstate/augment/_random.py +151 -151
- brainstate/compile/__init__.py +38 -38
- brainstate/compile/_ad_checkpoint.py +204 -204
- brainstate/compile/_ad_checkpoint_test.py +49 -49
- brainstate/compile/_conditions.py +256 -256
- brainstate/compile/_conditions_test.py +220 -220
- brainstate/compile/_error_if.py +92 -92
- brainstate/compile/_error_if_test.py +52 -52
- brainstate/compile/_jit.py +346 -346
- brainstate/compile/_jit_test.py +143 -143
- brainstate/compile/_loop_collect_return.py +536 -536
- brainstate/compile/_loop_collect_return_test.py +58 -58
- brainstate/compile/_loop_no_collection.py +184 -184
- brainstate/compile/_loop_no_collection_test.py +50 -50
- brainstate/compile/_make_jaxpr.py +888 -888
- brainstate/compile/_make_jaxpr_test.py +156 -156
- brainstate/compile/_progress_bar.py +202 -202
- brainstate/compile/_unvmap.py +159 -159
- brainstate/compile/_util.py +147 -147
- brainstate/environ.py +563 -563
- brainstate/environ_test.py +62 -62
- brainstate/functional/__init__.py +27 -26
- brainstate/graph/__init__.py +29 -29
- brainstate/graph/_graph_node.py +244 -244
- brainstate/graph/_graph_node_test.py +73 -73
- brainstate/graph/_graph_operation.py +1738 -1738
- brainstate/graph/_graph_operation_test.py +563 -563
- brainstate/init/__init__.py +26 -26
- brainstate/init/_base.py +52 -52
- brainstate/init/_generic.py +244 -244
- brainstate/init/_random_inits.py +553 -553
- brainstate/init/_random_inits_test.py +149 -149
- brainstate/init/_regular_inits.py +105 -105
- brainstate/init/_regular_inits_test.py +50 -50
- brainstate/mixin.py +365 -363
- brainstate/mixin_test.py +77 -73
- brainstate/nn/__init__.py +135 -131
- brainstate/{functional → nn}/_activations.py +808 -813
- brainstate/{functional → nn}/_activations_test.py +331 -331
- brainstate/nn/_collective_ops.py +514 -514
- brainstate/nn/_collective_ops_test.py +43 -43
- brainstate/nn/_common.py +178 -178
- brainstate/nn/_conv.py +501 -501
- brainstate/nn/_conv_test.py +238 -238
- brainstate/nn/_delay.py +509 -502
- brainstate/nn/_delay_test.py +238 -184
- brainstate/nn/_dropout.py +426 -426
- brainstate/nn/_dropout_test.py +100 -100
- brainstate/nn/_dynamics.py +1343 -1343
- brainstate/nn/_dynamics_test.py +78 -78
- brainstate/nn/_elementwise.py +1119 -1119
- brainstate/nn/_elementwise_test.py +169 -169
- brainstate/nn/_embedding.py +58 -58
- brainstate/nn/_exp_euler.py +92 -92
- brainstate/nn/_exp_euler_test.py +35 -35
- brainstate/nn/_fixedprob.py +239 -239
- brainstate/nn/_fixedprob_test.py +114 -114
- brainstate/nn/_inputs.py +608 -608
- brainstate/nn/_linear.py +424 -424
- brainstate/nn/_linear_mv.py +83 -83
- brainstate/nn/_linear_mv_test.py +120 -120
- brainstate/nn/_linear_test.py +107 -107
- brainstate/nn/_ltp.py +28 -28
- brainstate/nn/_module.py +377 -377
- brainstate/nn/_module_test.py +40 -40
- brainstate/nn/_neuron.py +705 -705
- brainstate/nn/_neuron_test.py +161 -161
- brainstate/nn/_normalizations.py +975 -918
- brainstate/nn/_normalizations_test.py +73 -73
- brainstate/{functional → nn}/_others.py +46 -46
- brainstate/nn/_poolings.py +1177 -1177
- brainstate/nn/_poolings_test.py +217 -217
- brainstate/nn/_projection.py +486 -486
- brainstate/nn/_rate_rnns.py +554 -554
- brainstate/nn/_rate_rnns_test.py +63 -63
- brainstate/nn/_readout.py +209 -209
- brainstate/nn/_readout_test.py +53 -53
- brainstate/nn/_stp.py +236 -236
- brainstate/nn/_synapse.py +505 -505
- brainstate/nn/_synapse_test.py +131 -131
- brainstate/nn/_synaptic_projection.py +423 -423
- brainstate/nn/_synouts.py +162 -162
- brainstate/nn/_synouts_test.py +57 -57
- brainstate/nn/_utils.py +89 -89
- brainstate/nn/metrics.py +388 -388
- brainstate/optim/__init__.py +38 -38
- brainstate/optim/_base.py +64 -64
- brainstate/optim/_lr_scheduler.py +448 -448
- brainstate/optim/_lr_scheduler_test.py +50 -50
- brainstate/optim/_optax_optimizer.py +152 -152
- brainstate/optim/_optax_optimizer_test.py +53 -53
- brainstate/optim/_sgd_optimizer.py +1104 -1104
- brainstate/random/__init__.py +24 -24
- brainstate/random/_rand_funs.py +3616 -3616
- brainstate/random/_rand_funs_test.py +567 -567
- brainstate/random/_rand_seed.py +210 -210
- brainstate/random/_rand_seed_test.py +48 -48
- brainstate/random/_rand_state.py +1409 -1409
- brainstate/random/_random_for_unit.py +52 -52
- brainstate/surrogate.py +1957 -1957
- brainstate/transform.py +23 -23
- brainstate/typing.py +304 -304
- brainstate/util/__init__.py +50 -50
- brainstate/util/caller.py +98 -98
- brainstate/util/error.py +55 -55
- brainstate/util/filter.py +469 -469
- brainstate/util/others.py +540 -540
- brainstate/util/pretty_pytree.py +945 -945
- brainstate/util/pretty_pytree_test.py +159 -159
- brainstate/util/pretty_repr.py +328 -328
- brainstate/util/pretty_table.py +2954 -2954
- brainstate/util/scaling.py +258 -258
- brainstate/util/struct.py +523 -523
- {brainstate-0.1.8.dist-info → brainstate-0.1.9.dist-info}/METADATA +91 -99
- brainstate-0.1.9.dist-info/RECORD +130 -0
- {brainstate-0.1.8.dist-info → brainstate-0.1.9.dist-info}/WHEEL +1 -1
- {brainstate-0.1.8.dist-info → brainstate-0.1.9.dist-info/licenses}/LICENSE +202 -202
- brainstate/functional/_normalization.py +0 -81
- brainstate/functional/_spikes.py +0 -204
- brainstate-0.1.8.dist-info/RECORD +0 -132
- {brainstate-0.1.8.dist-info → brainstate-0.1.9.dist-info}/top_level.txt +0 -0
@@ -1,50 +1,50 @@
|
|
1
|
-
# Copyright 2024 BDP 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
|
-
from __future__ import annotations
|
17
|
-
|
18
|
-
import unittest
|
19
|
-
|
20
|
-
import jax.numpy as jnp
|
21
|
-
|
22
|
-
import brainstate
|
23
|
-
|
24
|
-
|
25
|
-
class TestMultiStepLR(unittest.TestCase):
|
26
|
-
def test1(self):
|
27
|
-
lr = brainstate.optim.MultiStepLR(0.1, [10, 20, 30], gamma=0.1)
|
28
|
-
for i in range(40):
|
29
|
-
r = lr(i)
|
30
|
-
if i < 10:
|
31
|
-
self.assertEqual(r, 0.1)
|
32
|
-
elif i < 20:
|
33
|
-
self.assertTrue(jnp.allclose(r, 0.01))
|
34
|
-
elif i < 30:
|
35
|
-
self.assertTrue(jnp.allclose(r, 0.001))
|
36
|
-
else:
|
37
|
-
self.assertTrue(jnp.allclose(r, 0.0001))
|
38
|
-
|
39
|
-
def test2(self):
|
40
|
-
lr = brainstate.compile.jit(brainstate.optim.MultiStepLR(0.1, [10, 20, 30], gamma=0.1))
|
41
|
-
for i in range(40):
|
42
|
-
r = lr(i)
|
43
|
-
if i < 10:
|
44
|
-
self.assertEqual(r, 0.1)
|
45
|
-
elif i < 20:
|
46
|
-
self.assertTrue(jnp.allclose(r, 0.01))
|
47
|
-
elif i < 30:
|
48
|
-
self.assertTrue(jnp.allclose(r, 0.001))
|
49
|
-
else:
|
50
|
-
self.assertTrue(jnp.allclose(r, 0.0001))
|
1
|
+
# Copyright 2024 BDP 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
|
+
from __future__ import annotations
|
17
|
+
|
18
|
+
import unittest
|
19
|
+
|
20
|
+
import jax.numpy as jnp
|
21
|
+
|
22
|
+
import brainstate
|
23
|
+
|
24
|
+
|
25
|
+
class TestMultiStepLR(unittest.TestCase):
|
26
|
+
def test1(self):
|
27
|
+
lr = brainstate.optim.MultiStepLR(0.1, [10, 20, 30], gamma=0.1)
|
28
|
+
for i in range(40):
|
29
|
+
r = lr(i)
|
30
|
+
if i < 10:
|
31
|
+
self.assertEqual(r, 0.1)
|
32
|
+
elif i < 20:
|
33
|
+
self.assertTrue(jnp.allclose(r, 0.01))
|
34
|
+
elif i < 30:
|
35
|
+
self.assertTrue(jnp.allclose(r, 0.001))
|
36
|
+
else:
|
37
|
+
self.assertTrue(jnp.allclose(r, 0.0001))
|
38
|
+
|
39
|
+
def test2(self):
|
40
|
+
lr = brainstate.compile.jit(brainstate.optim.MultiStepLR(0.1, [10, 20, 30], gamma=0.1))
|
41
|
+
for i in range(40):
|
42
|
+
r = lr(i)
|
43
|
+
if i < 10:
|
44
|
+
self.assertEqual(r, 0.1)
|
45
|
+
elif i < 20:
|
46
|
+
self.assertTrue(jnp.allclose(r, 0.01))
|
47
|
+
elif i < 30:
|
48
|
+
self.assertTrue(jnp.allclose(r, 0.001))
|
49
|
+
else:
|
50
|
+
self.assertTrue(jnp.allclose(r, 0.0001))
|
@@ -1,152 +1,152 @@
|
|
1
|
-
# Copyright 2024 BDP 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
|
-
|
17
|
-
import importlib.util
|
18
|
-
from typing import Hashable, Dict, Optional
|
19
|
-
|
20
|
-
from brainstate._state import ShortTermState, State, StateDictManager
|
21
|
-
from brainstate.typing import PyTree
|
22
|
-
from ._base import Optimizer
|
23
|
-
|
24
|
-
optax_installed = importlib.util.find_spec('optax') is not None
|
25
|
-
|
26
|
-
__all__ = [
|
27
|
-
'OptaxOptimizer',
|
28
|
-
'LBFGS',
|
29
|
-
]
|
30
|
-
|
31
|
-
|
32
|
-
class OptaxOptimizer(Optimizer):
|
33
|
-
"""Simple train state for the common case with a single Optax optimizer.
|
34
|
-
|
35
|
-
Example usage::
|
36
|
-
|
37
|
-
>>> import jax
|
38
|
-
>>> import jax.numpy as jnp
|
39
|
-
>>> import brainstate as brainstate
|
40
|
-
>>> import optax
|
41
|
-
...
|
42
|
-
>>> class Model(brainstate.nn.Module):
|
43
|
-
... def __init__(self):
|
44
|
-
... super().__init__()
|
45
|
-
... self.linear1 = brainstate.nn.Linear(2, 3)
|
46
|
-
... self.linear2 = brainstate.nn.Linear(3, 4)
|
47
|
-
... def __call__(self, x):
|
48
|
-
... return self.linear2(self.linear1(x))
|
49
|
-
...
|
50
|
-
>>> x = brainstate.random.randn(1, 2)
|
51
|
-
>>> y = jnp.ones((1, 4))
|
52
|
-
...
|
53
|
-
>>> model = Model()
|
54
|
-
>>> tx = optax.adam(1e-3)
|
55
|
-
>>> optimizer = brainstate.optim.OptaxOptimizer(tx)
|
56
|
-
>>> optimizer.register_trainable_weights(model.states(brainstate.ParamState))
|
57
|
-
...
|
58
|
-
>>> loss_fn = lambda: ((model(x) - y) ** 2).mean()
|
59
|
-
>>> loss_fn()
|
60
|
-
Array(1.7055722, dtype=float32)
|
61
|
-
>>> grads = brainstate.augment.grad(loss_fn, model.states(brainstate.ParamState))()
|
62
|
-
>>> optimizer.update(grads)
|
63
|
-
>>> loss_fn()
|
64
|
-
Array(1.6925814, dtype=float32)
|
65
|
-
|
66
|
-
For more exotic usecases (e.g. multiple optimizers) it's probably best to
|
67
|
-
fork the class and modify it.
|
68
|
-
|
69
|
-
Attributes:
|
70
|
-
param_states: The parameter states to update.
|
71
|
-
tx: An Optax gradient transformation.
|
72
|
-
"""
|
73
|
-
|
74
|
-
param_states: StateDictManager
|
75
|
-
opt_state: Optional[ShortTermState]
|
76
|
-
|
77
|
-
def __init__(
|
78
|
-
self,
|
79
|
-
tx: 'optax.GradientTransformation',
|
80
|
-
):
|
81
|
-
"""
|
82
|
-
Instantiate the class and wrap the :class:`FlattedDict` and Optax gradient
|
83
|
-
transformation. Instantiate the optimizer state to keep track of
|
84
|
-
:class:`State`.
|
85
|
-
|
86
|
-
Args:
|
87
|
-
tx: An Optax gradient transformation.
|
88
|
-
"""
|
89
|
-
super().__init__()
|
90
|
-
|
91
|
-
# tx must be an instance of optax.GradientTransformation
|
92
|
-
import optax # type: ignore[import-not-found,import-untyped]
|
93
|
-
if not isinstance(tx, optax.GradientTransformation):
|
94
|
-
raise TypeError(f"tx must be an instance of optax.GradientTransformation, got {tx}")
|
95
|
-
self.tx = tx
|
96
|
-
|
97
|
-
# optimizer state
|
98
|
-
self.opt_state = None
|
99
|
-
|
100
|
-
def register_trainable_weights(self, param_states: Dict[Hashable, State]):
|
101
|
-
# model
|
102
|
-
if not isinstance(param_states, dict):
|
103
|
-
raise TypeError(f"states must be a dict, got {param_states}")
|
104
|
-
for k, v in param_states.items():
|
105
|
-
if not isinstance(v, State):
|
106
|
-
raise TypeError(f"states values must be ParamState, got {v}")
|
107
|
-
self.param_states.update(param_states)
|
108
|
-
self.param_states.unique_()
|
109
|
-
|
110
|
-
# wrt
|
111
|
-
self.opt_state = ShortTermState(self.tx.init({k: v.value for k, v in self.param_states.items()}))
|
112
|
-
return self
|
113
|
-
|
114
|
-
def update(self, grads: Dict[Hashable, PyTree]):
|
115
|
-
"""Update the model states with the gradients.
|
116
|
-
|
117
|
-
Args:
|
118
|
-
grads: the gradients derived from ``brainstate.augment.grad``.
|
119
|
-
"""
|
120
|
-
if self.opt_state is None:
|
121
|
-
raise ValueError("register_trainable_weights must be called before update.")
|
122
|
-
|
123
|
-
import optax # type: ignore[import-not-found,import-untyped]
|
124
|
-
grads = {k: grads[k] for k in self.param_states.keys()}
|
125
|
-
states = {k: v.value for k, v in self.param_states.items()}
|
126
|
-
|
127
|
-
# compute updates
|
128
|
-
updates, new_opt_state = self.tx.update(grads, self.opt_state.value, states)
|
129
|
-
new_params = optax.apply_updates(states, updates)
|
130
|
-
|
131
|
-
# update model states and optimizer states
|
132
|
-
for k, v in self.param_states.items():
|
133
|
-
v.value = new_params[k]
|
134
|
-
self.opt_state.value = new_opt_state
|
135
|
-
|
136
|
-
|
137
|
-
class LBFGS(OptaxOptimizer):
|
138
|
-
def __init__(
|
139
|
-
self,
|
140
|
-
lr: float,
|
141
|
-
memory_size: int = 10,
|
142
|
-
scale_init_precond: bool = True,
|
143
|
-
):
|
144
|
-
import optax # type: ignore[import-not-found,import-untyped]
|
145
|
-
super().__init__(
|
146
|
-
optax.lbfgs(
|
147
|
-
lr,
|
148
|
-
memory_size=memory_size,
|
149
|
-
scale_init_precond=scale_init_precond,
|
150
|
-
linesearch=None,
|
151
|
-
)
|
152
|
-
)
|
1
|
+
# Copyright 2024 BDP 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
|
+
|
17
|
+
import importlib.util
|
18
|
+
from typing import Hashable, Dict, Optional
|
19
|
+
|
20
|
+
from brainstate._state import ShortTermState, State, StateDictManager
|
21
|
+
from brainstate.typing import PyTree
|
22
|
+
from ._base import Optimizer
|
23
|
+
|
24
|
+
optax_installed = importlib.util.find_spec('optax') is not None
|
25
|
+
|
26
|
+
__all__ = [
|
27
|
+
'OptaxOptimizer',
|
28
|
+
'LBFGS',
|
29
|
+
]
|
30
|
+
|
31
|
+
|
32
|
+
class OptaxOptimizer(Optimizer):
|
33
|
+
"""Simple train state for the common case with a single Optax optimizer.
|
34
|
+
|
35
|
+
Example usage::
|
36
|
+
|
37
|
+
>>> import jax
|
38
|
+
>>> import jax.numpy as jnp
|
39
|
+
>>> import brainstate as brainstate
|
40
|
+
>>> import optax
|
41
|
+
...
|
42
|
+
>>> class Model(brainstate.nn.Module):
|
43
|
+
... def __init__(self):
|
44
|
+
... super().__init__()
|
45
|
+
... self.linear1 = brainstate.nn.Linear(2, 3)
|
46
|
+
... self.linear2 = brainstate.nn.Linear(3, 4)
|
47
|
+
... def __call__(self, x):
|
48
|
+
... return self.linear2(self.linear1(x))
|
49
|
+
...
|
50
|
+
>>> x = brainstate.random.randn(1, 2)
|
51
|
+
>>> y = jnp.ones((1, 4))
|
52
|
+
...
|
53
|
+
>>> model = Model()
|
54
|
+
>>> tx = optax.adam(1e-3)
|
55
|
+
>>> optimizer = brainstate.optim.OptaxOptimizer(tx)
|
56
|
+
>>> optimizer.register_trainable_weights(model.states(brainstate.ParamState))
|
57
|
+
...
|
58
|
+
>>> loss_fn = lambda: ((model(x) - y) ** 2).mean()
|
59
|
+
>>> loss_fn()
|
60
|
+
Array(1.7055722, dtype=float32)
|
61
|
+
>>> grads = brainstate.augment.grad(loss_fn, model.states(brainstate.ParamState))()
|
62
|
+
>>> optimizer.update(grads)
|
63
|
+
>>> loss_fn()
|
64
|
+
Array(1.6925814, dtype=float32)
|
65
|
+
|
66
|
+
For more exotic usecases (e.g. multiple optimizers) it's probably best to
|
67
|
+
fork the class and modify it.
|
68
|
+
|
69
|
+
Attributes:
|
70
|
+
param_states: The parameter states to update.
|
71
|
+
tx: An Optax gradient transformation.
|
72
|
+
"""
|
73
|
+
|
74
|
+
param_states: StateDictManager
|
75
|
+
opt_state: Optional[ShortTermState]
|
76
|
+
|
77
|
+
def __init__(
|
78
|
+
self,
|
79
|
+
tx: 'optax.GradientTransformation',
|
80
|
+
):
|
81
|
+
"""
|
82
|
+
Instantiate the class and wrap the :class:`FlattedDict` and Optax gradient
|
83
|
+
transformation. Instantiate the optimizer state to keep track of
|
84
|
+
:class:`State`.
|
85
|
+
|
86
|
+
Args:
|
87
|
+
tx: An Optax gradient transformation.
|
88
|
+
"""
|
89
|
+
super().__init__()
|
90
|
+
|
91
|
+
# tx must be an instance of optax.GradientTransformation
|
92
|
+
import optax # type: ignore[import-not-found,import-untyped]
|
93
|
+
if not isinstance(tx, optax.GradientTransformation):
|
94
|
+
raise TypeError(f"tx must be an instance of optax.GradientTransformation, got {tx}")
|
95
|
+
self.tx = tx
|
96
|
+
|
97
|
+
# optimizer state
|
98
|
+
self.opt_state = None
|
99
|
+
|
100
|
+
def register_trainable_weights(self, param_states: Dict[Hashable, State]):
|
101
|
+
# model
|
102
|
+
if not isinstance(param_states, dict):
|
103
|
+
raise TypeError(f"states must be a dict, got {param_states}")
|
104
|
+
for k, v in param_states.items():
|
105
|
+
if not isinstance(v, State):
|
106
|
+
raise TypeError(f"states values must be ParamState, got {v}")
|
107
|
+
self.param_states.update(param_states)
|
108
|
+
self.param_states.unique_()
|
109
|
+
|
110
|
+
# wrt
|
111
|
+
self.opt_state = ShortTermState(self.tx.init({k: v.value for k, v in self.param_states.items()}))
|
112
|
+
return self
|
113
|
+
|
114
|
+
def update(self, grads: Dict[Hashable, PyTree]):
|
115
|
+
"""Update the model states with the gradients.
|
116
|
+
|
117
|
+
Args:
|
118
|
+
grads: the gradients derived from ``brainstate.augment.grad``.
|
119
|
+
"""
|
120
|
+
if self.opt_state is None:
|
121
|
+
raise ValueError("register_trainable_weights must be called before update.")
|
122
|
+
|
123
|
+
import optax # type: ignore[import-not-found,import-untyped]
|
124
|
+
grads = {k: grads[k] for k in self.param_states.keys()}
|
125
|
+
states = {k: v.value for k, v in self.param_states.items()}
|
126
|
+
|
127
|
+
# compute updates
|
128
|
+
updates, new_opt_state = self.tx.update(grads, self.opt_state.value, states)
|
129
|
+
new_params = optax.apply_updates(states, updates)
|
130
|
+
|
131
|
+
# update model states and optimizer states
|
132
|
+
for k, v in self.param_states.items():
|
133
|
+
v.value = new_params[k]
|
134
|
+
self.opt_state.value = new_opt_state
|
135
|
+
|
136
|
+
|
137
|
+
class LBFGS(OptaxOptimizer):
|
138
|
+
def __init__(
|
139
|
+
self,
|
140
|
+
lr: float,
|
141
|
+
memory_size: int = 10,
|
142
|
+
scale_init_precond: bool = True,
|
143
|
+
):
|
144
|
+
import optax # type: ignore[import-not-found,import-untyped]
|
145
|
+
super().__init__(
|
146
|
+
optax.lbfgs(
|
147
|
+
lr,
|
148
|
+
memory_size=memory_size,
|
149
|
+
scale_init_precond=scale_init_precond,
|
150
|
+
linesearch=None,
|
151
|
+
)
|
152
|
+
)
|
@@ -1,53 +1,53 @@
|
|
1
|
-
# Copyright 2024 BDP 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
|
-
|
17
|
-
import unittest
|
18
|
-
|
19
|
-
import jax
|
20
|
-
import optax
|
21
|
-
|
22
|
-
import brainstate
|
23
|
-
|
24
|
-
|
25
|
-
class TestOptaxOptimizer(unittest.TestCase):
|
26
|
-
def test1(self):
|
27
|
-
class Model(brainstate.nn.Module):
|
28
|
-
def __init__(self):
|
29
|
-
super().__init__()
|
30
|
-
self.linear1 = brainstate.nn.Linear(2, 3)
|
31
|
-
self.linear2 = brainstate.nn.Linear(3, 4)
|
32
|
-
|
33
|
-
def __call__(self, x):
|
34
|
-
return self.linear2(self.linear1(x))
|
35
|
-
|
36
|
-
x = brainstate.random.randn(1, 2)
|
37
|
-
y = jax.numpy.ones((1, 4))
|
38
|
-
|
39
|
-
model = Model()
|
40
|
-
tx = optax.adam(1e-3)
|
41
|
-
optimizer = brainstate.optim.OptaxOptimizer(tx)
|
42
|
-
optimizer.register_trainable_weights(model.states(brainstate.ParamState))
|
43
|
-
|
44
|
-
loss_fn = lambda: ((model(x) - y) ** 2).mean()
|
45
|
-
prev_loss = loss_fn()
|
46
|
-
|
47
|
-
grads = brainstate.augment.grad(loss_fn, model.states(brainstate.ParamState))()
|
48
|
-
optimizer.update(grads)
|
49
|
-
|
50
|
-
new_loss = loss_fn()
|
51
|
-
|
52
|
-
print(new_loss, prev_loss)
|
53
|
-
self.assertLess(new_loss, prev_loss)
|
1
|
+
# Copyright 2024 BDP 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
|
+
|
17
|
+
import unittest
|
18
|
+
|
19
|
+
import jax
|
20
|
+
import optax
|
21
|
+
|
22
|
+
import brainstate
|
23
|
+
|
24
|
+
|
25
|
+
class TestOptaxOptimizer(unittest.TestCase):
|
26
|
+
def test1(self):
|
27
|
+
class Model(brainstate.nn.Module):
|
28
|
+
def __init__(self):
|
29
|
+
super().__init__()
|
30
|
+
self.linear1 = brainstate.nn.Linear(2, 3)
|
31
|
+
self.linear2 = brainstate.nn.Linear(3, 4)
|
32
|
+
|
33
|
+
def __call__(self, x):
|
34
|
+
return self.linear2(self.linear1(x))
|
35
|
+
|
36
|
+
x = brainstate.random.randn(1, 2)
|
37
|
+
y = jax.numpy.ones((1, 4))
|
38
|
+
|
39
|
+
model = Model()
|
40
|
+
tx = optax.adam(1e-3)
|
41
|
+
optimizer = brainstate.optim.OptaxOptimizer(tx)
|
42
|
+
optimizer.register_trainable_weights(model.states(brainstate.ParamState))
|
43
|
+
|
44
|
+
loss_fn = lambda: ((model(x) - y) ** 2).mean()
|
45
|
+
prev_loss = loss_fn()
|
46
|
+
|
47
|
+
grads = brainstate.augment.grad(loss_fn, model.states(brainstate.ParamState))()
|
48
|
+
optimizer.update(grads)
|
49
|
+
|
50
|
+
new_loss = loss_fn()
|
51
|
+
|
52
|
+
print(new_loss, prev_loss)
|
53
|
+
self.assertLess(new_loss, prev_loss)
|