brainstate 0.1.7__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 -146
  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 -470
  58. brainstate/nn/_delay_test.py +238 -0
  59. brainstate/nn/_dropout.py +426 -426
  60. brainstate/nn/_dropout_test.py +100 -100
  61. brainstate/nn/_dynamics.py +1343 -1361
  62. brainstate/nn/_dynamics_test.py +78 -78
  63. brainstate/nn/_elementwise.py +1119 -1120
  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 -208
  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.7.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.7.dist-info → brainstate-0.1.9.dist-info}/WHEEL +1 -1
  129. {brainstate-0.1.7.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.7.dist-info/RECORD +0 -131
  133. {brainstate-0.1.7.dist-info → brainstate-0.1.9.dist-info}/top_level.txt +0 -0
brainstate/nn/_delay.py CHANGED
@@ -1,470 +1,509 @@
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
- import math
17
- import numbers
18
- from functools import partial
19
- from typing import Optional, Dict, Callable, Union, Sequence
20
-
21
- import brainunit as u
22
- import jax
23
- import jax.numpy as jnp
24
- import numpy as np
25
-
26
- from brainstate import environ
27
- from brainstate._state import ShortTermState, State
28
- from brainstate.compile import jit_error_if
29
- from brainstate.graph import Node
30
- from brainstate.typing import ArrayLike, PyTree
31
- from ._collective_ops import call_order
32
- from ._module import Module
33
-
34
- __all__ = [
35
- 'Delay', 'DelayAccess', 'StateWithDelay',
36
- ]
37
-
38
- _DELAY_ROTATE = 'rotation'
39
- _DELAY_CONCAT = 'concat'
40
- _INTERP_LINEAR = 'linear_interp'
41
- _INTERP_ROUND = 'round'
42
-
43
-
44
- def _get_delay(delay_time, delay_step):
45
- if delay_time is None:
46
- if delay_step is None:
47
- return 0., 0
48
- else:
49
- assert isinstance(delay_step, int), '"delay_step" should be an integer.'
50
- if delay_step == 0:
51
- return 0., 0
52
- with jax.ensure_compile_time_eval():
53
- delay_time = delay_step * environ.get_dt()
54
- else:
55
- assert delay_step is None, '"delay_step" should be None if "delay_time" is given.'
56
- # assert isinstance(delay_time, (int, float))
57
- with jax.ensure_compile_time_eval():
58
- delay_step = delay_time / environ.get_dt()
59
- delay_step = math.ceil(float(delay_step))
60
- return delay_time, delay_step
61
-
62
-
63
- class DelayAccess(Node):
64
- """
65
- The delay access class.
66
-
67
- Args:
68
- delay: The delay instance.
69
- time: The delay time.
70
- indices: The indices of the delay data.
71
- delay_entry: The delay entry.
72
- """
73
-
74
- __module__ = 'brainstate.nn'
75
-
76
- def __init__(
77
- self,
78
- delay: 'Delay',
79
- time: Union[None, int, float],
80
- delay_entry: str,
81
- *indices,
82
- ):
83
- super().__init__()
84
- self.refs = {'delay': delay}
85
- assert isinstance(delay, Delay), 'The input delay should be an instance of Delay.'
86
- self._delay_entry = delay_entry
87
- delay.register_entry(self._delay_entry, time)
88
- self.indices = indices
89
-
90
- def update(self):
91
- return self.refs['delay'].at(self._delay_entry, *self.indices)
92
-
93
-
94
- class Delay(Module):
95
- """
96
- Generate Delays for the given :py:class:`~.State` instance.
97
-
98
- The data in this delay variable is arranged as::
99
-
100
- delay = 0 [ data
101
- delay = 1 data
102
- delay = 2 data
103
- ... ....
104
- ... ....
105
- delay = length-1 data
106
- delay = length data ]
107
-
108
- Args:
109
- time: int, float. The delay time.
110
- init: Any. The delay data. It can be a Python number, like float, int, boolean values.
111
- It can also be arrays. Or a callable function or instance of ``Connector``.
112
- Note that ``initial_delay_data`` should be arranged as the following way::
113
-
114
- delay = 1 [ data
115
- delay = 2 data
116
- ... ....
117
- ... ....
118
- delay = length-1 data
119
- delay = length data ]
120
- entries: optional, dict. The delay access entries.
121
- delay_method: str. The method used for updating delay. Default None.
122
- """
123
-
124
- __module__ = 'brainstate.nn'
125
-
126
- max_time: float #
127
- max_length: int
128
- history: Optional[ShortTermState]
129
-
130
- def __init__(
131
- self,
132
- target_info: PyTree,
133
- time: Optional[Union[int, float, u.Quantity]] = None, # delay time
134
- init: Optional[Union[ArrayLike, Callable]] = None, # delay data before t0
135
- entries: Optional[Dict] = None, # delay access entry
136
- delay_method: Optional[str] = _DELAY_ROTATE, # delay method
137
- interp_method: str = _INTERP_LINEAR, # interpolation method
138
- take_aware_unit: bool = False
139
- ):
140
- # target information
141
- self.target_info = jax.tree.map(lambda a: jax.ShapeDtypeStruct(a.shape, a.dtype), target_info)
142
-
143
- # delay method
144
- assert delay_method in [_DELAY_ROTATE, _DELAY_CONCAT], (f'Un-supported delay method {delay_method}. '
145
- f'Only support {_DELAY_ROTATE} and {_DELAY_CONCAT}')
146
- self.delay_method = delay_method
147
-
148
- # interp method
149
- assert interp_method in [_INTERP_LINEAR, _INTERP_ROUND], (f'Un-supported interpolation method {interp_method}. '
150
- f'we only support: {[_INTERP_LINEAR, _INTERP_ROUND]}')
151
- self.interp_method = interp_method
152
-
153
- # delay length and time
154
- self.max_time, delay_length = _get_delay(time, None)
155
- self.max_length = delay_length + 1
156
-
157
- super().__init__()
158
-
159
- # delay data
160
- if init is not None:
161
- if not isinstance(init, (numbers.Number, jax.Array, np.ndarray, Callable)):
162
- raise TypeError(f'init should be Array, Callable, or None. But got {init}')
163
- self._init = init
164
- self._history = None
165
-
166
- # other info
167
- self._registered_entries = dict()
168
-
169
- # other info
170
- if entries is not None:
171
- for entry, delay_time in entries.items():
172
- self.register_entry(entry, delay_time)
173
-
174
- self.take_aware_unit = take_aware_unit
175
- self._unit = None
176
-
177
- @property
178
- def history(self):
179
- return self._history
180
-
181
- @history.setter
182
- def history(self, value):
183
- self._history = value
184
-
185
- def _f_to_init(self, a, batch_size, length):
186
- shape = list(a.shape)
187
- if batch_size is not None:
188
- shape.insert(0, batch_size)
189
- shape.insert(0, length)
190
- if isinstance(self._init, (jax.Array, np.ndarray, numbers.Number)):
191
- data = jnp.broadcast_to(jnp.asarray(self._init, a.dtype), shape)
192
- elif callable(self._init):
193
- data = self._init(shape, dtype=a.dtype)
194
- else:
195
- assert self._init is None, f'init should be Array, Callable, or None. but got {self._init}'
196
- data = jnp.zeros(shape, dtype=a.dtype)
197
- return data
198
-
199
- @call_order(3)
200
- def init_state(self, batch_size: int = None, **kwargs):
201
- fun = partial(self._f_to_init, length=self.max_length, batch_size=batch_size)
202
- self.history = ShortTermState(jax.tree.map(fun, self.target_info))
203
-
204
- def reset_state(self, batch_size: int = None, **kwargs):
205
- fun = partial(self._f_to_init, length=self.max_length, batch_size=batch_size)
206
- self.history.value = jax.tree.map(fun, self.target_info)
207
-
208
- def register_delay(
209
- self,
210
- delay_time: Optional[Union[int, float]] = None,
211
- delay_step: Optional[int] = None,
212
- ):
213
- if isinstance(delay_time, (np.ndarray, jax.Array)):
214
- assert delay_time.size == 1 and delay_time.ndim == 0
215
- delay_time = delay_time.item()
216
-
217
- _, delay_step = _get_delay(delay_time, delay_step)
218
-
219
- # delay variable
220
- if self.max_length <= delay_step + 1:
221
- self.max_length = delay_step + 1
222
- self.max_time = delay_time
223
- return self
224
-
225
- def register_entry(
226
- self,
227
- entry: str,
228
- delay_time: Optional[Union[int, float]] = None,
229
- delay_step: Optional[int] = None,
230
- ) -> 'Delay':
231
- """
232
- Register an entry to access the delay data.
233
-
234
- Args:
235
- entry: str. The entry to access the delay data.
236
- delay_time: The delay time of the entry (can be a float).
237
- delay_step: The delay step of the entry (must be an int). ``delat_step = delay_time / dt``.
238
-
239
- Returns:
240
- Return the self.
241
- """
242
- if entry in self._registered_entries:
243
- raise KeyError(f'Entry {entry} has been registered. '
244
- f'The existing delay for the key {entry} is {self._registered_entries[entry]}. '
245
- f'The new delay for the key {entry} is {delay_time}. '
246
- f'You can use another key. ')
247
-
248
- if isinstance(delay_time, (np.ndarray, jax.Array)):
249
- assert delay_time.size == 1 and delay_time.ndim == 0
250
- delay_time = delay_time.item()
251
-
252
- _, delay_step = _get_delay(delay_time, delay_step)
253
-
254
- # delay variable
255
- if self.max_length <= delay_step + 1:
256
- self.max_length = delay_step + 1
257
- self.max_time = delay_time
258
- self._registered_entries[entry] = delay_step
259
- return self
260
-
261
- def access(
262
- self,
263
- entry: str = None,
264
- time: Sequence = None,
265
- ) -> DelayAccess:
266
- return DelayAccess(self, time, delay_entry=entry)
267
-
268
- def at(self, entry: str, *indices) -> ArrayLike:
269
- """
270
- Get the data at the given entry.
271
-
272
- Args:
273
- entry: str. The entry to access the data.
274
- *indices: The slicing indices. Not include the slice at the batch dimension.
275
-
276
- Returns:
277
- The data.
278
- """
279
- assert isinstance(entry, str), (f'entry should be a string for describing the '
280
- f'entry of the delay data. But we got {entry}.')
281
- if entry not in self._registered_entries:
282
- raise KeyError(f'Does not find delay entry "{entry}".')
283
- delay_step = self._registered_entries[entry]
284
- if delay_step is None:
285
- delay_step = 0
286
- return self.retrieve_at_step(delay_step, *indices)
287
-
288
- def retrieve_at_step(self, delay_step, *indices) -> PyTree:
289
- """
290
- Retrieve the delay data at the given delay time step (the integer to indicate the time step).
291
-
292
- Parameters
293
- ----------
294
- delay_step: int_like
295
- Retrieve the data at the given time step.
296
- indices: tuple
297
- The indices to slice the data.
298
-
299
- Returns
300
- -------
301
- delay_data: The delay data at the given delay step.
302
-
303
- """
304
- assert self.history is not None, 'The delay history is not initialized.'
305
- assert delay_step is not None, 'The delay step should be given.'
306
-
307
- if environ.get(environ.JIT_ERROR_CHECK, False):
308
- def _check_delay(delay_len):
309
- raise ValueError(f'The request delay length should be less than the '
310
- f'maximum delay {self.max_length - 1}. But we got {delay_len}')
311
-
312
- jit_error_if(delay_step >= self.max_length, _check_delay, delay_step)
313
-
314
- # rotation method
315
- if self.delay_method == _DELAY_ROTATE:
316
- i = environ.get(environ.I, desc='The time step index.')
317
- di = i - delay_step
318
- delay_idx = jnp.asarray(di % self.max_length, dtype=jnp.int32)
319
- delay_idx = jax.lax.stop_gradient(delay_idx)
320
-
321
- elif self.delay_method == _DELAY_CONCAT:
322
- delay_idx = delay_step
323
-
324
- else:
325
- raise ValueError(f'Unknown delay updating method "{self.delay_method}"')
326
-
327
- # the delay index
328
- if hasattr(delay_idx, 'dtype') and not jnp.issubdtype(delay_idx.dtype, jnp.integer):
329
- raise ValueError(f'"delay_len" must be integer, but we got {delay_idx}')
330
- indices = (delay_idx,) + indices
331
-
332
- # the delay data
333
- if self._unit is None:
334
- return jax.tree.map(lambda a: a[indices], self.history.value)
335
- else:
336
- return jax.tree.map(
337
- lambda hist, unit: u.maybe_decimal(hist[indices] * unit),
338
- self.history.value,
339
- self._unit
340
- )
341
-
342
- def retrieve_at_time(self, delay_time, *indices) -> PyTree:
343
- """
344
- Retrieve the delay data at the given delay time step (the integer to indicate the time step).
345
-
346
- Parameters
347
- ----------
348
- delay_time: float
349
- Retrieve the data at the given time.
350
- indices: tuple
351
- The indices to slice the data.
352
-
353
- Returns
354
- -------
355
- delay_data: The delay data at the given delay step.
356
-
357
- """
358
- assert self.history is not None, 'The delay history is not initialized.'
359
- assert delay_time is not None, 'The delay time should be given.'
360
-
361
- current_time = environ.get(environ.T, desc='The current time.')
362
- dt = environ.get_dt()
363
-
364
- if environ.get(environ.JIT_ERROR_CHECK, False):
365
- def _check_delay(t_now, t_delay):
366
- raise ValueError(f'The request delay time should be within '
367
- f'[{t_now - self.max_time - dt}, {t_now}], '
368
- f'but we got {t_delay}')
369
-
370
- jit_error_if(
371
- jnp.logical_or(delay_time > current_time,
372
- delay_time < current_time - self.max_time - dt),
373
- _check_delay,
374
- current_time,
375
- delay_time
376
- )
377
-
378
- diff = current_time - delay_time
379
- float_time_step = diff / dt
380
-
381
- if self.interp_method == _INTERP_LINEAR: # "linear" interpolation
382
- data_at_t0 = self.retrieve_at_step(jnp.asarray(jnp.floor(float_time_step), dtype=jnp.int32), *indices)
383
- data_at_t1 = self.retrieve_at_step(jnp.asarray(jnp.ceil(float_time_step), dtype=jnp.int32), *indices)
384
- t_diff = float_time_step - jnp.floor(float_time_step)
385
- return jax.tree.map(lambda a, b: a * (1 - t_diff) + b * t_diff, data_at_t0, data_at_t1)
386
-
387
- elif self.interp_method == _INTERP_ROUND: # "round" interpolation
388
- return self.retrieve_at_step(
389
- jnp.asarray(jnp.round(float_time_step), dtype=jnp.int32),
390
- *indices
391
- )
392
-
393
- else: # raise error
394
- raise ValueError(f'Un-supported interpolation method {self.interp_method}, '
395
- f'we only support: {[_INTERP_LINEAR, _INTERP_ROUND]}')
396
-
397
- def update(self, current: PyTree) -> None:
398
- """
399
- Update delay variable with the new data.
400
- """
401
- assert self.history is not None, 'The delay history is not initialized.'
402
-
403
- if self.take_aware_unit and self._unit is None:
404
- self._unit = jax.tree.map(lambda x: u.get_unit(x), current, is_leaf=u.math.is_quantity)
405
-
406
- # update the delay data at the rotation index
407
- if self.delay_method == _DELAY_ROTATE:
408
- i = environ.get(environ.I)
409
- idx = jnp.asarray(i % self.max_length, dtype=environ.dutype())
410
- idx = jax.lax.stop_gradient(idx)
411
- self.history.value = jax.tree.map(
412
- lambda hist, cur: hist.at[idx].set(cur),
413
- self.history.value,
414
- current
415
- )
416
- # update the delay data at the first position
417
- elif self.delay_method == _DELAY_CONCAT:
418
- current = jax.tree.map(lambda a: jnp.expand_dims(a, 0), current)
419
- if self.max_length > 1:
420
- self.history.value = jax.tree.map(
421
- lambda hist, cur: jnp.concatenate([cur, hist[:-1]], axis=0),
422
- self.history.value,
423
- current
424
- )
425
- else:
426
- self.history.value = current
427
-
428
- else:
429
- raise ValueError(f'Unknown updating method "{self.delay_method}"')
430
-
431
-
432
-
433
-
434
- class StateWithDelay(Delay):
435
- """
436
- A ``State`` type that defines the state in a differential equation.
437
- """
438
-
439
- __module__ = 'brainstate.nn'
440
-
441
- state: State # state
442
-
443
- def __init__(self, target: Node, item: str):
444
- super().__init__(None)
445
-
446
- self._target = target
447
- self._target_term = item
448
-
449
- @property
450
- def state(self) -> State:
451
- r = getattr(self._target, self._target_term)
452
- if not isinstance(r, State):
453
- raise TypeError(f'The term "{self._target_term}" in the module "{self._target}" is not a State.')
454
- return r
455
-
456
- @call_order(3)
457
- def init_state(self, *args, **kwargs):
458
- """
459
- State initialization function.
460
- """
461
- state = self.state
462
- self.target_info = jax.tree.map(lambda a: jax.ShapeDtypeStruct(a.shape, a.dtype), state.value)
463
- super().init_state(*args, **kwargs)
464
-
465
- def update(self, *args) -> None:
466
- """
467
- Update the delay variable with the new data.
468
- """
469
- value = self.state.value
470
- return super().update(value)
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
+ import numbers
17
+ from functools import partial
18
+ from typing import Optional, Dict, Callable, Union, Sequence
19
+
20
+ import brainunit as u
21
+ import jax
22
+ import jax.numpy as jnp
23
+ import numpy as np
24
+
25
+ from brainstate import environ
26
+ from brainstate._state import ShortTermState, State
27
+ from brainstate.compile import jit_error_if
28
+ from brainstate.graph import Node
29
+ from brainstate.typing import ArrayLike, PyTree
30
+ from ._collective_ops import call_order
31
+ from ._module import Module
32
+
33
+ __all__ = [
34
+ 'Delay', 'DelayAccess', 'StateWithDelay',
35
+ ]
36
+
37
+ _DELAY_ROTATE = 'rotation'
38
+ _DELAY_CONCAT = 'concat'
39
+ _INTERP_LINEAR = 'linear_interp'
40
+ _INTERP_ROUND = 'round'
41
+
42
+
43
+ def _get_delay(delay_time):
44
+ if delay_time is None:
45
+ return 0. * environ.get_dt(), 0
46
+ delay_step = delay_time / environ.get_dt()
47
+ assert u.get_dim(delay_step) == u.DIMENSIONLESS
48
+ delay_step = jnp.ceil(delay_step).astype(environ.ditype())
49
+ return delay_time, delay_step
50
+
51
+
52
+ class DelayAccess(Node):
53
+ """
54
+ Accessor node for a registered entry in a Delay instance.
55
+
56
+ This node holds a reference to a Delay and a named entry that was
57
+ registered on that Delay. It is used by graphs to query delayed
58
+ values by delegating to the underlying Delay instance.
59
+
60
+ Args:
61
+ delay: The delay instance.
62
+ time: The delay time.
63
+ delay_entry: The delay entry.
64
+ """
65
+
66
+ __module__ = 'brainstate.nn'
67
+
68
+ def __init__(
69
+ self,
70
+ delay: 'Delay',
71
+ time: Union[None, int, float],
72
+ delay_entry: str,
73
+ ):
74
+ super().__init__()
75
+ self.refs = {'delay': delay}
76
+ assert isinstance(delay, Delay), 'The input delay should be an instance of Delay.'
77
+ self._delay_entry = delay_entry
78
+ self.delay_info = delay.register_entry(self._delay_entry, time)
79
+
80
+ def update(self):
81
+ return self.refs['delay'].at(self._delay_entry)
82
+
83
+
84
+ class Delay(Module):
85
+ """
86
+ Generate Delays for the given :py:class:`~.State` instance.
87
+
88
+ The data in this delay variable is arranged as::
89
+
90
+ delay = 0 [ data
91
+ delay = 1 data
92
+ delay = 2 data
93
+ ... ....
94
+ ... ....
95
+ delay = length-1 data
96
+ delay = length data ]
97
+
98
+ Args:
99
+ time: int, float. The delay time.
100
+ init: Any. The delay data. It can be a Python number, like float, int, boolean values.
101
+ It can also be arrays. Or a callable function or instance of ``Connector``.
102
+ Note that ``initial_delay_data`` should be arranged as the following way::
103
+
104
+ delay = 1 [ data
105
+ delay = 2 data
106
+ ... ....
107
+ ... ....
108
+ delay = length-1 data
109
+ delay = length data ]
110
+ entries: optional, dict. The delay access entries.
111
+ delay_method: str. The method used for updating delay. Default None.
112
+ """
113
+
114
+ __module__ = 'brainstate.nn'
115
+
116
+ max_time: float #
117
+ max_length: int
118
+ history: Optional[ShortTermState]
119
+
120
+ def __init__(
121
+ self,
122
+ target_info: PyTree,
123
+ time: Optional[Union[int, float, u.Quantity]] = None, # delay time
124
+ init: Optional[Union[ArrayLike, Callable]] = None, # delay data before t0
125
+ entries: Optional[Dict] = None, # delay access entry
126
+ delay_method: Optional[str] = _DELAY_ROTATE, # delay method
127
+ interp_method: str = _INTERP_LINEAR, # interpolation method
128
+ take_aware_unit: bool = False
129
+ ):
130
+ # target information
131
+ self.target_info = jax.tree.map(lambda a: jax.ShapeDtypeStruct(a.shape, a.dtype), target_info)
132
+
133
+ # delay method
134
+ assert delay_method in [_DELAY_ROTATE, _DELAY_CONCAT], (
135
+ f'Un-supported delay method {delay_method}. '
136
+ f'Only support {_DELAY_ROTATE} and {_DELAY_CONCAT}'
137
+ )
138
+ self.delay_method = delay_method
139
+
140
+ # interp method
141
+ assert interp_method in [_INTERP_LINEAR, _INTERP_ROUND], (
142
+ f'Un-supported interpolation method {interp_method}. '
143
+ f'we only support: {[_INTERP_LINEAR, _INTERP_ROUND]}'
144
+ )
145
+ self.interp_method = interp_method
146
+
147
+ # delay length and time
148
+ with jax.ensure_compile_time_eval():
149
+ self.max_time, delay_length = _get_delay(time)
150
+ self.max_length = delay_length + 1
151
+
152
+ super().__init__()
153
+
154
+ # delay data
155
+ if init is not None:
156
+ if not isinstance(init, (numbers.Number, jax.Array, np.ndarray, Callable)):
157
+ raise TypeError(f'init should be Array, Callable, or None. But got {init}')
158
+ self._init = init
159
+ self._history = None
160
+
161
+ # other info
162
+ self._registered_entries = dict()
163
+
164
+ # other info
165
+ if entries is not None:
166
+ for entry, delay_time in entries.items():
167
+ if isinstance(delay_time, (tuple, list)):
168
+ self.register_entry(entry, *delay_time)
169
+ else:
170
+ self.register_entry(entry, delay_time)
171
+
172
+ self.take_aware_unit = take_aware_unit
173
+ self._unit = None
174
+
175
+ @property
176
+ def history(self):
177
+ return self._history
178
+
179
+ @history.setter
180
+ def history(self, value):
181
+ self._history = value
182
+
183
+ def _f_to_init(self, a, batch_size, length):
184
+ shape = list(a.shape)
185
+ if batch_size is not None:
186
+ shape.insert(0, batch_size)
187
+ shape.insert(0, length)
188
+ if isinstance(self._init, (jax.Array, np.ndarray, numbers.Number)):
189
+ data = jnp.broadcast_to(jnp.asarray(self._init, a.dtype), shape)
190
+ elif callable(self._init):
191
+ data = self._init(shape, dtype=a.dtype)
192
+ else:
193
+ assert self._init is None, f'init should be Array, Callable, or None. but got {self._init}'
194
+ data = jnp.zeros(shape, dtype=a.dtype)
195
+ return data
196
+
197
+ @call_order(3)
198
+ def init_state(self, batch_size: int = None, **kwargs):
199
+ fun = partial(self._f_to_init, length=self.max_length, batch_size=batch_size)
200
+ self.history = ShortTermState(jax.tree.map(fun, self.target_info))
201
+
202
+ def reset_state(self, batch_size: int = None, **kwargs):
203
+ fun = partial(self._f_to_init, length=self.max_length, batch_size=batch_size)
204
+ self.history.value = jax.tree.map(fun, self.target_info)
205
+
206
+ def register_delay(self, *delay_time):
207
+ """
208
+ Register delay times and update the maximum delay configuration.
209
+
210
+ This method processes one or more delay times, validates their format and consistency,
211
+ and updates the delay buffer size if necessary. It handles both scalar and vector
212
+ delay times, ensuring all vector delays have the same size.
213
+
214
+ Args:
215
+ *delay_time: Variable number of delay time arguments. The first argument should be
216
+ the primary delay time (float, int, or array-like). Additional arguments are
217
+ treated as indices or secondary delay parameters. All delay times should be
218
+ non-negative numbers or arrays of the same size.
219
+
220
+ Returns:
221
+ tuple or None: If delay_time[0] is None, returns None. Otherwise, returns a tuple
222
+ containing (delay_step, *delay_time[1:]) where delay_step is the computed
223
+ delay step in integer time units, and the remaining elements are the
224
+ additional delay parameters passed in.
225
+
226
+ Raises:
227
+ AssertionError: If no delay time is provided (empty delay_time).
228
+ ValueError: If delay times have inconsistent sizes when using vector delays,
229
+ or if delay times are not scalar or 1D arrays.
230
+
231
+ Note:
232
+ - The method updates self.max_time and self.max_length if the new delay
233
+ requires a larger buffer size.
234
+ - Delay steps are computed using the current environment time step (dt).
235
+ - All delay indices (delay_time[1:]) must be integers.
236
+ - Vector delays must all have the same size as the first delay time.
237
+
238
+ Example:
239
+ >>> delay_obj.register_delay(5.0) # Register 5ms delay
240
+ >>> delay_obj.register_delay(jnp.array([2.0, 3.0]), 0, 1) # Vector delay with indices
241
+ """
242
+ assert len(delay_time) >= 1, 'You should provide at least one delay time.'
243
+ delay_size = u.math.size(delay_time[0])
244
+ for dt in delay_time[1:]:
245
+ assert jnp.issubdtype(u.math.get_dtype(dt), jnp.integer), f'The index should be integer. But got {dt}.'
246
+ # delay_size = u.math.size(delay_time[0])
247
+ # for dt in delay_time:
248
+ # if u.math.ndim(dt) == 0:
249
+ # pass
250
+ # elif u.math.ndim(dt) == 1:
251
+ # if u.math.size(dt) != delay_size:
252
+ # raise ValueError(
253
+ # f'The delay time should be a scalar or a vector with the same size. '
254
+ # f'But got {delay_time}. The delay time {dt} has size {u.math.size(dt)}'
255
+ # )
256
+ # else:
257
+ # raise ValueError(f'The delay time should be a scalar/vector. But got {dt}.')
258
+ if delay_time[0] is None:
259
+ return None
260
+ with jax.ensure_compile_time_eval():
261
+ time, delay_step = _get_delay(delay_time[0])
262
+ max_delay_step = jnp.max(delay_step)
263
+ self.max_time = u.math.max(time)
264
+
265
+ # delay variable
266
+ if self.max_length <= max_delay_step + 1:
267
+ self.max_length = max_delay_step + 1
268
+ return delay_step, *delay_time[1:]
269
+
270
+ def register_entry(self, entry: str, *delay_time) -> 'Delay':
271
+ """
272
+ Register an entry to access the delay data.
273
+
274
+ Args:
275
+ entry: str. The entry to access the delay data.
276
+ delay_time: The delay time of the entry, the first element is the delay time,
277
+ the second and later element is the index.
278
+ """
279
+ if entry in self._registered_entries:
280
+ raise KeyError(
281
+ f'Entry {entry} has been registered. '
282
+ f'The existing delay for the key {entry} is {self._registered_entries[entry]}. '
283
+ f'The new delay for the key {entry} is {delay_time}. '
284
+ f'You can use another key. '
285
+ )
286
+ delay_info = self.register_delay(*delay_time)
287
+ self._registered_entries[entry] = delay_info
288
+ return delay_info
289
+
290
+ def access(self, entry: str, delay_time: Sequence) -> DelayAccess:
291
+ """
292
+ Create a DelayAccess object for a specific delay entry and delay time.
293
+
294
+ Args:
295
+ entry (str): The name of the delay entry to access.
296
+ delay_time (Sequence): The delay time or parameters associated with the entry.
297
+
298
+ Returns:
299
+ DelayAccess: An object that provides access to the delay data for the specified entry and time.
300
+ """
301
+ return DelayAccess(self, delay_time, delay_entry=entry)
302
+
303
+ def at(self, entry: str) -> ArrayLike:
304
+ """
305
+ Get the data at the given entry.
306
+
307
+ Args:
308
+ entry: str. The entry to access the data.
309
+
310
+ Returns:
311
+ The data.
312
+ """
313
+ assert isinstance(entry, str), (f'entry should be a string for describing the '
314
+ f'entry of the delay data. But we got {entry}.')
315
+ if entry not in self._registered_entries:
316
+ raise KeyError(f'Does not find delay entry "{entry}".')
317
+ delay_step = self._registered_entries[entry]
318
+ if delay_step is None:
319
+ delay_step = (0,)
320
+ return self.retrieve_at_step(*delay_step)
321
+
322
+ def retrieve_at_step(self, delay_step, *indices) -> PyTree:
323
+ """
324
+ Retrieve the delay data at the given delay time step (the integer to indicate the time step).
325
+
326
+ Parameters
327
+ ----------
328
+ delay_step: int_like
329
+ Retrieve the data at the given time step.
330
+ indices: tuple
331
+ The indices to slice the data.
332
+
333
+ Returns
334
+ -------
335
+ delay_data: The delay data at the given delay step.
336
+
337
+ """
338
+ assert self.history is not None, 'The delay history is not initialized.'
339
+ assert delay_step is not None, 'The delay step should be given.'
340
+
341
+ if environ.get(environ.JIT_ERROR_CHECK, False):
342
+ def _check_delay(delay_len):
343
+ raise ValueError(
344
+ f'The request delay length should be less than the '
345
+ f'maximum delay {self.max_length - 1}. But we got {delay_len}'
346
+ )
347
+
348
+ jit_error_if(delay_step >= self.max_length, _check_delay, delay_step)
349
+
350
+ # rotation method
351
+ with jax.ensure_compile_time_eval():
352
+ if self.delay_method == _DELAY_ROTATE:
353
+ i = environ.get(environ.I, desc='The time step index.')
354
+ di = i - delay_step
355
+ delay_idx = jnp.asarray(di % self.max_length, dtype=jnp.int32)
356
+ delay_idx = jax.lax.stop_gradient(delay_idx)
357
+
358
+ elif self.delay_method == _DELAY_CONCAT:
359
+ delay_idx = delay_step
360
+
361
+ else:
362
+ raise ValueError(f'Unknown delay updating method "{self.delay_method}"')
363
+
364
+ # the delay index
365
+ if hasattr(delay_idx, 'dtype') and not jnp.issubdtype(delay_idx.dtype, jnp.integer):
366
+ raise ValueError(f'"delay_len" must be integer, but we got {delay_idx}')
367
+ indices = (delay_idx,) + indices
368
+
369
+ # the delay data
370
+ if self._unit is None:
371
+ return jax.tree.map(lambda a: a[indices], self.history.value)
372
+ else:
373
+ return jax.tree.map(
374
+ lambda hist, unit: u.maybe_decimal(hist[indices] * unit),
375
+ self.history.value,
376
+ self._unit
377
+ )
378
+
379
+ def retrieve_at_time(self, delay_time, *indices) -> PyTree:
380
+ """
381
+ Retrieve the delay data at the given delay time step (the integer to indicate the time step).
382
+
383
+ Parameters
384
+ ----------
385
+ delay_time: float
386
+ Retrieve the data at the given time.
387
+ indices: tuple
388
+ The indices to slice the data.
389
+
390
+ Returns
391
+ -------
392
+ delay_data: The delay data at the given delay step.
393
+
394
+ """
395
+ assert self.history is not None, 'The delay history is not initialized.'
396
+ assert delay_time is not None, 'The delay time should be given.'
397
+
398
+ current_time = environ.get(environ.T, desc='The current time.')
399
+ dt = environ.get_dt()
400
+
401
+ if environ.get(environ.JIT_ERROR_CHECK, False):
402
+ def _check_delay(t_now, t_delay):
403
+ raise ValueError(
404
+ f'The request delay time should be within '
405
+ f'[{t_now - self.max_time - dt}, {t_now}], '
406
+ f'but we got {t_delay}'
407
+ )
408
+
409
+ jit_error_if(
410
+ jnp.logical_or(
411
+ delay_time > current_time,
412
+ delay_time < current_time - self.max_time - dt
413
+ ),
414
+ _check_delay,
415
+ current_time,
416
+ delay_time
417
+ )
418
+
419
+ with jax.ensure_compile_time_eval():
420
+ diff = current_time - delay_time
421
+ float_time_step = diff / dt
422
+
423
+ if self.interp_method == _INTERP_LINEAR: # "linear" interpolation
424
+ data_at_t0 = self.retrieve_at_step(jnp.asarray(jnp.floor(float_time_step), dtype=jnp.int32), *indices)
425
+ data_at_t1 = self.retrieve_at_step(jnp.asarray(jnp.ceil(float_time_step), dtype=jnp.int32), *indices)
426
+ t_diff = float_time_step - jnp.floor(float_time_step)
427
+ return jax.tree.map(lambda a, b: a * (1 - t_diff) + b * t_diff, data_at_t0, data_at_t1)
428
+
429
+ elif self.interp_method == _INTERP_ROUND: # "round" interpolation
430
+ return self.retrieve_at_step(jnp.asarray(jnp.round(float_time_step), dtype=jnp.int32), *indices)
431
+
432
+ else: # raise error
433
+ raise ValueError(f'Un-supported interpolation method {self.interp_method}, '
434
+ f'we only support: {[_INTERP_LINEAR, _INTERP_ROUND]}')
435
+
436
+ def update(self, current: PyTree) -> None:
437
+ """
438
+ Update delay variable with the new data.
439
+ """
440
+
441
+ with jax.ensure_compile_time_eval():
442
+ assert self.history is not None, 'The delay history is not initialized.'
443
+
444
+ if self.take_aware_unit and self._unit is None:
445
+ self._unit = jax.tree.map(lambda x: u.get_unit(x), current, is_leaf=u.math.is_quantity)
446
+
447
+ # update the delay data at the rotation index
448
+ if self.delay_method == _DELAY_ROTATE:
449
+ i = environ.get(environ.I)
450
+ idx = jnp.asarray(i % self.max_length, dtype=environ.dutype())
451
+ idx = jax.lax.stop_gradient(idx)
452
+ self.history.value = jax.tree.map(
453
+ lambda hist, cur: hist.at[idx].set(cur),
454
+ self.history.value,
455
+ current
456
+ )
457
+ # update the delay data at the first position
458
+ elif self.delay_method == _DELAY_CONCAT:
459
+ current = jax.tree.map(lambda a: jnp.expand_dims(a, 0), current)
460
+ if self.max_length > 1:
461
+ self.history.value = jax.tree.map(
462
+ lambda hist, cur: jnp.concatenate([cur, hist[:-1]], axis=0),
463
+ self.history.value,
464
+ current
465
+ )
466
+ else:
467
+ self.history.value = current
468
+
469
+ else:
470
+ raise ValueError(f'Unknown updating method "{self.delay_method}"')
471
+
472
+
473
+ class StateWithDelay(Delay):
474
+ """
475
+ A ``State`` type that defines the state in a differential equation.
476
+ """
477
+
478
+ __module__ = 'brainstate.nn'
479
+
480
+ state: State # state
481
+
482
+ def __init__(self, target: Node, item: str, init: Callable = None):
483
+ super().__init__(None, init=init)
484
+
485
+ self._target = target
486
+ self._target_term = item
487
+
488
+ @property
489
+ def state(self) -> State:
490
+ r = getattr(self._target, self._target_term)
491
+ if not isinstance(r, State):
492
+ raise TypeError(f'The term "{self._target_term}" in the module "{self._target}" is not a State.')
493
+ return r
494
+
495
+ @call_order(3)
496
+ def init_state(self, *args, **kwargs):
497
+ """
498
+ State initialization function.
499
+ """
500
+ state = self.state
501
+ self.target_info = jax.tree.map(lambda a: jax.ShapeDtypeStruct(a.shape, a.dtype), state.value)
502
+ super().init_state(*args, **kwargs)
503
+
504
+ def update(self, *args) -> None:
505
+ """
506
+ Update the delay variable with the new data.
507
+ """
508
+ value = self.state.value
509
+ return super().update(value)