brainstate 0.1.8__py2.py3-none-any.whl → 0.1.10__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 (133) hide show
  1. brainstate/__init__.py +58 -51
  2. brainstate/_compatible_import.py +148 -148
  3. brainstate/_state.py +1605 -1663
  4. brainstate/_state_test.py +52 -52
  5. brainstate/_utils.py +47 -47
  6. brainstate/augment/__init__.py +30 -30
  7. brainstate/augment/_autograd.py +778 -778
  8. brainstate/augment/_autograd_test.py +1289 -1289
  9. brainstate/augment/_eval_shape.py +99 -99
  10. brainstate/augment/_eval_shape_test.py +38 -38
  11. brainstate/augment/_mapping.py +1060 -1060
  12. brainstate/augment/_mapping_test.py +597 -597
  13. brainstate/augment/_random.py +151 -151
  14. brainstate/compile/__init__.py +38 -38
  15. brainstate/compile/_ad_checkpoint.py +204 -204
  16. brainstate/compile/_ad_checkpoint_test.py +49 -49
  17. brainstate/compile/_conditions.py +256 -256
  18. brainstate/compile/_conditions_test.py +220 -220
  19. brainstate/compile/_error_if.py +92 -92
  20. brainstate/compile/_error_if_test.py +52 -52
  21. brainstate/compile/_jit.py +346 -346
  22. brainstate/compile/_jit_test.py +143 -143
  23. brainstate/compile/_loop_collect_return.py +536 -536
  24. brainstate/compile/_loop_collect_return_test.py +58 -58
  25. brainstate/compile/_loop_no_collection.py +184 -184
  26. brainstate/compile/_loop_no_collection_test.py +50 -50
  27. brainstate/compile/_make_jaxpr.py +888 -888
  28. brainstate/compile/_make_jaxpr_test.py +156 -156
  29. brainstate/compile/_progress_bar.py +202 -202
  30. brainstate/compile/_unvmap.py +159 -159
  31. brainstate/compile/_util.py +147 -147
  32. brainstate/environ.py +563 -563
  33. brainstate/environ_test.py +62 -62
  34. brainstate/functional/__init__.py +27 -26
  35. brainstate/graph/__init__.py +29 -29
  36. brainstate/graph/_graph_node.py +244 -244
  37. brainstate/graph/_graph_node_test.py +73 -73
  38. brainstate/graph/_graph_operation.py +1738 -1738
  39. brainstate/graph/_graph_operation_test.py +563 -563
  40. brainstate/init/__init__.py +26 -26
  41. brainstate/init/_base.py +52 -52
  42. brainstate/init/_generic.py +244 -244
  43. brainstate/init/_random_inits.py +553 -553
  44. brainstate/init/_random_inits_test.py +149 -149
  45. brainstate/init/_regular_inits.py +105 -105
  46. brainstate/init/_regular_inits_test.py +50 -50
  47. brainstate/mixin.py +365 -363
  48. brainstate/mixin_test.py +77 -73
  49. brainstate/nn/__init__.py +135 -131
  50. brainstate/{functional → nn}/_activations.py +808 -813
  51. brainstate/{functional → nn}/_activations_test.py +331 -331
  52. brainstate/nn/_collective_ops.py +514 -514
  53. brainstate/nn/_collective_ops_test.py +43 -43
  54. brainstate/nn/_common.py +178 -178
  55. brainstate/nn/_conv.py +501 -501
  56. brainstate/nn/_conv_test.py +238 -238
  57. brainstate/nn/_delay.py +588 -502
  58. brainstate/nn/_delay_test.py +238 -184
  59. brainstate/nn/_dropout.py +426 -426
  60. brainstate/nn/_dropout_test.py +100 -100
  61. brainstate/nn/_dynamics.py +1343 -1343
  62. brainstate/nn/_dynamics_test.py +78 -78
  63. brainstate/nn/_elementwise.py +1119 -1119
  64. brainstate/nn/_elementwise_test.py +169 -169
  65. brainstate/nn/_embedding.py +58 -58
  66. brainstate/nn/_exp_euler.py +92 -92
  67. brainstate/nn/_exp_euler_test.py +35 -35
  68. brainstate/nn/_fixedprob.py +239 -239
  69. brainstate/nn/_fixedprob_test.py +114 -114
  70. brainstate/nn/_inputs.py +608 -608
  71. brainstate/nn/_linear.py +424 -424
  72. brainstate/nn/_linear_mv.py +83 -83
  73. brainstate/nn/_linear_mv_test.py +120 -120
  74. brainstate/nn/_linear_test.py +107 -107
  75. brainstate/nn/_ltp.py +28 -28
  76. brainstate/nn/_module.py +377 -377
  77. brainstate/nn/_module_test.py +40 -40
  78. brainstate/nn/_neuron.py +705 -705
  79. brainstate/nn/_neuron_test.py +161 -161
  80. brainstate/nn/_normalizations.py +975 -918
  81. brainstate/nn/_normalizations_test.py +73 -73
  82. brainstate/{functional → nn}/_others.py +46 -46
  83. brainstate/nn/_poolings.py +1177 -1177
  84. brainstate/nn/_poolings_test.py +217 -217
  85. brainstate/nn/_projection.py +486 -486
  86. brainstate/nn/_rate_rnns.py +554 -554
  87. brainstate/nn/_rate_rnns_test.py +63 -63
  88. brainstate/nn/_readout.py +209 -209
  89. brainstate/nn/_readout_test.py +53 -53
  90. brainstate/nn/_stp.py +236 -236
  91. brainstate/nn/_synapse.py +505 -505
  92. brainstate/nn/_synapse_test.py +131 -131
  93. brainstate/nn/_synaptic_projection.py +423 -423
  94. brainstate/nn/_synouts.py +162 -162
  95. brainstate/nn/_synouts_test.py +57 -57
  96. brainstate/nn/_utils.py +89 -89
  97. brainstate/nn/metrics.py +388 -388
  98. brainstate/optim/__init__.py +38 -38
  99. brainstate/optim/_base.py +64 -64
  100. brainstate/optim/_lr_scheduler.py +448 -448
  101. brainstate/optim/_lr_scheduler_test.py +50 -50
  102. brainstate/optim/_optax_optimizer.py +152 -152
  103. brainstate/optim/_optax_optimizer_test.py +53 -53
  104. brainstate/optim/_sgd_optimizer.py +1104 -1104
  105. brainstate/random/__init__.py +24 -24
  106. brainstate/random/_rand_funs.py +3616 -3616
  107. brainstate/random/_rand_funs_test.py +567 -567
  108. brainstate/random/_rand_seed.py +210 -210
  109. brainstate/random/_rand_seed_test.py +48 -48
  110. brainstate/random/_rand_state.py +1409 -1409
  111. brainstate/random/_random_for_unit.py +52 -52
  112. brainstate/surrogate.py +1957 -1957
  113. brainstate/transform.py +23 -23
  114. brainstate/typing.py +304 -304
  115. brainstate/util/__init__.py +50 -50
  116. brainstate/util/caller.py +98 -98
  117. brainstate/util/error.py +55 -55
  118. brainstate/util/filter.py +469 -469
  119. brainstate/util/others.py +540 -540
  120. brainstate/util/pretty_pytree.py +945 -945
  121. brainstate/util/pretty_pytree_test.py +159 -159
  122. brainstate/util/pretty_repr.py +328 -328
  123. brainstate/util/pretty_table.py +2954 -2954
  124. brainstate/util/scaling.py +258 -258
  125. brainstate/util/struct.py +523 -523
  126. {brainstate-0.1.8.dist-info → brainstate-0.1.10.dist-info}/METADATA +91 -99
  127. brainstate-0.1.10.dist-info/RECORD +130 -0
  128. {brainstate-0.1.8.dist-info → brainstate-0.1.10.dist-info}/WHEEL +1 -1
  129. {brainstate-0.1.8.dist-info → brainstate-0.1.10.dist-info/licenses}/LICENSE +202 -202
  130. brainstate/functional/_normalization.py +0 -81
  131. brainstate/functional/_spikes.py +0 -204
  132. brainstate-0.1.8.dist-info/RECORD +0 -132
  133. {brainstate-0.1.8.dist-info → brainstate-0.1.10.dist-info}/top_level.txt +0 -0
@@ -1,945 +1,945 @@
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)
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)