brainstate 0.1.8__py2.py3-none-any.whl → 0.1.9__py2.py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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 +509 -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.9.dist-info}/METADATA +91 -99
  127. brainstate-0.1.9.dist-info/RECORD +130 -0
  128. {brainstate-0.1.8.dist-info → brainstate-0.1.9.dist-info}/WHEEL +1 -1
  129. {brainstate-0.1.8.dist-info → brainstate-0.1.9.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.9.dist-info}/top_level.txt +0 -0
brainstate/util/struct.py CHANGED
@@ -1,523 +1,523 @@
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
- """Utilities for defining custom classes that can be used with jax transformations."""
19
-
20
- import collections
21
- import dataclasses
22
- from collections.abc import Hashable, Mapping
23
- from types import MappingProxyType
24
- from typing import Any, TypeVar
25
-
26
- import jax
27
- from typing_extensions import dataclass_transform # pytype: disable=not-supported-yet
28
-
29
- __all__ = [
30
- 'dataclass',
31
- 'field',
32
- 'PyTreeNode',
33
- 'FrozenDict',
34
- ]
35
-
36
- K = TypeVar('K')
37
- V = TypeVar('V')
38
- T = TypeVar('T')
39
-
40
-
41
- def field(pytree_node=True, *, metadata=None, **kwargs):
42
- return dataclasses.field(metadata=(metadata or {}) | {'pytree_node': pytree_node}, **kwargs)
43
-
44
-
45
- @dataclass_transform(field_specifiers=(field,)) # type: ignore[literal-required]
46
- def dataclass(clz: T, **kwargs) -> T:
47
- """
48
- Create a class which can be passed to functional transformations.
49
-
50
- .. note::
51
- Inherit from ``PyTreeNode`` instead to avoid type checking issues when
52
- using PyType.
53
-
54
- Jax transformations such as ``jax.jit`` and ``jax.grad`` require objects that are
55
- immutable and can be mapped over using the ``jax.tree_util`` methods.
56
- The ``dataclass`` decorator makes it easy to define custom classes that can be
57
- passed safely to Jax. For example::
58
-
59
- >>> import brainstate as brainstate
60
- >>> import jax
61
- >>> from typing import Any, Callable
62
-
63
- >>> @brainstate.util.dataclass
64
- ... class Model:
65
- ... params: Any
66
- ... # use pytree_node=False to indicate an attribute should not be touched
67
- ... # by Jax transformations.
68
- ... apply_fn: Callable = brainstate.util.field(pytree_node=False)
69
-
70
- ... def __apply__(self, *args):
71
- ... return self.apply_fn(*args)
72
-
73
- >>> params = {}
74
- >>> params_b = {}
75
- >>> apply_fn = lambda v, x: x
76
- >>> model = Model(params, apply_fn)
77
-
78
- >>> # model.params = params_b # Model is immutable. This will raise an error.
79
- >>> model_b = model.replace(params=params_b) # Use the replace method instead.
80
-
81
- >>> # This class can now be used safely in Jax to compute gradients w.r.t. the
82
- >>> # parameters.
83
- >>> model = Model(params, apply_fn)
84
- >>> loss_fn = lambda model: 3.
85
- >>> model_grad = jax.grad(loss_fn)(model)
86
-
87
- Note that dataclasses have an auto-generated ``__init__`` where
88
- the arguments of the constructor and the attributes of the created
89
- instance match 1:1. This correspondence is what makes these objects
90
- valid containers that work with JAX transformations and
91
- more generally the ``jax.tree_util`` library.
92
-
93
- Sometimes a "smart constructor" is desired, for example because
94
- some of the attributes can be (optionally) derived from others.
95
- The way to do this with Flax dataclasses is to make a static or
96
- class method that provides the smart constructor.
97
- This way the simple constructor used by ``jax.tree_util`` is
98
- preserved. Consider the following example::
99
-
100
- >>> @brainstate.util.dataclass
101
- ... class DirectionAndScaleKernel:
102
- ... direction: jax.Array
103
- ... scale: jax.Array
104
-
105
- ... @classmethod
106
- ... def create(cls, kernel):
107
- ... scale = jax.numpy.linalg.norm(kernel, axis=0, keepdims=True)
108
- ... direction = direction / scale
109
- ... return cls(direction, scale)
110
-
111
- Args:
112
- clz: the class that will be transformed by the decorator.
113
- Returns:
114
- The new class.
115
- """
116
- # check if already a flax dataclass
117
- if '_brainstate_dataclass' in clz.__dict__:
118
- return clz
119
-
120
- if 'frozen' not in kwargs.keys():
121
- kwargs['frozen'] = True
122
- data_clz = dataclasses.dataclass(**kwargs)(clz) # type: ignore
123
- meta_fields = []
124
- data_fields = []
125
- for field_info in dataclasses.fields(data_clz):
126
- is_pytree_node = field_info.metadata.get('pytree_node', True)
127
- if is_pytree_node:
128
- data_fields.append(field_info.name)
129
- else:
130
- meta_fields.append(field_info.name)
131
-
132
- def replace(self, **updates):
133
- """ "Returns a new object replacing the specified fields with new values."""
134
- return dataclasses.replace(self, **updates)
135
-
136
- data_clz.replace = replace
137
-
138
- # Remove this guard once minimux JAX version is >0.4.26.
139
- try:
140
- if hasattr(jax.tree_util, 'register_dataclass'):
141
- jax.tree_util.register_dataclass(
142
- data_clz, data_fields, meta_fields
143
- )
144
- else:
145
- raise NotImplementedError
146
- except NotImplementedError:
147
-
148
- def iterate_clz(x):
149
- meta = tuple(getattr(x, name) for name in meta_fields)
150
- data = tuple(getattr(x, name) for name in data_fields)
151
- return data, meta
152
-
153
- def iterate_clz_with_keys(x):
154
- meta = tuple(getattr(x, name) for name in meta_fields)
155
- data = tuple(
156
- (jax.tree_util.GetAttrKey(name), getattr(x, name))
157
- for name in data_fields
158
- )
159
- return data, meta
160
-
161
- def clz_from_iterable(meta, data):
162
- meta_args = tuple(zip(meta_fields, meta))
163
- data_args = tuple(zip(data_fields, data))
164
- kwargs = dict(meta_args + data_args)
165
- return data_clz(**kwargs)
166
-
167
- jax.tree_util.register_pytree_with_keys(
168
- data_clz,
169
- iterate_clz_with_keys,
170
- clz_from_iterable,
171
- iterate_clz,
172
- )
173
-
174
- # add a _brainstate_dataclass flag to distinguish from regular dataclasses
175
- data_clz._brainstate_dataclass = True # type: ignore[attr-defined]
176
-
177
- return data_clz # type: ignore
178
-
179
-
180
- TNode = TypeVar('TNode', bound='PyTreeNode')
181
-
182
-
183
- @dataclass_transform(field_specifiers=(field,)) # type: ignore[literal-required]
184
- class PyTreeNode:
185
- """Base class for dataclasses that should act like a JAX pytree node.
186
-
187
- See ``flax.struct.dataclass`` for the ``jax.tree_util`` behavior.
188
- This base class additionally avoids type checking errors when using PyType.
189
-
190
- Example::
191
-
192
- >>> import brainstate as brainstate
193
- >>> import jax
194
- >>> from typing import Any, Callable
195
-
196
- >>> class Model(brainstate.util.PyTreeNode):
197
- ... params: Any
198
- ... # use pytree_node=False to indicate an attribute should not be touched
199
- ... # by Jax transformations.
200
- ... apply_fn: Callable = brainstate.util.field(pytree_node=False)
201
-
202
- ... def __apply__(self, *args):
203
- ... return self.apply_fn(*args)
204
-
205
- >>> params = {}
206
- >>> params_b = {}
207
- >>> apply_fn = lambda v, x: x
208
- >>> model = Model(params, apply_fn)
209
-
210
- >>> # model.params = params_b # Model is immutable. This will raise an error.
211
- >>> model_b = model.replace(params=params_b) # Use the replace method instead.
212
-
213
- >>> # This class can now be used safely in Jax to compute gradients w.r.t. the
214
- >>> # parameters.
215
- >>> model = Model(params, apply_fn)
216
- >>> loss_fn = lambda model: 3.
217
- >>> model_grad = jax.grad(loss_fn)(model)
218
- """
219
-
220
- def __init_subclass__(cls, **kwargs):
221
- dataclass(cls, **kwargs) # pytype: disable=wrong-arg-types
222
-
223
- def __init__(self, *args, **kwargs):
224
- # stub for pytype
225
- raise NotImplementedError
226
-
227
- def replace(self: TNode, **overrides) -> TNode:
228
- # stub for pytype
229
- raise NotImplementedError
230
-
231
-
232
- def _indent(x, num_spaces):
233
- indent_str = ' ' * num_spaces
234
- lines = x.split('\n')
235
- assert not lines[-1]
236
- # skip the final line because it's empty and should not be indented.
237
- return '\n'.join(indent_str + line for line in lines[:-1]) + '\n'
238
-
239
-
240
- @jax.tree_util.register_pytree_with_keys_class
241
- class FrozenDict(Mapping[K, V]):
242
- """
243
- An immutable variant of the Python dict.
244
- """
245
-
246
- __slots__ = ('_dict', '_hash')
247
-
248
- def __init__(self, *args, __unsafe_skip_copy__=False, **kwargs): # pylint: disable=invalid-name
249
- # make sure the dict is as
250
- xs = dict(*args, **kwargs)
251
- if __unsafe_skip_copy__:
252
- self._dict = xs
253
- else:
254
- self._dict = _prepare_freeze(xs)
255
-
256
- self._hash = None
257
-
258
- def __getitem__(self, key):
259
- v = self._dict[key]
260
- if isinstance(v, dict):
261
- return FrozenDict(v)
262
- return v
263
-
264
- def __setitem__(self, key, value):
265
- raise ValueError('FrozenDict is immutable.')
266
-
267
- def __contains__(self, key):
268
- return key in self._dict
269
-
270
- def __iter__(self):
271
- return iter(self._dict)
272
-
273
- def __len__(self):
274
- return len(self._dict)
275
-
276
- def __repr__(self):
277
- return self.pretty_repr()
278
-
279
- def __reduce__(self):
280
- return FrozenDict, (self.unfreeze(),)
281
-
282
- def pretty_repr(self, num_spaces=4):
283
- """Returns an indented representation of the nested dictionary."""
284
-
285
- def pretty_dict(x):
286
- if not isinstance(x, dict):
287
- return repr(x)
288
- rep = ''
289
- for key, val in x.items():
290
- rep += f'{key}: {pretty_dict(val)},\n'
291
- if rep:
292
- return '{\n' + _indent(rep, num_spaces) + '}'
293
- else:
294
- return '{}'
295
-
296
- return f'FrozenDict({pretty_dict(self._dict)})'
297
-
298
- def __hash__(self):
299
- if self._hash is None:
300
- h = 0
301
- for key, value in self.items():
302
- h ^= hash((key, value))
303
- self._hash = h
304
- return self._hash
305
-
306
- def copy(
307
- self,
308
- add_or_replace: Mapping[K, V] = MappingProxyType({})
309
- ) -> 'FrozenDict[K, V]':
310
- """Create a new FrozenDict with additional or replaced entries."""
311
- return type(self)({**self, **unfreeze(add_or_replace)}) # type: ignore[arg-type]
312
-
313
- def keys(self):
314
- return FrozenKeysView(self)
315
-
316
- def values(self):
317
- return FrozenValuesView(self)
318
-
319
- def items(self):
320
- for key in self._dict:
321
- yield (key, self[key])
322
-
323
- def pop(self, key: K) -> tuple['FrozenDict[K, V]', V]:
324
- """Create a new FrozenDict where one entry is removed.
325
-
326
- Example::
327
-
328
- >>> variables = FrozenDict({'params': {...}, 'batch_stats': {...}})
329
- >>> new_variables, params = variables.pop('params')
330
-
331
- Args:
332
- key: the key to remove from the dict
333
- Returns:
334
- A pair with the new FrozenDict and the removed value.
335
- """
336
- value = self[key]
337
- new_dict = dict(self._dict)
338
- new_dict.pop(key)
339
- new_self = type(self)(new_dict)
340
- return new_self, value
341
-
342
- def unfreeze(self) -> dict[K, V]:
343
- """Unfreeze this FrozenDict.
344
-
345
- Returns:
346
- An unfrozen version of this FrozenDict instance.
347
- """
348
- return unfreeze(self)
349
-
350
- def tree_flatten_with_keys(self) -> tuple[tuple[Any, ...], Hashable]:
351
- """Flattens this FrozenDict.
352
-
353
- Returns:
354
- A flattened version of this FrozenDict instance.
355
- """
356
- sorted_keys = sorted(self._dict)
357
- return tuple(
358
- [(jax.tree_util.DictKey(k), self._dict[k]) for k in sorted_keys]
359
- ), tuple(sorted_keys)
360
-
361
- @classmethod
362
- def tree_unflatten(cls, keys, values):
363
- # data is already deep copied due to tree map mechanism
364
- # we can skip the deep copy in the constructor
365
- return cls({k: v for k, v in zip(keys, values)}, __unsafe_skip_copy__=True)
366
-
367
-
368
- def _prepare_freeze(xs: Any) -> Any:
369
- """Deep copy unfrozen dicts to make the dictionary FrozenDict safe."""
370
- if isinstance(xs, FrozenDict):
371
- # we can safely ref share the internal state of a FrozenDict
372
- # because it is immutable.
373
- return xs._dict # pylint: disable=protected-access
374
- if not isinstance(xs, dict):
375
- # return a leaf as is.
376
- return xs
377
- # recursively copy dictionary to avoid ref sharing
378
- return {key: _prepare_freeze(val) for key, val in xs.items()}
379
-
380
-
381
- def freeze(xs: Mapping[Any, Any]) -> FrozenDict[Any, Any]:
382
- """Freeze a nested dict.
383
-
384
- Makes a nested ``dict`` immutable by transforming it into ``FrozenDict``.
385
-
386
- Args:
387
- xs: Dictionary to freeze (a regualr Python dict).
388
- Returns:
389
- The frozen dictionary.
390
- """
391
- return FrozenDict(xs)
392
-
393
-
394
- def unfreeze(x: FrozenDict | dict[str, Any]) -> dict[Any, Any]:
395
- """Unfreeze a FrozenDict.
396
-
397
- Makes a mutable copy of a ``FrozenDict`` mutable by transforming
398
- it into (nested) dict.
399
-
400
- Args:
401
- x: Frozen dictionary to unfreeze.
402
- Returns:
403
- The unfrozen dictionary (a regular Python dict).
404
- """
405
- if isinstance(x, FrozenDict):
406
- # deep copy internal state of a FrozenDict
407
- # the dict branch would also work here but
408
- # it is much less performant because jax.tree_util.tree_map
409
- # uses an optimized C implementation.
410
- return jax.tree_util.tree_map(lambda y: y, x._dict) # type: ignore
411
- elif isinstance(x, dict):
412
- ys = {}
413
- for key, value in x.items():
414
- ys[key] = unfreeze(value)
415
- return ys
416
- else:
417
- return x
418
-
419
-
420
- def copy(
421
- x: FrozenDict | dict[str, Any],
422
- add_or_replace: FrozenDict[str, Any] | dict[str, Any] = FrozenDict({}),
423
- ) -> FrozenDict | dict[str, Any]:
424
- """Create a new dict with additional and/or replaced entries. This is a utility
425
- function that can act on either a FrozenDict or regular dict and mimics the
426
- behavior of ``FrozenDict.copy``.
427
-
428
- Example::
429
-
430
- >>> variables = FrozenDict({'params': {...}, 'batch_stats': {...}})
431
- >>> new_variables = copy(variables, {'additional_entries': 1})
432
-
433
- Args:
434
- x: the dictionary to be copied and updated
435
- add_or_replace: dictionary of key-value pairs to add or replace in the dict x
436
- Returns:
437
- A new dict with the additional and/or replaced entries.
438
- """
439
-
440
- if isinstance(x, FrozenDict):
441
- return x.copy(add_or_replace)
442
- elif isinstance(x, dict):
443
- new_dict = jax.tree_util.tree_map(
444
- lambda x: x, x
445
- ) # make a deep copy of dict x
446
- new_dict.update(add_or_replace)
447
- return new_dict
448
- raise TypeError(f'Expected FrozenDict or dict, got {type(x)}')
449
-
450
-
451
- def pop(
452
- x: FrozenDict | dict[str, Any], key: str
453
- ) -> tuple[FrozenDict | dict[str, Any], Any]:
454
- """Create a new dict where one entry is removed. This is a utility
455
- function that can act on either a FrozenDict or regular dict and
456
- mimics the behavior of ``FrozenDict.pop``.
457
-
458
- Example::
459
-
460
- >>> variables = FrozenDict({'params': {...}, 'batch_stats': {...}})
461
- >>> new_variables, params = pop(variables, 'params')
462
-
463
- Args:
464
- x: the dictionary to remove the entry from
465
- key: the key to remove from the dict
466
- Returns:
467
- A pair with the new dict and the removed value.
468
- """
469
-
470
- if isinstance(x, FrozenDict):
471
- return x.pop(key)
472
- elif isinstance(x, dict):
473
- new_dict = jax.tree_util.tree_map(
474
- lambda x: x, x
475
- ) # make a deep copy of dict x
476
- value = new_dict.pop(key)
477
- return new_dict, value
478
- raise TypeError(f'Expected FrozenDict or dict, got {type(x)}')
479
-
480
-
481
- def pretty_repr(x: Any, num_spaces: int = 4) -> str:
482
- """Returns an indented representation of the nested dictionary.
483
- This is a utility function that can act on either a FrozenDict or
484
- regular dict and mimics the behavior of ``FrozenDict.pretty_repr``.
485
- If x is any other dtype, this function will return ``repr(x)``.
486
-
487
- Args:
488
- x: the dictionary to be represented
489
- num_spaces: the number of space characters in each indentation level
490
- Returns:
491
- An indented string representation of the nested dictionary.
492
- """
493
-
494
- if isinstance(x, FrozenDict):
495
- return x.pretty_repr()
496
- else:
497
-
498
- def pretty_dict(x):
499
- if not isinstance(x, dict):
500
- return repr(x)
501
- rep = ''
502
- for key, val in x.items():
503
- rep += f'{key}: {pretty_dict(val)},\n'
504
- if rep:
505
- return '{\n' + _indent(rep, num_spaces) + '}'
506
- else:
507
- return '{}'
508
-
509
- return pretty_dict(x)
510
-
511
-
512
- class FrozenKeysView(collections.abc.KeysView):
513
- """A wrapper for a more useful repr of the keys in a frozen dict."""
514
-
515
- def __repr__(self):
516
- return f'frozen_dict_keys({list(self)})'
517
-
518
-
519
- class FrozenValuesView(collections.abc.ValuesView):
520
- """A wrapper for a more useful repr of the values in a frozen dict."""
521
-
522
- def __repr__(self):
523
- return f'frozen_dict_values({list(self)})'
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
+ """Utilities for defining custom classes that can be used with jax transformations."""
19
+
20
+ import collections
21
+ import dataclasses
22
+ from collections.abc import Hashable, Mapping
23
+ from types import MappingProxyType
24
+ from typing import Any, TypeVar
25
+
26
+ import jax
27
+ from typing_extensions import dataclass_transform # pytype: disable=not-supported-yet
28
+
29
+ __all__ = [
30
+ 'dataclass',
31
+ 'field',
32
+ 'PyTreeNode',
33
+ 'FrozenDict',
34
+ ]
35
+
36
+ K = TypeVar('K')
37
+ V = TypeVar('V')
38
+ T = TypeVar('T')
39
+
40
+
41
+ def field(pytree_node=True, *, metadata=None, **kwargs):
42
+ return dataclasses.field(metadata=(metadata or {}) | {'pytree_node': pytree_node}, **kwargs)
43
+
44
+
45
+ @dataclass_transform(field_specifiers=(field,)) # type: ignore[literal-required]
46
+ def dataclass(clz: T, **kwargs) -> T:
47
+ """
48
+ Create a class which can be passed to functional transformations.
49
+
50
+ .. note::
51
+ Inherit from ``PyTreeNode`` instead to avoid type checking issues when
52
+ using PyType.
53
+
54
+ Jax transformations such as ``jax.jit`` and ``jax.grad`` require objects that are
55
+ immutable and can be mapped over using the ``jax.tree_util`` methods.
56
+ The ``dataclass`` decorator makes it easy to define custom classes that can be
57
+ passed safely to Jax. For example::
58
+
59
+ >>> import brainstate as brainstate
60
+ >>> import jax
61
+ >>> from typing import Any, Callable
62
+
63
+ >>> @brainstate.util.dataclass
64
+ ... class Model:
65
+ ... params: Any
66
+ ... # use pytree_node=False to indicate an attribute should not be touched
67
+ ... # by Jax transformations.
68
+ ... apply_fn: Callable = brainstate.util.field(pytree_node=False)
69
+
70
+ ... def __apply__(self, *args):
71
+ ... return self.apply_fn(*args)
72
+
73
+ >>> params = {}
74
+ >>> params_b = {}
75
+ >>> apply_fn = lambda v, x: x
76
+ >>> model = Model(params, apply_fn)
77
+
78
+ >>> # model.params = params_b # Model is immutable. This will raise an error.
79
+ >>> model_b = model.replace(params=params_b) # Use the replace method instead.
80
+
81
+ >>> # This class can now be used safely in Jax to compute gradients w.r.t. the
82
+ >>> # parameters.
83
+ >>> model = Model(params, apply_fn)
84
+ >>> loss_fn = lambda model: 3.
85
+ >>> model_grad = jax.grad(loss_fn)(model)
86
+
87
+ Note that dataclasses have an auto-generated ``__init__`` where
88
+ the arguments of the constructor and the attributes of the created
89
+ instance match 1:1. This correspondence is what makes these objects
90
+ valid containers that work with JAX transformations and
91
+ more generally the ``jax.tree_util`` library.
92
+
93
+ Sometimes a "smart constructor" is desired, for example because
94
+ some of the attributes can be (optionally) derived from others.
95
+ The way to do this with Flax dataclasses is to make a static or
96
+ class method that provides the smart constructor.
97
+ This way the simple constructor used by ``jax.tree_util`` is
98
+ preserved. Consider the following example::
99
+
100
+ >>> @brainstate.util.dataclass
101
+ ... class DirectionAndScaleKernel:
102
+ ... direction: jax.Array
103
+ ... scale: jax.Array
104
+
105
+ ... @classmethod
106
+ ... def create(cls, kernel):
107
+ ... scale = jax.numpy.linalg.norm(kernel, axis=0, keepdims=True)
108
+ ... direction = direction / scale
109
+ ... return cls(direction, scale)
110
+
111
+ Args:
112
+ clz: the class that will be transformed by the decorator.
113
+ Returns:
114
+ The new class.
115
+ """
116
+ # check if already a flax dataclass
117
+ if '_brainstate_dataclass' in clz.__dict__:
118
+ return clz
119
+
120
+ if 'frozen' not in kwargs.keys():
121
+ kwargs['frozen'] = True
122
+ data_clz = dataclasses.dataclass(**kwargs)(clz) # type: ignore
123
+ meta_fields = []
124
+ data_fields = []
125
+ for field_info in dataclasses.fields(data_clz):
126
+ is_pytree_node = field_info.metadata.get('pytree_node', True)
127
+ if is_pytree_node:
128
+ data_fields.append(field_info.name)
129
+ else:
130
+ meta_fields.append(field_info.name)
131
+
132
+ def replace(self, **updates):
133
+ """ "Returns a new object replacing the specified fields with new values."""
134
+ return dataclasses.replace(self, **updates)
135
+
136
+ data_clz.replace = replace
137
+
138
+ # Remove this guard once minimux JAX version is >0.4.26.
139
+ try:
140
+ if hasattr(jax.tree_util, 'register_dataclass'):
141
+ jax.tree_util.register_dataclass(
142
+ data_clz, data_fields, meta_fields
143
+ )
144
+ else:
145
+ raise NotImplementedError
146
+ except NotImplementedError:
147
+
148
+ def iterate_clz(x):
149
+ meta = tuple(getattr(x, name) for name in meta_fields)
150
+ data = tuple(getattr(x, name) for name in data_fields)
151
+ return data, meta
152
+
153
+ def iterate_clz_with_keys(x):
154
+ meta = tuple(getattr(x, name) for name in meta_fields)
155
+ data = tuple(
156
+ (jax.tree_util.GetAttrKey(name), getattr(x, name))
157
+ for name in data_fields
158
+ )
159
+ return data, meta
160
+
161
+ def clz_from_iterable(meta, data):
162
+ meta_args = tuple(zip(meta_fields, meta))
163
+ data_args = tuple(zip(data_fields, data))
164
+ kwargs = dict(meta_args + data_args)
165
+ return data_clz(**kwargs)
166
+
167
+ jax.tree_util.register_pytree_with_keys(
168
+ data_clz,
169
+ iterate_clz_with_keys,
170
+ clz_from_iterable,
171
+ iterate_clz,
172
+ )
173
+
174
+ # add a _brainstate_dataclass flag to distinguish from regular dataclasses
175
+ data_clz._brainstate_dataclass = True # type: ignore[attr-defined]
176
+
177
+ return data_clz # type: ignore
178
+
179
+
180
+ TNode = TypeVar('TNode', bound='PyTreeNode')
181
+
182
+
183
+ @dataclass_transform(field_specifiers=(field,)) # type: ignore[literal-required]
184
+ class PyTreeNode:
185
+ """Base class for dataclasses that should act like a JAX pytree node.
186
+
187
+ See ``flax.struct.dataclass`` for the ``jax.tree_util`` behavior.
188
+ This base class additionally avoids type checking errors when using PyType.
189
+
190
+ Example::
191
+
192
+ >>> import brainstate as brainstate
193
+ >>> import jax
194
+ >>> from typing import Any, Callable
195
+
196
+ >>> class Model(brainstate.util.PyTreeNode):
197
+ ... params: Any
198
+ ... # use pytree_node=False to indicate an attribute should not be touched
199
+ ... # by Jax transformations.
200
+ ... apply_fn: Callable = brainstate.util.field(pytree_node=False)
201
+
202
+ ... def __apply__(self, *args):
203
+ ... return self.apply_fn(*args)
204
+
205
+ >>> params = {}
206
+ >>> params_b = {}
207
+ >>> apply_fn = lambda v, x: x
208
+ >>> model = Model(params, apply_fn)
209
+
210
+ >>> # model.params = params_b # Model is immutable. This will raise an error.
211
+ >>> model_b = model.replace(params=params_b) # Use the replace method instead.
212
+
213
+ >>> # This class can now be used safely in Jax to compute gradients w.r.t. the
214
+ >>> # parameters.
215
+ >>> model = Model(params, apply_fn)
216
+ >>> loss_fn = lambda model: 3.
217
+ >>> model_grad = jax.grad(loss_fn)(model)
218
+ """
219
+
220
+ def __init_subclass__(cls, **kwargs):
221
+ dataclass(cls, **kwargs) # pytype: disable=wrong-arg-types
222
+
223
+ def __init__(self, *args, **kwargs):
224
+ # stub for pytype
225
+ raise NotImplementedError
226
+
227
+ def replace(self: TNode, **overrides) -> TNode:
228
+ # stub for pytype
229
+ raise NotImplementedError
230
+
231
+
232
+ def _indent(x, num_spaces):
233
+ indent_str = ' ' * num_spaces
234
+ lines = x.split('\n')
235
+ assert not lines[-1]
236
+ # skip the final line because it's empty and should not be indented.
237
+ return '\n'.join(indent_str + line for line in lines[:-1]) + '\n'
238
+
239
+
240
+ @jax.tree_util.register_pytree_with_keys_class
241
+ class FrozenDict(Mapping[K, V]):
242
+ """
243
+ An immutable variant of the Python dict.
244
+ """
245
+
246
+ __slots__ = ('_dict', '_hash')
247
+
248
+ def __init__(self, *args, __unsafe_skip_copy__=False, **kwargs): # pylint: disable=invalid-name
249
+ # make sure the dict is as
250
+ xs = dict(*args, **kwargs)
251
+ if __unsafe_skip_copy__:
252
+ self._dict = xs
253
+ else:
254
+ self._dict = _prepare_freeze(xs)
255
+
256
+ self._hash = None
257
+
258
+ def __getitem__(self, key):
259
+ v = self._dict[key]
260
+ if isinstance(v, dict):
261
+ return FrozenDict(v)
262
+ return v
263
+
264
+ def __setitem__(self, key, value):
265
+ raise ValueError('FrozenDict is immutable.')
266
+
267
+ def __contains__(self, key):
268
+ return key in self._dict
269
+
270
+ def __iter__(self):
271
+ return iter(self._dict)
272
+
273
+ def __len__(self):
274
+ return len(self._dict)
275
+
276
+ def __repr__(self):
277
+ return self.pretty_repr()
278
+
279
+ def __reduce__(self):
280
+ return FrozenDict, (self.unfreeze(),)
281
+
282
+ def pretty_repr(self, num_spaces=4):
283
+ """Returns an indented representation of the nested dictionary."""
284
+
285
+ def pretty_dict(x):
286
+ if not isinstance(x, dict):
287
+ return repr(x)
288
+ rep = ''
289
+ for key, val in x.items():
290
+ rep += f'{key}: {pretty_dict(val)},\n'
291
+ if rep:
292
+ return '{\n' + _indent(rep, num_spaces) + '}'
293
+ else:
294
+ return '{}'
295
+
296
+ return f'FrozenDict({pretty_dict(self._dict)})'
297
+
298
+ def __hash__(self):
299
+ if self._hash is None:
300
+ h = 0
301
+ for key, value in self.items():
302
+ h ^= hash((key, value))
303
+ self._hash = h
304
+ return self._hash
305
+
306
+ def copy(
307
+ self,
308
+ add_or_replace: Mapping[K, V] = MappingProxyType({})
309
+ ) -> 'FrozenDict[K, V]':
310
+ """Create a new FrozenDict with additional or replaced entries."""
311
+ return type(self)({**self, **unfreeze(add_or_replace)}) # type: ignore[arg-type]
312
+
313
+ def keys(self):
314
+ return FrozenKeysView(self)
315
+
316
+ def values(self):
317
+ return FrozenValuesView(self)
318
+
319
+ def items(self):
320
+ for key in self._dict:
321
+ yield (key, self[key])
322
+
323
+ def pop(self, key: K) -> tuple['FrozenDict[K, V]', V]:
324
+ """Create a new FrozenDict where one entry is removed.
325
+
326
+ Example::
327
+
328
+ >>> variables = FrozenDict({'params': {...}, 'batch_stats': {...}})
329
+ >>> new_variables, params = variables.pop('params')
330
+
331
+ Args:
332
+ key: the key to remove from the dict
333
+ Returns:
334
+ A pair with the new FrozenDict and the removed value.
335
+ """
336
+ value = self[key]
337
+ new_dict = dict(self._dict)
338
+ new_dict.pop(key)
339
+ new_self = type(self)(new_dict)
340
+ return new_self, value
341
+
342
+ def unfreeze(self) -> dict[K, V]:
343
+ """Unfreeze this FrozenDict.
344
+
345
+ Returns:
346
+ An unfrozen version of this FrozenDict instance.
347
+ """
348
+ return unfreeze(self)
349
+
350
+ def tree_flatten_with_keys(self) -> tuple[tuple[Any, ...], Hashable]:
351
+ """Flattens this FrozenDict.
352
+
353
+ Returns:
354
+ A flattened version of this FrozenDict instance.
355
+ """
356
+ sorted_keys = sorted(self._dict)
357
+ return tuple(
358
+ [(jax.tree_util.DictKey(k), self._dict[k]) for k in sorted_keys]
359
+ ), tuple(sorted_keys)
360
+
361
+ @classmethod
362
+ def tree_unflatten(cls, keys, values):
363
+ # data is already deep copied due to tree map mechanism
364
+ # we can skip the deep copy in the constructor
365
+ return cls({k: v for k, v in zip(keys, values)}, __unsafe_skip_copy__=True)
366
+
367
+
368
+ def _prepare_freeze(xs: Any) -> Any:
369
+ """Deep copy unfrozen dicts to make the dictionary FrozenDict safe."""
370
+ if isinstance(xs, FrozenDict):
371
+ # we can safely ref share the internal state of a FrozenDict
372
+ # because it is immutable.
373
+ return xs._dict # pylint: disable=protected-access
374
+ if not isinstance(xs, dict):
375
+ # return a leaf as is.
376
+ return xs
377
+ # recursively copy dictionary to avoid ref sharing
378
+ return {key: _prepare_freeze(val) for key, val in xs.items()}
379
+
380
+
381
+ def freeze(xs: Mapping[Any, Any]) -> FrozenDict[Any, Any]:
382
+ """Freeze a nested dict.
383
+
384
+ Makes a nested ``dict`` immutable by transforming it into ``FrozenDict``.
385
+
386
+ Args:
387
+ xs: Dictionary to freeze (a regualr Python dict).
388
+ Returns:
389
+ The frozen dictionary.
390
+ """
391
+ return FrozenDict(xs)
392
+
393
+
394
+ def unfreeze(x: FrozenDict | dict[str, Any]) -> dict[Any, Any]:
395
+ """Unfreeze a FrozenDict.
396
+
397
+ Makes a mutable copy of a ``FrozenDict`` mutable by transforming
398
+ it into (nested) dict.
399
+
400
+ Args:
401
+ x: Frozen dictionary to unfreeze.
402
+ Returns:
403
+ The unfrozen dictionary (a regular Python dict).
404
+ """
405
+ if isinstance(x, FrozenDict):
406
+ # deep copy internal state of a FrozenDict
407
+ # the dict branch would also work here but
408
+ # it is much less performant because jax.tree_util.tree_map
409
+ # uses an optimized C implementation.
410
+ return jax.tree_util.tree_map(lambda y: y, x._dict) # type: ignore
411
+ elif isinstance(x, dict):
412
+ ys = {}
413
+ for key, value in x.items():
414
+ ys[key] = unfreeze(value)
415
+ return ys
416
+ else:
417
+ return x
418
+
419
+
420
+ def copy(
421
+ x: FrozenDict | dict[str, Any],
422
+ add_or_replace: FrozenDict[str, Any] | dict[str, Any] = FrozenDict({}),
423
+ ) -> FrozenDict | dict[str, Any]:
424
+ """Create a new dict with additional and/or replaced entries. This is a utility
425
+ function that can act on either a FrozenDict or regular dict and mimics the
426
+ behavior of ``FrozenDict.copy``.
427
+
428
+ Example::
429
+
430
+ >>> variables = FrozenDict({'params': {...}, 'batch_stats': {...}})
431
+ >>> new_variables = copy(variables, {'additional_entries': 1})
432
+
433
+ Args:
434
+ x: the dictionary to be copied and updated
435
+ add_or_replace: dictionary of key-value pairs to add or replace in the dict x
436
+ Returns:
437
+ A new dict with the additional and/or replaced entries.
438
+ """
439
+
440
+ if isinstance(x, FrozenDict):
441
+ return x.copy(add_or_replace)
442
+ elif isinstance(x, dict):
443
+ new_dict = jax.tree_util.tree_map(
444
+ lambda x: x, x
445
+ ) # make a deep copy of dict x
446
+ new_dict.update(add_or_replace)
447
+ return new_dict
448
+ raise TypeError(f'Expected FrozenDict or dict, got {type(x)}')
449
+
450
+
451
+ def pop(
452
+ x: FrozenDict | dict[str, Any], key: str
453
+ ) -> tuple[FrozenDict | dict[str, Any], Any]:
454
+ """Create a new dict where one entry is removed. This is a utility
455
+ function that can act on either a FrozenDict or regular dict and
456
+ mimics the behavior of ``FrozenDict.pop``.
457
+
458
+ Example::
459
+
460
+ >>> variables = FrozenDict({'params': {...}, 'batch_stats': {...}})
461
+ >>> new_variables, params = pop(variables, 'params')
462
+
463
+ Args:
464
+ x: the dictionary to remove the entry from
465
+ key: the key to remove from the dict
466
+ Returns:
467
+ A pair with the new dict and the removed value.
468
+ """
469
+
470
+ if isinstance(x, FrozenDict):
471
+ return x.pop(key)
472
+ elif isinstance(x, dict):
473
+ new_dict = jax.tree_util.tree_map(
474
+ lambda x: x, x
475
+ ) # make a deep copy of dict x
476
+ value = new_dict.pop(key)
477
+ return new_dict, value
478
+ raise TypeError(f'Expected FrozenDict or dict, got {type(x)}')
479
+
480
+
481
+ def pretty_repr(x: Any, num_spaces: int = 4) -> str:
482
+ """Returns an indented representation of the nested dictionary.
483
+ This is a utility function that can act on either a FrozenDict or
484
+ regular dict and mimics the behavior of ``FrozenDict.pretty_repr``.
485
+ If x is any other dtype, this function will return ``repr(x)``.
486
+
487
+ Args:
488
+ x: the dictionary to be represented
489
+ num_spaces: the number of space characters in each indentation level
490
+ Returns:
491
+ An indented string representation of the nested dictionary.
492
+ """
493
+
494
+ if isinstance(x, FrozenDict):
495
+ return x.pretty_repr()
496
+ else:
497
+
498
+ def pretty_dict(x):
499
+ if not isinstance(x, dict):
500
+ return repr(x)
501
+ rep = ''
502
+ for key, val in x.items():
503
+ rep += f'{key}: {pretty_dict(val)},\n'
504
+ if rep:
505
+ return '{\n' + _indent(rep, num_spaces) + '}'
506
+ else:
507
+ return '{}'
508
+
509
+ return pretty_dict(x)
510
+
511
+
512
+ class FrozenKeysView(collections.abc.KeysView):
513
+ """A wrapper for a more useful repr of the keys in a frozen dict."""
514
+
515
+ def __repr__(self):
516
+ return f'frozen_dict_keys({list(self)})'
517
+
518
+
519
+ class FrozenValuesView(collections.abc.ValuesView):
520
+ """A wrapper for a more useful repr of the values in a frozen dict."""
521
+
522
+ def __repr__(self):
523
+ return f'frozen_dict_values({list(self)})'