brainstate 0.1.10__py2.py3-none-any.whl → 0.2.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.
Files changed (163) hide show
  1. brainstate/__init__.py +130 -19
  2. brainstate/_compatible_import.py +201 -9
  3. brainstate/_compatible_import_test.py +681 -0
  4. brainstate/_deprecation.py +210 -0
  5. brainstate/_deprecation_test.py +2319 -0
  6. brainstate/{util/error.py → _error.py} +10 -20
  7. brainstate/_state.py +94 -47
  8. brainstate/_state_test.py +1 -1
  9. brainstate/_utils.py +1 -1
  10. brainstate/environ.py +1279 -347
  11. brainstate/environ_test.py +1187 -26
  12. brainstate/graph/__init__.py +6 -13
  13. brainstate/graph/_node.py +240 -0
  14. brainstate/graph/_node_test.py +589 -0
  15. brainstate/graph/{_graph_operation.py → _operation.py} +632 -746
  16. brainstate/graph/_operation_test.py +1147 -0
  17. brainstate/mixin.py +1209 -141
  18. brainstate/mixin_test.py +991 -51
  19. brainstate/nn/__init__.py +74 -72
  20. brainstate/nn/_activations.py +587 -295
  21. brainstate/nn/_activations_test.py +109 -86
  22. brainstate/nn/_collective_ops.py +393 -274
  23. brainstate/nn/_collective_ops_test.py +746 -15
  24. brainstate/nn/_common.py +114 -66
  25. brainstate/nn/_common_test.py +154 -0
  26. brainstate/nn/_conv.py +1652 -143
  27. brainstate/nn/_conv_test.py +838 -227
  28. brainstate/nn/_delay.py +15 -28
  29. brainstate/nn/_delay_test.py +25 -20
  30. brainstate/nn/_dropout.py +359 -167
  31. brainstate/nn/_dropout_test.py +429 -52
  32. brainstate/nn/_dynamics.py +14 -90
  33. brainstate/nn/_dynamics_test.py +1 -12
  34. brainstate/nn/_elementwise.py +492 -313
  35. brainstate/nn/_elementwise_test.py +806 -145
  36. brainstate/nn/_embedding.py +369 -19
  37. brainstate/nn/_embedding_test.py +156 -0
  38. brainstate/nn/{_fixedprob.py → _event_fixedprob.py} +10 -16
  39. brainstate/nn/{_fixedprob_test.py → _event_fixedprob_test.py} +6 -5
  40. brainstate/nn/{_linear_mv.py → _event_linear.py} +2 -2
  41. brainstate/nn/{_linear_mv_test.py → _event_linear_test.py} +6 -5
  42. brainstate/nn/_exp_euler.py +200 -38
  43. brainstate/nn/_exp_euler_test.py +350 -8
  44. brainstate/nn/_linear.py +391 -71
  45. brainstate/nn/_linear_test.py +427 -59
  46. brainstate/nn/_metrics.py +1070 -0
  47. brainstate/nn/_metrics_test.py +611 -0
  48. brainstate/nn/_module.py +10 -3
  49. brainstate/nn/_module_test.py +1 -1
  50. brainstate/nn/_normalizations.py +688 -329
  51. brainstate/nn/_normalizations_test.py +663 -37
  52. brainstate/nn/_paddings.py +1020 -0
  53. brainstate/nn/_paddings_test.py +723 -0
  54. brainstate/nn/_poolings.py +1404 -342
  55. brainstate/nn/_poolings_test.py +828 -92
  56. brainstate/nn/{_rate_rnns.py → _rnns.py} +446 -54
  57. brainstate/nn/_rnns_test.py +593 -0
  58. brainstate/nn/_utils.py +132 -5
  59. brainstate/nn/_utils_test.py +402 -0
  60. brainstate/{init/_random_inits.py → nn/init.py} +301 -45
  61. brainstate/{init/_random_inits_test.py → nn/init_test.py} +51 -20
  62. brainstate/random/__init__.py +247 -1
  63. brainstate/random/_rand_funs.py +668 -346
  64. brainstate/random/_rand_funs_test.py +74 -1
  65. brainstate/random/_rand_seed.py +541 -76
  66. brainstate/random/_rand_seed_test.py +1 -1
  67. brainstate/random/_rand_state.py +601 -393
  68. brainstate/random/_rand_state_test.py +551 -0
  69. brainstate/transform/__init__.py +59 -0
  70. brainstate/transform/_ad_checkpoint.py +176 -0
  71. brainstate/{compile → transform}/_ad_checkpoint_test.py +1 -1
  72. brainstate/{augment → transform}/_autograd.py +360 -113
  73. brainstate/{augment → transform}/_autograd_test.py +2 -2
  74. brainstate/transform/_conditions.py +316 -0
  75. brainstate/{compile → transform}/_conditions_test.py +11 -11
  76. brainstate/{compile → transform}/_error_if.py +22 -20
  77. brainstate/{compile → transform}/_error_if_test.py +1 -1
  78. brainstate/transform/_eval_shape.py +145 -0
  79. brainstate/{augment → transform}/_eval_shape_test.py +1 -1
  80. brainstate/{compile → transform}/_jit.py +99 -46
  81. brainstate/{compile → transform}/_jit_test.py +3 -3
  82. brainstate/{compile → transform}/_loop_collect_return.py +219 -80
  83. brainstate/{compile → transform}/_loop_collect_return_test.py +1 -1
  84. brainstate/{compile → transform}/_loop_no_collection.py +133 -34
  85. brainstate/{compile → transform}/_loop_no_collection_test.py +2 -2
  86. brainstate/transform/_make_jaxpr.py +2016 -0
  87. brainstate/transform/_make_jaxpr_test.py +1510 -0
  88. brainstate/transform/_mapping.py +529 -0
  89. brainstate/transform/_mapping_test.py +194 -0
  90. brainstate/{compile → transform}/_progress_bar.py +78 -25
  91. brainstate/{augment → transform}/_random.py +65 -45
  92. brainstate/{compile → transform}/_unvmap.py +102 -5
  93. brainstate/transform/_util.py +286 -0
  94. brainstate/typing.py +594 -61
  95. brainstate/typing_test.py +780 -0
  96. brainstate/util/__init__.py +9 -32
  97. brainstate/util/_others.py +1025 -0
  98. brainstate/util/_others_test.py +962 -0
  99. brainstate/util/_pretty_pytree.py +1301 -0
  100. brainstate/util/_pretty_pytree_test.py +675 -0
  101. brainstate/util/{pretty_repr.py → _pretty_repr.py} +161 -27
  102. brainstate/util/_pretty_repr_test.py +696 -0
  103. brainstate/util/filter.py +557 -81
  104. brainstate/util/filter_test.py +912 -0
  105. brainstate/util/struct.py +769 -382
  106. brainstate/util/struct_test.py +602 -0
  107. {brainstate-0.1.10.dist-info → brainstate-0.2.0.dist-info}/METADATA +34 -17
  108. brainstate-0.2.0.dist-info/RECORD +111 -0
  109. brainstate/augment/__init__.py +0 -30
  110. brainstate/augment/_eval_shape.py +0 -99
  111. brainstate/augment/_mapping.py +0 -1060
  112. brainstate/augment/_mapping_test.py +0 -597
  113. brainstate/compile/__init__.py +0 -38
  114. brainstate/compile/_ad_checkpoint.py +0 -204
  115. brainstate/compile/_conditions.py +0 -256
  116. brainstate/compile/_make_jaxpr.py +0 -888
  117. brainstate/compile/_make_jaxpr_test.py +0 -156
  118. brainstate/compile/_util.py +0 -147
  119. brainstate/functional/__init__.py +0 -27
  120. brainstate/graph/_graph_node.py +0 -244
  121. brainstate/graph/_graph_node_test.py +0 -73
  122. brainstate/graph/_graph_operation_test.py +0 -563
  123. brainstate/init/__init__.py +0 -26
  124. brainstate/init/_base.py +0 -52
  125. brainstate/init/_generic.py +0 -244
  126. brainstate/init/_regular_inits.py +0 -105
  127. brainstate/init/_regular_inits_test.py +0 -50
  128. brainstate/nn/_inputs.py +0 -608
  129. brainstate/nn/_ltp.py +0 -28
  130. brainstate/nn/_neuron.py +0 -705
  131. brainstate/nn/_neuron_test.py +0 -161
  132. brainstate/nn/_others.py +0 -46
  133. brainstate/nn/_projection.py +0 -486
  134. brainstate/nn/_rate_rnns_test.py +0 -63
  135. brainstate/nn/_readout.py +0 -209
  136. brainstate/nn/_readout_test.py +0 -53
  137. brainstate/nn/_stp.py +0 -236
  138. brainstate/nn/_synapse.py +0 -505
  139. brainstate/nn/_synapse_test.py +0 -131
  140. brainstate/nn/_synaptic_projection.py +0 -423
  141. brainstate/nn/_synouts.py +0 -162
  142. brainstate/nn/_synouts_test.py +0 -57
  143. brainstate/nn/metrics.py +0 -388
  144. brainstate/optim/__init__.py +0 -38
  145. brainstate/optim/_base.py +0 -64
  146. brainstate/optim/_lr_scheduler.py +0 -448
  147. brainstate/optim/_lr_scheduler_test.py +0 -50
  148. brainstate/optim/_optax_optimizer.py +0 -152
  149. brainstate/optim/_optax_optimizer_test.py +0 -53
  150. brainstate/optim/_sgd_optimizer.py +0 -1104
  151. brainstate/random/_random_for_unit.py +0 -52
  152. brainstate/surrogate.py +0 -1957
  153. brainstate/transform.py +0 -23
  154. brainstate/util/caller.py +0 -98
  155. brainstate/util/others.py +0 -540
  156. brainstate/util/pretty_pytree.py +0 -945
  157. brainstate/util/pretty_pytree_test.py +0 -159
  158. brainstate/util/pretty_table.py +0 -2954
  159. brainstate/util/scaling.py +0 -258
  160. brainstate-0.1.10.dist-info/RECORD +0 -130
  161. {brainstate-0.1.10.dist-info → brainstate-0.2.0.dist-info}/WHEEL +0 -0
  162. {brainstate-0.1.10.dist-info → brainstate-0.2.0.dist-info}/licenses/LICENSE +0 -0
  163. {brainstate-0.1.10.dist-info → brainstate-0.2.0.dist-info}/top_level.txt +0 -0
@@ -1,945 +0,0 @@
1
- # The file is adapted from the Flax library (https://github.com/google/flax).
2
- # The credit should go to the Flax authors.
3
- #
4
- # Copyright 2024 The Flax Authors.
5
- #
6
- # Licensed under the Apache License, Version 2.0 (the "License");
7
- # you may not use this file except in compliance with the License.
8
- # You may obtain a copy of the License at
9
- #
10
- # http://www.apache.org/licenses/LICENSE-2.0
11
- #
12
- # Unless required by applicable law or agreed to in writing, software
13
- # distributed under the License is distributed on an "AS IS" BASIS,
14
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
- # See the License for the specific language governing permissions and
16
- # limitations under the License.
17
-
18
- from collections import abc
19
- from typing import TypeVar, Hashable, Union, Iterable, Any, Optional, Tuple, Dict
20
-
21
- import jax
22
-
23
- from brainstate.typing import Filter, PathParts
24
- from .pretty_repr import PrettyRepr, PrettyType, PrettyAttr, yield_unique_pretty_repr_items, pretty_repr_object
25
- from .struct import dataclass
26
- from .filter import to_predicate
27
-
28
- __all__ = [
29
- 'PrettyDict',
30
- 'NestedDict',
31
- 'FlattedDict',
32
- 'flat_mapping',
33
- 'nest_mapping',
34
- 'PrettyList',
35
- 'PrettyObject',
36
- ]
37
-
38
- A = TypeVar('A')
39
- K = TypeVar('K', bound=Hashable)
40
- V = TypeVar('V')
41
-
42
- FlattedStateMapping = dict[PathParts, V]
43
- ExtractValueFn = abc.Callable[[Any], Any]
44
- SetValueFn = abc.Callable[[V, Any], V]
45
-
46
-
47
- class PrettyObject(PrettyRepr):
48
- """
49
- A class for generating a pretty representation of a tree-like structure.
50
-
51
- This class extends the PrettyRepr class to provide a mechanism for
52
- generating a human-readable, pretty representation of tree-like data
53
- structures. It utilizes custom functions to represent the object and
54
- its attributes in a structured and visually appealing format.
55
-
56
- Methods
57
- -------
58
- __pretty_repr__: Generates a sequence of pretty representation items
59
- for the object.
60
- __pretty_repr_item__: Returns a tuple of the key and value for pretty
61
- representation of an item in the data structure.
62
- """
63
-
64
- def __pretty_repr__(self):
65
- """
66
- Generates a pretty representation of the object.
67
-
68
- This method yields a sequence of pretty representation items for the object,
69
- using specified functions to represent the object and its attributes.
70
-
71
- Yields:
72
- Pretty representation items generated by `yield_unique_pretty_repr_items`.
73
- """
74
- yield from yield_unique_pretty_repr_items(
75
- self,
76
- repr_object=_repr_object_general,
77
- repr_attr=_repr_attribute_general,
78
- )
79
-
80
- def __pretty_repr_item__(self, k, v):
81
- """
82
- Returns a tuple of the key and value for pretty representation.
83
-
84
- This method is used to generate a pretty representation of an item
85
- in a data structure, typically for debugging or logging purposes.
86
-
87
- Args:
88
- k: The key of the item.
89
- v: The value of the item.
90
-
91
- Returns:
92
- A tuple containing the key and value.
93
- """
94
- return k, v
95
-
96
-
97
- PrettyReprTree = PrettyObject
98
-
99
-
100
- # the empty node is a struct.dataclass to be compatible with JAX.
101
- @dataclass
102
- class _EmptyNode:
103
- pass
104
-
105
-
106
- _default_leaf = lambda *args: False
107
- empty_node = _EmptyNode()
108
- IsLeafCallable = abc.Callable[[Tuple[Any, ...], abc.Mapping[Any, Any]], bool]
109
-
110
-
111
- def flat_mapping(
112
- xs: abc.Mapping[Any, Any],
113
- /,
114
- *,
115
- keep_empty_nodes: bool = False,
116
- is_leaf: Optional[IsLeafCallable] = _default_leaf,
117
- sep: Optional[str] = None
118
- ) -> 'FlattedDict':
119
- """Flatten a nested mapping.
120
-
121
- The nested keys are flattened to a tuple. See ``unflatten_mapping`` on how to
122
- restore the nested mapping.
123
-
124
- Example::
125
-
126
- >>> xs = {'foo': 1, 'bar': {'a': 2, 'b': {}}}
127
- >>> flat_xs = flat_mapping(xs)
128
- >>> flat_xs
129
- {('foo',): 1, ('bar', 'a'): 2}
130
-
131
- Note that empty mappings are ignored and will not be restored by
132
- ``unflatten_mapping``.
133
-
134
- Args:
135
- xs: A nested mapping.
136
- keep_empty_nodes: replaces empty mappings with ``empty_node``.
137
- is_leaf: An optional function that takes the next nested mapping and nested
138
- keys and returns True if the nested mapping is a leaf (i.e., should not be
139
- flattened further).
140
- sep: If specified, then the keys of the returned mapping will be
141
- ``sep``-joined strings (if ``None``, then keys will be tuples).
142
-
143
- Returns:
144
- The flattened mapping.
145
- """
146
- assert isinstance(xs, abc.Mapping), f'expected Mapping; got {type(xs).__qualname__}'
147
-
148
- if sep is None:
149
- def _key(path: Tuple[Any, ...]) -> Tuple[Any, ...] | str:
150
- return path
151
- else:
152
-
153
- def _key(path: Tuple[Any, ...]) -> Tuple[Any, ...] | str:
154
- return sep.join(path)
155
-
156
- def _flatten(xs: Any, prefix: Tuple[Any, ...]) -> Dict[Any, Any]:
157
- if not isinstance(xs, abc.Mapping) or is_leaf(prefix, xs):
158
- return {_key(prefix): xs}
159
-
160
- result = {}
161
- is_empty = True
162
- for key, value in xs.items():
163
- is_empty = False
164
- result.update(_flatten(value, prefix + (key,)))
165
- if keep_empty_nodes and is_empty:
166
- if prefix == (): # when the whole input is empty
167
- return {}
168
- return {_key(prefix): empty_node}
169
- return result
170
-
171
- return FlattedDict(_flatten(xs, ()))
172
-
173
-
174
- def nest_mapping(
175
- xs: Any,
176
- /,
177
- *,
178
- sep: str | None = None
179
- ) -> 'NestedDict':
180
- """Unflatten a mapping.
181
-
182
- See ``flatten_mapping``
183
-
184
- Example::
185
-
186
- >>> flat_xs = {
187
- ... ('foo',): 1,
188
- ... ('bar', 'a'): 2,
189
- ... }
190
- >>> xs = nest_mapping(flat_xs)
191
- >>> xs
192
- {'foo': 1, 'bar': {'a': 2}}
193
-
194
- Args:
195
- xs: a flattened mapping.
196
- sep: separator (same as used with ``flatten_mapping()``).
197
-
198
- Returns:
199
- The nested mapping.
200
- """
201
- assert isinstance(xs, abc.Mapping), f'expected Mapping; got {type(xs).__qualname__}'
202
- result: Dict[Any, Any] = {}
203
- for path, value in xs.items():
204
- if sep is not None:
205
- path = path.split(sep)
206
- if value is empty_node:
207
- value = {}
208
- cursor = result
209
- for key in path[:-1]:
210
- if key not in cursor:
211
- cursor[key] = {}
212
- cursor = cursor[key]
213
- cursor[path[-1]] = value
214
- return NestedDict(result)
215
-
216
-
217
- def _default_compare(x, values):
218
- return id(x) in values
219
-
220
-
221
- def _default_process(x):
222
- return id(x)
223
-
224
-
225
- class PrettyDict(dict, PrettyRepr):
226
- __module__ = 'brainstate.util'
227
-
228
- def __getattr__(self, key: K): # type: ignore[misc]
229
- return self[key]
230
-
231
- def treefy_state(self):
232
- """
233
- Convert the :class:`State` objects to a reference tree of the state.
234
- """
235
- from brainstate._state import State
236
- leaves, treedef = jax.tree.flatten(self)
237
- leaves = jax.tree.map(lambda x: x.to_state_ref() if isinstance(x, State) else x, leaves)
238
- return treedef.unflatten(leaves)
239
-
240
- def to_dict(self) -> Dict[K, Dict[K, Any] | V]:
241
- """
242
- Convert the :class:`PrettyDict` to a dictionary.
243
-
244
- Returns:
245
- The dictionary.
246
- """
247
- return dict(self) # type: ignore
248
-
249
- def __repr__(self) -> str:
250
- # repr the individual object with the pretty representation
251
- return pretty_repr_object(self)
252
-
253
- def __pretty_repr__(self):
254
- yield from yield_unique_pretty_repr_items(self, _default_repr_object, _default_repr_attr)
255
-
256
- def split(self, *filters) -> Union['PrettyDict[K, V]', Tuple['PrettyDict[K, V]', ...]]:
257
- raise NotImplementedError
258
-
259
- def filter(self, *filters) -> Union['PrettyDict[K, V]', Tuple['PrettyDict[K, V]', ...]]:
260
- raise NotImplementedError
261
-
262
- def merge(self, *states) -> 'PrettyDict[K, V]':
263
- raise NotImplementedError
264
-
265
- def subset(self, *filters) -> Union['PrettyDict[K, V]', Tuple['PrettyDict[K, V]', ...]]:
266
- """
267
- Subset a :class:`PrettyDict` into one or more :class:`PrettyDict`'s. The user must pass at least one
268
- `:class:`Filter` (i.e. :class:`State`), and the filters must be exhaustive (i.e. they must cover all
269
- :class:`State` types in the :class:`PrettyDict`).
270
- """
271
- return self.filter(*filters)
272
-
273
-
274
- class NestedStateRepr(PrettyRepr):
275
- def __init__(self, state: PrettyDict):
276
- self.state = state
277
-
278
- def __pretty_repr__(self):
279
- yield PrettyType('', value_sep=': ', start='{', end='}')
280
-
281
- for r in self.state.__pretty_repr__():
282
- if isinstance(r, PrettyType):
283
- continue
284
- yield r
285
-
286
- def __treescope_repr__(self, path, subtree_renderer):
287
- children = {}
288
- for k, v in self.state.items():
289
- if isinstance(v, PrettyDict):
290
- v = NestedStateRepr(v)
291
- children[k] = v
292
- # Render as the dictionary itself at the same path.
293
- return subtree_renderer(children, path=path)
294
-
295
-
296
- def _default_repr_object(node: PrettyDict):
297
- yield PrettyType('', value_sep=': ', start='{', end='}')
298
-
299
-
300
- def _default_repr_attr(node):
301
- for k, v in node.items():
302
- if isinstance(v, list):
303
- v = PrettyList(v)
304
-
305
- if isinstance(v, dict):
306
- v = PrettyDict(v)
307
-
308
- if isinstance(v, PrettyDict):
309
- v = NestedStateRepr(v)
310
-
311
- yield PrettyAttr(repr(k), v)
312
-
313
-
314
- class NestedDict(PrettyDict):
315
- """
316
- A pytree-like structure that contains a :class:`Mapping` from strings or integers to leaves.
317
-
318
- A valid leaf type is either :class:`State`, ``jax.Array``, ``numpy.ndarray`` or nested
319
- :class:`NestedDict` and :class:`FlattedDict`.
320
- """
321
- __module__ = 'brainstate.util'
322
-
323
- def __or__(self, other: 'NestedDict[K, V]') -> 'NestedDict[K, V]':
324
- if not other:
325
- return self
326
- assert isinstance(other, NestedDict), f'expected NestedDict; got {type(other).__qualname__}'
327
- return NestedDict.merge(self, other)
328
-
329
- def __sub__(self, other: 'NestedDict[K, V]') -> 'NestedDict[K, V]':
330
- if not other:
331
- return self
332
-
333
- assert isinstance(other, NestedDict), f'expected NestedDict; got {type(other).__qualname__}'
334
- self_flat = self.to_flat()
335
- other_flat = other.to_flat()
336
- diff = {k: v for k, v in self_flat.items() if k not in other_flat}
337
- return NestedDict.from_flat(diff)
338
-
339
- def to_flat(self) -> 'FlattedDict':
340
- """
341
- Flatten the nested mapping into a flat mapping.
342
-
343
- Returns:
344
- The flattened mapping.
345
- """
346
- return flat_mapping(self)
347
-
348
- @classmethod
349
- def from_flat(cls, flat_dict: abc.Mapping[PathParts, V] | Iterable[tuple[PathParts, V]]) -> 'NestedDict':
350
- """
351
- Create a :class:`NestedDict` from a flat mapping.
352
-
353
- Args:
354
- flat_dict: The flat mapping.
355
-
356
- Returns:
357
- The :class:`NestedDict`.
358
- """
359
- nested_state = nest_mapping(dict(flat_dict))
360
- return cls(nested_state)
361
-
362
- def split( # type: ignore[misc]
363
- self,
364
- first: Filter,
365
- /,
366
- *filters: Filter
367
- ) -> Union['NestedDict[K, V]', Tuple['NestedDict[K, V]', ...]]:
368
- """
369
- Split a :class:`NestedDict` into one or more :class:`NestedDict`'s. The
370
- user must pass at least one `:class:`Filter` (i.e. :class:`State`),
371
- and the filters must be exhaustive (i.e. they must cover all
372
- :class:`State` types in the :class:`NestedDict`).
373
-
374
- Example usage::
375
-
376
- >>> import brainstate as brainstate
377
-
378
- >>> class Model(brainstate.nn.Module):
379
- ... def __init__(self):
380
- ... super().__init__()
381
- ... self.batchnorm = brainstate.nn.BatchNorm1d([10, 3])
382
- ... self.linear = brainstate.nn.Linear(2, 3)
383
- ... def __call__(self, x):
384
- ... return self.linear(self.batchnorm(x))
385
-
386
- >>> model = Model()
387
- >>> state_map = brainstate.graph.treefy_states(model)
388
- >>> param, others = state_map.treefy_split(brainstate.ParamState, ...)
389
-
390
- Arguments:
391
- first: The first filter
392
- *filters: The optional, additional filters to group the state into mutually exclusive substates.
393
-
394
- Returns:
395
- One or more ``States`` equal to the number of filters passed.
396
- """
397
- filters = (first, *filters)
398
- *states_, rest = _split_nested_mapping(self, *filters)
399
- if rest:
400
- raise ValueError(f'Non-exhaustive filters, got a non-empty remainder: {rest}.\n'
401
- f'Use `...` to match all remaining elements.')
402
-
403
- states: NestedDict | Tuple[NestedDict, ...]
404
- if len(states_) == 1:
405
- states = states_[0]
406
- else:
407
- states = tuple(states_)
408
- return states # type: ignore[bad-return-type]
409
-
410
- def filter(
411
- self,
412
- first: Filter,
413
- /,
414
- *filters: Filter,
415
- ) -> Union['NestedDict[K, V]', Tuple['NestedDict[K, V]', ...]]:
416
- """
417
- Filter a :class:`NestedDict` into one or more :class:`NestedDict`'s. The
418
- user must pass at least one `:class:`Filter` (i.e. :class:`State`).
419
- This method is similar to :meth:`split() <flax.nnx.NestedDict.state.split>`,
420
- except the filters can be non-exhaustive.
421
-
422
- Arguments:
423
- first: The first filter
424
- *filters: The optional, additional filters to group the state into mutually exclusive substates.
425
-
426
- Returns:
427
- One or more ``States`` equal to the number of filters passed.
428
- """
429
- *states_, _rest = _split_nested_mapping(self, first, *filters)
430
- assert len(states_) == len(filters) + 1, f'Expected {len(filters) + 1} states, got {len(states_)}'
431
- if len(states_) == 1:
432
- states = states_[0]
433
- else:
434
- states = tuple(states_)
435
- return states # type: ignore[bad-return-type]
436
-
437
- @staticmethod
438
- def merge(
439
- state: Union['NestedDict[K, V]', 'FlattedDict[K, V]'],
440
- /,
441
- *states: Union['NestedDict[K, V]', 'FlattedDict[K, V]']
442
- ) -> 'NestedDict[K, V]':
443
- """
444
- The inverse of :meth:`split()`.
445
-
446
- ``merge`` takes one or more :class:`PrettyDict`'s and creates a new :class:`PrettyDict`.
447
-
448
- Args:
449
- state: A :class:`PrettyDict` object.
450
- *states: Additional :class:`PrettyDict` objects.
451
-
452
- Returns:
453
- The merged :class:`PrettyDict`.
454
- """
455
- if not states:
456
- return state
457
- states = (state, *states)
458
- new_state: FlattedDict = FlattedDict()
459
- for state in states:
460
- if isinstance(state, NestedDict):
461
- new_state.update(state.to_flat()) # type: ignore[attribute-error] # pytype is wrong here
462
- elif isinstance(state, FlattedDict):
463
- new_state.update(state)
464
- else:
465
- raise TypeError(f'Expected Nested or Flatted Mapping, got {type(state)} instead.')
466
- return NestedDict.from_flat(new_state)
467
-
468
- def to_pure_dict(self) -> Dict[str, Any]:
469
- flat_values = {k: x for k, x in self.to_flat().items()}
470
- return nest_mapping(flat_values).to_dict()
471
-
472
- def replace_by_pure_dict(
473
- self,
474
- pure_dict: Dict[str, Any],
475
- replace_fn: Optional[SetValueFn] = None
476
- ):
477
- if replace_fn is None:
478
- replace_fn = lambda x, v: x.replace(v) if hasattr(x, 'replace') else v
479
- current_flat = self.to_flat()
480
- for kp, v in flat_mapping(pure_dict).items():
481
- if kp not in current_flat:
482
- raise ValueError(f'key in pure_dict not available in state: {kp}')
483
- current_flat[kp] = replace_fn(current_flat[kp], v)
484
- self.update(nest_mapping(current_flat))
485
-
486
-
487
- class FlattedDict(PrettyDict):
488
- """
489
- A pytree-like structure that contains a :class:`Mapping` from strings or integers to leaves.
490
-
491
- A valid leaf type is either :class:`State`, ``jax.Array``, ``numpy.ndarray`` or Python variables.
492
-
493
- A :class:`NestedDict` can be generated by either calling :func:`states()` or
494
- :func:`nodes()` on the :class:`Module`.
495
-
496
- Example usage::
497
-
498
- >>> import brainstate as brainstate
499
- >>> import jax.numpy as jnp
500
- >>>
501
- >>> class Model(brainstate.nn.Module):
502
- ... def __init__(self):
503
- ... super().__init__()
504
- ... self.batchnorm = brainstate.nn.BatchNorm1d([10, 3])
505
- ... self.linear = brainstate.nn.Linear(2, 3)
506
- ... def __call__(self, x):
507
- ... return self.linear(self.batchnorm(x))
508
- >>>
509
- >>> model = Model()
510
-
511
- >>> # retrieve the states of the model
512
- >>> model.states() # with the same to the function of ``brainstate.graph.states()``
513
- FlattedDict({
514
- ('batchnorm', 'running_mean'): LongTermState(
515
- value=Array([[0., 0., 0.]], dtype=float32)
516
- ),
517
- ('batchnorm', 'running_var'): LongTermState(
518
- value=Array([[1., 1., 1.]], dtype=float32)
519
- ),
520
- ('batchnorm', 'weight'): ParamState(
521
- value={'bias': Array([[0., 0., 0.]], dtype=float32), 'scale': Array([[1., 1., 1.]], dtype=float32)}
522
- ),
523
- ('linear', 'weight'): ParamState(
524
- value={'weight': Array([[-0.21467684, 0.7621282 , -0.50756454, -0.49047297],
525
- [-0.90413696, 0.6711 , -0.1254792 , 0.50412565],
526
- [ 0.23975602, 0.47905368, 1.4851435 , 0.16745673]], dtype=float32), 'bias': Array([0., 0., 0., 0.], dtype=float32)}
527
- )
528
- })
529
-
530
- >>> # retrieve the nodes of the model
531
- >>> model.nodes() # with the same to the function of ``brainstate.graph.nodes()``
532
- FlattedDict({
533
- ('batchnorm',): BatchNorm1d(
534
- in_size=(10, 3),
535
- out_size=(10, 3),
536
- affine=True,
537
- bias_initializer=Constant(value=0.0, dtype=<class 'numpy.float32'>),
538
- scale_initializer=Constant(value=1.0, dtype=<class 'numpy.float32'>),
539
- dtype=<class 'numpy.float32'>,
540
- track_running_stats=True,
541
- momentum=Array(shape=(), dtype=float32),
542
- epsilon=Array(shape=(), dtype=float32),
543
- feature_axis=(1,),
544
- axis_name=None,
545
- axis_index_groups=None,
546
- running_mean=LongTermState(
547
- value=Array(shape=(1, 3), dtype=float32)
548
- ),
549
- running_var=LongTermState(
550
- value=Array(shape=(1, 3), dtype=float32)
551
- ),
552
- weight=ParamState(
553
- value={'bias': Array(shape=(1, 3), dtype=float32), 'scale': Array(shape=(1, 3), dtype=float32)}
554
- )
555
- ),
556
- ('linear',): Linear(
557
- in_size=(10, 3),
558
- out_size=(10, 4),
559
- w_mask=None,
560
- weight=ParamState(
561
- value={'bias': Array(shape=(4,), dtype=float32), 'weight': Array(shape=(3, 4), dtype=float32)}
562
- )
563
- ),
564
- (): Model(
565
- batchnorm=BatchNorm1d(...),
566
- linear=Linear(...)
567
- )
568
- })
569
- """
570
- __module__ = 'brainstate.util'
571
-
572
- def __or__(self, other: 'FlattedDict[K, V]') -> 'FlattedDict[K, V]':
573
- if not other:
574
- return self
575
- assert isinstance(other, FlattedDict), f'expected NestedDict; got {type(other).__qualname__}'
576
- return FlattedDict.merge(self, other)
577
-
578
- def __sub__(self, other: 'FlattedDict[K, V]') -> 'FlattedDict[K, V]':
579
- if not other:
580
- return self
581
- assert isinstance(other, FlattedDict), f'expected NestedDict; got {type(other).__qualname__}'
582
- diff = {k: v for k, v in self.items() if k not in other}
583
- return FlattedDict(diff)
584
-
585
- def to_nest(self) -> NestedDict:
586
- """
587
- Unflatten the flat mapping into a nested mapping.
588
-
589
- Returns:
590
- The nested mapping.
591
- """
592
- return nest_mapping(self)
593
-
594
- @classmethod
595
- def from_nest(
596
- cls, nested_dict: abc.Mapping[PathParts, V] | Iterable[tuple[PathParts, V]],
597
- ) -> 'FlattedDict':
598
- """
599
- Create a :class:`NestedDict` from a flat mapping.
600
-
601
- Args:
602
- nested_dict: The flat mapping.
603
-
604
- Returns:
605
- The :class:`NestedDict`.
606
- """
607
- return flat_mapping(nested_dict)
608
-
609
- def split( # type: ignore[misc]
610
- self,
611
- first: Filter,
612
- /,
613
- *filters: Filter
614
- ) -> Union['FlattedDict[K, V]', tuple['FlattedDict[K, V]', ...]]:
615
- """
616
- Split a :class:`FlattedDict` into one or more :class:`FlattedDict`'s. The
617
- user must pass at least one `:class:`Filter` (i.e. :class:`State`),
618
- and the filters must be exhaustive (i.e. they must cover all
619
- :class:`State` types in the :class:`NestedDict`).
620
-
621
- Arguments:
622
- first: The first filter
623
- *filters: The optional, additional filters to group the state into mutually exclusive substates.
624
-
625
- Returns:
626
- One or more ``States`` equal to the number of filters passed.
627
- """
628
- filters = (first, *filters)
629
- *states_, rest = _split_flatted_mapping(self, *filters)
630
- if rest:
631
- raise ValueError(f'Non-exhaustive filters, got a non-empty remainder: {rest}.\n'
632
- f'Use `...` to match all remaining elements.')
633
-
634
- states: FlattedDict | Tuple[FlattedDict, ...]
635
- if len(states_) == 1:
636
- states = states_[0]
637
- else:
638
- states = tuple(states_)
639
- return states # type: ignore[bad-return-type]
640
-
641
- def filter(
642
- self,
643
- first: Filter,
644
- /,
645
- *filters: Filter,
646
- ) -> Union['FlattedDict[K, V]', Tuple['FlattedDict[K, V]', ...]]:
647
- """
648
- Filter a :class:`FlattedDict` into one or more :class:`FlattedDict`'s. The
649
- user must pass at least one `:class:`Filter` (i.e. :class:`State`).
650
- This method is similar to :meth:`split() <flax.nnx.NestedDict.state.split>`,
651
- except the filters can be non-exhaustive.
652
-
653
- Arguments:
654
- first: The first filter
655
- *filters: The optional, additional filters to group the state into mutually exclusive substates.
656
-
657
- Returns:
658
- One or more ``States`` equal to the number of filters passed.
659
- """
660
- *states_, _rest = _split_flatted_mapping(self, first, *filters)
661
- assert len(states_) == len(filters) + 1, f'Expected {len(filters) + 1} states, got {len(states_)}'
662
- if len(states_) == 1:
663
- states = states_[0]
664
- else:
665
- states = tuple(states_)
666
- return states # type: ignore[bad-return-type]
667
-
668
- @staticmethod
669
- def merge(
670
- state: Union['FlattedDict[K, V]', 'NestedDict[K, V]'],
671
- /,
672
- *states: Union['FlattedDict[K, V]', 'NestedDict[K, V]']
673
- ) -> 'FlattedDict[K, V]':
674
- """
675
- The inverse of :meth:`split()`.
676
-
677
- ``merge`` takes one or more :class:`FlattedDict`'s and creates a new :class:`FlattedDict`.
678
-
679
- Args:
680
- state: A :class:`PrettyDict` object.
681
- *states: Additional :class:`PrettyDict` objects.
682
-
683
- Returns:
684
- The merged :class:`PrettyDict`.
685
- """
686
- if not states:
687
- return state
688
- states = (state, *states)
689
- new_state: FlattedStateMapping[V] = {}
690
- for state in states:
691
- if isinstance(state, NestedDict):
692
- new_state.update(state.to_flat()) # type: ignore[attribute-error] # pytype is wrong here
693
- elif isinstance(state, FlattedDict):
694
- new_state.update(state)
695
- else:
696
- raise TypeError(f'Expected Nested or Flatted Mapping, got {type(state)} instead.')
697
- return FlattedDict(new_state)
698
-
699
- def to_dict_values(self):
700
- """
701
- Convert a FlattedDict containing State objects to a plain dictionary of values.
702
-
703
- This method extracts the underlying values from any State objects in the FlattedDict,
704
- creating a new dictionary with the same keys but where each State object is replaced
705
- by its value attribute. Non-State objects are kept as is.
706
-
707
- Returns:
708
- dict: A dictionary with the same keys as the FlattedDict, but where each State
709
- object is replaced by its value attribute. Non-State objects remain unchanged.
710
-
711
- Example:
712
- >>> flat_dict = FlattedDict({('model', 'layer1', 'weight'): ParamState(value=jnp.ones((10, 5)))})
713
- >>> flat_dict.to_dict_values()
714
- {('model', 'layer1', 'weight'): Array([[1., 1., ...]], dtype=float32)}
715
- """
716
- from brainstate._state import State
717
- return {
718
- k: v.value if isinstance(v, State) else v
719
- for k, v in self.items()
720
- }
721
-
722
- def assign_dict_values(self, data: dict):
723
- """
724
- Assign values from a dictionary to this FlattedDict.
725
-
726
- This method updates the values in the FlattedDict with values from the provided
727
- dictionary. For keys that correspond to State objects, the value attribute of
728
- the State is updated. For other keys, the value in the FlattedDict is directly
729
- replaced with the new value.
730
-
731
- The method requires that all keys in the FlattedDict exist in the provided
732
- dictionary, otherwise a KeyError is raised.
733
-
734
- Args:
735
- data (dict): A dictionary containing the values to assign, where keys
736
- must match those in the FlattedDict.
737
-
738
- Raises:
739
- KeyError: If a key in the FlattedDict is not present in the provided dictionary.
740
-
741
- Example:
742
- >>> flat_dict = FlattedDict({('model', 'weight'): ParamState(value=jnp.zeros((5, 5)))})
743
- >>> flat_dict.assign_dict_values({('model', 'weight'): jnp.ones((5, 5))})
744
- # The ParamState's value is now an array of ones
745
- """
746
- from brainstate._state import State
747
- for k in self.keys():
748
- if k not in data:
749
- raise KeyError(f'Invalid key: {k!r}')
750
- val = self[k]
751
- if isinstance(val, State):
752
- val.value = data[k]
753
- else:
754
- self[k] = data[k]
755
-
756
-
757
- def _split_nested_mapping(
758
- mapping: 'NestedDict[K, V]',
759
- *filters: Filter,
760
- ) -> Tuple['NestedDict[K, V]', ...]:
761
- # check if the filters are exhaustive
762
- for i, filter_ in enumerate(filters):
763
- if filter_ in (..., True) and i != len(filters) - 1:
764
- remaining_filters = filters[i + 1:]
765
- if not all(f in (..., True) for f in remaining_filters):
766
- raise ValueError('`...` or `True` can only be used as the last filters, '
767
- f'got {filter_} it at index {i}.')
768
-
769
- # change the filters to predicates
770
- predicates = tuple(map(to_predicate, filters))
771
-
772
- # we have n + 1 state mappings, where n is the number of predicates
773
- # the last state mapping is for values that don't match any predicate
774
- flat_states: tuple[FlattedStateMapping[V], ...] = tuple({} for _ in range(len(predicates) + 1))
775
-
776
- assert isinstance(mapping, NestedDict), f'expected NestedDict; got {type(mapping).__qualname__}'
777
- flat_state = mapping.to_flat()
778
- for path, value in flat_state.items():
779
- for i, predicate in enumerate(predicates):
780
- if predicate(path, value):
781
- flat_states[i][path] = value # type: ignore[index] # mypy is wrong here?
782
- break
783
- else:
784
- # if we didn't break, set leaf to last state
785
- flat_states[-1][path] = value # type: ignore[index] # mypy is wrong here?
786
-
787
- return tuple(NestedDict.from_flat(flat_state) for flat_state in flat_states)
788
-
789
-
790
- def _split_flatted_mapping(
791
- mapping: FlattedDict[K, V],
792
- *filters: Filter,
793
- ) -> Tuple[FlattedDict[K, V], ...]:
794
- # check if the filters are exhaustive
795
- for i, filter_ in enumerate(filters):
796
- if filter_ in (..., True) and i != len(filters) - 1:
797
- remaining_filters = filters[i + 1:]
798
- if not all(f in (..., True) for f in remaining_filters):
799
- raise ValueError('`...` or `True` can only be used as the last filters, '
800
- f'got {filter_} it at index {i}.')
801
-
802
- # change the filters to predicates
803
- predicates = tuple(map(to_predicate, filters))
804
-
805
- # we have n + 1 state mappings, where n is the number of predicates
806
- # the last state mapping is for values that don't match any predicate
807
- flat_states: tuple[FlattedStateMapping[V], ...] = tuple({} for _ in range(len(predicates) + 1))
808
-
809
- assert isinstance(mapping, FlattedDict), f'expected FlattedDict; got {type(mapping).__qualname__}'
810
- for path, value in mapping.items():
811
- for i, predicate in enumerate(predicates):
812
- if predicate(path, value):
813
- flat_states[i][path] = value # type: ignore[index] # mypy is wrong here?
814
- break
815
- else:
816
- # if we didn't break, set leaf to last state
817
- flat_states[-1][path] = value # type: ignore[index] # mypy is wrong here?
818
-
819
- return tuple(FlattedDict(flat_state) for flat_state in flat_states)
820
-
821
-
822
- # register :class:`NestedDict` as a pytree
823
- def _nest_flatten_with_keys(x: NestedDict):
824
- items = sorted(x.items())
825
- children = tuple((jax.tree_util.DictKey(key), value) for key, value in items)
826
- return children, tuple(key for key, _ in items)
827
-
828
-
829
- def _nest_unflatten(
830
- static: Tuple[K, ...],
831
- leaves: Tuple[V, ...] | Tuple[Dict[K, V]],
832
- ):
833
- return NestedDict(zip(static, leaves))
834
-
835
-
836
- jax.tree_util.register_pytree_with_keys(NestedDict,
837
- _nest_flatten_with_keys,
838
- _nest_unflatten) # type: ignore[arg-type]
839
-
840
-
841
- # register :class:`FlattedDict` as a pytree
842
-
843
- def _flat_unflatten(
844
- static: Tuple[K, ...],
845
- leaves: Tuple[V, ...] | Tuple[Dict[K, V]],
846
- ):
847
- return FlattedDict(zip(static, leaves))
848
-
849
-
850
- jax.tree_util.register_pytree_with_keys(FlattedDict,
851
- _nest_flatten_with_keys,
852
- _flat_unflatten) # type: ignore[arg-type]
853
-
854
-
855
- @jax.tree_util.register_pytree_node_class
856
- class PrettyList(list, PrettyRepr):
857
- __module__ = 'brainstate.util'
858
-
859
- def __pretty_repr__(self):
860
- yield from yield_unique_pretty_repr_items(self, _list_repr_object, _list_repr_attr)
861
-
862
- def __repr__(self):
863
- return pretty_repr_object(self)
864
-
865
- def tree_flatten(self):
866
- return list(self), ()
867
-
868
- @classmethod
869
- def tree_unflatten(cls, aux_data, children):
870
- return cls(children)
871
-
872
-
873
- def _list_repr_attr(node: PrettyList):
874
- for v in node:
875
- if isinstance(v, list):
876
- v = PrettyList(v)
877
- if isinstance(v, dict):
878
- v = PrettyDict(v)
879
- if isinstance(v, PrettyDict):
880
- v = NestedStateRepr(v)
881
- yield PrettyAttr('', v)
882
-
883
-
884
- def _list_repr_object(node: PrettyDict):
885
- yield PrettyType('', value_sep='', start='[', end=']')
886
-
887
-
888
- def _repr_object_general(node: PrettyDict):
889
- """
890
- Generate a general representation of a PrettyDict object.
891
-
892
- This function is used to create a pretty representation of a PrettyDict
893
- object, which includes the type of the object and its value separator.
894
-
895
- Args:
896
- node (PrettyDict): The PrettyDict object to be represented.
897
-
898
- Yields:
899
- PrettyType: A PrettyType object representing the type of the node,
900
- with specified value separator, start, and end characters.
901
- """
902
- yield PrettyType(type(node), value_sep='=', start='(', end=')')
903
-
904
-
905
- def _repr_attribute_general(node):
906
- """
907
- Generate a pretty representation of the attributes of a node.
908
-
909
- This function iterates over the attributes of a given node and attempts
910
- to generate a pretty representation for each attribute. It handles
911
- conversion of lists and dictionaries to their pretty representation
912
- counterparts and yields a PrettyAttr object for each attribute.
913
-
914
- Args:
915
- node: The object whose attributes are to be represented.
916
-
917
- Yields:
918
- PrettyAttr: A PrettyAttr object representing the key and value of
919
- each attribute in a pretty format.
920
- """
921
- for k, v in vars(node).items():
922
- try:
923
- res = node.__pretty_repr_item__(k, v)
924
- if res is None:
925
- continue
926
- k, v = res
927
- except AttributeError:
928
- pass
929
-
930
- if k is None:
931
- continue
932
-
933
- # convert list to PrettyList
934
- if isinstance(v, list):
935
- v = PrettyList(v)
936
-
937
- # convert dict to PrettyDict
938
- if isinstance(v, dict):
939
- v = PrettyDict(v)
940
-
941
- # convert PrettyDict to NestedStateRepr
942
- if isinstance(v, PrettyDict):
943
- v = NestedStateRepr(v)
944
-
945
- yield PrettyAttr(k, v)