brainstate 0.1.10__py2.py3-none-any.whl → 0.2.1__py2.py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (163) hide show
  1. brainstate/__init__.py +169 -58
  2. brainstate/_compatible_import.py +340 -148
  3. brainstate/_compatible_import_test.py +681 -0
  4. brainstate/_deprecation.py +210 -0
  5. brainstate/_deprecation_test.py +2319 -0
  6. brainstate/{util/error.py → _error.py} +45 -55
  7. brainstate/_state.py +1652 -1605
  8. brainstate/_state_test.py +52 -52
  9. brainstate/_utils.py +47 -47
  10. brainstate/environ.py +1495 -563
  11. brainstate/environ_test.py +1223 -62
  12. brainstate/graph/__init__.py +22 -29
  13. brainstate/graph/_node.py +240 -0
  14. brainstate/graph/_node_test.py +589 -0
  15. brainstate/graph/{_graph_operation.py → _operation.py} +1624 -1738
  16. brainstate/graph/_operation_test.py +1147 -0
  17. brainstate/mixin.py +1433 -365
  18. brainstate/mixin_test.py +1017 -77
  19. brainstate/nn/__init__.py +137 -135
  20. brainstate/nn/_activations.py +1100 -808
  21. brainstate/nn/_activations_test.py +354 -331
  22. brainstate/nn/_collective_ops.py +633 -514
  23. brainstate/nn/_collective_ops_test.py +774 -43
  24. brainstate/nn/_common.py +226 -178
  25. brainstate/nn/_common_test.py +154 -0
  26. brainstate/nn/_conv.py +2010 -501
  27. brainstate/nn/_conv_test.py +849 -238
  28. brainstate/nn/_delay.py +575 -588
  29. brainstate/nn/_delay_test.py +243 -238
  30. brainstate/nn/_dropout.py +618 -426
  31. brainstate/nn/_dropout_test.py +477 -100
  32. brainstate/nn/_dynamics.py +1267 -1343
  33. brainstate/nn/_dynamics_test.py +67 -78
  34. brainstate/nn/_elementwise.py +1298 -1119
  35. brainstate/nn/_elementwise_test.py +830 -169
  36. brainstate/nn/_embedding.py +408 -58
  37. brainstate/nn/_embedding_test.py +156 -0
  38. brainstate/nn/{_fixedprob.py → _event_fixedprob.py} +233 -239
  39. brainstate/nn/{_fixedprob_test.py → _event_fixedprob_test.py} +115 -114
  40. brainstate/nn/{_linear_mv.py → _event_linear.py} +83 -83
  41. brainstate/nn/{_linear_mv_test.py → _event_linear_test.py} +121 -120
  42. brainstate/nn/_exp_euler.py +254 -92
  43. brainstate/nn/_exp_euler_test.py +377 -35
  44. brainstate/nn/_linear.py +744 -424
  45. brainstate/nn/_linear_test.py +475 -107
  46. brainstate/nn/_metrics.py +1070 -0
  47. brainstate/nn/_metrics_test.py +611 -0
  48. brainstate/nn/_module.py +384 -377
  49. brainstate/nn/_module_test.py +40 -40
  50. brainstate/nn/_normalizations.py +1334 -975
  51. brainstate/nn/_normalizations_test.py +699 -73
  52. brainstate/nn/_paddings.py +1020 -0
  53. brainstate/nn/_paddings_test.py +723 -0
  54. brainstate/nn/_poolings.py +2239 -1177
  55. brainstate/nn/_poolings_test.py +953 -217
  56. brainstate/nn/{_rate_rnns.py → _rnns.py} +946 -554
  57. brainstate/nn/_rnns_test.py +593 -0
  58. brainstate/nn/_utils.py +216 -89
  59. brainstate/nn/_utils_test.py +402 -0
  60. brainstate/{init/_random_inits.py → nn/init.py} +809 -553
  61. brainstate/{init/_random_inits_test.py → nn/init_test.py} +180 -149
  62. brainstate/random/__init__.py +270 -24
  63. brainstate/random/_rand_funs.py +3938 -3616
  64. brainstate/random/_rand_funs_test.py +640 -567
  65. brainstate/random/_rand_seed.py +675 -210
  66. brainstate/random/_rand_seed_test.py +48 -48
  67. brainstate/random/_rand_state.py +1617 -1409
  68. brainstate/random/_rand_state_test.py +551 -0
  69. brainstate/transform/__init__.py +59 -0
  70. brainstate/transform/_ad_checkpoint.py +176 -0
  71. brainstate/{compile → transform}/_ad_checkpoint_test.py +49 -49
  72. brainstate/{augment → transform}/_autograd.py +1025 -778
  73. brainstate/{augment → transform}/_autograd_test.py +1289 -1289
  74. brainstate/transform/_conditions.py +316 -0
  75. brainstate/{compile → transform}/_conditions_test.py +220 -220
  76. brainstate/{compile → transform}/_error_if.py +94 -92
  77. brainstate/{compile → transform}/_error_if_test.py +52 -52
  78. brainstate/transform/_eval_shape.py +145 -0
  79. brainstate/{augment → transform}/_eval_shape_test.py +38 -38
  80. brainstate/{compile → transform}/_jit.py +399 -346
  81. brainstate/{compile → transform}/_jit_test.py +143 -143
  82. brainstate/{compile → transform}/_loop_collect_return.py +675 -536
  83. brainstate/{compile → transform}/_loop_collect_return_test.py +58 -58
  84. brainstate/{compile → transform}/_loop_no_collection.py +283 -184
  85. brainstate/{compile → transform}/_loop_no_collection_test.py +50 -50
  86. brainstate/transform/_make_jaxpr.py +2016 -0
  87. brainstate/transform/_make_jaxpr_test.py +1510 -0
  88. brainstate/transform/_mapping.py +529 -0
  89. brainstate/transform/_mapping_test.py +194 -0
  90. brainstate/{compile → transform}/_progress_bar.py +255 -202
  91. brainstate/{augment → transform}/_random.py +171 -151
  92. brainstate/{compile → transform}/_unvmap.py +256 -159
  93. brainstate/transform/_util.py +286 -0
  94. brainstate/typing.py +837 -304
  95. brainstate/typing_test.py +780 -0
  96. brainstate/util/__init__.py +27 -50
  97. brainstate/util/_others.py +1025 -0
  98. brainstate/util/_others_test.py +962 -0
  99. brainstate/util/_pretty_pytree.py +1301 -0
  100. brainstate/util/_pretty_pytree_test.py +675 -0
  101. brainstate/util/{pretty_repr.py → _pretty_repr.py} +462 -328
  102. brainstate/util/_pretty_repr_test.py +696 -0
  103. brainstate/util/filter.py +945 -469
  104. brainstate/util/filter_test.py +912 -0
  105. brainstate/util/struct.py +910 -523
  106. brainstate/util/struct_test.py +602 -0
  107. {brainstate-0.1.10.dist-info → brainstate-0.2.1.dist-info}/METADATA +108 -91
  108. brainstate-0.2.1.dist-info/RECORD +111 -0
  109. {brainstate-0.1.10.dist-info → brainstate-0.2.1.dist-info}/licenses/LICENSE +202 -202
  110. brainstate/augment/__init__.py +0 -30
  111. brainstate/augment/_eval_shape.py +0 -99
  112. brainstate/augment/_mapping.py +0 -1060
  113. brainstate/augment/_mapping_test.py +0 -597
  114. brainstate/compile/__init__.py +0 -38
  115. brainstate/compile/_ad_checkpoint.py +0 -204
  116. brainstate/compile/_conditions.py +0 -256
  117. brainstate/compile/_make_jaxpr.py +0 -888
  118. brainstate/compile/_make_jaxpr_test.py +0 -156
  119. brainstate/compile/_util.py +0 -147
  120. brainstate/functional/__init__.py +0 -27
  121. brainstate/graph/_graph_node.py +0 -244
  122. brainstate/graph/_graph_node_test.py +0 -73
  123. brainstate/graph/_graph_operation_test.py +0 -563
  124. brainstate/init/__init__.py +0 -26
  125. brainstate/init/_base.py +0 -52
  126. brainstate/init/_generic.py +0 -244
  127. brainstate/init/_regular_inits.py +0 -105
  128. brainstate/init/_regular_inits_test.py +0 -50
  129. brainstate/nn/_inputs.py +0 -608
  130. brainstate/nn/_ltp.py +0 -28
  131. brainstate/nn/_neuron.py +0 -705
  132. brainstate/nn/_neuron_test.py +0 -161
  133. brainstate/nn/_others.py +0 -46
  134. brainstate/nn/_projection.py +0 -486
  135. brainstate/nn/_rate_rnns_test.py +0 -63
  136. brainstate/nn/_readout.py +0 -209
  137. brainstate/nn/_readout_test.py +0 -53
  138. brainstate/nn/_stp.py +0 -236
  139. brainstate/nn/_synapse.py +0 -505
  140. brainstate/nn/_synapse_test.py +0 -131
  141. brainstate/nn/_synaptic_projection.py +0 -423
  142. brainstate/nn/_synouts.py +0 -162
  143. brainstate/nn/_synouts_test.py +0 -57
  144. brainstate/nn/metrics.py +0 -388
  145. brainstate/optim/__init__.py +0 -38
  146. brainstate/optim/_base.py +0 -64
  147. brainstate/optim/_lr_scheduler.py +0 -448
  148. brainstate/optim/_lr_scheduler_test.py +0 -50
  149. brainstate/optim/_optax_optimizer.py +0 -152
  150. brainstate/optim/_optax_optimizer_test.py +0 -53
  151. brainstate/optim/_sgd_optimizer.py +0 -1104
  152. brainstate/random/_random_for_unit.py +0 -52
  153. brainstate/surrogate.py +0 -1957
  154. brainstate/transform.py +0 -23
  155. brainstate/util/caller.py +0 -98
  156. brainstate/util/others.py +0 -540
  157. brainstate/util/pretty_pytree.py +0 -945
  158. brainstate/util/pretty_pytree_test.py +0 -159
  159. brainstate/util/pretty_table.py +0 -2954
  160. brainstate/util/scaling.py +0 -258
  161. brainstate-0.1.10.dist-info/RECORD +0 -130
  162. {brainstate-0.1.10.dist-info → brainstate-0.2.1.dist-info}/WHEEL +0 -0
  163. {brainstate-0.1.10.dist-info → brainstate-0.2.1.dist-info}/top_level.txt +0 -0
brainstate/nn/_module.py CHANGED
@@ -1,377 +1,384 @@
1
- # Copyright 2024 BDP Ecosystem Limited. All Rights Reserved.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing, software
10
- # distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
- # ==============================================================================
15
-
16
- # -*- coding: utf-8 -*-
17
-
18
-
19
- """
20
- All the basic classes for neural networks in ``brainstate``.
21
-
22
- The basic classes include:
23
-
24
- - ``Module``: The base class for all the objects in the ecosystem.
25
- - ``Sequential``: The class for a sequential of modules, which update the modules sequentially.
26
-
27
- """
28
-
29
- import warnings
30
- from typing import Sequence, Optional, Tuple, Union, TYPE_CHECKING, Callable
31
-
32
- import numpy as np
33
-
34
- from brainstate._state import State
35
- from brainstate.graph import Node, states, nodes, flatten
36
- from brainstate.mixin import ParamDescriber, ParamDesc
37
- from brainstate.typing import PathParts, Size
38
- from brainstate.util import FlattedDict, NestedDict, BrainStateError
39
-
40
- # maximum integer
41
- max_int = np.iinfo(np.int32).max
42
-
43
- __all__ = [
44
- 'Module', 'ElementWiseBlock', 'Sequential',
45
- ]
46
-
47
-
48
- class Module(Node, ParamDesc):
49
- """
50
- The Module class for the whole ecosystem.
51
-
52
- The ``Module`` is the base class for all the objects in the ecosystem. It
53
- provides the basic functionalities for the objects, including:
54
-
55
- - ``states()``: Collect all states in this node and the children nodes.
56
- - ``nodes()``: Collect all children nodes.
57
- - ``update()``: The function to specify the updating rule.
58
- - ``init_state()``: State initialization function.
59
- - ``reset_state()``: State resetting function.
60
-
61
- """
62
-
63
- __module__ = 'brainstate.nn'
64
-
65
- _in_size: Optional[Size]
66
- _out_size: Optional[Size]
67
- _name: Optional[str]
68
-
69
- if not TYPE_CHECKING:
70
- def __init__(self, name: str = None):
71
- # check the name
72
- if name is not None:
73
- assert isinstance(name, str), f'The name must be a string, but we got {type(name)}: {name}'
74
- self._name = name
75
-
76
- # input and output size
77
- self._in_size = None
78
- self._out_size = None
79
-
80
- @property
81
- def name(self):
82
- """Name of the model."""
83
- return self._name
84
-
85
- @name.setter
86
- def name(self, name: str = None):
87
- raise AttributeError('The name of the model is read-only.')
88
-
89
- @property
90
- def in_size(self) -> Size:
91
- return self._in_size
92
-
93
- @in_size.setter
94
- def in_size(self, in_size: Sequence[int] | int):
95
- if isinstance(in_size, int):
96
- in_size = (in_size,)
97
- assert isinstance(in_size, (tuple, list)), f"Invalid type of in_size: {type(in_size)}"
98
- self._in_size = tuple(in_size)
99
-
100
- @property
101
- def out_size(self) -> Size:
102
- return self._out_size
103
-
104
- @out_size.setter
105
- def out_size(self, out_size: Sequence[int] | int):
106
- if isinstance(out_size, int):
107
- out_size = (out_size,)
108
- assert isinstance(out_size, (tuple, list)), f"Invalid type of out_size: {type(out_size)}"
109
- self._out_size = tuple(out_size)
110
-
111
- def update(self, *args, **kwargs):
112
- """
113
- The function to specify the updating rule.
114
- """
115
- raise NotImplementedError(
116
- f'Subclass of {self.__class__.__name__} must implement "update" function. \n'
117
- f'This instance is: \n'
118
- f'{self}'
119
- )
120
-
121
- def __call__(self, *args, **kwargs):
122
- return self.update(*args, **kwargs)
123
-
124
- def __rrshift__(self, other):
125
- """
126
- Support using right shift operator to call modules.
127
-
128
- Examples
129
- --------
130
-
131
- >>> import brainstate as brainstate
132
- >>> x = brainstate.random.rand((10, 10))
133
- >>> l = brainstate.nn.Dropout(0.5)
134
- >>> y = x >> l
135
- """
136
- return self.__call__(other)
137
-
138
- def states(
139
- self,
140
- *filters,
141
- allowed_hierarchy: Tuple[int, int] = (0, max_int),
142
- level: int = None,
143
- ) -> FlattedDict[PathParts, State] | Tuple[FlattedDict[PathParts, State], ...]:
144
- """
145
- Collect all states in this node and the children nodes.
146
-
147
- Parameters
148
- ----------
149
- filters : Any
150
- The filters to select the states.
151
- allowed_hierarchy : tuple of int
152
- The hierarchy of the states to be collected.
153
- level : int
154
- The level of the states to be collected. Has been deprecated.
155
-
156
- Returns
157
- -------
158
- states : FlattedDict, tuple of FlattedDict
159
- The collection contained (the path, the state).
160
- """
161
- if level is not None:
162
- allowed_hierarchy = (0, level)
163
- warnings.warn('The "level" argument is deprecated. Please use "allowed_hierarchy" instead.',
164
- DeprecationWarning)
165
-
166
- return states(self, *filters, allowed_hierarchy=allowed_hierarchy)
167
-
168
- def state_trees(
169
- self,
170
- *filters,
171
- ) -> NestedDict[PathParts, State] | Tuple[NestedDict[PathParts, State], ...]:
172
- """
173
- Collect all states in this node and the children nodes.
174
-
175
- Parameters
176
- ----------
177
- filters : tuple
178
- The filters to select the states.
179
-
180
- Returns
181
- -------
182
- states : FlattedDict, tuple of FlattedDict
183
- The collection contained (the path, the state).
184
- """
185
- graph_def, state_tree = flatten(self)
186
- if len(filters):
187
- return state_tree.filter(*filters)
188
- return state_tree
189
-
190
- def nodes(
191
- self,
192
- *filters,
193
- allowed_hierarchy: Tuple[int, int] = (0, max_int),
194
- level: int = None,
195
- ) -> FlattedDict[PathParts, Node] | Tuple[FlattedDict[PathParts, Node], ...]:
196
- """
197
- Collect all children nodes.
198
-
199
- Parameters
200
- ----------
201
- filters : Any
202
- The filters to select the states.
203
- allowed_hierarchy : tuple of int
204
- The hierarchy of the states to be collected.
205
- level : int
206
- The level of the states to be collected. Has been deprecated.
207
-
208
- Returns
209
- -------
210
- nodes : FlattedDict, tuple of FlattedDict
211
- The collection contained (the path, the node).
212
- """
213
- if level is not None:
214
- allowed_hierarchy = (0, level)
215
- warnings.warn('The "level" argument is deprecated. Please use "allowed_hierarchy" instead.',
216
- DeprecationWarning)
217
-
218
- return nodes(self, *filters, allowed_hierarchy=allowed_hierarchy)
219
-
220
- def init_state(self, *args, **kwargs):
221
- """
222
- State initialization function.
223
- """
224
- pass
225
-
226
- def reset_state(self, *args, **kwargs):
227
- """
228
- State resetting function.
229
- """
230
- pass
231
-
232
- def __pretty_repr_item__(self, name, value):
233
- if name.startswith('_'):
234
- return None if value is None else (name[1:], value) # skip the first `_`
235
- return name, value
236
-
237
-
238
- class ElementWiseBlock(Module):
239
- __module__ = 'brainstate.nn'
240
-
241
-
242
- class Sequential(Module):
243
- """
244
- A sequential `input-output` module.
245
-
246
- Modules will be added to it in the order they are passed in the
247
- constructor. Alternatively, an ``dict`` of modules can be
248
- passed in. The ``update()`` method of ``Sequential`` accepts any
249
- input and forwards it to the first module it contains. It then
250
- "chains" outputs to inputs sequentially for each subsequent module,
251
- finally returning the output of the last module.
252
-
253
- The value a ``Sequential`` provides over manually calling a sequence
254
- of modules is that it allows treating the whole container as a
255
- single module, such that performing a transformation on the
256
- ``Sequential`` applies to each of the modules it stores (which are
257
- each a registered submodule of the ``Sequential``).
258
-
259
- What's the difference between a ``Sequential`` and a
260
- :py:class:`Container`? A ``Container`` is exactly what it
261
- sounds like--a container to store :py:class:`DynamicalSystem` s!
262
- On the other hand, the layers in a ``Sequential`` are connected
263
- in a cascading way.
264
-
265
- Examples
266
- --------
267
-
268
- >>> import jax
269
- >>> import brainstate as brainstate
270
- >>> import brainstate.nn as nn
271
- >>>
272
- >>> # composing ANN models
273
- >>> l = nn.Sequential(nn.Linear(100, 10),
274
- >>> jax.nn.relu,
275
- >>> nn.Linear(10, 2))
276
- >>> l(brainstate.random.random((256, 100)))
277
-
278
- Args:
279
- modules_as_tuple: The children modules.
280
- modules_as_dict: The children modules.
281
- name: The object name.
282
- """
283
- __module__ = 'brainstate.nn'
284
-
285
- def __init__(self, first: Module, *layers):
286
- super().__init__()
287
- self.layers = []
288
-
289
- # add all modules
290
- assert isinstance(first, Module), 'The first module should be an instance of Module.'
291
- in_size = first.out_size
292
- self.layers.append(first)
293
- for module in layers:
294
- module, in_size = self._format_module(module, in_size)
295
- self.layers.append(module)
296
-
297
- # the input and output shape
298
- if first.in_size is not None:
299
- self.in_size = first.in_size
300
- if in_size is not None:
301
- self.out_size = tuple(in_size)
302
-
303
- def update(self, x):
304
- """Update function of a sequential model.
305
- """
306
- for m in self.layers:
307
- try:
308
- x = m(x)
309
- except Exception as e:
310
- raise BrainStateError(
311
- f'The module \n'
312
- f'{m}\n'
313
- f'failed to update with input {x}\n'
314
- ) from e
315
- return x
316
-
317
- def __getitem__(self, key: Union[int, slice]):
318
- if isinstance(key, slice):
319
- return Sequential(*self.layers[key])
320
- elif isinstance(key, int):
321
- return self.layers[key]
322
- elif isinstance(key, (tuple, list)):
323
- return Sequential(*[self.layers[k] for k in key])
324
- else:
325
- raise KeyError(f'Unknown type of key: {type(key)}')
326
-
327
- def append(self, layer: Callable):
328
- """
329
- Append a layer to the sequential model.
330
-
331
- This method adds a new layer to the end of the sequential model. The layer can be
332
- either a Module instance, an ElementWiseBlock instance, or a callable function. If the
333
- layer is a callable function, it will be wrapped in an ElementWiseBlock instance.
334
-
335
- Parameters:
336
- ----------
337
- layer : Callable
338
- The layer to be appended to the sequential model. It can be a Module instance,
339
- an ElementWiseBlock instance, or a callable function.
340
-
341
- Raises:
342
- -------
343
- ValueError
344
- If the sequential model is empty and the first layer is a callable function.
345
-
346
- Returns:
347
- --------
348
- None
349
- The method does not return any value. It modifies the sequential model by adding
350
- the new layer to the end.
351
- """
352
- if len(self.layers) == 0:
353
- raise ValueError('The first layer should be a module, not a function.')
354
- module, in_size = self._format_module(layer, self.out_size)
355
- self.layers.append(module)
356
- self.out_size = in_size
357
-
358
- def _format_module(self, module, in_size):
359
- if isinstance(module, ParamDescriber):
360
- if in_size is None:
361
- raise ValueError(
362
- 'The input size should be specified. '
363
- f'Please set the in_size attribute of the previous module: \n'
364
- f'{self.layers[-1]}'
365
- )
366
- module = module(in_size=in_size)
367
- assert isinstance(module, Module), 'The module should be an instance of Module.'
368
- out_size = module.out_size
369
- elif isinstance(module, ElementWiseBlock):
370
- out_size = in_size
371
- elif isinstance(module, Module):
372
- out_size = module.out_size
373
- elif callable(module):
374
- out_size = in_size
375
- else:
376
- raise TypeError(f"Unsupported type {type(module)}. ")
377
- return module, out_size
1
+ # Copyright 2024 BrainX Ecosystem Limited. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
15
+
16
+ # -*- coding: utf-8 -*-
17
+
18
+
19
+ """
20
+ All the basic classes for neural networks in ``brainstate``.
21
+
22
+ The basic classes include:
23
+
24
+ - ``Module``: The base class for all the objects in the ecosystem.
25
+ - ``Sequential``: The class for a sequential of modules, which update the modules sequentially.
26
+
27
+ """
28
+
29
+ import warnings
30
+ from typing import Sequence, Optional, Tuple, Union, TYPE_CHECKING, Callable
31
+
32
+ import numpy as np
33
+
34
+ from brainstate._error import BrainStateError
35
+ from brainstate._state import State
36
+ from brainstate.graph import Node, states, nodes, flatten
37
+ from brainstate.mixin import ParamDescriber, ParamDesc
38
+ from brainstate.typing import PathParts, Size
39
+ from brainstate.util import FlattedDict, NestedDict
40
+
41
+ # maximum integer
42
+ max_int = np.iinfo(np.int32).max
43
+
44
+ __all__ = [
45
+ 'Module', 'ElementWiseBlock', 'Sequential',
46
+ ]
47
+
48
+
49
+ class Module(Node, ParamDesc):
50
+ """
51
+ The Module class for the whole ecosystem.
52
+
53
+ The ``Module`` is the base class for all the objects in the ecosystem. It
54
+ provides the basic functionalities for the objects, including:
55
+
56
+ - ``states()``: Collect all states in this node and the children nodes.
57
+ - ``nodes()``: Collect all children nodes.
58
+ - ``update()``: The function to specify the updating rule.
59
+ - ``init_state()``: State initialization function.
60
+ - ``reset_state()``: State resetting function.
61
+
62
+ """
63
+
64
+ __module__ = 'brainstate.nn'
65
+
66
+ _in_size: Optional[Size]
67
+ _out_size: Optional[Size]
68
+ _name: Optional[str]
69
+
70
+ if not TYPE_CHECKING:
71
+ def __init__(self, name: str = None):
72
+ # check the name
73
+ if name is not None:
74
+ assert isinstance(name, str), f'The name must be a string, but we got {type(name)}: {name}'
75
+ self._name = name
76
+
77
+ # input and output size
78
+ self._in_size = None
79
+ self._out_size = None
80
+
81
+ @property
82
+ def name(self):
83
+ """Name of the model."""
84
+ return self._name
85
+
86
+ @name.setter
87
+ def name(self, name: str = None):
88
+ raise AttributeError('The name of the model is read-only.')
89
+
90
+ @property
91
+ def in_size(self) -> Size:
92
+ return self._in_size
93
+
94
+ @in_size.setter
95
+ def in_size(self, in_size: Sequence[int] | int):
96
+ if isinstance(in_size, int):
97
+ in_size = (in_size,)
98
+ elif isinstance(in_size, np.generic):
99
+ if np.issubdtype(in_size, np.integer) and in_size.ndim == 0:
100
+ in_size = (int(in_size),)
101
+ assert isinstance(in_size, (tuple, list)), f"Invalid type of in_size: {in_size} {type(in_size)}"
102
+ self._in_size = tuple(in_size)
103
+
104
+ @property
105
+ def out_size(self) -> Size:
106
+ return self._out_size
107
+
108
+ @out_size.setter
109
+ def out_size(self, out_size: Sequence[int] | int):
110
+ if isinstance(out_size, int):
111
+ out_size = (out_size,)
112
+ elif isinstance(out_size, np.ndarray):
113
+ if np.issubdtype(out_size, np.integer) and out_size.ndim == 0:
114
+ out_size = (int(out_size),)
115
+ assert isinstance(out_size, (tuple, list)), f"Invalid type of out_size: {type(out_size)}"
116
+ self._out_size = tuple(out_size)
117
+
118
+ def update(self, *args, **kwargs):
119
+ """
120
+ The function to specify the updating rule.
121
+ """
122
+ raise NotImplementedError(
123
+ f'Subclass of {self.__class__.__name__} must implement "update" function. \n'
124
+ f'This instance is: \n'
125
+ f'{self}'
126
+ )
127
+
128
+ def __call__(self, *args, **kwargs):
129
+ return self.update(*args, **kwargs)
130
+
131
+ def __rrshift__(self, other):
132
+ """
133
+ Support using right shift operator to call modules.
134
+
135
+ Examples
136
+ --------
137
+
138
+ >>> import brainstate as brainstate
139
+ >>> x = brainstate.random.rand((10, 10))
140
+ >>> l = brainstate.nn.Dropout(0.5)
141
+ >>> y = x >> l
142
+ """
143
+ return self.__call__(other)
144
+
145
+ def states(
146
+ self,
147
+ *filters,
148
+ allowed_hierarchy: Tuple[int, int] = (0, max_int),
149
+ level: int = None,
150
+ ) -> FlattedDict[PathParts, State] | Tuple[FlattedDict[PathParts, State], ...]:
151
+ """
152
+ Collect all states in this node and the children nodes.
153
+
154
+ Parameters
155
+ ----------
156
+ filters : Any
157
+ The filters to select the states.
158
+ allowed_hierarchy : tuple of int
159
+ The hierarchy of the states to be collected.
160
+ level : int
161
+ The level of the states to be collected. Has been deprecated.
162
+
163
+ Returns
164
+ -------
165
+ states : FlattedDict, tuple of FlattedDict
166
+ The collection contained (the path, the state).
167
+ """
168
+ if level is not None:
169
+ allowed_hierarchy = (0, level)
170
+ warnings.warn('The "level" argument is deprecated. Please use "allowed_hierarchy" instead.',
171
+ DeprecationWarning)
172
+
173
+ return states(self, *filters, allowed_hierarchy=allowed_hierarchy)
174
+
175
+ def state_trees(
176
+ self,
177
+ *filters,
178
+ ) -> NestedDict[PathParts, State] | Tuple[NestedDict[PathParts, State], ...]:
179
+ """
180
+ Collect all states in this node and the children nodes.
181
+
182
+ Parameters
183
+ ----------
184
+ filters : tuple
185
+ The filters to select the states.
186
+
187
+ Returns
188
+ -------
189
+ states : FlattedDict, tuple of FlattedDict
190
+ The collection contained (the path, the state).
191
+ """
192
+ graph_def, state_tree = flatten(self)
193
+ if len(filters):
194
+ return state_tree.filter(*filters)
195
+ return state_tree
196
+
197
+ def nodes(
198
+ self,
199
+ *filters,
200
+ allowed_hierarchy: Tuple[int, int] = (0, max_int),
201
+ level: int = None,
202
+ ) -> FlattedDict[PathParts, Node] | Tuple[FlattedDict[PathParts, Node], ...]:
203
+ """
204
+ Collect all children nodes.
205
+
206
+ Parameters
207
+ ----------
208
+ filters : Any
209
+ The filters to select the states.
210
+ allowed_hierarchy : tuple of int
211
+ The hierarchy of the states to be collected.
212
+ level : int
213
+ The level of the states to be collected. Has been deprecated.
214
+
215
+ Returns
216
+ -------
217
+ nodes : FlattedDict, tuple of FlattedDict
218
+ The collection contained (the path, the node).
219
+ """
220
+ if level is not None:
221
+ allowed_hierarchy = (0, level)
222
+ warnings.warn('The "level" argument is deprecated. Please use "allowed_hierarchy" instead.',
223
+ DeprecationWarning)
224
+
225
+ return nodes(self, *filters, allowed_hierarchy=allowed_hierarchy)
226
+
227
+ def init_state(self, *args, **kwargs):
228
+ """
229
+ State initialization function.
230
+ """
231
+ pass
232
+
233
+ def reset_state(self, *args, **kwargs):
234
+ """
235
+ State resetting function.
236
+ """
237
+ pass
238
+
239
+ def __pretty_repr_item__(self, name, value):
240
+ if name.startswith('_'):
241
+ return None if value is None else (name[1:], value) # skip the first `_`
242
+ return name, value
243
+
244
+
245
+ class ElementWiseBlock(Module):
246
+ __module__ = 'brainstate.nn'
247
+
248
+
249
+ class Sequential(Module):
250
+ """
251
+ A sequential `input-output` module.
252
+
253
+ Modules will be added to it in the order they are passed in the
254
+ constructor. Alternatively, an ``dict`` of modules can be
255
+ passed in. The ``update()`` method of ``Sequential`` accepts any
256
+ input and forwards it to the first module it contains. It then
257
+ "chains" outputs to inputs sequentially for each subsequent module,
258
+ finally returning the output of the last module.
259
+
260
+ The value a ``Sequential`` provides over manually calling a sequence
261
+ of modules is that it allows treating the whole container as a
262
+ single module, such that performing a transformation on the
263
+ ``Sequential`` applies to each of the modules it stores (which are
264
+ each a registered submodule of the ``Sequential``).
265
+
266
+ What's the difference between a ``Sequential`` and a
267
+ :py:class:`Container`? A ``Container`` is exactly what it
268
+ sounds like--a container to store :py:class:`DynamicalSystem` s!
269
+ On the other hand, the layers in a ``Sequential`` are connected
270
+ in a cascading way.
271
+
272
+ Examples
273
+ --------
274
+
275
+ >>> import jax
276
+ >>> import brainstate as brainstate
277
+ >>> import brainstate.nn as nn
278
+ >>>
279
+ >>> # composing ANN models
280
+ >>> l = nn.Sequential(nn.Linear(100, 10),
281
+ >>> jax.nn.relu,
282
+ >>> nn.Linear(10, 2))
283
+ >>> l(brainstate.random.random((256, 100)))
284
+
285
+ Args:
286
+ modules_as_tuple: The children modules.
287
+ modules_as_dict: The children modules.
288
+ name: The object name.
289
+ """
290
+ __module__ = 'brainstate.nn'
291
+
292
+ def __init__(self, first: Module, *layers):
293
+ super().__init__()
294
+ self.layers = []
295
+
296
+ # add all modules
297
+ assert isinstance(first, Module), 'The first module should be an instance of Module.'
298
+ in_size = first.out_size
299
+ self.layers.append(first)
300
+ for module in layers:
301
+ module, in_size = self._format_module(module, in_size)
302
+ self.layers.append(module)
303
+
304
+ # the input and output shape
305
+ if first.in_size is not None:
306
+ self.in_size = first.in_size
307
+ if in_size is not None:
308
+ self.out_size = tuple(in_size)
309
+
310
+ def update(self, x):
311
+ """Update function of a sequential model.
312
+ """
313
+ for m in self.layers:
314
+ try:
315
+ x = m(x)
316
+ except Exception as e:
317
+ raise BrainStateError(
318
+ f'The module \n'
319
+ f'{m}\n'
320
+ f'failed to update with input {x}\n'
321
+ ) from e
322
+ return x
323
+
324
+ def __getitem__(self, key: Union[int, slice]):
325
+ if isinstance(key, slice):
326
+ return Sequential(*self.layers[key])
327
+ elif isinstance(key, int):
328
+ return self.layers[key]
329
+ elif isinstance(key, (tuple, list)):
330
+ return Sequential(*[self.layers[k] for k in key])
331
+ else:
332
+ raise KeyError(f'Unknown type of key: {type(key)}')
333
+
334
+ def append(self, layer: Callable):
335
+ """
336
+ Append a layer to the sequential model.
337
+
338
+ This method adds a new layer to the end of the sequential model. The layer can be
339
+ either a Module instance, an ElementWiseBlock instance, or a callable function. If the
340
+ layer is a callable function, it will be wrapped in an ElementWiseBlock instance.
341
+
342
+ Parameters:
343
+ ----------
344
+ layer : Callable
345
+ The layer to be appended to the sequential model. It can be a Module instance,
346
+ an ElementWiseBlock instance, or a callable function.
347
+
348
+ Raises:
349
+ -------
350
+ ValueError
351
+ If the sequential model is empty and the first layer is a callable function.
352
+
353
+ Returns:
354
+ --------
355
+ None
356
+ The method does not return any value. It modifies the sequential model by adding
357
+ the new layer to the end.
358
+ """
359
+ if len(self.layers) == 0:
360
+ raise ValueError('The first layer should be a module, not a function.')
361
+ module, in_size = self._format_module(layer, self.out_size)
362
+ self.layers.append(module)
363
+ self.out_size = in_size
364
+
365
+ def _format_module(self, module, in_size):
366
+ if isinstance(module, ParamDescriber):
367
+ if in_size is None:
368
+ raise ValueError(
369
+ 'The input size should be specified. '
370
+ f'Please set the in_size attribute of the previous module: \n'
371
+ f'{self.layers[-1]}'
372
+ )
373
+ module = module(in_size=in_size)
374
+ assert isinstance(module, Module), 'The module should be an instance of Module.'
375
+ out_size = module.out_size
376
+ elif isinstance(module, ElementWiseBlock):
377
+ out_size = in_size
378
+ elif isinstance(module, Module):
379
+ out_size = module.out_size
380
+ elif callable(module):
381
+ out_size = in_size
382
+ else:
383
+ raise TypeError(f"Unsupported type {type(module)}. ")
384
+ return module, out_size