brainstate 0.0.2.post20240913__py2.py3-none-any.whl → 0.0.2.post20241010__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 (50) hide show
  1. brainstate/__init__.py +4 -2
  2. brainstate/_module.py +102 -67
  3. brainstate/_state.py +2 -2
  4. brainstate/_visualization.py +47 -0
  5. brainstate/environ.py +116 -9
  6. brainstate/environ_test.py +56 -0
  7. brainstate/functional/_activations.py +134 -56
  8. brainstate/functional/_activations_test.py +331 -0
  9. brainstate/functional/_normalization.py +21 -10
  10. brainstate/init/_generic.py +4 -2
  11. brainstate/mixin.py +1 -1
  12. brainstate/nn/__init__.py +7 -2
  13. brainstate/nn/_base.py +2 -2
  14. brainstate/nn/_connections.py +4 -4
  15. brainstate/nn/_dynamics.py +5 -5
  16. brainstate/nn/_elementwise.py +9 -9
  17. brainstate/nn/_embedding.py +3 -3
  18. brainstate/nn/_normalizations.py +3 -3
  19. brainstate/nn/_others.py +2 -2
  20. brainstate/nn/_poolings.py +6 -6
  21. brainstate/nn/_rate_rnns.py +1 -1
  22. brainstate/nn/_readout.py +1 -1
  23. brainstate/nn/_synouts.py +1 -1
  24. brainstate/nn/event/__init__.py +25 -0
  25. brainstate/nn/event/_misc.py +34 -0
  26. brainstate/nn/event/csr.py +312 -0
  27. brainstate/nn/event/csr_test.py +118 -0
  28. brainstate/nn/event/fixed_probability.py +276 -0
  29. brainstate/nn/event/fixed_probability_test.py +127 -0
  30. brainstate/nn/event/linear.py +220 -0
  31. brainstate/nn/event/linear_test.py +111 -0
  32. brainstate/nn/metrics.py +390 -0
  33. brainstate/optim/__init__.py +5 -1
  34. brainstate/optim/_optax_optimizer.py +208 -0
  35. brainstate/optim/_optax_optimizer_test.py +14 -0
  36. brainstate/random/__init__.py +24 -0
  37. brainstate/{random.py → random/_rand_funs.py} +7 -1596
  38. brainstate/random/_rand_seed.py +169 -0
  39. brainstate/random/_rand_state.py +1498 -0
  40. brainstate/{_random_for_unit.py → random/_random_for_unit.py} +1 -1
  41. brainstate/{random_test.py → random/random_test.py} +208 -191
  42. brainstate/transform/_jit.py +1 -1
  43. brainstate/transform/_jit_test.py +19 -0
  44. brainstate/transform/_make_jaxpr.py +1 -1
  45. {brainstate-0.0.2.post20240913.dist-info → brainstate-0.0.2.post20241010.dist-info}/METADATA +1 -1
  46. brainstate-0.0.2.post20241010.dist-info/RECORD +87 -0
  47. brainstate-0.0.2.post20240913.dist-info/RECORD +0 -70
  48. {brainstate-0.0.2.post20240913.dist-info → brainstate-0.0.2.post20241010.dist-info}/LICENSE +0 -0
  49. {brainstate-0.0.2.post20240913.dist-info → brainstate-0.0.2.post20241010.dist-info}/WHEEL +0 -0
  50. {brainstate-0.0.2.post20240913.dist-info → brainstate-0.0.2.post20241010.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,208 @@
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
+ from __future__ import annotations
18
+
19
+ import importlib.util
20
+ from typing import Any
21
+
22
+ import jax.numpy as jnp
23
+
24
+ from brainstate._module import Module
25
+ from brainstate._state import ShortTermState, ParamState
26
+
27
+ __all__ = [
28
+ 'OptaxOptimizer',
29
+ ]
30
+
31
+ optax_installed = importlib.util.find_spec('optax') is not None
32
+
33
+
34
+ class OptaxState(ShortTermState):
35
+ """Wrapper class for Optimizer Variables."""
36
+ pass
37
+
38
+
39
+ class OptaxOptimizer(Module):
40
+ """Simple train state for the common case with a single Optax optimizer.
41
+
42
+ Example usage::
43
+
44
+ >>> import jax, jax.numpy as jnp
45
+ >>> import brainstate as bst
46
+ >>> from brainstate import nn
47
+ >>> import optax
48
+ ...
49
+ >>> class Model(bst.Module):
50
+ ... def __init__(self):
51
+ ... super().__init__()
52
+ ... self.linear1 = nn.Linear(2, 3)
53
+ ... self.linear2 = nn.Linear(3, 4)
54
+ ... def __call__(self, x):
55
+ ... return self.linear2(self.linear1(x))
56
+ ...
57
+ >>> x = jax.random.normal(jax.random.key(0), (1, 2))
58
+ >>> y = jnp.ones((1, 4))
59
+ ...
60
+ >>> model = Model()
61
+ >>> tx = optax.adam(1e-3)
62
+ >>> state = bst.optim.OptaxOptimizer(model, tx)
63
+ ...
64
+ >>> loss_fn = lambda model: ((model(x) - y) ** 2).mean()
65
+ >>> loss_fn(model)
66
+ Array(1.7055722, dtype=float32)
67
+ >>> grads = bst.transform.grad(loss_fn)(state.model)
68
+ >>> state.update(grads)
69
+ >>> loss_fn(model)
70
+ Array(1.6925814, dtype=float32)
71
+
72
+ Note that you can easily extend this class by subclassing it for storing
73
+ additional data (e.g. adding metrics).
74
+
75
+ Example usage::
76
+
77
+ >>> class TrainState(nnx.Optimizer):
78
+ ... def __init__(self, model, tx, metrics):
79
+ ... self.metrics = metrics
80
+ ... super().__init__(model, tx)
81
+ ... def update(self, *, grads, **updates):
82
+ ... self.metrics.update(**updates)
83
+ ... super().update(grads)
84
+ ...
85
+ >>> metrics = nnx.metrics.Average()
86
+ >>> state = TrainState(model, tx, metrics)
87
+ ...
88
+ >>> grads = nnx.grad(loss_fn)(state.model)
89
+ >>> state.update(grads=grads, values=loss_fn(state.model))
90
+ >>> state.metrics.compute()
91
+ Array(1.6925814, dtype=float32)
92
+ >>> state.update(grads=grads, values=loss_fn(state.model))
93
+ >>> state.metrics.compute()
94
+ Array(1.68612, dtype=float32)
95
+
96
+ For more exotic usecases (e.g. multiple optimizers) it's probably best to
97
+ fork the class and modify it.
98
+
99
+ Attributes:
100
+ step: An ``OptaxState`` :class:`Variable` that tracks the step count.
101
+ model: The wrapped :class:`Module`.
102
+ tx: An Optax gradient transformation.
103
+ opt_state: The Optax optimizer state.
104
+ """
105
+
106
+ def __init__(
107
+ self,
108
+ model: Module,
109
+ tx: 'optax.GradientTransformation',
110
+ wrt: Any = ParamState,
111
+ ):
112
+ """
113
+ Instantiate the class and wrap the :class:`Module` and Optax gradient
114
+ transformation. Instantiate the optimizer state to keep track of
115
+ :class:`Variable` types specified in ``wrt``. Set the step count to 0.
116
+
117
+ Args:
118
+ model: An NNX Module.
119
+ tx: An Optax gradient transformation.
120
+ wrt: optional argument to filter for which :class:`Variable`'s to keep
121
+ track of in the optimizer state. These should be the :class:`Variable`'s
122
+ that you plan on updating; i.e. this argument value should match the
123
+ ``wrt`` argument passed to the ``nnx.grad`` call that will generate the
124
+ gradients that will be passed into the ``grads`` argument of the
125
+ :func:`update` method.
126
+ """
127
+
128
+ # tx must be an instance of optax.GradientTransformation
129
+ import optax # type: ignore[import-not-found,import-untyped]
130
+ if not isinstance(tx, optax.GradientTransformation):
131
+ raise TypeError(f"tx must be an instance of optax.GradientTransformation, got {tx}")
132
+ self.tx = tx
133
+
134
+ # model
135
+ if not callable(model):
136
+ raise TypeError(f"model must be a callable, got {model}")
137
+ self.model = model
138
+
139
+ # wrt
140
+ self.opt_state = tx.init(nnx.state(model, wrt))
141
+ self.wrt = wrt
142
+
143
+ def update(self, grads):
144
+ """Updates ``step``, ``params``, ``opt_state`` and ``**kwargs`` in return value.
145
+ The ``grads`` must be derived from ``nnx.grad(..., wrt=self.wrt)``, where the
146
+ gradients are with respect to the same :class:`Variable` types as defined in
147
+ ``self.wrt`` during instantiation of this ``Optimizer``. For example::
148
+
149
+ >>> from flax import nnx
150
+ >>> import jax, jax.numpy as jnp
151
+ >>> import optax
152
+
153
+ >>> class CustomVariable(nnx.Variable):
154
+ ... pass
155
+
156
+ >>> class Model(nnx.Module):
157
+ ... def __init__(self, rngs):
158
+ ... self.linear = nnx.Linear(2, 3, rngs=rngs)
159
+ ... self.custom_variable = CustomVariable(jnp.ones((1, 3)))
160
+ ... def __call__(self, x):
161
+ ... return self.linear(x) + self.custom_variable
162
+ >>> model = Model(rngs=nnx.Rngs(0))
163
+ >>> jax.tree.map(jnp.shape, nnx.state(model))
164
+ State({
165
+ 'custom_variable': VariableState(
166
+ type=CustomVariable,
167
+ value=(1, 3)
168
+ ),
169
+ 'linear': {
170
+ 'bias': VariableState(
171
+ type=Param,
172
+ value=(3,)
173
+ ),
174
+ 'kernel': VariableState(
175
+ type=Param,
176
+ value=(2, 3)
177
+ )
178
+ }
179
+ })
180
+
181
+ >>> # update:
182
+ >>> # - only Linear layer parameters
183
+ >>> # - only CustomVariable parameters
184
+ >>> # - both Linear layer and CustomVariable parameters
185
+ >>> loss_fn = lambda model, x, y: ((model(x) - y) ** 2).mean()
186
+ >>> for variable in (nnx.Param, CustomVariable, (nnx.Param, CustomVariable)):
187
+ ... # make sure `wrt` arguments match for `nnx.Optimizer` and `nnx.grad`
188
+ ... state = nnx.Optimizer(model, optax.adam(1e-3), wrt=variable)
189
+ ... grads = nnx.grad(loss_fn, argnums=nnx.DiffState(0, variable))(
190
+ ... state.model, jnp.ones((1, 2)), jnp.ones((1, 3))
191
+ ... )
192
+ ... state.update(grads=grads)
193
+
194
+ Note that internally this function calls ``.tx.update()`` followed by a call
195
+ to ``optax.apply_updates()`` to update ``params`` and ``opt_state``.
196
+
197
+ Args:
198
+ grads: the gradients derived from ``nnx.grad``.
199
+ """
200
+ import optax # type: ignore[import-not-found,import-untyped]
201
+ state = nnx.state(self.model, self.wrt)
202
+
203
+ updates, new_opt_state = self.tx.update(grads, self.opt_state, state)
204
+ new_params = optax.apply_updates(state, updates)
205
+ assert isinstance(new_params, nnx.State)
206
+
207
+ nnx.update(self.model, new_params)
208
+ self.opt_state = new_opt_state
@@ -0,0 +1,14 @@
1
+ # Copyright 2024 The Flax Authors.
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
+
@@ -0,0 +1,24 @@
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 ._rand_funs import *
17
+ from ._rand_funs import __all__ as __all_random__
18
+ from ._rand_seed import *
19
+ from ._rand_seed import __all__ as __all_seed__
20
+ from ._rand_state import *
21
+ from ._rand_state import __all__ as __all_state__
22
+
23
+ __all__ = __all_random__ + __all_state__ + __all_seed__
24
+ del __all_random__, __all_state__, __all_seed__