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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (133) hide show
  1. brainstate/__init__.py +58 -51
  2. brainstate/_compatible_import.py +148 -148
  3. brainstate/_state.py +1605 -1663
  4. brainstate/_state_test.py +52 -52
  5. brainstate/_utils.py +47 -47
  6. brainstate/augment/__init__.py +30 -30
  7. brainstate/augment/_autograd.py +778 -778
  8. brainstate/augment/_autograd_test.py +1289 -1289
  9. brainstate/augment/_eval_shape.py +99 -99
  10. brainstate/augment/_eval_shape_test.py +38 -38
  11. brainstate/augment/_mapping.py +1060 -1060
  12. brainstate/augment/_mapping_test.py +597 -597
  13. brainstate/augment/_random.py +151 -151
  14. brainstate/compile/__init__.py +38 -38
  15. brainstate/compile/_ad_checkpoint.py +204 -204
  16. brainstate/compile/_ad_checkpoint_test.py +49 -49
  17. brainstate/compile/_conditions.py +256 -256
  18. brainstate/compile/_conditions_test.py +220 -220
  19. brainstate/compile/_error_if.py +92 -92
  20. brainstate/compile/_error_if_test.py +52 -52
  21. brainstate/compile/_jit.py +346 -346
  22. brainstate/compile/_jit_test.py +143 -143
  23. brainstate/compile/_loop_collect_return.py +536 -536
  24. brainstate/compile/_loop_collect_return_test.py +58 -58
  25. brainstate/compile/_loop_no_collection.py +184 -184
  26. brainstate/compile/_loop_no_collection_test.py +50 -50
  27. brainstate/compile/_make_jaxpr.py +888 -888
  28. brainstate/compile/_make_jaxpr_test.py +156 -156
  29. brainstate/compile/_progress_bar.py +202 -202
  30. brainstate/compile/_unvmap.py +159 -159
  31. brainstate/compile/_util.py +147 -147
  32. brainstate/environ.py +563 -563
  33. brainstate/environ_test.py +62 -62
  34. brainstate/functional/__init__.py +27 -26
  35. brainstate/graph/__init__.py +29 -29
  36. brainstate/graph/_graph_node.py +244 -244
  37. brainstate/graph/_graph_node_test.py +73 -73
  38. brainstate/graph/_graph_operation.py +1738 -1738
  39. brainstate/graph/_graph_operation_test.py +563 -563
  40. brainstate/init/__init__.py +26 -26
  41. brainstate/init/_base.py +52 -52
  42. brainstate/init/_generic.py +244 -244
  43. brainstate/init/_random_inits.py +553 -553
  44. brainstate/init/_random_inits_test.py +149 -149
  45. brainstate/init/_regular_inits.py +105 -105
  46. brainstate/init/_regular_inits_test.py +50 -50
  47. brainstate/mixin.py +365 -363
  48. brainstate/mixin_test.py +77 -73
  49. brainstate/nn/__init__.py +135 -131
  50. brainstate/{functional → nn}/_activations.py +808 -813
  51. brainstate/{functional → nn}/_activations_test.py +331 -331
  52. brainstate/nn/_collective_ops.py +514 -514
  53. brainstate/nn/_collective_ops_test.py +43 -43
  54. brainstate/nn/_common.py +178 -178
  55. brainstate/nn/_conv.py +501 -501
  56. brainstate/nn/_conv_test.py +238 -238
  57. brainstate/nn/_delay.py +509 -502
  58. brainstate/nn/_delay_test.py +238 -184
  59. brainstate/nn/_dropout.py +426 -426
  60. brainstate/nn/_dropout_test.py +100 -100
  61. brainstate/nn/_dynamics.py +1343 -1343
  62. brainstate/nn/_dynamics_test.py +78 -78
  63. brainstate/nn/_elementwise.py +1119 -1119
  64. brainstate/nn/_elementwise_test.py +169 -169
  65. brainstate/nn/_embedding.py +58 -58
  66. brainstate/nn/_exp_euler.py +92 -92
  67. brainstate/nn/_exp_euler_test.py +35 -35
  68. brainstate/nn/_fixedprob.py +239 -239
  69. brainstate/nn/_fixedprob_test.py +114 -114
  70. brainstate/nn/_inputs.py +608 -608
  71. brainstate/nn/_linear.py +424 -424
  72. brainstate/nn/_linear_mv.py +83 -83
  73. brainstate/nn/_linear_mv_test.py +120 -120
  74. brainstate/nn/_linear_test.py +107 -107
  75. brainstate/nn/_ltp.py +28 -28
  76. brainstate/nn/_module.py +377 -377
  77. brainstate/nn/_module_test.py +40 -40
  78. brainstate/nn/_neuron.py +705 -705
  79. brainstate/nn/_neuron_test.py +161 -161
  80. brainstate/nn/_normalizations.py +975 -918
  81. brainstate/nn/_normalizations_test.py +73 -73
  82. brainstate/{functional → nn}/_others.py +46 -46
  83. brainstate/nn/_poolings.py +1177 -1177
  84. brainstate/nn/_poolings_test.py +217 -217
  85. brainstate/nn/_projection.py +486 -486
  86. brainstate/nn/_rate_rnns.py +554 -554
  87. brainstate/nn/_rate_rnns_test.py +63 -63
  88. brainstate/nn/_readout.py +209 -209
  89. brainstate/nn/_readout_test.py +53 -53
  90. brainstate/nn/_stp.py +236 -236
  91. brainstate/nn/_synapse.py +505 -505
  92. brainstate/nn/_synapse_test.py +131 -131
  93. brainstate/nn/_synaptic_projection.py +423 -423
  94. brainstate/nn/_synouts.py +162 -162
  95. brainstate/nn/_synouts_test.py +57 -57
  96. brainstate/nn/_utils.py +89 -89
  97. brainstate/nn/metrics.py +388 -388
  98. brainstate/optim/__init__.py +38 -38
  99. brainstate/optim/_base.py +64 -64
  100. brainstate/optim/_lr_scheduler.py +448 -448
  101. brainstate/optim/_lr_scheduler_test.py +50 -50
  102. brainstate/optim/_optax_optimizer.py +152 -152
  103. brainstate/optim/_optax_optimizer_test.py +53 -53
  104. brainstate/optim/_sgd_optimizer.py +1104 -1104
  105. brainstate/random/__init__.py +24 -24
  106. brainstate/random/_rand_funs.py +3616 -3616
  107. brainstate/random/_rand_funs_test.py +567 -567
  108. brainstate/random/_rand_seed.py +210 -210
  109. brainstate/random/_rand_seed_test.py +48 -48
  110. brainstate/random/_rand_state.py +1409 -1409
  111. brainstate/random/_random_for_unit.py +52 -52
  112. brainstate/surrogate.py +1957 -1957
  113. brainstate/transform.py +23 -23
  114. brainstate/typing.py +304 -304
  115. brainstate/util/__init__.py +50 -50
  116. brainstate/util/caller.py +98 -98
  117. brainstate/util/error.py +55 -55
  118. brainstate/util/filter.py +469 -469
  119. brainstate/util/others.py +540 -540
  120. brainstate/util/pretty_pytree.py +945 -945
  121. brainstate/util/pretty_pytree_test.py +159 -159
  122. brainstate/util/pretty_repr.py +328 -328
  123. brainstate/util/pretty_table.py +2954 -2954
  124. brainstate/util/scaling.py +258 -258
  125. brainstate/util/struct.py +523 -523
  126. {brainstate-0.1.8.dist-info → brainstate-0.1.9.dist-info}/METADATA +91 -99
  127. brainstate-0.1.9.dist-info/RECORD +130 -0
  128. {brainstate-0.1.8.dist-info → brainstate-0.1.9.dist-info}/WHEEL +1 -1
  129. {brainstate-0.1.8.dist-info → brainstate-0.1.9.dist-info/licenses}/LICENSE +202 -202
  130. brainstate/functional/_normalization.py +0 -81
  131. brainstate/functional/_spikes.py +0 -204
  132. brainstate-0.1.8.dist-info/RECORD +0 -132
  133. {brainstate-0.1.8.dist-info → brainstate-0.1.9.dist-info}/top_level.txt +0 -0
brainstate/_state.py CHANGED
@@ -1,1663 +1,1605 @@
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
- from __future__ import annotations
17
-
18
- import contextlib
19
- import dataclasses
20
- import threading
21
- from functools import wraps, partial
22
- from typing import (
23
- Any,
24
- Union,
25
- Callable,
26
- Generic,
27
- Mapping,
28
- TypeVar,
29
- Optional,
30
- TYPE_CHECKING,
31
- Tuple,
32
- Dict,
33
- List,
34
- Sequence,
35
- Generator,
36
- )
37
-
38
- import jax
39
- import numpy as np
40
- from jax.api_util import shaped_abstractify
41
- from jax.extend import source_info_util
42
-
43
- from brainstate.typing import ArrayLike, PyTree, Missing, Filter
44
- from brainstate.util import DictManager, PrettyObject
45
- from brainstate.util.filter import Nothing
46
-
47
- __all__ = [
48
- 'State',
49
- 'ShortTermState',
50
- 'LongTermState',
51
- 'HiddenState',
52
- 'ParamState',
53
- 'BatchState',
54
- 'TreefyState',
55
- 'FakeState',
56
-
57
- 'StateDictManager',
58
- 'StateTraceStack',
59
- 'check_state_value_tree',
60
- 'check_state_jax_tracer',
61
- 'catch_new_states',
62
- 'maybe_state',
63
- ]
64
-
65
- A = TypeVar('A')
66
- B = TypeVar('B')
67
- T = TypeVar('T')
68
- F = TypeVar('F', bound=Callable[..., Any])
69
-
70
- max_int = np.iinfo(np.int32)
71
-
72
-
73
- # The global state of the state stack is accessed by a thread-local object.
74
- # This allows concurrent tracing in separate threads; passing traced objects
75
- # between threads is forbidden.
76
- class ThreadLocalStack(threading.local):
77
- """
78
- A thread-local storage class for managing state-related information.
79
-
80
- This class provides thread-local storage for various state management components,
81
- ensuring that each thread has its own isolated set of state-related data structures.
82
-
83
- Attributes:
84
- state_stack (List[StateTraceStack]): A list to store StateTraceStack objects for the current thread.
85
- tree_check (List[bool]): A list of boolean flags for tree structure checking, initialized with [False].
86
- jax_tracer_check (List[bool]): A list of boolean flags for JAX tracer checking, initialized with [False].
87
- new_state_catcher (List[StateCatcher]): A list to store Catcher objects for capturing new states in the current thread.
88
- """
89
-
90
- def __init__(self):
91
- """
92
- Initialize the ThreadLocalStack with empty data structures.
93
-
94
- This constructor sets up the initial state for each thread-local instance,
95
- creating empty lists for state stack, tree checking, JAX tracer checking,
96
- and new state catching.
97
- """
98
- self.state_stack: List[StateTraceStack] = []
99
- self.tree_check: List[bool] = [False]
100
- self.jax_tracer_check: List[bool] = [False]
101
- self.new_state_catcher: List[StateCatcher] = []
102
-
103
-
104
- TRACE_CONTEXT = ThreadLocalStack()
105
-
106
-
107
- @contextlib.contextmanager
108
- def check_state_value_tree(val: bool = True) -> Generator[None, None, None]:
109
- """
110
- The contex manager to check weather the tree structure of the state value keeps consistently.
111
-
112
- Once a :py:class:`~.State` is created, the tree structure of the value is fixed. In default,
113
- the tree structure of the value is not checked to avoid off the repeated evaluation.
114
- If you want to check the tree structure of the value once the new value is assigned,
115
- you can use this context manager.
116
-
117
- Example::
118
-
119
- >>> import brainstate as brainstate
120
- >>> import jax.numpy as jnp
121
- >>> state = brainstate.ShortTermState(jnp.zeros((2, 3)))
122
- >>> with brainstate.check_state_value_tree():
123
- >>> # The line below will not raise an error.
124
- >>> state.value = jnp.zeros((2, 3))
125
- ...
126
- >>> # The following code will raise an error, since it changes the tree structure.
127
- >>> state.value = (jnp.zeros((2, 3)), jnp.zeros((2, 3)))
128
-
129
- """
130
- try:
131
- TRACE_CONTEXT.tree_check.append(val)
132
- yield
133
- finally:
134
- TRACE_CONTEXT.tree_check.pop()
135
-
136
-
137
- def maybe_state(val: Any) -> Any:
138
- """
139
- Extracts the value from a State object if given, otherwise returns the input value.
140
-
141
- This function is useful for handling both State objects and raw values uniformly.
142
- If the input is a State object, it returns the value stored in that State.
143
- If the input is not a State object, it returns the input as is.
144
-
145
- Args:
146
- val (Any): The input value, which can be either a State object or any other type.
147
-
148
- Returns:
149
- Any: The value stored in the State if the input is a State object,
150
- otherwise the input value itself.
151
- """
152
- if isinstance(val, State):
153
- return val.value
154
- else:
155
- return val
156
-
157
-
158
- @contextlib.contextmanager
159
- def check_state_jax_tracer(val: bool = True) -> Generator[None, None, None]:
160
- """
161
- The context manager to check whether the state is valid to trace.
162
-
163
- Example::
164
-
165
- >>> import jax
166
- >>> import brainstate as brainstate
167
- >>> import jax.numpy as jnp
168
- >>>
169
- >>> a = brainstate.ShortTermState(jnp.zeros((2, 3)))
170
- >>>
171
- >>> @jax.jit
172
- >>> def run_state(b):
173
- >>> a.value = b
174
- >>> return a.value
175
- >>>
176
- >>> # The following code will not raise an error, since the state is valid to trace.
177
- >>> run_state(jnp.ones((2, 3)))
178
- >>>
179
- >>> with check_state_jax_tracer():
180
- >>> # The line below will not raise an error.
181
- >>> run_state(jnp.ones((2, 4)))
182
- """
183
- try:
184
- TRACE_CONTEXT.jax_tracer_check.append(val)
185
- yield
186
- finally:
187
- TRACE_CONTEXT.jax_tracer_check.pop()
188
-
189
-
190
- @dataclasses.dataclass
191
- class StateMetadata(Generic[A]):
192
- """
193
- A dataclass representing metadata for a state object.
194
-
195
- This class encapsulates the raw value of a state along with associated metadata.
196
- It is generic over the type of the raw value.
197
-
198
- Attributes:
199
- raw_value (A): The raw value of the state. The type A is a generic type parameter.
200
- metadata (Mapping[str, Any]): A mapping of string keys to arbitrary values,
201
- representing additional metadata for the state.
202
- Defaults to an empty dictionary.
203
- """
204
- raw_value: A
205
- metadata: Mapping[str, Any] = dataclasses.field(default_factory=dict)
206
-
207
-
208
- def with_metadata(initializer: F, **metadata: Any) -> F:
209
- """
210
- A decorator that adds metadata to a state initialization function.
211
-
212
- This decorator wraps the given initializer function, allowing additional
213
- metadata to be associated with the state it creates. The metadata is
214
- incorporated into a StateMetadata object along with the state's value.
215
-
216
- Args:
217
- initializer (F): The original state initialization function to be wrapped.
218
- **metadata (Any): Arbitrary keyword arguments representing metadata
219
- to be associated with the state.
220
-
221
- Returns:
222
- F: A wrapped version of the initializer function that returns a
223
- StateMetadata object containing both the original state value
224
- and the provided metadata.
225
-
226
- Example::
227
- @with_metadata(tag='model_param')
228
- def init_weights(shape):
229
- return np.zeros(shape)
230
-
231
- state = init_weights((100, 100))
232
- # state is now a StateMetadata object with the initialized weights
233
- # and the 'tag' metadata
234
- """
235
-
236
- @wraps(initializer)
237
- def wrapper(*args):
238
- return StateMetadata(initializer(*args), metadata=metadata)
239
-
240
- return wrapper # type: ignore
241
-
242
-
243
- def _get_trace_stack_level() -> int:
244
- return len(TRACE_CONTEXT.state_stack)
245
-
246
-
247
- class State(Generic[A], PrettyObject):
248
- """
249
- A generic class representing a dynamic data pointer in the BrainState framework.
250
-
251
- The State class serves as a base for various types of state objects used to
252
- manage and track dynamic data within a program. It provides mechanisms for
253
- value storage, metadata management, and integration with the BrainState
254
- tracing system.
255
-
256
- Type Parameters:
257
- A: The type of the value stored in the state.
258
-
259
- Attributes:
260
- name (Optional[str]): An optional name for the state.
261
- value (PyTree): The actual value stored in the state.
262
- tag (Optional[str]): An optional tag for categorizing or grouping states.
263
-
264
- Args:
265
- value (Union[PyTree[ArrayLike], StateMetadata[PyTree[ArrayLike]]]):
266
- The initial value for the state. Can be a PyTree of array-like objects
267
- or a StateMetadata object.
268
- name (Optional[str]): An optional name for the state.
269
- **metadata: Additional metadata to be stored with the state.
270
-
271
- Example:
272
- >>> class MyState(State):
273
- ... pass
274
- >>> state = MyState(jnp.zeros((3, 3)), name="my_matrix")
275
- >>> print(state.value)
276
- [[0. 0. 0.]
277
- [0. 0. 0.]
278
- [0. 0. 0.]]
279
-
280
- Note:
281
- - Subclasses of :class:`State` (e.g., ShortTermState, LongTermState, ParamState,
282
- RandomState) are typically used for specific purposes in a program.
283
- - The class integrates with BrainState's tracing system to track state
284
- creation and modifications.
285
-
286
- The typical examples of :py:class:`~.State` subclass are:
287
-
288
- - :py:class:`ShortTermState`: The short-term state, which is used to store the short-term data in the program.
289
- - :py:class:`LongTermState`: The long-term state, which is used to store the long-term data in the program.
290
- - :py:class:`ParamState`: The parameter state, which is used to store the parameters in the program.
291
- - :py:class:`RandomState`: The random generator state, which is used to store the random key in the program.
292
-
293
- Args:
294
- value: PyTree. It can be anything as a pyTree.
295
- name: Optional[str]. The name of the state.
296
- tag: Optional[str]. The tag of the state.
297
- """
298
- __module__ = 'brainstate'
299
- _level: int
300
- _source_info: source_info_util.SourceInfo
301
- _name: Optional[str]
302
- _value: PyTree
303
- _been_writen: bool # useful in `unflatten` and `flatten` graph processing
304
- tag: Optional[str]
305
-
306
- def __init__(
307
- self,
308
- value: Union[PyTree[ArrayLike], StateMetadata[PyTree[ArrayLike]]],
309
- name: Optional[str] = None,
310
- **metadata: Any
311
- ):
312
- """
313
- Initialize a new HiddenState instance.
314
-
315
- This constructor sets up the initial state for a hidden state in a dynamic model,
316
- handling various input types and metadata.
317
-
318
- Args:
319
- value (Union[PyTree[ArrayLike], StateMetadata[PyTree[ArrayLike]]]):
320
- The initial value for the hidden state. Can be a PyTree of array-like objects
321
- or a StateMetadata object containing both value and metadata.
322
- name (Optional[str], optional): A name for the hidden state. Defaults to None.
323
- **metadata: Additional metadata to be stored with the hidden state, including:
324
- - tag (Optional[str]): A tag for categorizing or grouping states.
325
- - Any other custom metadata fields.
326
-
327
- Note:
328
- This method initializes the hidden state, processes the input value and metadata,
329
- sets up internal attributes, and records the state initialization.
330
- """
331
- tag = metadata.pop('tag', None)
332
-
333
- # set the value and metadata
334
- if isinstance(value, StateMetadata):
335
- metadata.update(dict(value.metadata))
336
- value = value.raw_value
337
- if isinstance(value, State):
338
- value = value.value
339
-
340
- # update metadata
341
- metadata.update(
342
- _value=value,
343
- _level=_get_trace_stack_level(),
344
- _source_info=source_info_util.current(),
345
- _name=name,
346
- _been_writen=False,
347
- tag=tag,
348
- )
349
-
350
- # avoid using self._setattr to avoid the check
351
- vars(self).update(metadata)
352
-
353
- # record the state initialization
354
- record_state_init(self)
355
-
356
- def decrease_stack_level(self):
357
- """
358
- Decrease the stack level of the state by one, ensuring it doesn't go below zero.
359
-
360
- This method is used to adjust the stack level of the state, typically when
361
- exiting a nested context or scope. It ensures that the level never becomes
362
- negative.
363
- """
364
- self._level = max(self._level - 1, 0)
365
-
366
- def increase_stack_level(self):
367
- """
368
- Increase the stack level of the state by one.
369
-
370
- This method is used to adjust the stack level of the state, typically when
371
- entering a nested context or scope. It increments the internal level counter
372
- by one.
373
- """
374
- self._level = self._level + 1
375
-
376
- @property
377
- def name(self) -> Optional[str]:
378
- """
379
- The name of the state.
380
- """
381
- return self._name
382
-
383
- @name.setter
384
- def name(self, name: str) -> None:
385
- """
386
- Set the name of the state.
387
- """
388
- self._name = name
389
-
390
- @property
391
- def value(self) -> PyTree[ArrayLike]:
392
- """
393
- The data and its value.
394
- """
395
- record_state_value_read(self)
396
- return self._read_value()
397
-
398
- @value.setter
399
- def value(self, v) -> None:
400
- """
401
- Set the value of the state.
402
-
403
- Args:
404
- v: The value.
405
- """
406
- # NOTE: the following order is important
407
-
408
- if isinstance(v, State): # value checking
409
- raise ValueError('Cannot set value to a State, ' 'use `copy_from` method instead')
410
- self._check_value_tree(v) # check the tree structure
411
- record_state_value_write(self) # record the value by the stack (>= level)
412
- self._been_writen = True # set the flag
413
- self._write_value(v) # write the value
414
-
415
- @property
416
- def stack_level(self):
417
- """
418
- The stack level of the state.
419
-
420
- Returns:
421
- The stack level.
422
- """
423
- return self._level
424
-
425
- @stack_level.setter
426
- def stack_level(self, level: int):
427
- """
428
- Set the stack level of the state.
429
-
430
- Args:
431
- level: The stack level.
432
- """
433
- self._level = level
434
-
435
- def _read_value(self) -> PyTree[ArrayLike]:
436
- """
437
- The interface to customize the value reading.
438
- """
439
- self.check_if_deleted()
440
- return self._value
441
-
442
- def _write_value(self, v) -> None:
443
- """
444
- The interface to customize the value writing.
445
- """
446
- self._value = v
447
-
448
- def restore_value(self, v) -> None:
449
- """
450
- Restore the value of the state.
451
-
452
- Args:
453
- v: The value.
454
- """
455
- # value checking
456
- if isinstance(v, State):
457
- raise ValueError('Cannot set value to a State, ' 'use `copy_from` method instead')
458
- with check_state_value_tree():
459
- self._check_value_tree(v)
460
- # record the value by the stack (>= level)
461
- record_state_value_restore(self)
462
- # set the value
463
- self._value = v
464
-
465
- def value_call(self, func: Callable[..., Any]) -> Any:
466
- """
467
- Call the function with the value of the state.
468
- """
469
- return jax.tree.map(func, self.value)
470
-
471
- def _check_value_tree(self, v):
472
- """
473
- Check if the value tree structure is consistent.
474
- """
475
- if TRACE_CONTEXT.tree_check[-1]:
476
- in_tree = jax.tree.structure(v)
477
- self_tree = jax.tree.structure(self._value)
478
- if in_tree != self_tree:
479
- self.raise_error_with_source_info(
480
- ValueError(f'The given value {in_tree} does not match with the origin tree structure {self_tree}.')
481
- )
482
-
483
- def raise_error_with_source_info(self, error: Exception):
484
- """
485
- Raise an error with the source information for easy debugging.
486
- """
487
- name_stack = source_info_util.current_name_stack() + self.source_info.name_stack
488
- with source_info_util.user_context(self.source_info.traceback, name_stack=name_stack):
489
- raise error
490
-
491
- def check_if_deleted(self):
492
- pass
493
-
494
- @property
495
- def source_info(self) -> source_info_util.SourceInfo:
496
- """
497
- The source information of the state, can be useful to identify
498
- the source code where the definition of the state.
499
-
500
- Returns:
501
- The source information.
502
- """
503
- return self._source_info
504
-
505
- def update_from_ref(self, state_ref: TreefyState[A]) -> None:
506
- """
507
- Update the state from the state reference :py:class:`TreefyState`.
508
-
509
- Args:
510
- state_ref: The state reference.
511
- """
512
- metadata = state_ref.get_metadata()
513
- variable_vars = vars(self)
514
- variable_vars.update(**metadata)
515
- if metadata.pop('_been_writen', True):
516
- self.value = state_ref.value
517
- else:
518
- self.restore_value(state_ref.value)
519
-
520
- def replace(self, value: Any = Missing, **kwargs) -> State[Any]:
521
- """
522
- Replace the attribute of the state.
523
- """
524
- if value is not Missing:
525
- kwargs['_value'] = value
526
-
527
- # return `value` if it is a State
528
- if '_value' in kwargs and isinstance(value := kwargs['_value'], State):
529
- # remove value from kwargs
530
- kwargs.pop('_value')
531
- if type(self) is not type(value):
532
- raise ValueError('Cannot replace value from incompatible container, '
533
- f'expected {type(self).__name__}, got {type(value).__name__}')
534
- # if kwargs aren't empty, recursively call replace
535
- # else return variable value
536
- if kwargs:
537
- return value.replace(**kwargs)
538
- else:
539
- return value
540
-
541
- # get and update attributes
542
- attributes = vars(self).copy()
543
- attributes.update(**kwargs)
544
- # return new instance with updated attributes
545
- obj = object.__new__(type(self))
546
- vars(obj).update(attributes)
547
- return obj
548
-
549
- def copy(self: State[A]) -> State[A]:
550
- """
551
- Copy the state.
552
- """
553
- obj = object.__new__(type(self))
554
- attributes = vars(self).copy()
555
- # keep its own trace state and stack level
556
- attributes['_level'] = _get_trace_stack_level()
557
- attributes['_source_info'] = source_info_util.current()
558
- attributes.pop('_been_writen', None)
559
- # update the metadata
560
- vars(obj).update(attributes)
561
- return obj
562
-
563
- def to_state_ref(self: State[A]) -> TreefyState[A]:
564
- metadata = vars(self).copy()
565
- del metadata['_value']
566
- return TreefyState(type(self), self._value, **metadata)
567
-
568
- def __pretty_repr_item__(self, k, v):
569
- if k in ['_level', '_source_info', '_been_writen']:
570
- return None
571
- if k == '_value':
572
- return 'value', jax.tree.map(shaped_abstractify, v)
573
-
574
- if k == '_name':
575
- if self.name is None:
576
- return None
577
- else:
578
- return 'name', v
579
-
580
- if k == 'tag':
581
- if self.tag is None:
582
- return None
583
- else:
584
- return 'tag', v
585
-
586
- return k, v
587
-
588
- def __eq__(self, other: object) -> bool:
589
- return type(self) is type(other) and vars(other) == vars(self)
590
-
591
- def __hash__(self):
592
- """
593
- Make the state hashable.
594
- """
595
- return hash(id(self))
596
-
597
- def numel(self) -> int:
598
- """
599
- Calculate the total number of elements in the state value.
600
-
601
- This method traverses the state's value, which may be a nested structure (PyTree),
602
- and computes the sum of sizes of all leaf nodes.
603
-
604
- Returns:
605
- int: The total number of elements across all arrays in the state value.
606
- For scalar values, this will be 1. For arrays or nested structures,
607
- it will be the sum of the sizes of all contained arrays.
608
-
609
- Note:
610
- This method uses jax.tree.leaves to flatten any nested structure in the state value,
611
- and jax.numpy.size to compute the size of each leaf node.
612
- """
613
- sizes = [jax.numpy.size(val) for val in jax.tree.leaves(self._value)]
614
- return sum(sizes)
615
-
616
-
617
- def record_state_init(st: State[A]):
618
- """
619
- Record the initialization of a new :class:`State` object.
620
-
621
- This function iterates through all registered state catchers in the current
622
- trace context and appends the newly initialized state to each catcher.
623
-
624
- Args:
625
- st (State[A]): The newly initialized :class:`State` object to be recorded.
626
-
627
- Note:
628
- This function is typically called internally when a new :class:`State` object
629
- is created to ensure proper tracking and management of states within
630
- the current execution context.
631
- """
632
- trace: StateCatcher
633
- for trace in TRACE_CONTEXT.new_state_catcher:
634
- trace.append(st)
635
-
636
-
637
- def record_state_value_read(st: State[A]):
638
- """
639
- Record that a state's value has been read in all relevant trace stacks.
640
-
641
- This function iterates through all state trace stacks at or above the
642
- state's stack level in the current trace context, and records that
643
- the given state's value has been read.
644
-
645
- Args:
646
- st (State[A]): The state object whose value read is being recorded.
647
- 'A' is a generic type parameter representing the
648
- type of the state's value.
649
-
650
- Note:
651
- This function modifies the state trace stacks in the current
652
- trace context but does not return any value.
653
- """
654
- trace: StateTraceStack
655
- for trace in TRACE_CONTEXT.state_stack[st.stack_level:]:
656
- trace.read_its_value(st)
657
-
658
-
659
- def record_state_value_write(st: State[A]):
660
- """
661
- Record that a state's value has been written in all relevant trace stacks.
662
-
663
- This function iterates through all state trace stacks at or above the
664
- state's stack level in the current trace context, and records that
665
- the given state's value has been written.
666
-
667
- Args:
668
- st (State[A]): The state object whose value write is being recorded.
669
- 'A' is a generic type parameter representing the
670
- type of the state's value.
671
-
672
- Note:
673
- This function modifies the state trace stacks in the current
674
- trace context but does not return any value.
675
- """
676
- trace: StateTraceStack
677
- for trace in TRACE_CONTEXT.state_stack[st.stack_level:]:
678
- trace.write_its_value(st)
679
-
680
-
681
- def record_state_value_restore(st: State[A]):
682
- """
683
- Record that a state's value has been restored.
684
-
685
- This function is used to indicate that a state's value has been restored
686
- to a previous value. It internally calls the record_state_value_read
687
- function to mark the state as having been accessed.
688
-
689
- Args:
690
- st (State[A]): The state object whose value restoration is being recorded.
691
- 'A' is a generic type parameter representing the
692
- type of the state's value.
693
-
694
- See Also:
695
- record_state_value_read: Record that a state's value has been read.
696
-
697
- Note:
698
- This function does not actually restore the state's value; it only
699
- records that a restoration has occurred.
700
- """
701
- record_state_value_read(st)
702
-
703
-
704
- class ShortTermState(State):
705
- """
706
- A class representing short-term state in a program.
707
-
708
- :class:`ShortTermState` is used to store temporary or transient data that is only relevant
709
- for a short duration within the program's execution. This class extends the base
710
- State class, inheriting its properties and methods while specifically denoting
711
- the short-term nature of the stored data.
712
-
713
- For example, in a machine learning training process, the gradients of the model
714
- would typically be represented as :class:`ShortTermState`, as they are computed and used
715
- within each iteration but not necessarily preserved across iterations.
716
-
717
- Attributes:
718
- Inherits all attributes from the base State class.
719
-
720
- Note:
721
- This class does not introduce new methods or attributes beyond those
722
- inherited from the State class. Its primary purpose is to semantically
723
- distinguish short-term states from other types of states in the program.
724
-
725
- Example:
726
- >>> gradient = ShortTermState(np.zeros(100), name="model_gradient")
727
- >>> intermediate_result = ShortTermState({}, name="layer_activations")
728
- """
729
-
730
- __module__ = 'brainstate'
731
-
732
-
733
- class LongTermState(State):
734
- """
735
- The long-term state, which is used to store the long-term data in the program.
736
-
737
- This class extends the base :class:`State` class and is specifically designed to represent
738
- and manage long-term data within a program. Long-term states are typically used
739
- for data that persists across multiple iterations or epochs of a process.
740
-
741
- For example, in a training process, the weights of the model are considered
742
- long-term states as they are updated and maintained throughout the entire
743
- training procedure.
744
-
745
- Attributes:
746
- Inherits all attributes from the base :class:`State` class.
747
-
748
- Note:
749
- This class does not introduce new methods or attributes beyond those
750
- inherited from the :class:`State` class. Its primary purpose is to semantically
751
- distinguish long-term states from other types of states in the program.
752
-
753
- Example:
754
- >>> model_weights = LongTermState(np.random.randn(100, 100), name="model_weights")
755
- >>> optimizer_state = LongTermState({}, name="optimizer_state")
756
- """
757
-
758
- __module__ = 'brainstate'
759
-
760
-
761
- class BatchState(LongTermState):
762
- """
763
- The batch state, which is used to store the batch data in the program.
764
-
765
- This class extends :class:`LongTermState` and is specifically designed to represent
766
- and manage batch data within a program. It provides a way to encapsulate
767
- batch-related information and associated metadata, facilitating operations
768
- like batch processing in machine learning or data analysis tasks.
769
-
770
- Attributes:
771
- Inherits all attributes from :class:`LongTermState`.
772
-
773
- Note:
774
- This class does not introduce new methods or attributes beyond those
775
- inherited from :class:`LongTermState`. Its primary purpose is to semantically
776
- distinguish batch states from other types of long-term states
777
- in the program.
778
-
779
- Example:
780
- >>> batch_data = BatchState(np.array([1, 2, 3, 4, 5]), name="current_batch")
781
- >>> batch_labels = BatchState(np.array([0, 1, 0, 1, 1]), name="batch_labels")
782
- """
783
-
784
- __module__ = 'brainstate'
785
-
786
-
787
- class HiddenState(ShortTermState):
788
- """
789
- Represents hidden state variables in neurons or synapses.
790
-
791
- This class extends :class:`ShortTermState` and is specifically designed to represent
792
- and manage hidden states within dynamic models, such as recurrent neural networks.
793
- It provides a way to encapsulate hidden state values and associated metadata,
794
- facilitating operations like state updates during model execution.
795
-
796
- Note:
797
- :class:`HiddenState` and :class:`ParamState` are two most important state types
798
- in brainstate. The former is used to store the hidden states in neurons, synapses,
799
- or networks. The latter is used to store the trainable parameters in the model,
800
- such as synaptic weights.
801
-
802
- Example:
803
- >>> lstm_hidden = HiddenState(np.zeros(128), name="lstm_hidden_state")
804
- >>> gru_hidden = HiddenState(np.zeros(64), name="gru_hidden_state")
805
- """
806
-
807
- __module__ = 'brainstate'
808
-
809
-
810
- class ParamState(LongTermState):
811
- """
812
- The parameter state, which is used to store the trainable parameters in the model.
813
-
814
- This class extends :class:`LongTermState` and is specifically designed to represent
815
- and manage trainable parameters within a neural network or machine learning model.
816
- It provides a way to encapsulate parameter values and associated metadata,
817
- facilitating operations like parameter updates during training.
818
-
819
- Note:
820
- :class:`HiddenState` and :class:`ParamState` are two most important state types
821
- in brainstate. The former is used to store the hidden states in neurons, synapses,
822
- or networks. The latter is used to store the trainable parameters in the model,
823
- such as synaptic weights.
824
-
825
- Example:
826
- >>> weight = ParamState(np.random.randn(10, 10), name="layer1_weights")
827
- >>> bias = ParamState(np.zeros(10), name="layer1_bias")
828
- """
829
-
830
- __module__ = 'brainstate'
831
-
832
-
833
- class FakeState:
834
- """
835
- The faked state, which is used to store the faked data in the program.
836
- """
837
-
838
- __module__ = 'brainstate'
839
-
840
- def __init__(self, value: Any, name: Optional[str] = None):
841
- """
842
- Initialize a FakeState instance.
843
-
844
- Args:
845
- value (Any): The value to be stored in the fake state.
846
- name (Optional[str], optional): The name of the fake state. Defaults to None.
847
- """
848
- self._value = value
849
- self._name = name
850
-
851
- @property
852
- def value(self) -> Any:
853
- """
854
- Get the value stored in the fake state.
855
-
856
- Returns:
857
- Any: The value stored in the fake state.
858
- """
859
- return self._value
860
-
861
- @value.setter
862
- def value(self, v) -> None:
863
- """
864
- Set the value of the fake state.
865
-
866
- Args:
867
- v (Any): The new value to be stored in the fake state.
868
- """
869
- self._value = v
870
-
871
- def __repr__(self) -> str:
872
- """
873
- Return a string representation of the FakeState instance.
874
-
875
- Returns:
876
- str: A string representation of the FakeState instance.
877
- """
878
- return f'FakedState(value={self._value})'
879
-
880
- @property
881
- def name(self) -> Optional[str]:
882
- """
883
- Get the name of the fake state.
884
-
885
- Returns:
886
- Optional[str]: The name of the fake state, or None if not set.
887
- """
888
- return self._name
889
-
890
- @name.setter
891
- def name(self, name: str) -> None:
892
- """
893
- Set the name of the fake state.
894
-
895
- Args:
896
- name (str): The new name for the fake state.
897
- """
898
- self._name = name
899
-
900
-
901
- class StateDictManager(DictManager):
902
- """
903
- State stack, for collecting all :py:class:`~.State` used in the program.
904
-
905
- :py:class:`~.StateDictManager` supports all features of python dict.
906
- """
907
-
908
- __module__ = 'brainstate'
909
-
910
- def assign_values(self, *args: Dict) -> None:
911
- """
912
- Assign the value for each element according to the given ``data``.
913
- """
914
- for arg in args:
915
- assert isinstance(arg, dict), 'Must be an instance of dict.'
916
- for k, v in arg.items():
917
- self._set_elem(k, v)
918
-
919
- def split_values(self, *filters: type) -> Tuple[Dict, ...]:
920
- """
921
- Split the values into several subsets of stack by the given types.
922
- """
923
- results = tuple(DictManager() for _ in range(len(filters) + 1))
924
- for k, v in self.items():
925
- for i, filt in enumerate(filters):
926
- if isinstance(v, filt):
927
- results[i][k] = v.value
928
- break
929
- else:
930
- results[-1][k] = v.value
931
- return results
932
-
933
- def collect_values(self) -> Dict:
934
- """
935
- Collect the values by the given types.
936
- """
937
- results = DictManager()
938
- for k, v in self.items():
939
- results[k] = v.value
940
- return results
941
-
942
- def split(self, first: type, *others: type) -> Tuple['StateDictManager', ...]:
943
- return super().split(first, *others)
944
-
945
- def to_dict_values(self) -> Dict:
946
- """
947
- Convert the values into a dict.
948
- """
949
- return {k: v.value for k, v in self.items()}
950
-
951
- def _check_elem(self, elem):
952
- assert isinstance(elem, State), f'must be instance of {State}'
953
-
954
- def _set_elem(self, key: Any, value: Any) -> None:
955
- self[key].value = value
956
-
957
-
958
- class StateTraceStack(Generic[A]):
959
- """
960
- A stack for tracing and managing states during program execution.
961
-
962
- ``StateTraceStack`` is used to automatically trace and manage State objects,
963
- keeping track of which states are read from or written to during the
964
- execution of a function or block of code. It provides methods for
965
- recording state accesses, retrieving state values, and managing the
966
- lifecycle of states within a tracing context.
967
-
968
- The class is generic over type A, allowing for type-safe usage with
969
- different types of State objects.
970
-
971
- Attributes:
972
- states (List[State]): A list of all State objects encountered during tracing.
973
- been_writen (List[bool]): A parallel list to states, indicating whether each state has been written to.
974
- _state_id_index (dict): A dictionary mapping state ids to their index in the states list.
975
- _original_state_values (List): A list of the original values of all states when first encountered.
976
- _jax_trace_new_arg (Callable): A function used to transform state values during tracing.
977
-
978
- Methods:
979
- __enter__: Enters a new tracing context.
980
- __exit__: Exits the current tracing context.
981
- read_its_value: Records a read operation on a state.
982
- write_its_value: Records a write operation on a state.
983
- get_state_values: Retrieves the current values of all traced states.
984
- recovery_original_values: Restores all states to their original values.
985
- merge: Merges multiple ``StateTraceStack`` instances.
986
- get_read_states: Retrieves states that were read during tracing.
987
- get_read_state_values: Retrieves values of states that were read during tracing.
988
-
989
- The ``StateTraceStack`` is a crucial component in implementing state-based
990
- computations and is particularly useful in scenarios involving automatic
991
- differentiation or other forms of program transformation.
992
- """
993
-
994
- def __init__(
995
- self,
996
- new_arg: Callable = None,
997
- name: Optional[str] = None,
998
- ):
999
- self.name = name
1000
- self.states: List[State] = []
1001
- self.been_writen: List[bool] = [] # False: read, True: write
1002
- self._state_id_index = dict()
1003
- self._original_state_values = []
1004
- self._jax_trace_new_arg: Callable = new_arg
1005
- self._stack_level = None
1006
-
1007
- def __str__(self) -> str:
1008
- _stack_level = self.name if self._stack_level is None else self._stack_level
1009
- if _stack_level is None:
1010
- _stack_level = ''
1011
- return f"{self.__class__.__name__}({_stack_level})"
1012
-
1013
- @property
1014
- def original_state_values(self) -> Tuple[PyTree, ...]:
1015
- """
1016
- Get the original values of all states in the StateTraceStack.
1017
-
1018
- This property provides access to the initial values of all states
1019
- that were captured when they were first added to the stack. It's
1020
- useful for comparing current state values with their original values
1021
- or for reverting states to their initial condition.
1022
-
1023
- Returns:
1024
- Tuple[PyTree, ...]: A tuple containing the original values of all
1025
- states in the order they were added to the stack. Each element
1026
- is a PyTree representing the structure and values of a state.
1027
- """
1028
- return tuple(self._original_state_values)
1029
-
1030
- def set_new_arg(self, new_arg: Callable) -> None:
1031
- self._jax_trace_new_arg = new_arg
1032
-
1033
- def new_arg(self, state: State) -> None:
1034
- """
1035
- Apply a transformation to the value of a given state using a predefined function.
1036
-
1037
- This method is used internally to transform the value of a state during tracing.
1038
- If a transformation function (``_jax_trace_new_arg``) is defined, it applies this
1039
- function to each element of the state's value using JAX's tree mapping.
1040
-
1041
- Args:
1042
- state (State): The State object whose value needs to be transformed.
1043
-
1044
- Returns:
1045
- None: This function modifies the state in-place and doesn't return anything.
1046
-
1047
- Note:
1048
- This method is intended for internal use and relies on the presence of
1049
- a ``_jax_trace_new_arg`` function, which should be set separately.
1050
- """
1051
- if self._jax_trace_new_arg is not None:
1052
- # internal use
1053
- state._value = jax.tree.map(self._jax_trace_new_arg, state._value)
1054
-
1055
- def __enter__(self) -> 'StateTraceStack':
1056
- TRACE_CONTEXT.state_stack.append(self)
1057
- self._stack_level = ' / '.join([st.name for st in TRACE_CONTEXT.state_stack if st.name is not None])
1058
- return self
1059
-
1060
- def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None:
1061
- TRACE_CONTEXT.state_stack.pop()
1062
-
1063
- def read_its_value(self, state: State) -> None:
1064
- """
1065
- Record that a state's value has been read during tracing.
1066
-
1067
- This method marks the given state as having been read in the current
1068
- tracing context. If the state hasn't been encountered before, it adds
1069
- it to the internal tracking structures and applies any necessary
1070
- transformations via the new_arg method.
1071
-
1072
- Args:
1073
- state (State): The State object whose value is being read.
1074
-
1075
- Returns:
1076
- None
1077
-
1078
- Note:
1079
- This method updates the internal tracking of state accesses.
1080
- It doesn't actually read or return the state's value.
1081
- """
1082
- id_ = id(state)
1083
- if id_ not in self._state_id_index:
1084
- self._state_id_index[id_] = len(self.states)
1085
- self.states.append(state)
1086
- self.been_writen.append(False)
1087
- self._original_state_values.append(state._value) # internal use
1088
- self.new_arg(state)
1089
-
1090
- def write_its_value(self, state: State) -> None:
1091
- """
1092
- Record that a state's value has been written to during tracing.
1093
-
1094
- This method marks the given state as having been written to in the current
1095
- tracing context. If the state hasn't been encountered before, it first
1096
- records it as being read before marking it as written.
1097
-
1098
- Args:
1099
- state (State): The State object whose value is being written to.
1100
-
1101
- Returns:
1102
- None
1103
-
1104
- Note:
1105
- This method updates the internal tracking of state modifications.
1106
- It doesn't actually modify the state's value.
1107
- """
1108
- id_ = id(state)
1109
- if id_ not in self._state_id_index:
1110
- self.read_its_value(state)
1111
- index = self._state_id_index[id_]
1112
- self.been_writen[index] = True
1113
-
1114
- def get_state_values(
1115
- self,
1116
- separate: bool = False,
1117
- replace: bool = False
1118
- ) -> Sequence[PyTree] | Tuple[Sequence[PyTree], Sequence[PyTree]]:
1119
- """
1120
- Retrieve the values of all states in the StateTraceStack.
1121
-
1122
- This method returns the values of all states, optionally separating them
1123
- into written and read states, and optionally replacing values with None
1124
- for states that weren't accessed in a particular way.
1125
-
1126
- Args:
1127
- separate (bool, optional): If True, separate the values into written
1128
- and read states. If False, return all values in a single sequence.
1129
- Defaults to False.
1130
- replace (bool, optional): If True and separate is True, replace values
1131
- with None for states that weren't written/read. If False, only
1132
- include values for states that were written/read. Defaults to False.
1133
-
1134
- Returns:
1135
- Sequence[PyTree] | Tuple[Sequence[PyTree], Sequence[PyTree]]:
1136
- If separate is False:
1137
- A sequence of all state values.
1138
- If separate is True:
1139
- A tuple containing two sequences:
1140
- - The first sequence contains values of written states.
1141
- - The second sequence contains values of read states.
1142
- If replace is True, these sequences will have None for
1143
- states that weren't written/read respectively.
1144
-
1145
- """
1146
- if separate:
1147
- if replace:
1148
- writes, reads = [], []
1149
- for st, been_writen in zip(self.states, self.been_writen):
1150
- if been_writen:
1151
- writes.append(st.value)
1152
- reads.append(None)
1153
- else:
1154
- reads.append(st.value)
1155
- writes.append(None)
1156
- return tuple(writes), tuple(reads)
1157
- else:
1158
- writes, reads = [], []
1159
- for st, been_writen in zip(self.states, self.been_writen):
1160
- if been_writen:
1161
- writes.append(st.value)
1162
- else:
1163
- reads.append(st.value)
1164
- return tuple(writes), tuple(reads)
1165
- else:
1166
- return tuple([st.value for st in self.states])
1167
-
1168
- def recovery_original_values(self) -> None:
1169
- """
1170
- Restore the original values of all states in the StateTraceStack.
1171
-
1172
- This method iterates through all states in the stack and restores
1173
- their values to the original ones that were captured when the states
1174
- were first added to the stack. This is useful for reverting changes
1175
- made during tracing or for resetting the states to their initial condition.
1176
-
1177
- Note:
1178
- This method modifies the states in-place.
1179
-
1180
- Returns:
1181
- None
1182
- """
1183
- for st, val in zip(self.states, self._original_state_values):
1184
- # internal use
1185
- st.restore_value(val)
1186
-
1187
- def merge(self, *traces) -> 'StateTraceStack':
1188
- """
1189
- Merge other state traces into the current ``StateTraceStack``.
1190
-
1191
- This method combines the states, their write status, and original values from
1192
- other ``StateTraceStack`` instances into the current one. If a state from another
1193
- trace is not present in the current trace, it is added. If a state is already
1194
- present, its write status is updated if necessary.
1195
-
1196
- Args:
1197
- *traces: Variable number of ``StateTraceStack`` instances to be merged into
1198
- the current instance.
1199
-
1200
- Returns:
1201
- StateTraceStack: The current ``StateTraceStack`` instance with merged traces.
1202
-
1203
- Note:
1204
- This method modifies the current ``StateTraceStack`` in-place and also returns it.
1205
- """
1206
- trace: StateTraceStack
1207
- for trace in traces:
1208
- for st, been_writen, org_val in zip(trace.states, trace.been_writen, trace._original_state_values):
1209
- if id(st) not in self._state_id_index: # read the value
1210
- self._state_id_index[id(st)] = len(self.states)
1211
- self._original_state_values.append(org_val) # add the original value
1212
- self.states.append(st) # append the state
1213
- self.been_writen.append(False)
1214
- if been_writen:
1215
- self.write_its_value(st)
1216
- return self
1217
-
1218
- def get_read_states(self, replace_writen: bool = False) -> Tuple[State, ...]:
1219
- """
1220
- Retrieve the states that were read during the function execution.
1221
-
1222
- This method returns the states that were accessed (read from) during
1223
- the traced function's execution. It can optionally replace written
1224
- states with None.
1225
-
1226
- Args:
1227
- replace_writen (bool, optional): If True, replace written states with None
1228
- in the returned tuple. If False, exclude written states entirely from
1229
- the result. Defaults to False.
1230
-
1231
- Returns:
1232
- Tuple[State, ...]: A tuple containing the read states.
1233
- If replace_writen is True, the tuple will have the same length as the
1234
- total number of states, with None for written states.
1235
- If replace_writen is False, the tuple will only contain read-only states.
1236
- """
1237
- if replace_writen:
1238
- return tuple([st if not been_writen else None
1239
- for st, been_writen in zip(self.states, self.been_writen)])
1240
- else:
1241
- return tuple([st for st, been_writen in zip(self.states, self.been_writen) if not been_writen])
1242
-
1243
- def get_read_state_values(self, replace_writen: bool = False) -> Tuple[PyTree, ...]:
1244
- """
1245
- Retrieve the values of states that were read during the function execution.
1246
-
1247
- This method returns the values of states that were accessed (read from) during
1248
- the traced function's execution. It can optionally replace written states with None.
1249
-
1250
- Args:
1251
- replace_writen (bool, optional): If True, replace the values of written
1252
- states with None in the returned tuple. If False, exclude written
1253
- states entirely from the result. Defaults to False.
1254
-
1255
- Returns:
1256
- Tuple[PyTree, ...]: A tuple containing the values of read states.
1257
- If replace_writen is True, the tuple will have the same length as the
1258
- total number of states, with None for written states.
1259
- If replace_writen is False, the tuple will only contain values of
1260
- read-only states.
1261
- """
1262
- if replace_writen:
1263
- return tuple(
1264
- [st.value if not been_writen else None
1265
- for st, been_writen in zip(self.states, self.been_writen)]
1266
- )
1267
- else:
1268
- return tuple([st.value for st, been_writen in zip(self.states, self.been_writen) if not been_writen])
1269
-
1270
- def get_write_states(self, replace_read: bool = False) -> Tuple[State, ...]:
1271
- """
1272
- Retrieve the states that were written during the function execution.
1273
-
1274
- This method returns the states that were modified (written to) during
1275
- the traced function's execution. It can optionally replace unwritten (read-only)
1276
- states with None.
1277
-
1278
- Args:
1279
- replace_read (bool, optional): If True, replace read-only states with None
1280
- in the returned tuple. If False, exclude read-only states entirely from
1281
- the result. Defaults to False.
1282
-
1283
- Returns:
1284
- Tuple[State, ...]: A tuple containing the written states.
1285
- If replace_read is True, the tuple will have the same length as the
1286
- total number of states, with None for read-only states.
1287
- If replace_read is False, the tuple will only contain written states.
1288
- """
1289
- if replace_read:
1290
- return tuple([st if been_writen else None
1291
- for st, been_writen in zip(self.states, self.been_writen)])
1292
- else:
1293
- return tuple([st for st, been_writen in zip(self.states, self.been_writen) if been_writen])
1294
-
1295
- def get_write_state_values(self, replace_read: bool = False) -> Tuple[PyTree, ...]:
1296
- """
1297
- Retrieve the values of states that were written during the function execution.
1298
-
1299
- This method returns the values of states that were modified (written to) during
1300
- the traced function's execution. It can optionally replace unwritten (read-only)
1301
- states with None.
1302
-
1303
- Args:
1304
- replace_read (bool, optional): If True, replace the values of read-only
1305
- states with None in the returned tuple. If False, exclude read-only
1306
- states entirely from the result. Defaults to False.
1307
-
1308
- Returns:
1309
- Tuple[PyTree, ...]: A tuple containing the values of written states.
1310
- If replace_read is True, the tuple will have the same length as the
1311
- total number of states, with None for read-only states.
1312
- If replace_read is False, the tuple will only contain values of
1313
- written states.
1314
-
1315
- """
1316
- if replace_read:
1317
- return tuple([st.value if been_writen else None for st, been_writen in zip(self.states, self.been_writen)])
1318
- else:
1319
- return tuple([st.value for st, been_writen in zip(self.states, self.been_writen) if been_writen])
1320
-
1321
- def __add__(self, other: 'StateTraceStack') -> 'StateTraceStack':
1322
- """
1323
- Support the syntax of `+` to merge the state traces.
1324
- """
1325
- return StateTraceStack().merge(self, other)
1326
-
1327
- def assign_state_vals(self, state_vals: Sequence[PyTree]) -> None:
1328
- """
1329
- Assign new values to the states tracked by this ``StateTraceStack``.
1330
-
1331
- This method updates the values of the states based on whether they were
1332
- written to or only read during the tracing process. For states that were
1333
- written to, it directly assigns the new value. For states that were only
1334
- read, it restores the value using the state's restore_value method.
1335
-
1336
- Args:
1337
- state_vals (Sequence[PyTree]): A sequence of new state values to be
1338
- assigned. Each element in this sequence corresponds to a state
1339
- in the ``StateTraceStack``'s states list.
1340
-
1341
- Raises:
1342
- ValueError: If the length of state_vals doesn't match the number of
1343
- states in the ``StateTraceStack``.
1344
-
1345
- Returns:
1346
- None
1347
-
1348
- Note:
1349
- The order of state_vals should match the order of states in the
1350
- ``StateTraceStack``'s states list.
1351
- """
1352
- if len(state_vals) != len(self.states):
1353
- raise ValueError('The length of the state values must be equal to the states. '
1354
- f'Bug got {len(state_vals)} and {len(self.states)}')
1355
- for st, written, val in zip(self.states, self.been_writen, state_vals):
1356
- if written:
1357
- st.value = val
1358
- else:
1359
- st.restore_value(val)
1360
-
1361
- def state_subset(self, state_type: type) -> List:
1362
- """
1363
- Get a subset of states of a specific type from the ``StateTraceStack``.
1364
-
1365
- This method filters the states in the ``StateTraceStack`` and returns only
1366
- those that match the specified state type.
1367
-
1368
- Args:
1369
- state_type (type): The type of state to filter by. This should be
1370
- a subclass of State or State itself.
1371
-
1372
- Returns:
1373
- List[State]: A list containing all states in the ``StateTraceStack``
1374
- that are instances of the specified state_type.
1375
-
1376
- Example:
1377
- >>> stack = StateTraceStack()
1378
- >>> # Assume stack has been populated with various state types
1379
- >>> short_term_states = stack.state_subset(ShortTermState)
1380
- """
1381
- return [st for st in self.states if isinstance(st, state_type)]
1382
-
1383
-
1384
- class TreefyState(Generic[A], PrettyObject):
1385
- """
1386
- The state as a pytree.
1387
- """
1388
-
1389
- def __init__(
1390
- self,
1391
- type: type[State[Any]],
1392
- value: A,
1393
- **metadata
1394
- ):
1395
- self.type = type
1396
- self.value = value
1397
- vars(self).update(metadata)
1398
-
1399
- if TYPE_CHECKING:
1400
- def __getattr__(self, name: str) -> None: ...
1401
-
1402
- def __setattr__(self, name: str, value: Any) -> None: ...
1403
-
1404
- def __delattr__(self, name: str) -> None: ...
1405
-
1406
- def __pretty_repr_item__(self, k, v):
1407
- if k in ['_level', '_source_info', '_been_writen']:
1408
- return None
1409
- if k == '_value':
1410
- return 'value', v
1411
-
1412
- if k == '_name':
1413
- return None if v is None else ('name', v)
1414
- return k, v
1415
-
1416
- @property
1417
- def name(self) -> Optional[str]:
1418
- """
1419
- The name of the state.
1420
- """
1421
- return self._name
1422
-
1423
- @name.setter
1424
- def name(self, name: str) -> None:
1425
- """
1426
- Set the name of the state.
1427
- """
1428
- self._name = name
1429
-
1430
- def replace(self, value: B) -> TreefyState[B]:
1431
- """
1432
- Replace the value of the state reference.
1433
- """
1434
- return TreefyState(self.type, value, **self.get_metadata())
1435
-
1436
- def to_state(self) -> State[A]:
1437
- """
1438
- Convert the state reference to the state.
1439
- """
1440
- # we use object.__new__ to avoid calling __init__ and bypass the
1441
- # __init__ logic which should not be called twice
1442
- metadata = self.get_metadata()
1443
- state = object.__new__(self.type)
1444
- metadata.pop('_value', None)
1445
- metadata.pop('_level', None)
1446
- vars(state).update(**metadata, _value=self.value, _level=_get_trace_stack_level())
1447
- return state
1448
-
1449
- def copy(self: TreefyState[A]) -> TreefyState[A]:
1450
- """
1451
- Copy the state reference.
1452
- """
1453
- return jax.tree.map(lambda x: x, self)
1454
-
1455
- def get_metadata(self) -> Dict[str, Any]:
1456
- """
1457
- Get the metadata of the state reference
1458
- """
1459
- metadata = vars(self).copy()
1460
- del metadata['type']
1461
- del metadata['value']
1462
- return metadata
1463
-
1464
-
1465
- def _state_ref_flatten(x: TreefyState[Any], *, with_keys: bool):
1466
- metadata = tuple(x.get_metadata().items())
1467
- if with_keys:
1468
- node = (jax.tree_util.GetAttrKey('value'), x.value)
1469
- else:
1470
- node = x.value
1471
- return (node,), (x.type, metadata)
1472
-
1473
-
1474
- def _state_ref_unflatten(
1475
- static: Tuple[type[State[A]], Tuple[Tuple[str, Any], ...]],
1476
- children: Tuple[A],
1477
- ) -> TreefyState[A]:
1478
- return TreefyState(type=static[0], value=children[0], **dict(static[1]))
1479
-
1480
-
1481
- jax.tree_util.register_pytree_with_keys(
1482
- TreefyState,
1483
- partial(_state_ref_flatten, with_keys=True), # type: ignore
1484
- _state_ref_unflatten, # type: ignore
1485
- flatten_func=partial(_state_ref_flatten, with_keys=False), # type: ignore
1486
- )
1487
-
1488
-
1489
- class StateCatcher(PrettyObject):
1490
- """
1491
- The catcher to catch and manage new states.
1492
-
1493
- This class provides functionality to collect and tag new State objects.
1494
- It ensures that each state is only added once and assigns a tag to each state.
1495
-
1496
- Attributes:
1497
- state_tag (str): A string identifier used to tag the caught states.
1498
- state_ids (set): A set of state IDs to ensure uniqueness.
1499
- states (list): A list to store the caught State objects.
1500
- """
1501
-
1502
- def __init__(
1503
- self,
1504
- state_tag: str,
1505
- state_to_exclude: Filter = Nothing()
1506
- ):
1507
- """
1508
- Initialize a new Catcher instance.
1509
-
1510
- Args:
1511
- state_tag (str): The tag to be assigned to caught states.
1512
- state_to_exclude (Filter, optional): A filter to exclude states from being caught.
1513
- """
1514
- if state_to_exclude is None:
1515
- state_to_exclude = Nothing()
1516
- self.state_to_exclude = state_to_exclude
1517
- self.state_tag = state_tag
1518
- self.state_ids = set()
1519
- self.states = []
1520
-
1521
- def get_state_values(self) -> List[PyTree]:
1522
- """
1523
- Get the values of the caught states.
1524
-
1525
- Returns:
1526
- list: A list of values of the caught states.
1527
- """
1528
- return [state.value for state in self.states]
1529
-
1530
- def get_states(self) -> List[State]:
1531
- """
1532
- Get the caught states.
1533
-
1534
- Returns:
1535
- list: A list of the caught states.
1536
- """
1537
- return self.states
1538
-
1539
- def append(self, state: State):
1540
- """
1541
- Add a new state to the catcher if it hasn't been added before.
1542
-
1543
- This method adds the state to the internal list, records its ID,
1544
- and assigns the catcher's tag to the state.
1545
-
1546
- Args:
1547
- state (State): The State object to be added.
1548
- """
1549
- if self.state_to_exclude((), state):
1550
- return
1551
- if id(state) not in self.state_ids:
1552
- self.state_ids.add(id(state))
1553
- self.states.append(state)
1554
- state.tag = self.state_tag
1555
-
1556
- def __iter__(self):
1557
- """
1558
- Allow iteration over the caught states.
1559
-
1560
- Returns:
1561
- iterator: An iterator over the list of caught states.
1562
- """
1563
- return iter(self.states)
1564
-
1565
- def __len__(self):
1566
- """
1567
- Return the number of caught states.
1568
-
1569
- Returns:
1570
- int: The number of caught states.
1571
- """
1572
- return len(self.states)
1573
-
1574
- def __getitem__(self, index):
1575
- """
1576
- Get a state by index.
1577
-
1578
- Args:
1579
- index (int): The index of the state to retrieve.
1580
-
1581
- Returns:
1582
- State: The state at the specified index.
1583
- """
1584
- return self.states[index]
1585
-
1586
- def clear(self):
1587
- """
1588
- Clear all caught states.
1589
- """
1590
- self.state_ids.clear()
1591
- self.states.clear()
1592
-
1593
- def get_by_tag(self, tag: str):
1594
- """
1595
- Get all states with a specific tag.
1596
-
1597
- Args:
1598
- tag (str): The tag to filter by.
1599
-
1600
- Returns:
1601
- list: A list of states with the specified tag.
1602
- """
1603
- return [state for state in self.states if state.tag == tag]
1604
-
1605
- def remove(self, state: State):
1606
- """
1607
- Remove a specific state from the catcher.
1608
-
1609
- Args:
1610
- state (State): The state to remove.
1611
- """
1612
- if id(state) in self.state_ids:
1613
- self.state_ids.remove(id(state))
1614
- self.states.remove(state)
1615
-
1616
- def __contains__(self, state: State):
1617
- """
1618
- Check if a state is in the catcher.
1619
-
1620
- Args:
1621
- state (State): The state to check for.
1622
-
1623
- Returns:
1624
- bool: True if the state is in the catcher, False otherwise.
1625
- """
1626
- return id(state) in self.state_ids
1627
-
1628
-
1629
- @contextlib.contextmanager
1630
- def catch_new_states(
1631
- state_tag: str = None,
1632
- state_to_exclude: Filter = Nothing()
1633
- ) -> Generator[StateCatcher, None, None]:
1634
- """
1635
- A context manager that catches and tracks new states created within its scope.
1636
-
1637
- This function creates a new Catcher object and adds it to the TRACE_CONTEXT's
1638
- new_state_catcher list. It allows for tracking and managing new states created
1639
- within the context.
1640
-
1641
- Args:
1642
- state_tag (str, optional): A string tag to associate with the caught states.
1643
- Defaults to None.
1644
- state_to_exclude (Filter, optional): A filter object to specify which states
1645
- should be excluded from catching. Defaults to Nothing(), which excludes no states.
1646
-
1647
- Yields:
1648
- Catcher: A Catcher object that can be used to access and manage the
1649
- newly created states within the context.
1650
-
1651
- Example::
1652
-
1653
- with catch_new_states("my_tag") as catcher:
1654
- # Create new states here
1655
- # They will be caught and tagged with "my_tag"
1656
- # Access caught states through catcher object
1657
- """
1658
- try:
1659
- catcher = StateCatcher(state_tag=state_tag, state_to_exclude=state_to_exclude)
1660
- TRACE_CONTEXT.new_state_catcher.append(catcher)
1661
- yield catcher
1662
- finally:
1663
- TRACE_CONTEXT.new_state_catcher.pop()
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
+ from __future__ import annotations
17
+
18
+ import contextlib
19
+ import threading
20
+ from functools import partial
21
+ from typing import (
22
+ Any,
23
+ Union,
24
+ Callable,
25
+ Generic,
26
+ TypeVar,
27
+ Optional,
28
+ TYPE_CHECKING,
29
+ Tuple,
30
+ Dict,
31
+ List,
32
+ Sequence,
33
+ Generator,
34
+ )
35
+
36
+ import jax
37
+ import numpy as np
38
+ from jax.api_util import shaped_abstractify
39
+ from jax.extend import source_info_util
40
+
41
+ from brainstate.typing import ArrayLike, PyTree, Missing, Filter
42
+ from brainstate.util import DictManager, PrettyObject
43
+ from brainstate.util.filter import Nothing
44
+
45
+ __all__ = [
46
+ 'State',
47
+ 'ShortTermState',
48
+ 'LongTermState',
49
+ 'HiddenState',
50
+ 'ParamState',
51
+ 'BatchState',
52
+ 'TreefyState',
53
+ 'FakeState',
54
+
55
+ 'StateDictManager',
56
+ 'StateTraceStack',
57
+ 'check_state_value_tree',
58
+ 'check_state_jax_tracer',
59
+ 'catch_new_states',
60
+ 'maybe_state',
61
+ ]
62
+
63
+ A = TypeVar('A')
64
+ B = TypeVar('B')
65
+ T = TypeVar('T')
66
+ F = TypeVar('F', bound=Callable[..., Any])
67
+
68
+ max_int = np.iinfo(np.int32)
69
+
70
+
71
+ # The global state of the state stack is accessed by a thread-local object.
72
+ # This allows concurrent tracing in separate threads; passing traced objects
73
+ # between threads is forbidden.
74
+ class ThreadLocalStack(threading.local):
75
+ """
76
+ A thread-local storage class for managing state-related information.
77
+
78
+ This class provides thread-local storage for various state management components,
79
+ ensuring that each thread has its own isolated set of state-related data structures.
80
+
81
+ Attributes:
82
+ state_stack (List[StateTraceStack]): A list to store StateTraceStack objects for the current thread.
83
+ tree_check (List[bool]): A list of boolean flags for tree structure checking, initialized with [False].
84
+ jax_tracer_check (List[bool]): A list of boolean flags for JAX tracer checking, initialized with [False].
85
+ new_state_catcher (List[StateCatcher]): A list to store Catcher objects for capturing new states in the current thread.
86
+ """
87
+
88
+ def __init__(self):
89
+ """
90
+ Initialize the ThreadLocalStack with empty data structures.
91
+
92
+ This constructor sets up the initial state for each thread-local instance,
93
+ creating empty lists for state stack, tree checking, JAX tracer checking,
94
+ and new state catching.
95
+ """
96
+ self.state_stack: List[StateTraceStack] = []
97
+ self.tree_check: List[bool] = [False]
98
+ self.jax_tracer_check: List[bool] = [False]
99
+ self.new_state_catcher: List[StateCatcher] = []
100
+
101
+
102
+ TRACE_CONTEXT = ThreadLocalStack()
103
+
104
+
105
+ @contextlib.contextmanager
106
+ def check_state_value_tree(val: bool = True) -> Generator[None, None, None]:
107
+ """
108
+ The contex manager to check weather the tree structure of the state value keeps consistently.
109
+
110
+ Once a :py:class:`~.State` is created, the tree structure of the value is fixed. In default,
111
+ the tree structure of the value is not checked to avoid off the repeated evaluation.
112
+ If you want to check the tree structure of the value once the new value is assigned,
113
+ you can use this context manager.
114
+
115
+ Example::
116
+
117
+ >>> import brainstate as brainstate
118
+ >>> import jax.numpy as jnp
119
+ >>> state = brainstate.ShortTermState(jnp.zeros((2, 3)))
120
+ >>> with brainstate.check_state_value_tree():
121
+ >>> # The line below will not raise an error.
122
+ >>> state.value = jnp.zeros((2, 3))
123
+ ...
124
+ >>> # The following code will raise an error, since it changes the tree structure.
125
+ >>> state.value = (jnp.zeros((2, 3)), jnp.zeros((2, 3)))
126
+
127
+ """
128
+ try:
129
+ TRACE_CONTEXT.tree_check.append(val)
130
+ yield
131
+ finally:
132
+ TRACE_CONTEXT.tree_check.pop()
133
+
134
+
135
+ def maybe_state(val: Any) -> Any:
136
+ """
137
+ Extracts the value from a State object if given, otherwise returns the input value.
138
+
139
+ This function is useful for handling both State objects and raw values uniformly.
140
+ If the input is a State object, it returns the value stored in that State.
141
+ If the input is not a State object, it returns the input as is.
142
+
143
+ Args:
144
+ val (Any): The input value, which can be either a State object or any other type.
145
+
146
+ Returns:
147
+ Any: The value stored in the State if the input is a State object,
148
+ otherwise the input value itself.
149
+ """
150
+ if isinstance(val, State):
151
+ return val.value
152
+ else:
153
+ return val
154
+
155
+
156
+ @contextlib.contextmanager
157
+ def check_state_jax_tracer(val: bool = True) -> Generator[None, None, None]:
158
+ """
159
+ The context manager to check whether the state is valid to trace.
160
+
161
+ Example::
162
+
163
+ >>> import jax
164
+ >>> import brainstate as brainstate
165
+ >>> import jax.numpy as jnp
166
+ >>>
167
+ >>> a = brainstate.ShortTermState(jnp.zeros((2, 3)))
168
+ >>>
169
+ >>> @jax.jit
170
+ >>> def run_state(b):
171
+ >>> a.value = b
172
+ >>> return a.value
173
+ >>>
174
+ >>> # The following code will not raise an error, since the state is valid to trace.
175
+ >>> run_state(jnp.ones((2, 3)))
176
+ >>>
177
+ >>> with check_state_jax_tracer():
178
+ >>> # The line below will not raise an error.
179
+ >>> run_state(jnp.ones((2, 4)))
180
+ """
181
+ try:
182
+ TRACE_CONTEXT.jax_tracer_check.append(val)
183
+ yield
184
+ finally:
185
+ TRACE_CONTEXT.jax_tracer_check.pop()
186
+
187
+
188
+ def _get_trace_stack_level() -> int:
189
+ return len(TRACE_CONTEXT.state_stack)
190
+
191
+
192
+ class State(Generic[A], PrettyObject):
193
+ """
194
+ A generic class representing a dynamic data pointer in the BrainState framework.
195
+
196
+ The State class serves as a base for various types of state objects used to
197
+ manage and track dynamic data within a program. It provides mechanisms for
198
+ value storage, metadata management, and integration with the BrainState
199
+ tracing system.
200
+
201
+ Type Parameters:
202
+ A: The type of the value stored in the state.
203
+
204
+ Attributes:
205
+ name (Optional[str]): An optional name for the state.
206
+ value (PyTree): The actual value stored in the state.
207
+ tag (Optional[str]): An optional tag for categorizing or grouping states.
208
+
209
+ Args:
210
+ value (Union[PyTree[ArrayLike], StateMetadata[PyTree[ArrayLike]]]):
211
+ The initial value for the state. Can be a PyTree of array-like objects
212
+ or a StateMetadata object.
213
+ name (Optional[str]): An optional name for the state.
214
+ **metadata: Additional metadata to be stored with the state.
215
+
216
+ Example:
217
+ >>> class MyState(State):
218
+ ... pass
219
+ >>> state = MyState(jnp.zeros((3, 3)), name="my_matrix")
220
+ >>> print(state.value)
221
+ [[0. 0. 0.]
222
+ [0. 0. 0.]
223
+ [0. 0. 0.]]
224
+
225
+ Note:
226
+ - Subclasses of :class:`State` (e.g., ShortTermState, LongTermState, ParamState,
227
+ RandomState) are typically used for specific purposes in a program.
228
+ - The class integrates with BrainState's tracing system to track state
229
+ creation and modifications.
230
+
231
+ The typical examples of :py:class:`~.State` subclass are:
232
+
233
+ - :py:class:`ShortTermState`: The short-term state, which is used to store the short-term data in the program.
234
+ - :py:class:`LongTermState`: The long-term state, which is used to store the long-term data in the program.
235
+ - :py:class:`ParamState`: The parameter state, which is used to store the parameters in the program.
236
+ - :py:class:`RandomState`: The random generator state, which is used to store the random key in the program.
237
+
238
+ Args:
239
+ value: PyTree. It can be anything as a pyTree.
240
+ name: Optional[str]. The name of the state.
241
+ tag: Optional[str]. The tag of the state.
242
+ """
243
+ __module__ = 'brainstate'
244
+ _level: int
245
+ _source_info: source_info_util.SourceInfo
246
+ _name: Optional[str]
247
+ _value: PyTree
248
+ _been_writen: bool # useful in `unflatten` and `flatten` graph processing
249
+ tag: Optional[str]
250
+
251
+ def __init__(
252
+ self,
253
+ value: PyTree[ArrayLike],
254
+ name: Optional[str] = None,
255
+ **metadata: Any
256
+ ):
257
+ """
258
+ Initialize a new HiddenState instance.
259
+
260
+ This constructor sets up the initial state for a hidden state in a dynamic model,
261
+ handling various input types and metadata.
262
+
263
+ Args:
264
+ value (Union[PyTree[ArrayLike], StateMetadata[PyTree[ArrayLike]]]):
265
+ The initial value for the hidden state. Can be a PyTree of array-like objects
266
+ or a StateMetadata object containing both value and metadata.
267
+ name (Optional[str], optional): A name for the hidden state. Defaults to None.
268
+ **metadata: Additional metadata to be stored with the hidden state, including:
269
+ - tag (Optional[str]): A tag for categorizing or grouping states.
270
+ - Any other custom metadata fields.
271
+
272
+ Note:
273
+ This method initializes the hidden state, processes the input value and metadata,
274
+ sets up internal attributes, and records the state initialization.
275
+ """
276
+ tag = metadata.pop('tag', None)
277
+
278
+ # set the value and metadata
279
+ if isinstance(value, State):
280
+ value = value.value
281
+
282
+ # update metadata
283
+ metadata.update(
284
+ _value=value,
285
+ _level=_get_trace_stack_level(),
286
+ _source_info=source_info_util.current(),
287
+ _name=name,
288
+ _been_writen=False,
289
+ tag=tag,
290
+ )
291
+
292
+ # avoid using self._setattr to avoid the check
293
+ vars(self).update(metadata)
294
+
295
+ # record the state initialization
296
+ record_state_init(self)
297
+
298
+ def decrease_stack_level(self):
299
+ """
300
+ Decrease the stack level of the state by one, ensuring it doesn't go below zero.
301
+
302
+ This method is used to adjust the stack level of the state, typically when
303
+ exiting a nested context or scope. It ensures that the level never becomes
304
+ negative.
305
+ """
306
+ self._level = max(self._level - 1, 0)
307
+
308
+ def increase_stack_level(self):
309
+ """
310
+ Increase the stack level of the state by one.
311
+
312
+ This method is used to adjust the stack level of the state, typically when
313
+ entering a nested context or scope. It increments the internal level counter
314
+ by one.
315
+ """
316
+ self._level = self._level + 1
317
+
318
+ @property
319
+ def name(self) -> Optional[str]:
320
+ """
321
+ The name of the state.
322
+ """
323
+ return self._name
324
+
325
+ @name.setter
326
+ def name(self, name: str) -> None:
327
+ """
328
+ Set the name of the state.
329
+ """
330
+ self._name = name
331
+
332
+ @property
333
+ def value(self) -> PyTree[ArrayLike]:
334
+ """
335
+ The data and its value.
336
+ """
337
+ record_state_value_read(self)
338
+ return self._read_value()
339
+
340
+ @value.setter
341
+ def value(self, v) -> None:
342
+ """
343
+ Set the value of the state.
344
+
345
+ Args:
346
+ v: The value.
347
+ """
348
+ # NOTE: the following order is important
349
+
350
+ if isinstance(v, State): # value checking
351
+ raise ValueError('Cannot set value to a State, ' 'use `copy_from` method instead')
352
+ self._check_value_tree(v) # check the tree structure
353
+ record_state_value_write(self) # record the value by the stack (>= level)
354
+ self._been_writen = True # set the flag
355
+ self._write_value(v) # write the value
356
+
357
+ @property
358
+ def stack_level(self):
359
+ """
360
+ The stack level of the state.
361
+
362
+ Returns:
363
+ The stack level.
364
+ """
365
+ return self._level
366
+
367
+ @stack_level.setter
368
+ def stack_level(self, level: int):
369
+ """
370
+ Set the stack level of the state.
371
+
372
+ Args:
373
+ level: The stack level.
374
+ """
375
+ self._level = level
376
+
377
+ def _read_value(self) -> PyTree[ArrayLike]:
378
+ """
379
+ The interface to customize the value reading.
380
+ """
381
+ self.check_if_deleted()
382
+ return self._value
383
+
384
+ def _write_value(self, v) -> None:
385
+ """
386
+ The interface to customize the value writing.
387
+ """
388
+ self._value = v
389
+
390
+ def restore_value(self, v) -> None:
391
+ """
392
+ Restore the value of the state.
393
+
394
+ Args:
395
+ v: The value.
396
+ """
397
+ # value checking
398
+ if isinstance(v, State):
399
+ raise ValueError('Cannot set value to a State, ' 'use `copy_from` method instead')
400
+ with check_state_value_tree():
401
+ self._check_value_tree(v)
402
+ # record the value by the stack (>= level)
403
+ record_state_value_restore(self)
404
+ # set the value
405
+ self._value = v
406
+
407
+ def value_call(self, func: Callable[..., Any]) -> Any:
408
+ """
409
+ Call the function with the value of the state.
410
+ """
411
+ return jax.tree.map(func, self.value)
412
+
413
+ def _check_value_tree(self, v):
414
+ """
415
+ Check if the value tree structure is consistent.
416
+ """
417
+ if TRACE_CONTEXT.tree_check[-1]:
418
+ in_tree = jax.tree.structure(v)
419
+ self_tree = jax.tree.structure(self._value)
420
+ if in_tree != self_tree:
421
+ self.raise_error_with_source_info(
422
+ ValueError(f'The given value {in_tree} does not match with the origin tree structure {self_tree}.')
423
+ )
424
+
425
+ def raise_error_with_source_info(self, error: Exception):
426
+ """
427
+ Raise an error with the source information for easy debugging.
428
+ """
429
+ name_stack = source_info_util.current_name_stack() + self.source_info.name_stack
430
+ with source_info_util.user_context(self.source_info.traceback, name_stack=name_stack):
431
+ raise error
432
+
433
+ def check_if_deleted(self):
434
+ pass
435
+
436
+ @property
437
+ def source_info(self) -> source_info_util.SourceInfo:
438
+ """
439
+ The source information of the state, can be useful to identify
440
+ the source code where the definition of the state.
441
+
442
+ Returns:
443
+ The source information.
444
+ """
445
+ return self._source_info
446
+
447
+ def update_from_ref(self, state_ref: TreefyState[A]) -> None:
448
+ """
449
+ Update the state from the state reference :py:class:`TreefyState`.
450
+
451
+ Args:
452
+ state_ref: The state reference.
453
+ """
454
+ metadata = state_ref.get_metadata()
455
+ variable_vars = vars(self)
456
+ variable_vars.update(**metadata)
457
+ if metadata.pop('_been_writen', True):
458
+ self.value = state_ref.value
459
+ else:
460
+ self.restore_value(state_ref.value)
461
+
462
+ def replace(self, value: Any = Missing, **kwargs) -> State[Any]:
463
+ """
464
+ Replace the attribute of the state.
465
+ """
466
+ if value is not Missing:
467
+ kwargs['_value'] = value
468
+
469
+ # return `value` if it is a State
470
+ if '_value' in kwargs and isinstance(value := kwargs['_value'], State):
471
+ # remove value from kwargs
472
+ kwargs.pop('_value')
473
+ if type(self) is not type(value):
474
+ raise ValueError('Cannot replace value from incompatible container, '
475
+ f'expected {type(self).__name__}, got {type(value).__name__}')
476
+ # if kwargs aren't empty, recursively call replace
477
+ # else return variable value
478
+ if kwargs:
479
+ return value.replace(**kwargs)
480
+ else:
481
+ return value
482
+
483
+ # get and update attributes
484
+ attributes = vars(self).copy()
485
+ attributes.update(**kwargs)
486
+ # return new instance with updated attributes
487
+ obj = object.__new__(type(self))
488
+ vars(obj).update(attributes)
489
+ return obj
490
+
491
+ def copy(self: State[A]) -> State[A]:
492
+ """
493
+ Copy the state.
494
+ """
495
+ obj = object.__new__(type(self))
496
+ attributes = vars(self).copy()
497
+ # keep its own trace state and stack level
498
+ attributes['_level'] = _get_trace_stack_level()
499
+ attributes['_source_info'] = source_info_util.current()
500
+ attributes.pop('_been_writen', None)
501
+ # update the metadata
502
+ vars(obj).update(attributes)
503
+ return obj
504
+
505
+ def to_state_ref(self: State[A]) -> TreefyState[A]:
506
+ metadata = vars(self).copy()
507
+ del metadata['_value']
508
+ return TreefyState(type(self), self._value, **metadata)
509
+
510
+ def __pretty_repr_item__(self, k, v):
511
+ if k in ['_level', '_source_info', '_been_writen']:
512
+ return None
513
+ if k == '_value':
514
+ return 'value', jax.tree.map(shaped_abstractify, v)
515
+
516
+ if k == '_name':
517
+ if self.name is None:
518
+ return None
519
+ else:
520
+ return 'name', v
521
+
522
+ if k == 'tag':
523
+ if self.tag is None:
524
+ return None
525
+ else:
526
+ return 'tag', v
527
+
528
+ return k, v
529
+
530
+ # def __eq__(self, other: object) -> bool:
531
+ # return type(self) is type(other) and vars(other) == vars(self)
532
+
533
+ def __hash__(self):
534
+ """
535
+ Make the state hashable.
536
+ """
537
+ return hash(id(self))
538
+
539
+ def numel(self) -> int:
540
+ """
541
+ Calculate the total number of elements in the state value.
542
+
543
+ This method traverses the state's value, which may be a nested structure (PyTree),
544
+ and computes the sum of sizes of all leaf nodes.
545
+
546
+ Returns:
547
+ int: The total number of elements across all arrays in the state value.
548
+ For scalar values, this will be 1. For arrays or nested structures,
549
+ it will be the sum of the sizes of all contained arrays.
550
+
551
+ Note:
552
+ This method uses jax.tree.leaves to flatten any nested structure in the state value,
553
+ and jax.numpy.size to compute the size of each leaf node.
554
+ """
555
+ sizes = [jax.numpy.size(val) for val in jax.tree.leaves(self._value)]
556
+ return sum(sizes)
557
+
558
+
559
+ def record_state_init(st: State[A]):
560
+ """
561
+ Record the initialization of a new :class:`State` object.
562
+
563
+ This function iterates through all registered state catchers in the current
564
+ trace context and appends the newly initialized state to each catcher.
565
+
566
+ Args:
567
+ st (State[A]): The newly initialized :class:`State` object to be recorded.
568
+
569
+ Note:
570
+ This function is typically called internally when a new :class:`State` object
571
+ is created to ensure proper tracking and management of states within
572
+ the current execution context.
573
+ """
574
+ trace: StateCatcher
575
+ for trace in TRACE_CONTEXT.new_state_catcher:
576
+ trace.append(st)
577
+
578
+
579
+ def record_state_value_read(st: State[A]):
580
+ """
581
+ Record that a state's value has been read in all relevant trace stacks.
582
+
583
+ This function iterates through all state trace stacks at or above the
584
+ state's stack level in the current trace context, and records that
585
+ the given state's value has been read.
586
+
587
+ Args:
588
+ st (State[A]): The state object whose value read is being recorded.
589
+ 'A' is a generic type parameter representing the
590
+ type of the state's value.
591
+
592
+ Note:
593
+ This function modifies the state trace stacks in the current
594
+ trace context but does not return any value.
595
+ """
596
+ trace: StateTraceStack
597
+ for trace in TRACE_CONTEXT.state_stack[st.stack_level:]:
598
+ trace.read_its_value(st)
599
+
600
+
601
+ def record_state_value_write(st: State[A]):
602
+ """
603
+ Record that a state's value has been written in all relevant trace stacks.
604
+
605
+ This function iterates through all state trace stacks at or above the
606
+ state's stack level in the current trace context, and records that
607
+ the given state's value has been written.
608
+
609
+ Args:
610
+ st (State[A]): The state object whose value write is being recorded.
611
+ 'A' is a generic type parameter representing the
612
+ type of the state's value.
613
+
614
+ Note:
615
+ This function modifies the state trace stacks in the current
616
+ trace context but does not return any value.
617
+ """
618
+ trace: StateTraceStack
619
+ for trace in TRACE_CONTEXT.state_stack[st.stack_level:]:
620
+ trace.write_its_value(st)
621
+
622
+
623
+ def record_state_value_restore(st: State[A]):
624
+ """
625
+ Record that a state's value has been restored.
626
+
627
+ This function is used to indicate that a state's value has been restored
628
+ to a previous value. It internally calls the record_state_value_read
629
+ function to mark the state as having been accessed.
630
+
631
+ Args:
632
+ st (State[A]): The state object whose value restoration is being recorded.
633
+ 'A' is a generic type parameter representing the
634
+ type of the state's value.
635
+
636
+ See Also:
637
+ record_state_value_read: Record that a state's value has been read.
638
+
639
+ Note:
640
+ This function does not actually restore the state's value; it only
641
+ records that a restoration has occurred.
642
+ """
643
+ record_state_value_read(st)
644
+
645
+
646
+ class ShortTermState(State):
647
+ """
648
+ A class representing short-term state in a program.
649
+
650
+ :class:`ShortTermState` is used to store temporary or transient data that is only relevant
651
+ for a short duration within the program's execution. This class extends the base
652
+ State class, inheriting its properties and methods while specifically denoting
653
+ the short-term nature of the stored data.
654
+
655
+ For example, in a machine learning training process, the gradients of the model
656
+ would typically be represented as :class:`ShortTermState`, as they are computed and used
657
+ within each iteration but not necessarily preserved across iterations.
658
+
659
+ Attributes:
660
+ Inherits all attributes from the base State class.
661
+
662
+ Note:
663
+ This class does not introduce new methods or attributes beyond those
664
+ inherited from the State class. Its primary purpose is to semantically
665
+ distinguish short-term states from other types of states in the program.
666
+
667
+ Example:
668
+ >>> gradient = ShortTermState(np.zeros(100), name="model_gradient")
669
+ >>> intermediate_result = ShortTermState({}, name="layer_activations")
670
+ """
671
+
672
+ __module__ = 'brainstate'
673
+
674
+
675
+ class LongTermState(State):
676
+ """
677
+ The long-term state, which is used to store the long-term data in the program.
678
+
679
+ This class extends the base :class:`State` class and is specifically designed to represent
680
+ and manage long-term data within a program. Long-term states are typically used
681
+ for data that persists across multiple iterations or epochs of a process.
682
+
683
+ For example, in a training process, the weights of the model are considered
684
+ long-term states as they are updated and maintained throughout the entire
685
+ training procedure.
686
+
687
+ Attributes:
688
+ Inherits all attributes from the base :class:`State` class.
689
+
690
+ Note:
691
+ This class does not introduce new methods or attributes beyond those
692
+ inherited from the :class:`State` class. Its primary purpose is to semantically
693
+ distinguish long-term states from other types of states in the program.
694
+
695
+ Example:
696
+ >>> model_weights = LongTermState(np.random.randn(100, 100), name="model_weights")
697
+ >>> optimizer_state = LongTermState({}, name="optimizer_state")
698
+ """
699
+
700
+ __module__ = 'brainstate'
701
+
702
+
703
+ class BatchState(LongTermState):
704
+ """
705
+ The batch state, which is used to store the batch data in the program.
706
+
707
+ This class extends :class:`LongTermState` and is specifically designed to represent
708
+ and manage batch data within a program. It provides a way to encapsulate
709
+ batch-related information and associated metadata, facilitating operations
710
+ like batch processing in machine learning or data analysis tasks.
711
+
712
+ Attributes:
713
+ Inherits all attributes from :class:`LongTermState`.
714
+
715
+ Note:
716
+ This class does not introduce new methods or attributes beyond those
717
+ inherited from :class:`LongTermState`. Its primary purpose is to semantically
718
+ distinguish batch states from other types of long-term states
719
+ in the program.
720
+
721
+ Example:
722
+ >>> batch_data = BatchState(np.array([1, 2, 3, 4, 5]), name="current_batch")
723
+ >>> batch_labels = BatchState(np.array([0, 1, 0, 1, 1]), name="batch_labels")
724
+ """
725
+
726
+ __module__ = 'brainstate'
727
+
728
+
729
+ class HiddenState(ShortTermState):
730
+ """
731
+ Represents hidden state variables in neurons or synapses.
732
+
733
+ This class extends :class:`ShortTermState` and is specifically designed to represent
734
+ and manage hidden states within dynamic models, such as recurrent neural networks.
735
+ It provides a way to encapsulate hidden state values and associated metadata,
736
+ facilitating operations like state updates during model execution.
737
+
738
+ Note:
739
+ :class:`HiddenState` and :class:`ParamState` are two most important state types
740
+ in brainstate. The former is used to store the hidden states in neurons, synapses,
741
+ or networks. The latter is used to store the trainable parameters in the model,
742
+ such as synaptic weights.
743
+
744
+ Example:
745
+ >>> lstm_hidden = HiddenState(np.zeros(128), name="lstm_hidden_state")
746
+ >>> gru_hidden = HiddenState(np.zeros(64), name="gru_hidden_state")
747
+ """
748
+
749
+ __module__ = 'brainstate'
750
+
751
+
752
+ class ParamState(LongTermState):
753
+ """
754
+ The parameter state, which is used to store the trainable parameters in the model.
755
+
756
+ This class extends :class:`LongTermState` and is specifically designed to represent
757
+ and manage trainable parameters within a neural network or machine learning model.
758
+ It provides a way to encapsulate parameter values and associated metadata,
759
+ facilitating operations like parameter updates during training.
760
+
761
+ Note:
762
+ :class:`HiddenState` and :class:`ParamState` are two most important state types
763
+ in brainstate. The former is used to store the hidden states in neurons, synapses,
764
+ or networks. The latter is used to store the trainable parameters in the model,
765
+ such as synaptic weights.
766
+
767
+ Example:
768
+ >>> weight = ParamState(np.random.randn(10, 10), name="layer1_weights")
769
+ >>> bias = ParamState(np.zeros(10), name="layer1_bias")
770
+ """
771
+
772
+ __module__ = 'brainstate'
773
+
774
+
775
+ class FakeState:
776
+ """
777
+ The faked state, which is used to store the faked data in the program.
778
+ """
779
+
780
+ __module__ = 'brainstate'
781
+
782
+ def __init__(self, value: Any, name: Optional[str] = None):
783
+ """
784
+ Initialize a FakeState instance.
785
+
786
+ Args:
787
+ value (Any): The value to be stored in the fake state.
788
+ name (Optional[str], optional): The name of the fake state. Defaults to None.
789
+ """
790
+ self._value = value
791
+ self._name = name
792
+
793
+ @property
794
+ def value(self) -> Any:
795
+ """
796
+ Get the value stored in the fake state.
797
+
798
+ Returns:
799
+ Any: The value stored in the fake state.
800
+ """
801
+ return self._value
802
+
803
+ @value.setter
804
+ def value(self, v) -> None:
805
+ """
806
+ Set the value of the fake state.
807
+
808
+ Args:
809
+ v (Any): The new value to be stored in the fake state.
810
+ """
811
+ self._value = v
812
+
813
+ def __repr__(self) -> str:
814
+ """
815
+ Return a string representation of the FakeState instance.
816
+
817
+ Returns:
818
+ str: A string representation of the FakeState instance.
819
+ """
820
+ return f'FakedState(value={self._value})'
821
+
822
+ @property
823
+ def name(self) -> Optional[str]:
824
+ """
825
+ Get the name of the fake state.
826
+
827
+ Returns:
828
+ Optional[str]: The name of the fake state, or None if not set.
829
+ """
830
+ return self._name
831
+
832
+ @name.setter
833
+ def name(self, name: str) -> None:
834
+ """
835
+ Set the name of the fake state.
836
+
837
+ Args:
838
+ name (str): The new name for the fake state.
839
+ """
840
+ self._name = name
841
+
842
+
843
+ class StateDictManager(DictManager):
844
+ """
845
+ State stack, for collecting all :py:class:`~.State` used in the program.
846
+
847
+ :py:class:`~.StateDictManager` supports all features of python dict.
848
+ """
849
+
850
+ __module__ = 'brainstate'
851
+
852
+ def assign_values(self, *args: Dict) -> None:
853
+ """
854
+ Assign the value for each element according to the given ``data``.
855
+ """
856
+ for arg in args:
857
+ assert isinstance(arg, dict), 'Must be an instance of dict.'
858
+ for k, v in arg.items():
859
+ self._set_elem(k, v)
860
+
861
+ def split_values(self, *filters: type) -> Tuple[Dict, ...]:
862
+ """
863
+ Split the values into several subsets of stack by the given types.
864
+ """
865
+ results = tuple(DictManager() for _ in range(len(filters) + 1))
866
+ for k, v in self.items():
867
+ for i, filt in enumerate(filters):
868
+ if isinstance(v, filt):
869
+ results[i][k] = v.value
870
+ break
871
+ else:
872
+ results[-1][k] = v.value
873
+ return results
874
+
875
+ def collect_values(self) -> Dict:
876
+ """
877
+ Collect the values by the given types.
878
+ """
879
+ results = DictManager()
880
+ for k, v in self.items():
881
+ results[k] = v.value
882
+ return results
883
+
884
+ def split(self, first: type, *others: type) -> Tuple['StateDictManager', ...]:
885
+ return super().split(first, *others)
886
+
887
+ def to_dict_values(self) -> Dict:
888
+ """
889
+ Convert the values into a dict.
890
+ """
891
+ return {k: v.value for k, v in self.items()}
892
+
893
+ def _check_elem(self, elem):
894
+ assert isinstance(elem, State), f'must be instance of {State}'
895
+
896
+ def _set_elem(self, key: Any, value: Any) -> None:
897
+ self[key].value = value
898
+
899
+
900
+ class StateTraceStack(Generic[A]):
901
+ """
902
+ A stack for tracing and managing states during program execution.
903
+
904
+ ``StateTraceStack`` is used to automatically trace and manage State objects,
905
+ keeping track of which states are read from or written to during the
906
+ execution of a function or block of code. It provides methods for
907
+ recording state accesses, retrieving state values, and managing the
908
+ lifecycle of states within a tracing context.
909
+
910
+ The class is generic over type A, allowing for type-safe usage with
911
+ different types of State objects.
912
+
913
+ Attributes:
914
+ states (List[State]): A list of all State objects encountered during tracing.
915
+ been_writen (List[bool]): A parallel list to states, indicating whether each state has been written to.
916
+ _state_id_index (dict): A dictionary mapping state ids to their index in the states list.
917
+ _original_state_values (List): A list of the original values of all states when first encountered.
918
+ _jax_trace_new_arg (Callable): A function used to transform state values during tracing.
919
+
920
+ Methods:
921
+ __enter__: Enters a new tracing context.
922
+ __exit__: Exits the current tracing context.
923
+ read_its_value: Records a read operation on a state.
924
+ write_its_value: Records a write operation on a state.
925
+ get_state_values: Retrieves the current values of all traced states.
926
+ recovery_original_values: Restores all states to their original values.
927
+ merge: Merges multiple ``StateTraceStack`` instances.
928
+ get_read_states: Retrieves states that were read during tracing.
929
+ get_read_state_values: Retrieves values of states that were read during tracing.
930
+
931
+ The ``StateTraceStack`` is a crucial component in implementing state-based
932
+ computations and is particularly useful in scenarios involving automatic
933
+ differentiation or other forms of program transformation.
934
+ """
935
+
936
+ def __init__(
937
+ self,
938
+ new_arg: Callable = None,
939
+ name: Optional[str] = None,
940
+ ):
941
+ self.name = name
942
+ self.states: List[State] = []
943
+ self.been_writen: List[bool] = [] # False: read, True: write
944
+ self._state_id_index = dict()
945
+ self._original_state_values = []
946
+ self._jax_trace_new_arg: Callable = new_arg
947
+ self._stack_level = None
948
+
949
+ def __str__(self) -> str:
950
+ _stack_level = self.name if self._stack_level is None else self._stack_level
951
+ if _stack_level is None:
952
+ _stack_level = ''
953
+ return f"{self.__class__.__name__}({_stack_level})"
954
+
955
+ @property
956
+ def original_state_values(self) -> Tuple[PyTree, ...]:
957
+ """
958
+ Get the original values of all states in the StateTraceStack.
959
+
960
+ This property provides access to the initial values of all states
961
+ that were captured when they were first added to the stack. It's
962
+ useful for comparing current state values with their original values
963
+ or for reverting states to their initial condition.
964
+
965
+ Returns:
966
+ Tuple[PyTree, ...]: A tuple containing the original values of all
967
+ states in the order they were added to the stack. Each element
968
+ is a PyTree representing the structure and values of a state.
969
+ """
970
+ return tuple(self._original_state_values)
971
+
972
+ def set_new_arg(self, new_arg: Callable) -> None:
973
+ self._jax_trace_new_arg = new_arg
974
+
975
+ def new_arg(self, state: State) -> None:
976
+ """
977
+ Apply a transformation to the value of a given state using a predefined function.
978
+
979
+ This method is used internally to transform the value of a state during tracing.
980
+ If a transformation function (``_jax_trace_new_arg``) is defined, it applies this
981
+ function to each element of the state's value using JAX's tree mapping.
982
+
983
+ Args:
984
+ state (State): The State object whose value needs to be transformed.
985
+
986
+ Returns:
987
+ None: This function modifies the state in-place and doesn't return anything.
988
+
989
+ Note:
990
+ This method is intended for internal use and relies on the presence of
991
+ a ``_jax_trace_new_arg`` function, which should be set separately.
992
+ """
993
+ if self._jax_trace_new_arg is not None:
994
+ # internal use
995
+ state._value = jax.tree.map(self._jax_trace_new_arg, state._value)
996
+
997
+ def __enter__(self) -> 'StateTraceStack':
998
+ TRACE_CONTEXT.state_stack.append(self)
999
+ self._stack_level = ' / '.join([st.name for st in TRACE_CONTEXT.state_stack if st.name is not None])
1000
+ return self
1001
+
1002
+ def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None:
1003
+ TRACE_CONTEXT.state_stack.pop()
1004
+
1005
+ def read_its_value(self, state: State) -> None:
1006
+ """
1007
+ Record that a state's value has been read during tracing.
1008
+
1009
+ This method marks the given state as having been read in the current
1010
+ tracing context. If the state hasn't been encountered before, it adds
1011
+ it to the internal tracking structures and applies any necessary
1012
+ transformations via the new_arg method.
1013
+
1014
+ Args:
1015
+ state (State): The State object whose value is being read.
1016
+
1017
+ Returns:
1018
+ None
1019
+
1020
+ Note:
1021
+ This method updates the internal tracking of state accesses.
1022
+ It doesn't actually read or return the state's value.
1023
+ """
1024
+ id_ = id(state)
1025
+ if id_ not in self._state_id_index:
1026
+ self._state_id_index[id_] = len(self.states)
1027
+ self.states.append(state)
1028
+ self.been_writen.append(False)
1029
+ self._original_state_values.append(state._value) # internal use
1030
+ self.new_arg(state)
1031
+
1032
+ def write_its_value(self, state: State) -> None:
1033
+ """
1034
+ Record that a state's value has been written to during tracing.
1035
+
1036
+ This method marks the given state as having been written to in the current
1037
+ tracing context. If the state hasn't been encountered before, it first
1038
+ records it as being read before marking it as written.
1039
+
1040
+ Args:
1041
+ state (State): The State object whose value is being written to.
1042
+
1043
+ Returns:
1044
+ None
1045
+
1046
+ Note:
1047
+ This method updates the internal tracking of state modifications.
1048
+ It doesn't actually modify the state's value.
1049
+ """
1050
+ id_ = id(state)
1051
+ if id_ not in self._state_id_index:
1052
+ self.read_its_value(state)
1053
+ index = self._state_id_index[id_]
1054
+ self.been_writen[index] = True
1055
+
1056
+ def get_state_values(
1057
+ self,
1058
+ separate: bool = False,
1059
+ replace: bool = False
1060
+ ) -> Sequence[PyTree] | Tuple[Sequence[PyTree], Sequence[PyTree]]:
1061
+ """
1062
+ Retrieve the values of all states in the StateTraceStack.
1063
+
1064
+ This method returns the values of all states, optionally separating them
1065
+ into written and read states, and optionally replacing values with None
1066
+ for states that weren't accessed in a particular way.
1067
+
1068
+ Args:
1069
+ separate (bool, optional): If True, separate the values into written
1070
+ and read states. If False, return all values in a single sequence.
1071
+ Defaults to False.
1072
+ replace (bool, optional): If True and separate is True, replace values
1073
+ with None for states that weren't written/read. If False, only
1074
+ include values for states that were written/read. Defaults to False.
1075
+
1076
+ Returns:
1077
+ Sequence[PyTree] | Tuple[Sequence[PyTree], Sequence[PyTree]]:
1078
+ If separate is False:
1079
+ A sequence of all state values.
1080
+ If separate is True:
1081
+ A tuple containing two sequences:
1082
+ - The first sequence contains values of written states.
1083
+ - The second sequence contains values of read states.
1084
+ If replace is True, these sequences will have None for
1085
+ states that weren't written/read respectively.
1086
+
1087
+ """
1088
+ if separate:
1089
+ if replace:
1090
+ writes, reads = [], []
1091
+ for st, been_writen in zip(self.states, self.been_writen):
1092
+ if been_writen:
1093
+ writes.append(st.value)
1094
+ reads.append(None)
1095
+ else:
1096
+ reads.append(st.value)
1097
+ writes.append(None)
1098
+ return tuple(writes), tuple(reads)
1099
+ else:
1100
+ writes, reads = [], []
1101
+ for st, been_writen in zip(self.states, self.been_writen):
1102
+ if been_writen:
1103
+ writes.append(st.value)
1104
+ else:
1105
+ reads.append(st.value)
1106
+ return tuple(writes), tuple(reads)
1107
+ else:
1108
+ return tuple([st.value for st in self.states])
1109
+
1110
+ def recovery_original_values(self) -> None:
1111
+ """
1112
+ Restore the original values of all states in the StateTraceStack.
1113
+
1114
+ This method iterates through all states in the stack and restores
1115
+ their values to the original ones that were captured when the states
1116
+ were first added to the stack. This is useful for reverting changes
1117
+ made during tracing or for resetting the states to their initial condition.
1118
+
1119
+ Note:
1120
+ This method modifies the states in-place.
1121
+
1122
+ Returns:
1123
+ None
1124
+ """
1125
+ for st, val in zip(self.states, self._original_state_values):
1126
+ # internal use
1127
+ st.restore_value(val)
1128
+
1129
+ def merge(self, *traces) -> 'StateTraceStack':
1130
+ """
1131
+ Merge other state traces into the current ``StateTraceStack``.
1132
+
1133
+ This method combines the states, their write status, and original values from
1134
+ other ``StateTraceStack`` instances into the current one. If a state from another
1135
+ trace is not present in the current trace, it is added. If a state is already
1136
+ present, its write status is updated if necessary.
1137
+
1138
+ Args:
1139
+ *traces: Variable number of ``StateTraceStack`` instances to be merged into
1140
+ the current instance.
1141
+
1142
+ Returns:
1143
+ StateTraceStack: The current ``StateTraceStack`` instance with merged traces.
1144
+
1145
+ Note:
1146
+ This method modifies the current ``StateTraceStack`` in-place and also returns it.
1147
+ """
1148
+ trace: StateTraceStack
1149
+ for trace in traces:
1150
+ for st, been_writen, org_val in zip(trace.states, trace.been_writen, trace._original_state_values):
1151
+ if id(st) not in self._state_id_index: # read the value
1152
+ self._state_id_index[id(st)] = len(self.states)
1153
+ self._original_state_values.append(org_val) # add the original value
1154
+ self.states.append(st) # append the state
1155
+ self.been_writen.append(False)
1156
+ if been_writen:
1157
+ self.write_its_value(st)
1158
+ return self
1159
+
1160
+ def get_read_states(self, replace_writen: bool = False) -> Tuple[State, ...]:
1161
+ """
1162
+ Retrieve the states that were read during the function execution.
1163
+
1164
+ This method returns the states that were accessed (read from) during
1165
+ the traced function's execution. It can optionally replace written
1166
+ states with None.
1167
+
1168
+ Args:
1169
+ replace_writen (bool, optional): If True, replace written states with None
1170
+ in the returned tuple. If False, exclude written states entirely from
1171
+ the result. Defaults to False.
1172
+
1173
+ Returns:
1174
+ Tuple[State, ...]: A tuple containing the read states.
1175
+ If replace_writen is True, the tuple will have the same length as the
1176
+ total number of states, with None for written states.
1177
+ If replace_writen is False, the tuple will only contain read-only states.
1178
+ """
1179
+ if replace_writen:
1180
+ return tuple([st if not been_writen else None
1181
+ for st, been_writen in zip(self.states, self.been_writen)])
1182
+ else:
1183
+ return tuple([st for st, been_writen in zip(self.states, self.been_writen) if not been_writen])
1184
+
1185
+ def get_read_state_values(self, replace_writen: bool = False) -> Tuple[PyTree, ...]:
1186
+ """
1187
+ Retrieve the values of states that were read during the function execution.
1188
+
1189
+ This method returns the values of states that were accessed (read from) during
1190
+ the traced function's execution. It can optionally replace written states with None.
1191
+
1192
+ Args:
1193
+ replace_writen (bool, optional): If True, replace the values of written
1194
+ states with None in the returned tuple. If False, exclude written
1195
+ states entirely from the result. Defaults to False.
1196
+
1197
+ Returns:
1198
+ Tuple[PyTree, ...]: A tuple containing the values of read states.
1199
+ If replace_writen is True, the tuple will have the same length as the
1200
+ total number of states, with None for written states.
1201
+ If replace_writen is False, the tuple will only contain values of
1202
+ read-only states.
1203
+ """
1204
+ if replace_writen:
1205
+ return tuple(
1206
+ [st.value if not been_writen else None
1207
+ for st, been_writen in zip(self.states, self.been_writen)]
1208
+ )
1209
+ else:
1210
+ return tuple([st.value for st, been_writen in zip(self.states, self.been_writen) if not been_writen])
1211
+
1212
+ def get_write_states(self, replace_read: bool = False) -> Tuple[State, ...]:
1213
+ """
1214
+ Retrieve the states that were written during the function execution.
1215
+
1216
+ This method returns the states that were modified (written to) during
1217
+ the traced function's execution. It can optionally replace unwritten (read-only)
1218
+ states with None.
1219
+
1220
+ Args:
1221
+ replace_read (bool, optional): If True, replace read-only states with None
1222
+ in the returned tuple. If False, exclude read-only states entirely from
1223
+ the result. Defaults to False.
1224
+
1225
+ Returns:
1226
+ Tuple[State, ...]: A tuple containing the written states.
1227
+ If replace_read is True, the tuple will have the same length as the
1228
+ total number of states, with None for read-only states.
1229
+ If replace_read is False, the tuple will only contain written states.
1230
+ """
1231
+ if replace_read:
1232
+ return tuple([st if been_writen else None
1233
+ for st, been_writen in zip(self.states, self.been_writen)])
1234
+ else:
1235
+ return tuple([st for st, been_writen in zip(self.states, self.been_writen) if been_writen])
1236
+
1237
+ def get_write_state_values(self, replace_read: bool = False) -> Tuple[PyTree, ...]:
1238
+ """
1239
+ Retrieve the values of states that were written during the function execution.
1240
+
1241
+ This method returns the values of states that were modified (written to) during
1242
+ the traced function's execution. It can optionally replace unwritten (read-only)
1243
+ states with None.
1244
+
1245
+ Args:
1246
+ replace_read (bool, optional): If True, replace the values of read-only
1247
+ states with None in the returned tuple. If False, exclude read-only
1248
+ states entirely from the result. Defaults to False.
1249
+
1250
+ Returns:
1251
+ Tuple[PyTree, ...]: A tuple containing the values of written states.
1252
+ If replace_read is True, the tuple will have the same length as the
1253
+ total number of states, with None for read-only states.
1254
+ If replace_read is False, the tuple will only contain values of
1255
+ written states.
1256
+
1257
+ """
1258
+ if replace_read:
1259
+ return tuple([st.value if been_writen else None for st, been_writen in zip(self.states, self.been_writen)])
1260
+ else:
1261
+ return tuple([st.value for st, been_writen in zip(self.states, self.been_writen) if been_writen])
1262
+
1263
+ def __add__(self, other: 'StateTraceStack') -> 'StateTraceStack':
1264
+ """
1265
+ Support the syntax of `+` to merge the state traces.
1266
+ """
1267
+ return StateTraceStack().merge(self, other)
1268
+
1269
+ def assign_state_vals(self, state_vals: Sequence[PyTree]) -> None:
1270
+ """
1271
+ Assign new values to the states tracked by this ``StateTraceStack``.
1272
+
1273
+ This method updates the values of the states based on whether they were
1274
+ written to or only read during the tracing process. For states that were
1275
+ written to, it directly assigns the new value. For states that were only
1276
+ read, it restores the value using the state's restore_value method.
1277
+
1278
+ Args:
1279
+ state_vals (Sequence[PyTree]): A sequence of new state values to be
1280
+ assigned. Each element in this sequence corresponds to a state
1281
+ in the ``StateTraceStack``'s states list.
1282
+
1283
+ Raises:
1284
+ ValueError: If the length of state_vals doesn't match the number of
1285
+ states in the ``StateTraceStack``.
1286
+
1287
+ Returns:
1288
+ None
1289
+
1290
+ Note:
1291
+ The order of state_vals should match the order of states in the
1292
+ ``StateTraceStack``'s states list.
1293
+ """
1294
+ if len(state_vals) != len(self.states):
1295
+ raise ValueError('The length of the state values must be equal to the states. '
1296
+ f'Bug got {len(state_vals)} and {len(self.states)}')
1297
+ for st, written, val in zip(self.states, self.been_writen, state_vals):
1298
+ if written:
1299
+ st.value = val
1300
+ else:
1301
+ st.restore_value(val)
1302
+
1303
+ def state_subset(self, state_type: type) -> List:
1304
+ """
1305
+ Get a subset of states of a specific type from the ``StateTraceStack``.
1306
+
1307
+ This method filters the states in the ``StateTraceStack`` and returns only
1308
+ those that match the specified state type.
1309
+
1310
+ Args:
1311
+ state_type (type): The type of state to filter by. This should be
1312
+ a subclass of State or State itself.
1313
+
1314
+ Returns:
1315
+ List[State]: A list containing all states in the ``StateTraceStack``
1316
+ that are instances of the specified state_type.
1317
+
1318
+ Example:
1319
+ >>> stack = StateTraceStack()
1320
+ >>> # Assume stack has been populated with various state types
1321
+ >>> short_term_states = stack.state_subset(ShortTermState)
1322
+ """
1323
+ return [st for st in self.states if isinstance(st, state_type)]
1324
+
1325
+
1326
+ class TreefyState(Generic[A], PrettyObject):
1327
+ """
1328
+ The state as a pytree.
1329
+ """
1330
+
1331
+ def __init__(
1332
+ self,
1333
+ type: type[State[Any]],
1334
+ value: A,
1335
+ **metadata
1336
+ ):
1337
+ self.type = type
1338
+ self.value = value
1339
+ vars(self).update(metadata)
1340
+
1341
+ if TYPE_CHECKING:
1342
+ def __getattr__(self, name: str) -> None: ...
1343
+
1344
+ def __setattr__(self, name: str, value: Any) -> None: ...
1345
+
1346
+ def __delattr__(self, name: str) -> None: ...
1347
+
1348
+ def __pretty_repr_item__(self, k, v):
1349
+ if k in ['_level', '_source_info', '_been_writen']:
1350
+ return None
1351
+ if k == '_value':
1352
+ return 'value', v
1353
+
1354
+ if k == '_name':
1355
+ return None if v is None else ('name', v)
1356
+ return k, v
1357
+
1358
+ @property
1359
+ def name(self) -> Optional[str]:
1360
+ """
1361
+ The name of the state.
1362
+ """
1363
+ return self._name
1364
+
1365
+ @name.setter
1366
+ def name(self, name: str) -> None:
1367
+ """
1368
+ Set the name of the state.
1369
+ """
1370
+ self._name = name
1371
+
1372
+ def replace(self, value: B) -> TreefyState[B]:
1373
+ """
1374
+ Replace the value of the state reference.
1375
+ """
1376
+ return TreefyState(self.type, value, **self.get_metadata())
1377
+
1378
+ def to_state(self) -> State[A]:
1379
+ """
1380
+ Convert the state reference to the state.
1381
+ """
1382
+ # we use object.__new__ to avoid calling __init__ and bypass the
1383
+ # __init__ logic which should not be called twice
1384
+ metadata = self.get_metadata()
1385
+ state = object.__new__(self.type)
1386
+ metadata.pop('_value', None)
1387
+ metadata.pop('_level', None)
1388
+ vars(state).update(**metadata, _value=self.value, _level=_get_trace_stack_level())
1389
+ return state
1390
+
1391
+ def copy(self: TreefyState[A]) -> TreefyState[A]:
1392
+ """
1393
+ Copy the state reference.
1394
+ """
1395
+ return jax.tree.map(lambda x: x, self)
1396
+
1397
+ def get_metadata(self) -> Dict[str, Any]:
1398
+ """
1399
+ Get the metadata of the state reference
1400
+ """
1401
+ metadata = vars(self).copy()
1402
+ del metadata['type']
1403
+ del metadata['value']
1404
+ return metadata
1405
+
1406
+
1407
+ def _state_ref_flatten(x: TreefyState[Any], *, with_keys: bool):
1408
+ metadata = tuple(x.get_metadata().items())
1409
+ if with_keys:
1410
+ node = (jax.tree_util.GetAttrKey('value'), x.value)
1411
+ else:
1412
+ node = x.value
1413
+ return (node,), (x.type, metadata)
1414
+
1415
+
1416
+ def _state_ref_unflatten(
1417
+ static: Tuple[type[State[A]], Tuple[Tuple[str, Any], ...]],
1418
+ children: Tuple[A],
1419
+ ) -> TreefyState[A]:
1420
+ return TreefyState(type=static[0], value=children[0], **dict(static[1]))
1421
+
1422
+
1423
+ jax.tree_util.register_pytree_with_keys(
1424
+ TreefyState,
1425
+ partial(_state_ref_flatten, with_keys=True), # type: ignore
1426
+ _state_ref_unflatten, # type: ignore
1427
+ flatten_func=partial(_state_ref_flatten, with_keys=False), # type: ignore
1428
+ )
1429
+
1430
+
1431
+ class StateCatcher(PrettyObject):
1432
+ """
1433
+ The catcher to catch and manage new states.
1434
+
1435
+ This class provides functionality to collect and tag new State objects.
1436
+ It ensures that each state is only added once and assigns a tag to each state.
1437
+
1438
+ Attributes:
1439
+ state_tag (str): A string identifier used to tag the caught states.
1440
+ state_ids (set): A set of state IDs to ensure uniqueness.
1441
+ states (list): A list to store the caught State objects.
1442
+ """
1443
+
1444
+ def __init__(
1445
+ self,
1446
+ state_tag: str,
1447
+ state_to_exclude: Filter = Nothing()
1448
+ ):
1449
+ """
1450
+ Initialize a new Catcher instance.
1451
+
1452
+ Args:
1453
+ state_tag (str): The tag to be assigned to caught states.
1454
+ state_to_exclude (Filter, optional): A filter to exclude states from being caught.
1455
+ """
1456
+ if state_to_exclude is None:
1457
+ state_to_exclude = Nothing()
1458
+ self.state_to_exclude = state_to_exclude
1459
+ self.state_tag = state_tag
1460
+ self.state_ids = set()
1461
+ self.states = []
1462
+
1463
+ def get_state_values(self) -> List[PyTree]:
1464
+ """
1465
+ Get the values of the caught states.
1466
+
1467
+ Returns:
1468
+ list: A list of values of the caught states.
1469
+ """
1470
+ return [state.value for state in self.states]
1471
+
1472
+ def get_states(self) -> List[State]:
1473
+ """
1474
+ Get the caught states.
1475
+
1476
+ Returns:
1477
+ list: A list of the caught states.
1478
+ """
1479
+ return self.states
1480
+
1481
+ def append(self, state: State):
1482
+ """
1483
+ Add a new state to the catcher if it hasn't been added before.
1484
+
1485
+ This method adds the state to the internal list, records its ID,
1486
+ and assigns the catcher's tag to the state.
1487
+
1488
+ Args:
1489
+ state (State): The State object to be added.
1490
+ """
1491
+ if self.state_to_exclude((), state):
1492
+ return
1493
+ if id(state) not in self.state_ids:
1494
+ self.state_ids.add(id(state))
1495
+ self.states.append(state)
1496
+ state.tag = self.state_tag
1497
+
1498
+ def __iter__(self):
1499
+ """
1500
+ Allow iteration over the caught states.
1501
+
1502
+ Returns:
1503
+ iterator: An iterator over the list of caught states.
1504
+ """
1505
+ return iter(self.states)
1506
+
1507
+ def __len__(self):
1508
+ """
1509
+ Return the number of caught states.
1510
+
1511
+ Returns:
1512
+ int: The number of caught states.
1513
+ """
1514
+ return len(self.states)
1515
+
1516
+ def __getitem__(self, index):
1517
+ """
1518
+ Get a state by index.
1519
+
1520
+ Args:
1521
+ index (int): The index of the state to retrieve.
1522
+
1523
+ Returns:
1524
+ State: The state at the specified index.
1525
+ """
1526
+ return self.states[index]
1527
+
1528
+ def clear(self):
1529
+ """
1530
+ Clear all caught states.
1531
+ """
1532
+ self.state_ids.clear()
1533
+ self.states.clear()
1534
+
1535
+ def get_by_tag(self, tag: str):
1536
+ """
1537
+ Get all states with a specific tag.
1538
+
1539
+ Args:
1540
+ tag (str): The tag to filter by.
1541
+
1542
+ Returns:
1543
+ list: A list of states with the specified tag.
1544
+ """
1545
+ return [state for state in self.states if state.tag == tag]
1546
+
1547
+ def remove(self, state: State):
1548
+ """
1549
+ Remove a specific state from the catcher.
1550
+
1551
+ Args:
1552
+ state (State): The state to remove.
1553
+ """
1554
+ if id(state) in self.state_ids:
1555
+ self.state_ids.remove(id(state))
1556
+ self.states.remove(state)
1557
+
1558
+ def __contains__(self, state: State):
1559
+ """
1560
+ Check if a state is in the catcher.
1561
+
1562
+ Args:
1563
+ state (State): The state to check for.
1564
+
1565
+ Returns:
1566
+ bool: True if the state is in the catcher, False otherwise.
1567
+ """
1568
+ return id(state) in self.state_ids
1569
+
1570
+
1571
+ @contextlib.contextmanager
1572
+ def catch_new_states(
1573
+ state_tag: str = None,
1574
+ state_to_exclude: Filter = Nothing()
1575
+ ) -> Generator[StateCatcher, None, None]:
1576
+ """
1577
+ A context manager that catches and tracks new states created within its scope.
1578
+
1579
+ This function creates a new Catcher object and adds it to the TRACE_CONTEXT's
1580
+ new_state_catcher list. It allows for tracking and managing new states created
1581
+ within the context.
1582
+
1583
+ Args:
1584
+ state_tag (str, optional): A string tag to associate with the caught states.
1585
+ Defaults to None.
1586
+ state_to_exclude (Filter, optional): A filter object to specify which states
1587
+ should be excluded from catching. Defaults to Nothing(), which excludes no states.
1588
+
1589
+ Yields:
1590
+ Catcher: A Catcher object that can be used to access and manage the
1591
+ newly created states within the context.
1592
+
1593
+ Example::
1594
+
1595
+ with catch_new_states("my_tag") as catcher:
1596
+ # Create new states here
1597
+ # They will be caught and tagged with "my_tag"
1598
+ # Access caught states through catcher object
1599
+ """
1600
+ try:
1601
+ catcher = StateCatcher(state_tag=state_tag, state_to_exclude=state_to_exclude)
1602
+ TRACE_CONTEXT.new_state_catcher.append(catcher)
1603
+ yield catcher
1604
+ finally:
1605
+ TRACE_CONTEXT.new_state_catcher.pop()