brainstate 0.1.0.post20250212__py2.py3-none-any.whl → 0.1.0.post20250216__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 (96) hide show
  1. brainstate/_state.py +853 -90
  2. brainstate/_state_test.py +1 -3
  3. brainstate/augment/__init__.py +2 -2
  4. brainstate/augment/_autograd.py +257 -115
  5. brainstate/augment/_autograd_test.py +2 -3
  6. brainstate/augment/_eval_shape.py +3 -4
  7. brainstate/augment/_mapping.py +582 -62
  8. brainstate/augment/_mapping_test.py +114 -30
  9. brainstate/augment/_random.py +61 -7
  10. brainstate/compile/_ad_checkpoint.py +2 -3
  11. brainstate/compile/_conditions.py +4 -5
  12. brainstate/compile/_conditions_test.py +1 -2
  13. brainstate/compile/_error_if.py +1 -2
  14. brainstate/compile/_error_if_test.py +1 -2
  15. brainstate/compile/_jit.py +23 -16
  16. brainstate/compile/_jit_test.py +1 -2
  17. brainstate/compile/_loop_collect_return.py +18 -10
  18. brainstate/compile/_loop_collect_return_test.py +1 -1
  19. brainstate/compile/_loop_no_collection.py +5 -5
  20. brainstate/compile/_make_jaxpr.py +23 -21
  21. brainstate/compile/_make_jaxpr_test.py +1 -2
  22. brainstate/compile/_progress_bar.py +1 -2
  23. brainstate/compile/_unvmap.py +1 -0
  24. brainstate/compile/_util.py +4 -2
  25. brainstate/environ.py +4 -4
  26. brainstate/environ_test.py +1 -2
  27. brainstate/functional/_activations.py +1 -2
  28. brainstate/functional/_activations_test.py +1 -1
  29. brainstate/functional/_normalization.py +1 -2
  30. brainstate/functional/_others.py +1 -2
  31. brainstate/functional/_spikes.py +136 -20
  32. brainstate/graph/_graph_node.py +2 -43
  33. brainstate/graph/_graph_operation.py +4 -20
  34. brainstate/graph/_graph_operation_test.py +3 -4
  35. brainstate/init/_base.py +1 -2
  36. brainstate/init/_generic.py +1 -2
  37. brainstate/nn/__init__.py +4 -0
  38. brainstate/nn/_collective_ops.py +351 -48
  39. brainstate/nn/_collective_ops_test.py +36 -0
  40. brainstate/nn/_common.py +194 -0
  41. brainstate/nn/_dyn_impl/_dynamics_neuron.py +1 -2
  42. brainstate/nn/_dyn_impl/_dynamics_neuron_test.py +1 -2
  43. brainstate/nn/_dyn_impl/_dynamics_synapse.py +1 -2
  44. brainstate/nn/_dyn_impl/_dynamics_synapse_test.py +1 -2
  45. brainstate/nn/_dyn_impl/_inputs.py +1 -2
  46. brainstate/nn/_dyn_impl/_rate_rnns.py +1 -2
  47. brainstate/nn/_dyn_impl/_rate_rnns_test.py +1 -2
  48. brainstate/nn/_dyn_impl/_readout.py +2 -3
  49. brainstate/nn/_dyn_impl/_readout_test.py +1 -2
  50. brainstate/nn/_dynamics/_dynamics_base.py +2 -3
  51. brainstate/nn/_dynamics/_dynamics_base_test.py +1 -2
  52. brainstate/nn/_dynamics/_state_delay.py +3 -3
  53. brainstate/nn/_dynamics/_synouts_test.py +1 -2
  54. brainstate/nn/_elementwise/_dropout.py +6 -7
  55. brainstate/nn/_elementwise/_dropout_test.py +1 -2
  56. brainstate/nn/_elementwise/_elementwise.py +1 -2
  57. brainstate/nn/_exp_euler.py +1 -2
  58. brainstate/nn/_exp_euler_test.py +1 -2
  59. brainstate/nn/_interaction/_conv.py +1 -2
  60. brainstate/nn/_interaction/_conv_test.py +1 -0
  61. brainstate/nn/_interaction/_linear.py +1 -2
  62. brainstate/nn/_interaction/_linear_test.py +1 -2
  63. brainstate/nn/_interaction/_normalizations.py +1 -2
  64. brainstate/nn/_interaction/_poolings.py +3 -4
  65. brainstate/nn/_module.py +63 -19
  66. brainstate/nn/_module_test.py +1 -2
  67. brainstate/nn/metrics.py +3 -4
  68. brainstate/optim/_lr_scheduler.py +1 -2
  69. brainstate/optim/_lr_scheduler_test.py +2 -3
  70. brainstate/optim/_optax_optimizer_test.py +1 -2
  71. brainstate/optim/_sgd_optimizer.py +2 -3
  72. brainstate/random/_rand_funs.py +1 -2
  73. brainstate/random/_rand_funs_test.py +2 -3
  74. brainstate/random/_rand_seed.py +2 -3
  75. brainstate/random/_rand_seed_test.py +1 -2
  76. brainstate/random/_rand_state.py +3 -4
  77. brainstate/surrogate.py +5 -2
  78. brainstate/transform.py +0 -3
  79. brainstate/typing.py +28 -25
  80. brainstate/util/__init__.py +9 -7
  81. brainstate/util/_caller.py +1 -2
  82. brainstate/util/_error.py +27 -0
  83. brainstate/util/_others.py +60 -15
  84. brainstate/util/{_dict.py → _pretty_pytree.py} +2 -2
  85. brainstate/util/{_dict_test.py → _pretty_pytree_test.py} +1 -2
  86. brainstate/util/_pretty_repr.py +1 -2
  87. brainstate/util/_pretty_table.py +2900 -0
  88. brainstate/util/_struct.py +11 -11
  89. brainstate/util/filter.py +472 -0
  90. {brainstate-0.1.0.post20250212.dist-info → brainstate-0.1.0.post20250216.dist-info}/METADATA +2 -2
  91. brainstate-0.1.0.post20250216.dist-info/RECORD +127 -0
  92. brainstate/util/_filter.py +0 -178
  93. brainstate-0.1.0.post20250212.dist-info/RECORD +0 -124
  94. {brainstate-0.1.0.post20250212.dist-info → brainstate-0.1.0.post20250216.dist-info}/LICENSE +0 -0
  95. {brainstate-0.1.0.post20250212.dist-info → brainstate-0.1.0.post20250216.dist-info}/WHEEL +0 -0
  96. {brainstate-0.1.0.post20250212.dist-info → brainstate-0.1.0.post20250216.dist-info}/top_level.txt +0 -0
@@ -16,14 +16,18 @@
16
16
  from __future__ import annotations
17
17
 
18
18
  from collections import namedtuple
19
- from typing import Dict, Callable, TypeVar
20
19
 
21
20
  import jax
21
+ from typing import (
22
+ Callable, TypeVar, Tuple, Any, Dict
23
+ )
22
24
 
23
25
  from brainstate._state import catch_new_states
24
26
  from brainstate._utils import set_module_as
27
+ from brainstate.augment import vmap, vmap_new_states
25
28
  from brainstate.graph import nodes
26
- from brainstate.util._filter import Filter
29
+ from brainstate.random import set_key, split_key
30
+ from brainstate.typing import Filter
27
31
  from ._module import Module
28
32
 
29
33
  # the maximum order
@@ -35,8 +39,16 @@ StateLoadResult = namedtuple('StateLoadResult', ['missing_keys', 'unexpected_key
35
39
  T = TypeVar('T', bound=Module)
36
40
 
37
41
  __all__ = [
38
- 'MAX_ORDER', 'call_order', 'init_all_states', 'reset_all_states',
39
- 'load_all_states', 'save_all_states', 'assign_state_values',
42
+ 'MAX_ORDER',
43
+ 'call_order',
44
+ 'call_all_functions',
45
+ 'vmap_call_all_functions',
46
+ 'init_all_states',
47
+ 'vmap_init_all_states',
48
+ 'reset_all_states',
49
+ 'load_all_states',
50
+ 'save_all_states',
51
+ 'assign_state_values',
40
52
  ]
41
53
 
42
54
 
@@ -76,77 +88,368 @@ def call_order(level: int = 0, check_order_boundary: bool = True):
76
88
 
77
89
 
78
90
  @set_module_as('brainstate.nn')
79
- def init_all_states(
91
+ def call_all_functions(
80
92
  target: T,
81
- *args,
82
- exclude: Filter = None,
83
- **kwargs
93
+ fun_name: str,
94
+ args: Tuple[Any, ...] | Any = (),
95
+ kwargs: Dict[str, Any] | None = None,
96
+ node_to_exclude: Filter = None,
97
+ fun_if_not_exist: str = 'raise',
84
98
  ) -> T:
85
99
  """
86
- Collectively initialize states of all children nodes in the given target.
87
-
88
- Args:
89
- target: The target Module.
90
- exclude: The filter to exclude some nodes.
91
- tag: The tag for the new states.
92
- args: The positional arguments for the initialization, which will be passed to the `init_state` method
93
- of each node.
94
- kwargs: The keyword arguments for the initialization, which will be passed to the `init_state` method
95
- of each node.
96
-
100
+ Call a specified function on all nodes of a target module, respecting call order if defined.
101
+
102
+ This function iterates through all nodes of the target module, calling a specified function
103
+ on each node. It respects the call order of functions if defined, and provides options for
104
+ handling cases where the specified function does not exist on a node.
105
+
106
+ Parameters:
107
+ -----------
108
+ target : T
109
+ The target module on which to call functions.
110
+ fun_name : str
111
+ The name of the function to call on each node.
112
+ args : Tuple[Any, ...] | Any, optional
113
+ Positional arguments to pass to the called function. Default is an empty tuple.
114
+ kwargs : Dict[str, Any] | None, optional
115
+ Keyword arguments to pass to the called function. Default is None.
116
+ node_to_exclude : Filter, optional
117
+ A filter function to exclude certain nodes from the function call.
118
+ fun_if_not_exist : str, optional
119
+ Specifies behavior when the function doesn't exist on a node. Options are:
120
+
121
+ - 'raise': Raise an exception (default)
122
+ - 'pass' or 'none': Skip the node and continue
123
+
97
124
  Returns:
98
- The target Module.
125
+ --------
126
+ T
127
+ The target module after calling the specified function on all applicable nodes.
128
+
129
+ Raises:
130
+ -------
131
+ AssertionError
132
+ If fun_name is not a string or kwargs is not a dictionary.
133
+ ValueError
134
+ If fun_if_not_exist is not one of the allowed values.
135
+ AttributeError
136
+ If the specified function doesn't exist on a node and fun_if_not_exist is 'raise'.
99
137
  """
138
+ assert isinstance(fun_name, str), f'fun_name must be a string, but got {fun_name}.'
100
139
 
101
- # node that has `call_order` decorated
102
- nodes_with_order = []
140
+ args = (args,) if not isinstance(args, tuple) else args
141
+ kwargs = kwargs or {}
142
+ assert isinstance(kwargs, dict), f'kwargs must be a dict, but got {kwargs}.'
103
143
 
104
- nodes_ = nodes(target).filter(Module)
105
- if exclude is not None:
106
- nodes_ = nodes_ - nodes_.filter(exclude)
144
+ all_nodes = nodes(target).filter(Module)
145
+ if node_to_exclude is not None:
146
+ all_nodes -= all_nodes.filter(node_to_exclude)
107
147
 
108
- # reset node whose `init_state` has no `call_order`
109
- for node in list(nodes_.values()):
110
- if hasattr(node.init_state, 'call_order'):
148
+ nodes_with_order = []
149
+ for node in all_nodes.values():
150
+ try:
151
+ fun = getattr(node, fun_name)
152
+ except AttributeError as e:
153
+ if fun_if_not_exist == 'raise':
154
+ raise
155
+ elif fun_if_not_exist in ('pass', 'none'):
156
+ continue
157
+ else:
158
+ raise ValueError(
159
+ f'fun_if_not_exist must be one of ["raise", "pass", "none"], but got {fun_if_not_exist}.')
160
+
161
+ assert callable(fun), f'{fun_name} must be a callable function, but got {fun}.'
162
+ if hasattr(fun, 'call_order'):
111
163
  nodes_with_order.append(node)
112
164
  else:
113
- node.init_state(*args, **kwargs)
165
+ fun(*args, **kwargs)
166
+
167
+ for node in sorted(nodes_with_order, key=lambda x: getattr(x, fun_name).call_order):
168
+ getattr(node, fun_name)(*args, **kwargs)
169
+
170
+ return target
171
+
172
+
173
+ def vmap_call_all_functions(
174
+ target: T,
175
+ fun_name: str,
176
+ args: Tuple[Any, ...] | Any = (),
177
+ kwargs: Dict[str, Any] | None = None,
178
+ axis_size: int = None,
179
+ node_to_exclude: Filter = None,
180
+ tag: str | None = None,
181
+ fun_if_not_exist: str = 'raise',
182
+ ) -> T:
183
+ """
184
+ Apply vectorized mapping (vmap) to call a specified function on all nodes of a target module.
185
+
186
+ This function vectorizes the process of calling a specified function across multiple instances
187
+ of the target module, effectively batching the operation.
188
+
189
+ Parameters:
190
+ -----------
191
+ target : T
192
+ The target module on which to call functions.
193
+ fun_name : str
194
+ The name of the function to call on each node.
195
+ args : Tuple[Any, ...] | Any, optional
196
+ Positional arguments to pass to the called function. Default is an empty tuple.
197
+ kwargs : Dict[str, Any] | None, optional
198
+ Keyword arguments to pass to the called function. Default is None.
199
+ axis_size : int, optional
200
+ The size of the batch axis for vmap. Must be a positive integer.
201
+ node_to_exclude : Filter, optional
202
+ A filter function to exclude certain nodes from the function call.
203
+ tag : str | None, optional
204
+ A tag to be used for catching new states.
205
+ fun_if_not_exist : str, optional
206
+ Specifies behavior when the function doesn't exist on a node. Options are:
207
+
208
+ - 'raise': Raise an exception (default)
209
+ - 'pass' or 'none': Skip the node and continue
210
+
211
+ Returns:
212
+ --------
213
+ T
214
+ The target module after applying the vectorized function call on all applicable nodes.
114
215
 
115
- # reset the node's states with `call_order`
116
- for node in sorted(nodes_with_order, key=lambda x: x.init_state.call_order):
117
- node.init_state(*args, **kwargs)
216
+ Raises:
217
+ -------
218
+ AssertionError
219
+ If axis_size is not specified or is not a positive integer.
220
+ """
221
+ assert axis_size is not None and axis_size > 0, f"axis_size must be a positive integer, got {axis_size}"
222
+
223
+ if not isinstance(args, tuple):
224
+ args = (args,)
225
+ kwargs = kwargs or {}
226
+ assert isinstance(kwargs, dict), f'kwargs must be a dict, but got {kwargs}.'
227
+
228
+ @vmap(out_axes=0, axis_size=axis_size)
229
+ def vmapped_fn(key):
230
+ set_key(key)
231
+ with catch_new_states(tag) as inner_catcher:
232
+ call_all_functions(
233
+ target,
234
+ fun_name=fun_name,
235
+ args=args,
236
+ kwargs=kwargs,
237
+ node_to_exclude=node_to_exclude,
238
+ fun_if_not_exist=fun_if_not_exist
239
+ )
240
+ values = inner_catcher.get_state_values()
241
+ return values
242
+
243
+ with catch_new_states(tag) as outer_catcher:
244
+ values = vmapped_fn(split_key(axis_size))
245
+ states = outer_catcher.get_states()
246
+ for state, value in zip(states, values):
247
+ state.value = value
118
248
 
119
249
  return target
120
250
 
121
251
 
122
252
  @set_module_as('brainstate.nn')
123
- def reset_all_states(target: Module, *args, **kwargs) -> Module:
253
+ def init_all_states(
254
+ target: T,
255
+ init_args: Tuple[Any, ...] | Any = (),
256
+ init_kwargs: Dict[str, Any] | None = None,
257
+ node_to_exclude: Filter = None,
258
+ ) -> T:
124
259
  """
125
- Collectively reset states of all children nodes in the given target.
260
+ Initialize all states for the given target module and its submodules.
126
261
 
127
- Args:
128
- target: The target Module.
262
+ This function initializes the states of the target module and all its submodules,
263
+ respecting any call order decorators that may be present on the init_state methods.
129
264
 
130
- Returns:
131
- The target Module.
265
+ Parameters
266
+ ----------
267
+ target : T
268
+ The target module whose states are to be initialized.
269
+ init_args : Tuple[Any, ...] | Any, optional
270
+ Positional arguments to be passed to each init_state method.
271
+ If a single non-tuple argument is provided, it will be wrapped in a tuple.
272
+ init_kwargs : Dict[str, Any] | None, optional
273
+ Keyword arguments to be passed to each init_state method.
274
+ If None, an empty dictionary will be used.
275
+ node_to_exclude : Filter, optional
276
+ A filter function or predicate to exclude certain nodes from initialization.
277
+
278
+ Returns
279
+ -------
280
+ T
281
+ The target module with all states initialized.
282
+
283
+ Raises
284
+ ------
285
+ AssertionError
286
+ If init_kwargs is provided but is not a dictionary.
132
287
  """
288
+ return call_all_functions(target, 'init_state', init_args, init_kwargs, node_to_exclude)
133
289
 
134
- nodes_with_order = []
135
290
 
136
- # reset node whose `init_state` has no `call_order`
137
- for path, node in nodes(target).filter(Module).items():
138
- if hasattr(node.reset_state, 'call_order'):
139
- nodes_with_order.append(node)
140
- else:
141
- node.reset_state(*args, **kwargs)
291
+ @set_module_as('brainstate.nn')
292
+ def vmap_init_all_states(
293
+ target: T,
294
+ init_args: Tuple[Any, ...] | Any = (),
295
+ init_kwargs: Dict[str, Any] | None = None,
296
+ axis_size: int = None,
297
+ node_to_exclude: Filter = None,
298
+ state_to_exclude: Filter = None,
299
+ state_tag: str | None = None,
300
+ ) -> T:
301
+ """
302
+ Initialize all vmap states for the given target module.
303
+
304
+ This function applies vectorized mapping (vmap) to initialize states across multiple
305
+ instances of the target module, effectively batching the initialization process.
306
+
307
+ Parameters:
308
+ -----------
309
+ target : T
310
+ The target module whose states are to be initialized.
311
+ init_args : Tuple[Any, ...] | Any, optional
312
+ Positional arguments to be passed to the init_all_states function. Default is an empty tuple.
313
+ init_kwargs : Dict[str, Any] | None, optional
314
+ Keyword arguments to be passed to the init_all_states function. Default is None.
315
+ axis_size : int, optional
316
+ The size of the batch axis for vmap. This must be specified and should be greater than 0.
317
+ node_to_exclude : Filter, optional
318
+ A filter to exclude certain nodes from initialization.
319
+ state_tag : str | None, optional
320
+ A tag to be used for catching new states.
142
321
 
143
- # reset the node's states
144
- for node in sorted(nodes_with_order, key=lambda x: x.reset_state.call_order):
145
- node.reset_state(*args, **kwargs)
322
+ Returns:
323
+ --------
324
+ T
325
+ The target module with initialized states.
146
326
 
327
+ Raises:
328
+ -------
329
+ AssertionError
330
+ If axis_size is not specified or is not greater than 0.
331
+ If init_kwargs is not a dictionary.
332
+ """
333
+
334
+ # return vmap_call_all_functions(
335
+ # target,
336
+ # 'init_state',
337
+ # args=init_args,
338
+ # kwargs=init_kwargs,
339
+ # axis_size=axis_size,
340
+ # node_to_exclude=node_to_exclude,
341
+ # tag=tag,
342
+ # )
343
+
344
+ def init_fn():
345
+ init_all_states(
346
+ target,
347
+ init_args=init_args,
348
+ init_kwargs=init_kwargs,
349
+ node_to_exclude=node_to_exclude,
350
+ )
351
+ return
352
+
353
+ vmap_new_states(init_fn, state_tag=state_tag, axis_size=axis_size, state_to_exclude=state_to_exclude)()
147
354
  return target
148
355
 
149
356
 
357
+ @set_module_as('brainstate.nn')
358
+ def reset_all_states(
359
+ target: T,
360
+ reset_args: Tuple[Any, ...] | Any = (),
361
+ reset_kwargs: Dict[str, Any] | None = None,
362
+ node_to_exclude: Filter = None,
363
+ ) -> T:
364
+ """
365
+ Reset all states for the given target module and its submodules.
366
+
367
+ This function resets the states of the target module and all its submodules,
368
+ respecting any call order decorators that may be present on the reset_state methods.
369
+
370
+ Parameters
371
+ ----------
372
+ target : T
373
+ The target module whose states are to be reset.
374
+ reset_args : Tuple[Any, ...] | Any, optional
375
+ Positional arguments to be passed to each reset_state method.
376
+ If a single non-tuple argument is provided, it will be wrapped in a tuple.
377
+ reset_kwargs : Dict[str, Any] | None, optional
378
+ Keyword arguments to be passed to each reset_state method.
379
+ If None, an empty dictionary will be used.
380
+ node_to_exclude : Filter, optional
381
+ A filter function or predicate to exclude certain nodes from reset.
382
+
383
+ Returns
384
+ -------
385
+ T
386
+ The target module with all states reset.
387
+
388
+ Raises
389
+ ------
390
+ AssertionError
391
+ If init_kwargs is provided but is not a dictionary.
392
+ """
393
+ return call_all_functions(
394
+ target,
395
+ fun_name='reset_state',
396
+ args=reset_args,
397
+ kwargs=reset_kwargs,
398
+ node_to_exclude=node_to_exclude
399
+ )
400
+
401
+
402
+ def vmap_reset_all_states(
403
+ target: T,
404
+ reset_args: Tuple[Any, ...] | Any = (),
405
+ reset_kwargs: Dict[str, Any] | None = None,
406
+ axis_size: int = None,
407
+ node_to_exclude: Filter = None,
408
+ tag: str | None = None,
409
+ ) -> T:
410
+ """
411
+ Reset all vmap states for the given target module.
412
+
413
+ This function applies vectorized mapping (vmap) to reset states across multiple
414
+ instances of the target module, effectively batching the reset process.
415
+
416
+ Parameters:
417
+ -----------
418
+ target : T
419
+ The target module whose states are to be reset.
420
+ reset_args : Tuple[Any, ...] | Any, optional
421
+ Positional arguments to be passed to the reset_all_states function. Default is an empty tuple.
422
+ reset_kwargs : Dict[str, Any] | None, optional
423
+ Keyword arguments to be passed to the reset_all_states function. Default is None.
424
+ axis_size : int, optional
425
+ The size of the batch axis for vmap. This must be specified and should be greater than 0.
426
+ node_to_exclude : Filter, optional
427
+ A filter to exclude certain nodes from reset.
428
+ tag : str | None, optional
429
+ A tag to be used for catching new states.
430
+
431
+ Returns:
432
+ --------
433
+ T
434
+ The target module with reset states.
435
+
436
+ Raises:
437
+ -------
438
+ AssertionError
439
+ If axis_size is not specified or is not greater than 0.
440
+ If reset_kwargs is not a dictionary.
441
+ """
442
+ return vmap_call_all_functions(
443
+ target,
444
+ fun_name='reset_state',
445
+ args=reset_args,
446
+ kwargs=reset_kwargs,
447
+ axis_size=axis_size,
448
+ node_to_exclude=node_to_exclude,
449
+ tag=tag,
450
+ )
451
+
452
+
150
453
  @set_module_as('brainstate.nn')
151
454
  def load_all_states(target: Module, state_dict: Dict, **kwargs):
152
455
  """
@@ -0,0 +1,36 @@
1
+ # Copyright 2025 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
+ import brainstate as bst
20
+
21
+
22
+ class Test_vmap_init_all_states:
23
+
24
+ def test_vmap_init_all_states(self):
25
+ gru = bst.nn.GRUCell(1, 2)
26
+ bst.nn.vmap_init_all_states(gru, axis_size=10)
27
+ print(gru)
28
+
29
+ def test_vmap_init_all_states_v2(self):
30
+ @bst.compile.jit
31
+ def init():
32
+ gru = bst.nn.GRUCell(1, 2)
33
+ bst.nn.vmap_init_all_states(gru, axis_size=10)
34
+ print(gru)
35
+
36
+ init()
@@ -0,0 +1,194 @@
1
+ # Copyright 2025 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
+ from __future__ import annotations
19
+
20
+ from collections import defaultdict
21
+
22
+ from typing import Any, Sequence, Hashable, Dict
23
+
24
+ from brainstate import environ
25
+ from brainstate.augment._mapping import vmap
26
+ from brainstate.typing import Filter
27
+ from ._module import Module
28
+
29
+ AxisName = Hashable
30
+
31
+ __all__ = [
32
+ 'EnvironContext',
33
+ 'Vmap',
34
+ ]
35
+
36
+
37
+ class EnvironContext(Module):
38
+ """
39
+ A wrapper class that provides an environment context for a given layer.
40
+
41
+ This class allows execution of a layer within a specific environment context,
42
+ which can be useful for controlling the execution environment of neural network layers.
43
+
44
+ This class is equivalent to the following code snippet:
45
+
46
+ ```python
47
+
48
+ import brainstate
49
+
50
+ with brainstate.environ.context(**context):
51
+ result = layer(*args, **kwargs)
52
+
53
+ ```
54
+
55
+ Attributes:
56
+ layer (Module): The layer to be executed within the environment context.
57
+ context (dict): The environment context parameters.
58
+ """
59
+
60
+ def __init__(self, layer: Module, **context):
61
+ """
62
+ Initialize the EnvironContext.
63
+
64
+ Args:
65
+ layer (Module): The layer to be wrapped with the environment context.
66
+ **context: Arbitrary keyword arguments representing the environment context parameters.
67
+ """
68
+ super().__init__()
69
+
70
+ assert isinstance(layer, Module), 'The layer must be an instance of Module.'
71
+ self.layer = layer
72
+ self.context = context
73
+
74
+ def update(self, *args, **kwargs):
75
+ """
76
+ Execute the wrapped layer within the specified environment context.
77
+
78
+ Args:
79
+ *args: Variable length argument list to be passed to the wrapped layer.
80
+ **kwargs: Arbitrary keyword arguments to be passed to the wrapped layer.
81
+
82
+ Returns:
83
+ The result of executing the wrapped layer within the environment context.
84
+ """
85
+ with environ.context(**self.context):
86
+ return self.layer(*args, **kwargs)
87
+
88
+ def add_context(self, **context):
89
+ """
90
+ Add additional environment context parameters to the existing context.
91
+
92
+ Args:
93
+ **context: Arbitrary keyword arguments representing the additional environment context parameters.
94
+ """
95
+ self.context.update(context)
96
+
97
+
98
+ def _filter_states(
99
+ module: Module,
100
+ filters: Filter | Dict[Filter, int],
101
+ ) -> Dict:
102
+ if filters is None:
103
+ filtered_states = None
104
+ elif isinstance(filters, dict):
105
+ in_states_filter = defaultdict(list)
106
+ for filter_, axis in filters:
107
+ assert isinstance(axis, int), 'The value of in_states must be the map axis, which should be an integer.'
108
+ in_states_filter[axis].append(filter_)
109
+ filtered_states = module.states(*in_states_filter.values())
110
+ in_states_axis = tuple(in_states_filter.keys())
111
+ filtered_states = {axis: states for axis, states in zip(in_states_axis, filtered_states)}
112
+ else:
113
+ filtered_states = module.states(filters)
114
+ return filtered_states
115
+
116
+
117
+ class Vmap(Module):
118
+ """
119
+ A class that applies vectorized mapping (vmap) to a given module.
120
+
121
+ This class wraps a module and applies vectorized mapping to its execution,
122
+ allowing for efficient parallel processing across specified axes.
123
+
124
+ Attributes:
125
+ module (Module): The module to be vmapped.
126
+ in_axes (int | None | Sequence[Any]): Specifies how to map over inputs.
127
+ out_axes (Any): Specifies how to map over outputs.
128
+ vmap_states (Filter | Dict[Filter, int]): Specifies which states to vmap and on which axes.
129
+ vmap_out_states (Filter | Dict[Filter, int]): Specifies which output states to vmap and on which axes.
130
+ axis_name (AxisName | None): Name of the axis being mapped over.
131
+ axis_size (int | None): Size of the axis being mapped over.
132
+ """
133
+
134
+ def __init__(
135
+ self,
136
+ module: Module,
137
+ in_axes: int | None | Sequence[Any] = 0,
138
+ out_axes: Any = 0,
139
+ vmap_states: Filter | Dict[Filter, int] = None,
140
+ vmap_out_states: Filter | Dict[Filter, int] = None,
141
+ axis_name: AxisName | None = None,
142
+ axis_size: int | None = None,
143
+ ):
144
+ """
145
+ Initialize the Vmap instance.
146
+
147
+ Args:
148
+ module (Module): The module to be vmapped.
149
+ in_axes (int | None | Sequence[Any], optional): Specifies how to map over inputs. Defaults to 0.
150
+ out_axes (Any, optional): Specifies how to map over outputs. Defaults to 0.
151
+ vmap_states (Filter | Dict[Filter, int], optional): Specifies which states to vmap and on which axes. Defaults to None.
152
+ vmap_out_states (Filter | Dict[Filter, int], optional): Specifies which output states to vmap and on which axes. Defaults to None.
153
+ axis_name (AxisName | None, optional): Name of the axis being mapped over. Defaults to None.
154
+ axis_size (int | None, optional): Size of the axis being mapped over. Defaults to None.
155
+ """
156
+ super().__init__()
157
+
158
+ # parameters
159
+ self.in_axes = in_axes
160
+ self.out_axes = out_axes
161
+ self.axis_name = axis_name
162
+ self.axis_size = axis_size
163
+ assert isinstance(module, Module), 'The module must be an instance of Module.'
164
+ self.module = module
165
+ vmap_states = _filter_states(module, vmap_states)
166
+ vmap_out_states = _filter_states(module, vmap_out_states)
167
+
168
+ @vmap(
169
+ in_axes=in_axes,
170
+ out_axes=out_axes,
171
+ in_states=vmap_states,
172
+ out_states=vmap_out_states,
173
+ axis_name=axis_name,
174
+ axis_size=axis_size,
175
+ )
176
+ def vmap_run(*args, **kwargs):
177
+ vmap_states_ = vmap_states
178
+ return module(*args, **kwargs)
179
+
180
+ # vmapped module
181
+ self.vmapped_fn = vmap_run
182
+
183
+ def update(self, *args, **kwargs):
184
+ """
185
+ Execute the vmapped module with the given arguments.
186
+
187
+ Args:
188
+ *args: Variable length argument list to be passed to the vmapped module.
189
+ **kwargs: Arbitrary keyword arguments to be passed to the vmapped module.
190
+
191
+ Returns:
192
+ The result of executing the vmapped module.
193
+ """
194
+ return self.vmapped_fn(*args, **kwargs)
@@ -17,10 +17,9 @@
17
17
 
18
18
  from __future__ import annotations
19
19
 
20
- from typing import Callable, Optional
21
-
22
20
  import brainunit as u
23
21
  import jax
22
+ from typing import Callable, Optional
24
23
 
25
24
  from brainstate import init, surrogate, environ
26
25
  from brainstate._state import HiddenState, ShortTermState