brainstate 0.0.2.post20241010__py2.py3-none-any.whl → 0.1.0__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 +31 -11
- brainstate/_state.py +760 -316
- brainstate/_state_test.py +41 -12
- brainstate/_utils.py +31 -4
- brainstate/augment/__init__.py +40 -0
- brainstate/augment/_autograd.py +608 -0
- brainstate/augment/_autograd_test.py +1193 -0
- brainstate/augment/_eval_shape.py +102 -0
- brainstate/augment/_eval_shape_test.py +40 -0
- brainstate/augment/_mapping.py +525 -0
- brainstate/augment/_mapping_test.py +210 -0
- brainstate/augment/_random.py +99 -0
- brainstate/{transform → compile}/__init__.py +25 -13
- brainstate/compile/_ad_checkpoint.py +204 -0
- brainstate/compile/_ad_checkpoint_test.py +51 -0
- brainstate/compile/_conditions.py +259 -0
- brainstate/compile/_conditions_test.py +221 -0
- brainstate/compile/_error_if.py +94 -0
- brainstate/compile/_error_if_test.py +54 -0
- brainstate/compile/_jit.py +314 -0
- brainstate/compile/_jit_test.py +143 -0
- brainstate/compile/_loop_collect_return.py +516 -0
- brainstate/compile/_loop_collect_return_test.py +59 -0
- brainstate/compile/_loop_no_collection.py +185 -0
- brainstate/compile/_loop_no_collection_test.py +51 -0
- brainstate/compile/_make_jaxpr.py +756 -0
- brainstate/compile/_make_jaxpr_test.py +134 -0
- brainstate/compile/_progress_bar.py +111 -0
- brainstate/compile/_unvmap.py +159 -0
- brainstate/compile/_util.py +147 -0
- brainstate/environ.py +408 -381
- brainstate/environ_test.py +34 -32
- brainstate/{nn/event → event}/__init__.py +6 -6
- brainstate/event/_csr.py +308 -0
- brainstate/event/_csr_test.py +118 -0
- brainstate/event/_fixed_probability.py +271 -0
- brainstate/event/_fixed_probability_test.py +128 -0
- brainstate/event/_linear.py +219 -0
- brainstate/event/_linear_test.py +112 -0
- brainstate/{nn/event → event}/_misc.py +7 -7
- brainstate/functional/_activations.py +521 -511
- brainstate/functional/_activations_test.py +300 -300
- brainstate/functional/_normalization.py +43 -43
- brainstate/functional/_others.py +15 -15
- brainstate/functional/_spikes.py +49 -49
- brainstate/graph/__init__.py +33 -0
- brainstate/graph/_graph_context.py +443 -0
- brainstate/graph/_graph_context_test.py +65 -0
- brainstate/graph/_graph_convert.py +246 -0
- brainstate/graph/_graph_node.py +300 -0
- brainstate/graph/_graph_node_test.py +75 -0
- brainstate/graph/_graph_operation.py +1746 -0
- brainstate/graph/_graph_operation_test.py +724 -0
- brainstate/init/_base.py +28 -10
- brainstate/init/_generic.py +175 -172
- brainstate/init/_random_inits.py +470 -415
- brainstate/init/_random_inits_test.py +150 -0
- brainstate/init/_regular_inits.py +66 -69
- brainstate/init/_regular_inits_test.py +51 -0
- brainstate/mixin.py +236 -244
- brainstate/mixin_test.py +44 -46
- brainstate/nn/__init__.py +26 -51
- brainstate/nn/_collective_ops.py +199 -0
- brainstate/nn/_dyn_impl/__init__.py +46 -0
- brainstate/nn/_dyn_impl/_dynamics_neuron.py +290 -0
- brainstate/nn/_dyn_impl/_dynamics_neuron_test.py +162 -0
- brainstate/nn/_dyn_impl/_dynamics_synapse.py +320 -0
- brainstate/nn/_dyn_impl/_dynamics_synapse_test.py +132 -0
- brainstate/nn/_dyn_impl/_inputs.py +154 -0
- brainstate/nn/{_projection/__init__.py → _dyn_impl/_projection_alignpost.py} +6 -13
- brainstate/nn/_dyn_impl/_rate_rnns.py +400 -0
- brainstate/nn/_dyn_impl/_rate_rnns_test.py +64 -0
- brainstate/nn/_dyn_impl/_readout.py +128 -0
- brainstate/nn/_dyn_impl/_readout_test.py +54 -0
- brainstate/nn/_dynamics/__init__.py +37 -0
- brainstate/nn/_dynamics/_dynamics_base.py +631 -0
- brainstate/nn/_dynamics/_dynamics_base_test.py +79 -0
- brainstate/nn/_dynamics/_projection_base.py +346 -0
- brainstate/nn/_dynamics/_state_delay.py +453 -0
- brainstate/nn/_dynamics/_synouts.py +161 -0
- brainstate/nn/_dynamics/_synouts_test.py +58 -0
- brainstate/nn/_elementwise/__init__.py +22 -0
- brainstate/nn/_elementwise/_dropout.py +418 -0
- brainstate/nn/_elementwise/_dropout_test.py +100 -0
- brainstate/nn/_elementwise/_elementwise.py +1122 -0
- brainstate/nn/_elementwise/_elementwise_test.py +171 -0
- brainstate/nn/_exp_euler.py +97 -0
- brainstate/nn/_exp_euler_test.py +36 -0
- brainstate/nn/_interaction/__init__.py +32 -0
- brainstate/nn/_interaction/_connections.py +726 -0
- brainstate/nn/_interaction/_connections_test.py +254 -0
- brainstate/nn/_interaction/_embedding.py +59 -0
- brainstate/nn/_interaction/_normalizations.py +388 -0
- brainstate/nn/_interaction/_normalizations_test.py +75 -0
- brainstate/nn/_interaction/_poolings.py +1179 -0
- brainstate/nn/_interaction/_poolings_test.py +219 -0
- brainstate/nn/_module.py +328 -0
- brainstate/nn/_module_test.py +211 -0
- brainstate/nn/metrics.py +309 -309
- brainstate/optim/__init__.py +14 -2
- brainstate/optim/_base.py +66 -0
- brainstate/optim/_lr_scheduler.py +363 -400
- brainstate/optim/_lr_scheduler_test.py +25 -24
- brainstate/optim/_optax_optimizer.py +103 -176
- brainstate/optim/_optax_optimizer_test.py +41 -1
- brainstate/optim/_sgd_optimizer.py +950 -1025
- brainstate/random/_rand_funs.py +3269 -3268
- brainstate/random/_rand_funs_test.py +568 -0
- brainstate/random/_rand_seed.py +149 -117
- brainstate/random/_rand_seed_test.py +50 -0
- brainstate/random/_rand_state.py +1356 -1321
- brainstate/random/_random_for_unit.py +13 -13
- brainstate/surrogate.py +1262 -1243
- brainstate/{nn/_projection/_utils.py → transform.py} +1 -2
- brainstate/typing.py +157 -130
- brainstate/util/__init__.py +52 -0
- brainstate/util/_caller.py +100 -0
- brainstate/util/_dict.py +734 -0
- brainstate/util/_dict_test.py +160 -0
- brainstate/util/_error.py +28 -0
- brainstate/util/_filter.py +178 -0
- brainstate/util/_others.py +497 -0
- brainstate/util/_pretty_repr.py +208 -0
- brainstate/util/_scaling.py +260 -0
- brainstate/util/_struct.py +524 -0
- brainstate/util/_tracers.py +75 -0
- brainstate/{_visualization.py → util/_visualization.py} +16 -16
- {brainstate-0.0.2.post20241010.dist-info → brainstate-0.1.0.dist-info}/METADATA +11 -11
- brainstate-0.1.0.dist-info/RECORD +135 -0
- brainstate/_module.py +0 -1637
- brainstate/_module_test.py +0 -207
- brainstate/nn/_base.py +0 -251
- brainstate/nn/_connections.py +0 -686
- brainstate/nn/_dynamics.py +0 -426
- brainstate/nn/_elementwise.py +0 -1438
- brainstate/nn/_embedding.py +0 -66
- brainstate/nn/_misc.py +0 -133
- brainstate/nn/_normalizations.py +0 -389
- brainstate/nn/_others.py +0 -101
- brainstate/nn/_poolings.py +0 -1229
- brainstate/nn/_poolings_test.py +0 -231
- brainstate/nn/_projection/_align_post.py +0 -546
- brainstate/nn/_projection/_align_pre.py +0 -599
- brainstate/nn/_projection/_delta.py +0 -241
- brainstate/nn/_projection/_vanilla.py +0 -101
- brainstate/nn/_rate_rnns.py +0 -410
- brainstate/nn/_readout.py +0 -136
- brainstate/nn/_synouts.py +0 -166
- brainstate/nn/event/csr.py +0 -312
- brainstate/nn/event/csr_test.py +0 -118
- brainstate/nn/event/fixed_probability.py +0 -276
- brainstate/nn/event/fixed_probability_test.py +0 -127
- brainstate/nn/event/linear.py +0 -220
- brainstate/nn/event/linear_test.py +0 -111
- brainstate/random/random_test.py +0 -593
- brainstate/transform/_autograd.py +0 -585
- brainstate/transform/_autograd_test.py +0 -1181
- brainstate/transform/_conditions.py +0 -334
- brainstate/transform/_conditions_test.py +0 -220
- brainstate/transform/_error_if.py +0 -94
- brainstate/transform/_error_if_test.py +0 -55
- brainstate/transform/_jit.py +0 -265
- brainstate/transform/_jit_test.py +0 -118
- brainstate/transform/_loop_collect_return.py +0 -502
- brainstate/transform/_loop_no_collection.py +0 -170
- brainstate/transform/_make_jaxpr.py +0 -739
- brainstate/transform/_make_jaxpr_test.py +0 -131
- brainstate/transform/_mapping.py +0 -109
- brainstate/transform/_progress_bar.py +0 -111
- brainstate/transform/_unvmap.py +0 -143
- brainstate/util.py +0 -746
- brainstate-0.0.2.post20241010.dist-info/RECORD +0 -87
- {brainstate-0.0.2.post20241010.dist-info → brainstate-0.1.0.dist-info}/LICENSE +0 -0
- {brainstate-0.0.2.post20241010.dist-info → brainstate-0.1.0.dist-info}/WHEEL +0 -0
- {brainstate-0.0.2.post20241010.dist-info → brainstate-0.1.0.dist-info}/top_level.txt +0 -0
brainstate/util/_dict.py
ADDED
@@ -0,0 +1,734 @@
|
|
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
|
+
from __future__ import annotations
|
16
|
+
|
17
|
+
from collections import abc
|
18
|
+
from typing import TypeVar, Hashable, Union, Iterable, Any, Optional, Tuple, Dict
|
19
|
+
|
20
|
+
import jax
|
21
|
+
|
22
|
+
from brainstate.typing import Filter, PathParts
|
23
|
+
from ._filter import to_predicate
|
24
|
+
from ._pretty_repr import PrettyRepr, PrettyType, PrettyAttr, pretty_repr_avoid_duplicate, get_repr
|
25
|
+
from ._struct import dataclass
|
26
|
+
|
27
|
+
__all__ = [
|
28
|
+
'NestedDict', 'FlattedDict', 'flat_mapping', 'nest_mapping',
|
29
|
+
]
|
30
|
+
|
31
|
+
A = TypeVar('A')
|
32
|
+
K = TypeVar('K', bound=Hashable)
|
33
|
+
V = TypeVar('V')
|
34
|
+
|
35
|
+
FlattedStateMapping = dict[PathParts, V]
|
36
|
+
ExtractValueFn = abc.Callable[[Any], Any]
|
37
|
+
SetValueFn = abc.Callable[[V, Any], V]
|
38
|
+
|
39
|
+
|
40
|
+
# the empty node is a struct.dataclass to be compatible with JAX.
|
41
|
+
@dataclass
|
42
|
+
class _EmptyNode:
|
43
|
+
pass
|
44
|
+
|
45
|
+
|
46
|
+
_default_leaf = lambda *args: False
|
47
|
+
empty_node = _EmptyNode()
|
48
|
+
IsLeafCallable = abc.Callable[[Tuple[Any, ...], abc.Mapping[Any, Any]], bool]
|
49
|
+
|
50
|
+
|
51
|
+
def flat_mapping(
|
52
|
+
xs: abc.Mapping[Any, Any],
|
53
|
+
/,
|
54
|
+
*,
|
55
|
+
keep_empty_nodes: bool = False,
|
56
|
+
is_leaf: Optional[IsLeafCallable] = _default_leaf,
|
57
|
+
sep: Optional[str] = None
|
58
|
+
) -> 'FlattedDict':
|
59
|
+
"""Flatten a nested mapping.
|
60
|
+
|
61
|
+
The nested keys are flattened to a tuple. See ``unflatten_mapping`` on how to
|
62
|
+
restore the nested mapping.
|
63
|
+
|
64
|
+
Example::
|
65
|
+
|
66
|
+
>>> xs = {'foo': 1, 'bar': {'a': 2, 'b': {}}}
|
67
|
+
>>> flat_xs = flat_mapping(xs)
|
68
|
+
>>> flat_xs
|
69
|
+
{('foo',): 1, ('bar', 'a'): 2}
|
70
|
+
|
71
|
+
Note that empty mappings are ignored and will not be restored by
|
72
|
+
``unflatten_mapping``.
|
73
|
+
|
74
|
+
Args:
|
75
|
+
xs: A nested mapping.
|
76
|
+
keep_empty_nodes: replaces empty mappings with ``empty_node``.
|
77
|
+
is_leaf: An optional function that takes the next nested mapping and nested
|
78
|
+
keys and returns True if the nested mapping is a leaf (i.e., should not be
|
79
|
+
flattened further).
|
80
|
+
sep: If specified, then the keys of the returned mapping will be
|
81
|
+
``sep``-joined strings (if ``None``, then keys will be tuples).
|
82
|
+
|
83
|
+
Returns:
|
84
|
+
The flattened mapping.
|
85
|
+
"""
|
86
|
+
assert isinstance(xs, abc.Mapping), f'expected Mapping; got {type(xs).__qualname__}'
|
87
|
+
|
88
|
+
if sep is None:
|
89
|
+
def _key(path: Tuple[Any, ...]) -> Tuple[Any, ...] | str:
|
90
|
+
return path
|
91
|
+
else:
|
92
|
+
|
93
|
+
def _key(path: Tuple[Any, ...]) -> Tuple[Any, ...] | str:
|
94
|
+
return sep.join(path)
|
95
|
+
|
96
|
+
def _flatten(xs: Any, prefix: Tuple[Any, ...]) -> Dict[Any, Any]:
|
97
|
+
if not isinstance(xs, abc.Mapping) or is_leaf(prefix, xs):
|
98
|
+
return {_key(prefix): xs}
|
99
|
+
|
100
|
+
result = {}
|
101
|
+
is_empty = True
|
102
|
+
for key, value in xs.items():
|
103
|
+
is_empty = False
|
104
|
+
result.update(_flatten(value, prefix + (key,)))
|
105
|
+
if keep_empty_nodes and is_empty:
|
106
|
+
if prefix == (): # when the whole input is empty
|
107
|
+
return {}
|
108
|
+
return {_key(prefix): empty_node}
|
109
|
+
return result
|
110
|
+
|
111
|
+
return FlattedDict(_flatten(xs, ()))
|
112
|
+
|
113
|
+
|
114
|
+
def nest_mapping(
|
115
|
+
xs: Any,
|
116
|
+
/,
|
117
|
+
*,
|
118
|
+
sep: str | None = None
|
119
|
+
) -> 'NestedDict':
|
120
|
+
"""Unflatten a mapping.
|
121
|
+
|
122
|
+
See ``flatten_mapping``
|
123
|
+
|
124
|
+
Example::
|
125
|
+
|
126
|
+
>>> flat_xs = {
|
127
|
+
... ('foo',): 1,
|
128
|
+
... ('bar', 'a'): 2,
|
129
|
+
... }
|
130
|
+
>>> xs = nest_mapping(flat_xs)
|
131
|
+
>>> xs
|
132
|
+
{'foo': 1, 'bar': {'a': 2}}
|
133
|
+
|
134
|
+
Args:
|
135
|
+
xs: a flattened mapping.
|
136
|
+
sep: separator (same as used with ``flatten_mapping()``).
|
137
|
+
|
138
|
+
Returns:
|
139
|
+
The nested mapping.
|
140
|
+
"""
|
141
|
+
assert isinstance(xs, abc.Mapping), f'expected Mapping; got {type(xs).__qualname__}'
|
142
|
+
result: Dict[Any, Any] = {}
|
143
|
+
for path, value in xs.items():
|
144
|
+
if sep is not None:
|
145
|
+
path = path.split(sep)
|
146
|
+
if value is empty_node:
|
147
|
+
value = {}
|
148
|
+
cursor = result
|
149
|
+
for key in path[:-1]:
|
150
|
+
if key not in cursor:
|
151
|
+
cursor[key] = {}
|
152
|
+
cursor = cursor[key]
|
153
|
+
cursor[path[-1]] = value
|
154
|
+
return NestedDict(result)
|
155
|
+
|
156
|
+
|
157
|
+
def _default_compare(x, values):
|
158
|
+
return id(x) in values
|
159
|
+
|
160
|
+
|
161
|
+
def _default_process(x):
|
162
|
+
return id(x)
|
163
|
+
|
164
|
+
|
165
|
+
class NestedStateRepr(PrettyRepr):
|
166
|
+
def __init__(self, state: PrettyDict):
|
167
|
+
self.state = state
|
168
|
+
|
169
|
+
def __pretty_repr__(self):
|
170
|
+
yield PrettyType('', value_sep=': ', start='{', end='}')
|
171
|
+
|
172
|
+
for r in self.state.__pretty_repr__():
|
173
|
+
if isinstance(r, PrettyType):
|
174
|
+
continue
|
175
|
+
yield r
|
176
|
+
|
177
|
+
def __treescope_repr__(self, path, subtree_renderer):
|
178
|
+
children = {}
|
179
|
+
for k, v in self.state.items():
|
180
|
+
if isinstance(v, PrettyDict):
|
181
|
+
v = NestedStateRepr(v)
|
182
|
+
children[k] = v
|
183
|
+
# Render as the dictionary itself at the same path.
|
184
|
+
return subtree_renderer(children, path=path)
|
185
|
+
|
186
|
+
|
187
|
+
class PrettyDict(dict, PrettyRepr):
|
188
|
+
__module__ = 'brainstate.util'
|
189
|
+
|
190
|
+
def __getattr__(self, key: K) -> NestedMapping | V: # type: ignore[misc]
|
191
|
+
return self[key]
|
192
|
+
|
193
|
+
def treefy_state(self):
|
194
|
+
"""
|
195
|
+
Convert the ``State`` objects to a reference tree of the state.
|
196
|
+
"""
|
197
|
+
from brainstate._state import State
|
198
|
+
leaves, treedef = jax.tree.flatten(self)
|
199
|
+
leaves = jax.tree.map(lambda x: x.to_state_ref() if isinstance(x, State) else x, leaves)
|
200
|
+
return treedef.unflatten(leaves)
|
201
|
+
|
202
|
+
def to_dict(self) -> Dict[K, Dict[K, Any] | V]:
|
203
|
+
"""
|
204
|
+
Convert the ``PrettyDict`` to a dictionary.
|
205
|
+
|
206
|
+
Returns:
|
207
|
+
The dictionary.
|
208
|
+
"""
|
209
|
+
return dict(self) # type: ignore
|
210
|
+
|
211
|
+
def __repr__(self) -> str:
|
212
|
+
# repr the individual object with the pretty representation
|
213
|
+
return get_repr(self)
|
214
|
+
|
215
|
+
def __pretty_repr__(self):
|
216
|
+
yield from pretty_repr_avoid_duplicate(self, _default_repr_object, _default_repr_attr)
|
217
|
+
|
218
|
+
def split(self, *filters) -> Union[PrettyDict[K, V], Tuple[PrettyDict[K, V], ...]]:
|
219
|
+
raise NotImplementedError
|
220
|
+
|
221
|
+
def filter(self, *filters) -> Union[PrettyDict[K, V], Tuple[PrettyDict[K, V], ...]]:
|
222
|
+
raise NotImplementedError
|
223
|
+
|
224
|
+
def merge(self, *states) -> PrettyDict[K, V]:
|
225
|
+
raise NotImplementedError
|
226
|
+
|
227
|
+
def subset(self, *filters) -> Union[PrettyDict[K, V], Tuple[PrettyDict[K, V], ...]]:
|
228
|
+
"""
|
229
|
+
Subset a ``PrettyDict`` into one or more ``PrettyDict``'s. The user must pass at least one
|
230
|
+
``Filter`` (i.e. :class:`State`), and the filters must be exhaustive (i.e. they must cover all
|
231
|
+
:class:`State` types in the ``PrettyDict``).
|
232
|
+
"""
|
233
|
+
return self.filter(*filters)
|
234
|
+
|
235
|
+
|
236
|
+
def _default_repr_object(node: PrettyDict):
|
237
|
+
yield PrettyType(type(node), value_sep=': ', start='({', end='})')
|
238
|
+
|
239
|
+
|
240
|
+
def _default_repr_attr(node: PrettyDict):
|
241
|
+
for k, v in node.items():
|
242
|
+
if isinstance(v, dict):
|
243
|
+
v = PrettyDict(v)
|
244
|
+
if isinstance(v, PrettyDict):
|
245
|
+
v = NestedStateRepr(v)
|
246
|
+
yield PrettyAttr(repr(k), v)
|
247
|
+
|
248
|
+
|
249
|
+
class NestedDict(PrettyDict):
|
250
|
+
"""
|
251
|
+
A pytree-like structure that contains a ``Mapping`` from strings or integers to leaves.
|
252
|
+
|
253
|
+
A valid leaf type is either :class:`State`, ``jax.Array``, ``numpy.ndarray`` or nested
|
254
|
+
``NestedDict`` and ``FlattedDict``.
|
255
|
+
"""
|
256
|
+
__module__ = 'brainstate.util'
|
257
|
+
|
258
|
+
def __or__(self, other: NestedDict[K, V]) -> NestedDict[K, V]:
|
259
|
+
if not other:
|
260
|
+
return self
|
261
|
+
assert isinstance(other, NestedDict), f'expected NestedDict; got {type(other).__qualname__}'
|
262
|
+
return NestedDict.merge(self, other)
|
263
|
+
|
264
|
+
def __sub__(self, other: NestedDict[K, V]) -> NestedDict[K, V]:
|
265
|
+
if not other:
|
266
|
+
return self
|
267
|
+
|
268
|
+
assert isinstance(other, NestedDict), f'expected NestedDict; got {type(other).__qualname__}'
|
269
|
+
self_flat = self.to_flat()
|
270
|
+
other_flat = other.to_flat()
|
271
|
+
diff = {k: v for k, v in self_flat.items() if k not in other_flat}
|
272
|
+
return NestedDict.from_flat(diff)
|
273
|
+
|
274
|
+
def to_flat(self) -> FlattedDict:
|
275
|
+
"""
|
276
|
+
Flatten the nested mapping into a flat mapping.
|
277
|
+
|
278
|
+
Returns:
|
279
|
+
The flattened mapping.
|
280
|
+
"""
|
281
|
+
return flat_mapping(self)
|
282
|
+
|
283
|
+
@classmethod
|
284
|
+
def from_flat(cls, flat_dict: abc.Mapping[PathParts, V] | Iterable[tuple[PathParts, V]]) -> NestedDict:
|
285
|
+
"""
|
286
|
+
Create a ``NestedDict`` from a flat mapping.
|
287
|
+
|
288
|
+
Args:
|
289
|
+
flat_dict: The flat mapping.
|
290
|
+
|
291
|
+
Returns:
|
292
|
+
The ``NestedDict``.
|
293
|
+
"""
|
294
|
+
nested_state = nest_mapping(dict(flat_dict))
|
295
|
+
return cls(nested_state)
|
296
|
+
|
297
|
+
def split( # type: ignore[misc]
|
298
|
+
self,
|
299
|
+
first: Filter,
|
300
|
+
/,
|
301
|
+
*filters: Filter
|
302
|
+
) -> Union[NestedDict[K, V], Tuple[NestedDict[K, V], ...]]:
|
303
|
+
"""
|
304
|
+
Split a ``NestedDict`` into one or more ``NestedDict``'s. The
|
305
|
+
user must pass at least one ``Filter`` (i.e. :class:`State`),
|
306
|
+
and the filters must be exhaustive (i.e. they must cover all
|
307
|
+
:class:`State` types in the ``NestedDict``).
|
308
|
+
|
309
|
+
Example usage::
|
310
|
+
|
311
|
+
>>> import brainstate as bst
|
312
|
+
|
313
|
+
>>> class Model(bst.nn.Module):
|
314
|
+
... def __init__(self):
|
315
|
+
... super().__init__()
|
316
|
+
... self.batchnorm = bst.nn.BatchNorm1d([10, 3])
|
317
|
+
... self.linear = bst.nn.Linear(2, 3)
|
318
|
+
... def __call__(self, x):
|
319
|
+
... return self.linear(self.batchnorm(x))
|
320
|
+
|
321
|
+
>>> model = Model()
|
322
|
+
>>> state_map = bst.graph.treefy_states(model)
|
323
|
+
>>> param, others = state_map.treefy_split(bst.ParamState, ...)
|
324
|
+
|
325
|
+
Arguments:
|
326
|
+
first: The first filter
|
327
|
+
*filters: The optional, additional filters to group the state into mutually exclusive substates.
|
328
|
+
|
329
|
+
Returns:
|
330
|
+
One or more ``States`` equal to the number of filters passed.
|
331
|
+
"""
|
332
|
+
filters = (first, *filters)
|
333
|
+
*states_, rest = _split_nested_mapping(self, *filters)
|
334
|
+
if rest:
|
335
|
+
raise ValueError(f'Non-exhaustive filters, got a non-empty remainder: {rest}.\n'
|
336
|
+
f'Use `...` to match all remaining elements.')
|
337
|
+
|
338
|
+
states: NestedDict | Tuple[NestedDict, ...]
|
339
|
+
if len(states_) == 1:
|
340
|
+
states = states_[0]
|
341
|
+
else:
|
342
|
+
states = tuple(states_)
|
343
|
+
return states # type: ignore[bad-return-type]
|
344
|
+
|
345
|
+
def filter(
|
346
|
+
self,
|
347
|
+
first: Filter,
|
348
|
+
/,
|
349
|
+
*filters: Filter,
|
350
|
+
) -> Union[NestedDict[K, V], Tuple[NestedDict[K, V], ...]]:
|
351
|
+
"""
|
352
|
+
Filter a ``NestedDict`` into one or more ``NestedDict``'s. The
|
353
|
+
user must pass at least one ``Filter`` (i.e. :class:`State`).
|
354
|
+
This method is similar to :meth:`split() <flax.nnx.NestedDict.state.split>`,
|
355
|
+
except the filters can be non-exhaustive.
|
356
|
+
|
357
|
+
Arguments:
|
358
|
+
first: The first filter
|
359
|
+
*filters: The optional, additional filters to group the state into mutually exclusive substates.
|
360
|
+
|
361
|
+
Returns:
|
362
|
+
One or more ``States`` equal to the number of filters passed.
|
363
|
+
"""
|
364
|
+
*states_, _rest = _split_nested_mapping(self, first, *filters)
|
365
|
+
assert len(states_) == len(filters) + 1, f'Expected {len(filters) + 1} states, got {len(states_)}'
|
366
|
+
if len(states_) == 1:
|
367
|
+
states = states_[0]
|
368
|
+
else:
|
369
|
+
states = tuple(states_)
|
370
|
+
return states # type: ignore[bad-return-type]
|
371
|
+
|
372
|
+
@staticmethod
|
373
|
+
def merge(
|
374
|
+
state: NestedDict[K, V] | FlattedDict[K, V],
|
375
|
+
/,
|
376
|
+
*states: NestedDict[K, V] | FlattedDict[K, V]
|
377
|
+
) -> NestedDict[K, V]:
|
378
|
+
"""
|
379
|
+
The inverse of :meth:`split()`.
|
380
|
+
|
381
|
+
``merge`` takes one or more ``PrettyDict``'s and creates a new ``PrettyDict``.
|
382
|
+
|
383
|
+
Args:
|
384
|
+
state: A ``PrettyDict`` object.
|
385
|
+
*states: Additional ``PrettyDict`` objects.
|
386
|
+
|
387
|
+
Returns:
|
388
|
+
The merged ``PrettyDict``.
|
389
|
+
"""
|
390
|
+
if not states:
|
391
|
+
return state
|
392
|
+
states = (state, *states)
|
393
|
+
new_state: FlattedDict = FlattedDict()
|
394
|
+
for state in states:
|
395
|
+
if isinstance(state, NestedDict):
|
396
|
+
new_state.update(state.to_flat()) # type: ignore[attribute-error] # pytype is wrong here
|
397
|
+
elif isinstance(state, FlattedDict):
|
398
|
+
new_state.update(state)
|
399
|
+
else:
|
400
|
+
raise TypeError(f'Expected Nested or Flatted Mapping, got {type(state)} instead.')
|
401
|
+
return NestedDict.from_flat(new_state)
|
402
|
+
|
403
|
+
def to_pure_dict(self) -> Dict[str, Any]:
|
404
|
+
flat_values = {k: x for k, x in self.to_flat().items()}
|
405
|
+
return nest_mapping(flat_values).to_dict()
|
406
|
+
|
407
|
+
def replace_by_pure_dict(
|
408
|
+
self,
|
409
|
+
pure_dict: Dict[str, Any],
|
410
|
+
replace_fn: Optional[SetValueFn] = None
|
411
|
+
):
|
412
|
+
if replace_fn is None:
|
413
|
+
replace_fn = lambda x, v: x.replace(v) if hasattr(x, 'replace') else v
|
414
|
+
current_flat = self.to_flat()
|
415
|
+
for kp, v in flat_mapping(pure_dict).items():
|
416
|
+
if kp not in current_flat:
|
417
|
+
raise ValueError(f'key in pure_dict not available in state: {kp}')
|
418
|
+
current_flat[kp] = replace_fn(current_flat[kp], v)
|
419
|
+
self.update(nest_mapping(current_flat))
|
420
|
+
|
421
|
+
|
422
|
+
class FlattedDict(PrettyDict):
|
423
|
+
"""
|
424
|
+
A pytree-like structure that contains a ``Mapping`` from strings or integers to leaves.
|
425
|
+
|
426
|
+
A valid leaf type is either :class:`State`, ``jax.Array``, ``numpy.ndarray`` or Python variables.
|
427
|
+
|
428
|
+
A ``NestedDict`` can be generated by either calling :func:`states()` or
|
429
|
+
:func:`nodes()` on the :class:`Module`.
|
430
|
+
|
431
|
+
Example usage::
|
432
|
+
|
433
|
+
>>> import brainstate as bst
|
434
|
+
>>> import jax.numpy as jnp
|
435
|
+
>>>
|
436
|
+
>>> class Model(bst.nn.Module):
|
437
|
+
... def __init__(self):
|
438
|
+
... super().__init__()
|
439
|
+
... self.batchnorm = bst.nn.BatchNorm1d([10, 3])
|
440
|
+
... self.linear = bst.nn.Linear(2, 3)
|
441
|
+
... def __call__(self, x):
|
442
|
+
... return self.linear(self.batchnorm(x))
|
443
|
+
>>>
|
444
|
+
>>> model = Model()
|
445
|
+
|
446
|
+
>>> # retrieve the states of the model
|
447
|
+
>>> model.states() # with the same to the function of ``brainstate.graph.states()``
|
448
|
+
FlattedDict({
|
449
|
+
('batchnorm', 'running_mean'): LongTermState(
|
450
|
+
value=Array([[0., 0., 0.]], dtype=float32)
|
451
|
+
),
|
452
|
+
('batchnorm', 'running_var'): LongTermState(
|
453
|
+
value=Array([[1., 1., 1.]], dtype=float32)
|
454
|
+
),
|
455
|
+
('batchnorm', 'weight'): ParamState(
|
456
|
+
value={'bias': Array([[0., 0., 0.]], dtype=float32), 'scale': Array([[1., 1., 1.]], dtype=float32)}
|
457
|
+
),
|
458
|
+
('linear', 'weight'): ParamState(
|
459
|
+
value={'weight': Array([[-0.21467684, 0.7621282 , -0.50756454, -0.49047297],
|
460
|
+
[-0.90413696, 0.6711 , -0.1254792 , 0.50412565],
|
461
|
+
[ 0.23975602, 0.47905368, 1.4851435 , 0.16745673]], dtype=float32), 'bias': Array([0., 0., 0., 0.], dtype=float32)}
|
462
|
+
)
|
463
|
+
})
|
464
|
+
|
465
|
+
>>> # retrieve the nodes of the model
|
466
|
+
>>> model.nodes() # with the same to the function of ``brainstate.graph.nodes()``
|
467
|
+
FlattedDict({
|
468
|
+
('batchnorm',): BatchNorm1d(
|
469
|
+
in_size=(10, 3),
|
470
|
+
out_size=(10, 3),
|
471
|
+
affine=True,
|
472
|
+
bias_initializer=Constant(value=0.0, dtype=<class 'numpy.float32'>),
|
473
|
+
scale_initializer=Constant(value=1.0, dtype=<class 'numpy.float32'>),
|
474
|
+
dtype=<class 'numpy.float32'>,
|
475
|
+
track_running_stats=True,
|
476
|
+
momentum=Array(shape=(), dtype=float32),
|
477
|
+
epsilon=Array(shape=(), dtype=float32),
|
478
|
+
feature_axis=(1,),
|
479
|
+
axis_name=None,
|
480
|
+
axis_index_groups=None,
|
481
|
+
running_mean=LongTermState(
|
482
|
+
value=Array(shape=(1, 3), dtype=float32)
|
483
|
+
),
|
484
|
+
running_var=LongTermState(
|
485
|
+
value=Array(shape=(1, 3), dtype=float32)
|
486
|
+
),
|
487
|
+
weight=ParamState(
|
488
|
+
value={'bias': Array(shape=(1, 3), dtype=float32), 'scale': Array(shape=(1, 3), dtype=float32)}
|
489
|
+
)
|
490
|
+
),
|
491
|
+
('linear',): Linear(
|
492
|
+
in_size=(10, 3),
|
493
|
+
out_size=(10, 4),
|
494
|
+
w_mask=None,
|
495
|
+
weight=ParamState(
|
496
|
+
value={'bias': Array(shape=(4,), dtype=float32), 'weight': Array(shape=(3, 4), dtype=float32)}
|
497
|
+
)
|
498
|
+
),
|
499
|
+
(): Model(
|
500
|
+
batchnorm=BatchNorm1d(...),
|
501
|
+
linear=Linear(...)
|
502
|
+
)
|
503
|
+
})
|
504
|
+
"""
|
505
|
+
__module__ = 'brainstate.util'
|
506
|
+
|
507
|
+
def __or__(self, other: FlattedDict[K, V]) -> FlattedDict[K, V]:
|
508
|
+
if not other:
|
509
|
+
return self
|
510
|
+
assert isinstance(other, FlattedDict), f'expected NestedDict; got {type(other).__qualname__}'
|
511
|
+
return FlattedDict.merge(self, other)
|
512
|
+
|
513
|
+
def __sub__(self, other: FlattedDict[K, V]) -> FlattedDict[K, V]:
|
514
|
+
if not other:
|
515
|
+
return self
|
516
|
+
assert isinstance(other, FlattedDict), f'expected NestedDict; got {type(other).__qualname__}'
|
517
|
+
diff = {k: v for k, v in self.items() if k not in other}
|
518
|
+
return FlattedDict(diff)
|
519
|
+
|
520
|
+
def to_nest(self) -> NestedDict:
|
521
|
+
"""
|
522
|
+
Unflatten the flat mapping into a nested mapping.
|
523
|
+
|
524
|
+
Returns:
|
525
|
+
The nested mapping.
|
526
|
+
"""
|
527
|
+
return nest_mapping(self)
|
528
|
+
|
529
|
+
@classmethod
|
530
|
+
def from_nest(
|
531
|
+
cls, nested_dict: abc.Mapping[PathParts, V] | Iterable[tuple[PathParts, V]],
|
532
|
+
) -> FlattedDict:
|
533
|
+
"""
|
534
|
+
Create a ``NestedDict`` from a flat mapping.
|
535
|
+
|
536
|
+
Args:
|
537
|
+
nested_dict: The flat mapping.
|
538
|
+
|
539
|
+
Returns:
|
540
|
+
The ``NestedDict``.
|
541
|
+
"""
|
542
|
+
return flat_mapping(nested_dict)
|
543
|
+
|
544
|
+
def split( # type: ignore[misc]
|
545
|
+
self,
|
546
|
+
first: Filter,
|
547
|
+
/,
|
548
|
+
*filters: Filter
|
549
|
+
) -> Union[FlattedDict[K, V], tuple[FlattedDict[K, V], ...]]:
|
550
|
+
"""
|
551
|
+
Split a ``FlattedDict`` into one or more ``FlattedDict``'s. The
|
552
|
+
user must pass at least one ``Filter`` (i.e. :class:`State`),
|
553
|
+
and the filters must be exhaustive (i.e. they must cover all
|
554
|
+
:class:`State` types in the ``NestedDict``).
|
555
|
+
|
556
|
+
Arguments:
|
557
|
+
first: The first filter
|
558
|
+
*filters: The optional, additional filters to group the state into mutually exclusive substates.
|
559
|
+
|
560
|
+
Returns:
|
561
|
+
One or more ``States`` equal to the number of filters passed.
|
562
|
+
"""
|
563
|
+
filters = (first, *filters)
|
564
|
+
*states_, rest = _split_flatted_mapping(self, *filters)
|
565
|
+
if rest:
|
566
|
+
raise ValueError(f'Non-exhaustive filters, got a non-empty remainder: {rest}.\n'
|
567
|
+
f'Use `...` to match all remaining elements.')
|
568
|
+
|
569
|
+
states: FlattedDict | Tuple[FlattedDict, ...]
|
570
|
+
if len(states_) == 1:
|
571
|
+
states = states_[0]
|
572
|
+
else:
|
573
|
+
states = tuple(states_)
|
574
|
+
return states # type: ignore[bad-return-type]
|
575
|
+
|
576
|
+
def filter(
|
577
|
+
self,
|
578
|
+
first: Filter,
|
579
|
+
/,
|
580
|
+
*filters: Filter,
|
581
|
+
) -> Union[FlattedDict[K, V], Tuple[FlattedDict[K, V], ...]]:
|
582
|
+
"""
|
583
|
+
Filter a ``FlattedDict`` into one or more ``FlattedDict``'s. The
|
584
|
+
user must pass at least one ``Filter`` (i.e. :class:`State`).
|
585
|
+
This method is similar to :meth:`split() <flax.nnx.NestedDict.state.split>`,
|
586
|
+
except the filters can be non-exhaustive.
|
587
|
+
|
588
|
+
Arguments:
|
589
|
+
first: The first filter
|
590
|
+
*filters: The optional, additional filters to group the state into mutually exclusive substates.
|
591
|
+
|
592
|
+
Returns:
|
593
|
+
One or more ``States`` equal to the number of filters passed.
|
594
|
+
"""
|
595
|
+
*states_, _rest = _split_flatted_mapping(self, first, *filters)
|
596
|
+
assert len(states_) == len(filters) + 1, f'Expected {len(filters) + 1} states, got {len(states_)}'
|
597
|
+
if len(states_) == 1:
|
598
|
+
states = states_[0]
|
599
|
+
else:
|
600
|
+
states = tuple(states_)
|
601
|
+
return states # type: ignore[bad-return-type]
|
602
|
+
|
603
|
+
@staticmethod
|
604
|
+
def merge(
|
605
|
+
state: FlattedDict[K, V] | NestedDict[K, V],
|
606
|
+
/,
|
607
|
+
*states: FlattedDict[K, V] | NestedDict[K, V]
|
608
|
+
) -> FlattedDict[K, V]:
|
609
|
+
"""
|
610
|
+
The inverse of :meth:`split()`.
|
611
|
+
|
612
|
+
``merge`` takes one or more ``FlattedDict``'s and creates a new ``FlattedDict``.
|
613
|
+
|
614
|
+
Args:
|
615
|
+
state: A ``PrettyDict`` object.
|
616
|
+
*states: Additional ``PrettyDict`` objects.
|
617
|
+
|
618
|
+
Returns:
|
619
|
+
The merged ``PrettyDict``.
|
620
|
+
"""
|
621
|
+
if not states:
|
622
|
+
return state
|
623
|
+
states = (state, *states)
|
624
|
+
new_state: FlattedStateMapping[V] = {}
|
625
|
+
for state in states:
|
626
|
+
if isinstance(state, NestedDict):
|
627
|
+
new_state.update(state.to_flat()) # type: ignore[attribute-error] # pytype is wrong here
|
628
|
+
elif isinstance(state, FlattedDict):
|
629
|
+
new_state.update(state)
|
630
|
+
else:
|
631
|
+
raise TypeError(f'Expected Nested or Flatted Mapping, got {type(state)} instead.')
|
632
|
+
return FlattedDict(new_state)
|
633
|
+
|
634
|
+
def to_dict_values(self):
|
635
|
+
from brainstate._state import State
|
636
|
+
return {k: v.value if isinstance(v, State) else v for k, v in self.items()}
|
637
|
+
|
638
|
+
|
639
|
+
def _split_nested_mapping(
|
640
|
+
mapping: NestedDict[K, V],
|
641
|
+
*filters: Filter,
|
642
|
+
) -> Tuple[NestedDict[K, V], ...]:
|
643
|
+
# check if the filters are exhaustive
|
644
|
+
for i, filter_ in enumerate(filters):
|
645
|
+
if filter_ in (..., True) and i != len(filters) - 1:
|
646
|
+
remaining_filters = filters[i + 1:]
|
647
|
+
if not all(f in (..., True) for f in remaining_filters):
|
648
|
+
raise ValueError('`...` or `True` can only be used as the last filters, '
|
649
|
+
f'got {filter_} it at index {i}.')
|
650
|
+
|
651
|
+
# change the filters to predicates
|
652
|
+
predicates = tuple(map(to_predicate, filters))
|
653
|
+
|
654
|
+
# we have n + 1 state mappings, where n is the number of predicates
|
655
|
+
# the last state mapping is for values that don't match any predicate
|
656
|
+
flat_states: tuple[FlattedStateMapping[V], ...] = tuple({} for _ in range(len(predicates) + 1))
|
657
|
+
|
658
|
+
assert isinstance(mapping, NestedDict), f'expected NestedDict; got {type(mapping).__qualname__}'
|
659
|
+
flat_state = mapping.to_flat()
|
660
|
+
for path, value in flat_state.items():
|
661
|
+
for i, predicate in enumerate(predicates):
|
662
|
+
if predicate(path, value):
|
663
|
+
flat_states[i][path] = value # type: ignore[index] # mypy is wrong here?
|
664
|
+
break
|
665
|
+
else:
|
666
|
+
# if we didn't break, set leaf to last state
|
667
|
+
flat_states[-1][path] = value # type: ignore[index] # mypy is wrong here?
|
668
|
+
|
669
|
+
return tuple(NestedDict.from_flat(flat_state) for flat_state in flat_states)
|
670
|
+
|
671
|
+
|
672
|
+
def _split_flatted_mapping(
|
673
|
+
mapping: FlattedDict[K, V],
|
674
|
+
*filters: Filter,
|
675
|
+
) -> Tuple[FlattedDict[K, V], ...]:
|
676
|
+
# check if the filters are exhaustive
|
677
|
+
for i, filter_ in enumerate(filters):
|
678
|
+
if filter_ in (..., True) and i != len(filters) - 1:
|
679
|
+
remaining_filters = filters[i + 1:]
|
680
|
+
if not all(f in (..., True) for f in remaining_filters):
|
681
|
+
raise ValueError('`...` or `True` can only be used as the last filters, '
|
682
|
+
f'got {filter_} it at index {i}.')
|
683
|
+
|
684
|
+
# change the filters to predicates
|
685
|
+
predicates = tuple(map(to_predicate, filters))
|
686
|
+
|
687
|
+
# we have n + 1 state mappings, where n is the number of predicates
|
688
|
+
# the last state mapping is for values that don't match any predicate
|
689
|
+
flat_states: tuple[FlattedStateMapping[V], ...] = tuple({} for _ in range(len(predicates) + 1))
|
690
|
+
|
691
|
+
assert isinstance(mapping, FlattedDict), f'expected FlattedDict; got {type(mapping).__qualname__}'
|
692
|
+
for path, value in mapping.items():
|
693
|
+
for i, predicate in enumerate(predicates):
|
694
|
+
if predicate(path, value):
|
695
|
+
flat_states[i][path] = value # type: ignore[index] # mypy is wrong here?
|
696
|
+
break
|
697
|
+
else:
|
698
|
+
# if we didn't break, set leaf to last state
|
699
|
+
flat_states[-1][path] = value # type: ignore[index] # mypy is wrong here?
|
700
|
+
|
701
|
+
return tuple(FlattedDict(flat_state) for flat_state in flat_states)
|
702
|
+
|
703
|
+
|
704
|
+
# register ``NestedDict`` as a pytree
|
705
|
+
def _nest_flatten_with_keys(x: NestedDict):
|
706
|
+
items = sorted(x.items())
|
707
|
+
children = tuple((jax.tree_util.DictKey(key), value) for key, value in items)
|
708
|
+
return children, tuple(key for key, _ in items)
|
709
|
+
|
710
|
+
|
711
|
+
def _nest_unflatten(
|
712
|
+
static: Tuple[K, ...],
|
713
|
+
leaves: Tuple[V, ...] | Tuple[Dict[K, V]],
|
714
|
+
):
|
715
|
+
return NestedDict(zip(static, leaves))
|
716
|
+
|
717
|
+
|
718
|
+
jax.tree_util.register_pytree_with_keys(NestedDict,
|
719
|
+
_nest_flatten_with_keys,
|
720
|
+
_nest_unflatten) # type: ignore[arg-type]
|
721
|
+
|
722
|
+
|
723
|
+
# register ``FlattedDict`` as a pytree
|
724
|
+
|
725
|
+
def _flat_unflatten(
|
726
|
+
static: Tuple[K, ...],
|
727
|
+
leaves: Tuple[V, ...] | Tuple[Dict[K, V]],
|
728
|
+
):
|
729
|
+
return FlattedDict(zip(static, leaves))
|
730
|
+
|
731
|
+
|
732
|
+
jax.tree_util.register_pytree_with_keys(FlattedDict,
|
733
|
+
_nest_flatten_with_keys,
|
734
|
+
_flat_unflatten) # type: ignore[arg-type]
|