brainstate 0.0.2.post20241010__py2.py3-none-any.whl → 0.1.0.post20241122__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.
- benchmark/COBA_2005.py +125 -0
- benchmark/CUBA_2005.py +149 -0
- brainstate/__init__.py +31 -11
- brainstate/_state.py +760 -316
- brainstate/_state_test.py +41 -12
- brainstate/_utils.py +31 -4
- brainstate/augment/__init__.py +40 -0
- brainstate/augment/_autograd.py +611 -0
- brainstate/augment/_autograd_test.py +1193 -0
- brainstate/augment/_eval_shape.py +102 -0
- brainstate/augment/_eval_shape_test.py +40 -0
- brainstate/augment/_mapping.py +525 -0
- brainstate/augment/_mapping_test.py +210 -0
- brainstate/augment/_random.py +99 -0
- brainstate/{transform → compile}/__init__.py +25 -13
- brainstate/compile/_ad_checkpoint.py +204 -0
- brainstate/compile/_ad_checkpoint_test.py +51 -0
- brainstate/compile/_conditions.py +259 -0
- brainstate/compile/_conditions_test.py +221 -0
- brainstate/compile/_error_if.py +94 -0
- brainstate/compile/_error_if_test.py +54 -0
- brainstate/compile/_jit.py +314 -0
- brainstate/compile/_jit_test.py +143 -0
- brainstate/compile/_loop_collect_return.py +516 -0
- brainstate/compile/_loop_collect_return_test.py +59 -0
- brainstate/compile/_loop_no_collection.py +185 -0
- brainstate/compile/_loop_no_collection_test.py +51 -0
- brainstate/compile/_make_jaxpr.py +756 -0
- brainstate/compile/_make_jaxpr_test.py +134 -0
- brainstate/compile/_progress_bar.py +111 -0
- brainstate/compile/_unvmap.py +159 -0
- brainstate/compile/_util.py +147 -0
- brainstate/environ.py +408 -381
- brainstate/environ_test.py +34 -32
- brainstate/event/__init__.py +27 -0
- brainstate/event/_csr.py +316 -0
- brainstate/event/_csr_benchmark.py +14 -0
- brainstate/event/_csr_test.py +118 -0
- brainstate/event/_fixed_probability.py +708 -0
- brainstate/event/_fixed_probability_benchmark.py +128 -0
- brainstate/event/_fixed_probability_test.py +131 -0
- brainstate/event/_linear.py +359 -0
- brainstate/event/_linear_benckmark.py +82 -0
- brainstate/event/_linear_test.py +117 -0
- brainstate/{nn/event → event}/_misc.py +7 -7
- brainstate/event/_xla_custom_op.py +312 -0
- brainstate/event/_xla_custom_op_test.py +55 -0
- brainstate/functional/_activations.py +521 -511
- brainstate/functional/_activations_test.py +300 -300
- brainstate/functional/_normalization.py +43 -43
- brainstate/functional/_others.py +15 -15
- brainstate/functional/_spikes.py +49 -49
- brainstate/graph/__init__.py +33 -0
- brainstate/graph/_graph_context.py +443 -0
- brainstate/graph/_graph_context_test.py +65 -0
- brainstate/graph/_graph_convert.py +246 -0
- brainstate/graph/_graph_node.py +300 -0
- brainstate/graph/_graph_node_test.py +75 -0
- brainstate/graph/_graph_operation.py +1746 -0
- brainstate/graph/_graph_operation_test.py +724 -0
- brainstate/init/_base.py +28 -10
- brainstate/init/_generic.py +175 -172
- brainstate/init/_random_inits.py +470 -415
- brainstate/init/_random_inits_test.py +150 -0
- brainstate/init/_regular_inits.py +66 -69
- brainstate/init/_regular_inits_test.py +51 -0
- brainstate/mixin.py +236 -244
- brainstate/mixin_test.py +44 -46
- brainstate/nn/__init__.py +26 -51
- brainstate/nn/_collective_ops.py +199 -0
- brainstate/nn/_dyn_impl/__init__.py +46 -0
- brainstate/nn/_dyn_impl/_dynamics_neuron.py +290 -0
- brainstate/nn/_dyn_impl/_dynamics_neuron_test.py +162 -0
- brainstate/nn/_dyn_impl/_dynamics_synapse.py +315 -0
- brainstate/nn/_dyn_impl/_dynamics_synapse_test.py +132 -0
- brainstate/nn/_dyn_impl/_inputs.py +154 -0
- brainstate/nn/{event/__init__.py → _dyn_impl/_projection_alignpost.py} +8 -8
- brainstate/nn/_dyn_impl/_rate_rnns.py +400 -0
- brainstate/nn/_dyn_impl/_rate_rnns_test.py +64 -0
- brainstate/nn/_dyn_impl/_readout.py +128 -0
- brainstate/nn/_dyn_impl/_readout_test.py +54 -0
- brainstate/nn/_dynamics/__init__.py +37 -0
- brainstate/nn/_dynamics/_dynamics_base.py +631 -0
- brainstate/nn/_dynamics/_dynamics_base_test.py +79 -0
- brainstate/nn/_dynamics/_projection_base.py +346 -0
- brainstate/nn/_dynamics/_state_delay.py +453 -0
- brainstate/nn/_dynamics/_synouts.py +161 -0
- brainstate/nn/_dynamics/_synouts_test.py +58 -0
- brainstate/nn/_elementwise/__init__.py +22 -0
- brainstate/nn/_elementwise/_dropout.py +418 -0
- brainstate/nn/_elementwise/_dropout_test.py +100 -0
- brainstate/nn/_elementwise/_elementwise.py +1122 -0
- brainstate/nn/_elementwise/_elementwise_test.py +171 -0
- brainstate/nn/_exp_euler.py +97 -0
- brainstate/nn/_exp_euler_test.py +36 -0
- brainstate/nn/_interaction/__init__.py +41 -0
- brainstate/nn/_interaction/_conv.py +499 -0
- brainstate/nn/_interaction/_conv_test.py +239 -0
- brainstate/nn/_interaction/_embedding.py +59 -0
- brainstate/nn/_interaction/_linear.py +582 -0
- brainstate/nn/_interaction/_linear_test.py +42 -0
- brainstate/nn/_interaction/_normalizations.py +388 -0
- brainstate/nn/_interaction/_normalizations_test.py +75 -0
- brainstate/nn/_interaction/_poolings.py +1179 -0
- brainstate/nn/_interaction/_poolings_test.py +219 -0
- brainstate/nn/_module.py +328 -0
- brainstate/nn/_module_test.py +211 -0
- brainstate/nn/metrics.py +309 -309
- brainstate/optim/__init__.py +14 -2
- brainstate/optim/_base.py +66 -0
- brainstate/optim/_lr_scheduler.py +363 -400
- brainstate/optim/_lr_scheduler_test.py +25 -24
- brainstate/optim/_optax_optimizer.py +121 -176
- brainstate/optim/_optax_optimizer_test.py +41 -1
- brainstate/optim/_sgd_optimizer.py +950 -1025
- brainstate/random/_rand_funs.py +3269 -3268
- brainstate/random/_rand_funs_test.py +568 -0
- brainstate/random/_rand_seed.py +149 -117
- brainstate/random/_rand_seed_test.py +50 -0
- brainstate/random/_rand_state.py +1356 -1321
- brainstate/random/_random_for_unit.py +13 -13
- brainstate/surrogate.py +1262 -1243
- brainstate/{nn/_projection/_utils.py → transform.py} +1 -2
- brainstate/typing.py +157 -130
- brainstate/util/__init__.py +52 -0
- brainstate/util/_caller.py +100 -0
- brainstate/util/_dict.py +734 -0
- brainstate/util/_dict_test.py +160 -0
- brainstate/{nn/_projection/__init__.py → util/_error.py} +9 -13
- brainstate/util/_filter.py +178 -0
- brainstate/util/_others.py +497 -0
- brainstate/util/_pretty_repr.py +208 -0
- brainstate/util/_scaling.py +260 -0
- brainstate/util/_struct.py +524 -0
- brainstate/util/_tracers.py +75 -0
- brainstate/{_visualization.py → util/_visualization.py} +16 -16
- {brainstate-0.0.2.post20241010.dist-info → brainstate-0.1.0.post20241122.dist-info}/METADATA +11 -11
- brainstate-0.1.0.post20241122.dist-info/RECORD +144 -0
- {brainstate-0.0.2.post20241010.dist-info → brainstate-0.1.0.post20241122.dist-info}/top_level.txt +1 -0
- brainstate/_module.py +0 -1637
- brainstate/_module_test.py +0 -207
- brainstate/nn/_base.py +0 -251
- brainstate/nn/_connections.py +0 -686
- brainstate/nn/_dynamics.py +0 -426
- brainstate/nn/_elementwise.py +0 -1438
- brainstate/nn/_embedding.py +0 -66
- brainstate/nn/_misc.py +0 -133
- brainstate/nn/_normalizations.py +0 -389
- brainstate/nn/_others.py +0 -101
- brainstate/nn/_poolings.py +0 -1229
- brainstate/nn/_poolings_test.py +0 -231
- brainstate/nn/_projection/_align_post.py +0 -546
- brainstate/nn/_projection/_align_pre.py +0 -599
- brainstate/nn/_projection/_delta.py +0 -241
- brainstate/nn/_projection/_vanilla.py +0 -101
- brainstate/nn/_rate_rnns.py +0 -410
- brainstate/nn/_readout.py +0 -136
- brainstate/nn/_synouts.py +0 -166
- brainstate/nn/event/csr.py +0 -312
- brainstate/nn/event/csr_test.py +0 -118
- brainstate/nn/event/fixed_probability.py +0 -276
- brainstate/nn/event/fixed_probability_test.py +0 -127
- brainstate/nn/event/linear.py +0 -220
- brainstate/nn/event/linear_test.py +0 -111
- brainstate/random/random_test.py +0 -593
- brainstate/transform/_autograd.py +0 -585
- brainstate/transform/_autograd_test.py +0 -1181
- brainstate/transform/_conditions.py +0 -334
- brainstate/transform/_conditions_test.py +0 -220
- brainstate/transform/_error_if.py +0 -94
- brainstate/transform/_error_if_test.py +0 -55
- brainstate/transform/_jit.py +0 -265
- brainstate/transform/_jit_test.py +0 -118
- brainstate/transform/_loop_collect_return.py +0 -502
- brainstate/transform/_loop_no_collection.py +0 -170
- brainstate/transform/_make_jaxpr.py +0 -739
- brainstate/transform/_make_jaxpr_test.py +0 -131
- brainstate/transform/_mapping.py +0 -109
- brainstate/transform/_progress_bar.py +0 -111
- brainstate/transform/_unvmap.py +0 -143
- brainstate/util.py +0 -746
- brainstate-0.0.2.post20241010.dist-info/RECORD +0 -87
- {brainstate-0.0.2.post20241010.dist-info → brainstate-0.1.0.post20241122.dist-info}/LICENSE +0 -0
- {brainstate-0.0.2.post20241010.dist-info → brainstate-0.1.0.post20241122.dist-info}/WHEEL +0 -0
@@ -0,0 +1,246 @@
|
|
1
|
+
# The file is adapted from the Flax library (https://github.com/google/flax).
|
2
|
+
# The credit should go to the Flax authors.
|
3
|
+
#
|
4
|
+
# Copyright 2024 The Flax Authors & 2024 BDP Ecosystem.
|
5
|
+
#
|
6
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
7
|
+
# you may not use this file except in compliance with the License.
|
8
|
+
# You may obtain a copy of the License at
|
9
|
+
#
|
10
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
11
|
+
#
|
12
|
+
# Unless required by applicable law or agreed to in writing, software
|
13
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
14
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
15
|
+
# See the License for the specific language governing permissions and
|
16
|
+
# limitations under the License.
|
17
|
+
# ==============================================================================
|
18
|
+
|
19
|
+
from __future__ import annotations
|
20
|
+
|
21
|
+
from typing import Any, Callable, Iterable, TypeVar, Hashable, Optional, Tuple, List
|
22
|
+
|
23
|
+
import jax
|
24
|
+
|
25
|
+
from brainstate._state import State
|
26
|
+
from brainstate.typing import Missing, PyTree, PathParts
|
27
|
+
from brainstate.util import PyTreeNode, field
|
28
|
+
from ._graph_context import SplitContext, MergeContext, split_context, merge_context
|
29
|
+
from ._graph_operation import (RefMap, iter_leaf, _is_graph_node, GraphDef, GraphStateMapping)
|
30
|
+
|
31
|
+
__all__ = [
|
32
|
+
'graph_to_tree', 'tree_to_graph', 'NodeStates'
|
33
|
+
]
|
34
|
+
|
35
|
+
Node = TypeVar('Node')
|
36
|
+
Leaf = TypeVar('Leaf')
|
37
|
+
|
38
|
+
KeyEntry = TypeVar('KeyEntry', bound=Hashable)
|
39
|
+
KeyPath = tuple[KeyEntry, ...]
|
40
|
+
Prefix = Any
|
41
|
+
|
42
|
+
|
43
|
+
def check_consistent_aliasing(
|
44
|
+
node: Tuple[Any, ...],
|
45
|
+
prefix: Tuple[Any, ...],
|
46
|
+
/,
|
47
|
+
*,
|
48
|
+
node_prefixes: Optional[RefMap[Any, List[Tuple[PathParts, Any]]]] = None,
|
49
|
+
):
|
50
|
+
node_prefixes = RefMap() if node_prefixes is None else node_prefixes
|
51
|
+
|
52
|
+
# collect all paths and prefixes for each node
|
53
|
+
for path, value in iter_leaf(node):
|
54
|
+
if isinstance(value, State):
|
55
|
+
# value.check_valid_trace(lambda: f'Trying to extract graph node '
|
56
|
+
# f'from different trace level, got {value!r}')
|
57
|
+
if value in node_prefixes:
|
58
|
+
paths_prefixes = node_prefixes[value]
|
59
|
+
paths_prefixes.append((path, prefix))
|
60
|
+
else:
|
61
|
+
node_prefixes[value] = [(path, prefix)]
|
62
|
+
|
63
|
+
# check for inconsistent aliasing
|
64
|
+
node_msgs = []
|
65
|
+
for node, paths_prefixes in node_prefixes.items():
|
66
|
+
unique_prefixes = {prefix for _, prefix in paths_prefixes}
|
67
|
+
if len(unique_prefixes) > 1:
|
68
|
+
path_prefix_repr = '\n'.join([f' {"/".join(map(str, path)) if path else "<root>"}: {prefix}'
|
69
|
+
for path, prefix in paths_prefixes])
|
70
|
+
nodes_msg = f'Node: {type(node)}\n{path_prefix_repr}'
|
71
|
+
node_msgs.append(nodes_msg)
|
72
|
+
|
73
|
+
if node_msgs:
|
74
|
+
raise ValueError('Inconsistent aliasing detected. The '
|
75
|
+
'following nodes have different prefixes:\n'
|
76
|
+
+ '\n'.join(node_msgs))
|
77
|
+
|
78
|
+
|
79
|
+
# -----------------------------
|
80
|
+
# to_tree/from_tree
|
81
|
+
# -----------------------------
|
82
|
+
|
83
|
+
def broadcast_prefix(
|
84
|
+
prefix_tree: Any,
|
85
|
+
full_tree: Any,
|
86
|
+
prefix_is_leaf: Optional[Callable[[Any], bool]] = None,
|
87
|
+
tree_is_leaf: Optional[Callable[[Any], bool]] = None,
|
88
|
+
) -> List[Any]:
|
89
|
+
"""
|
90
|
+
Broadcasts a prefix tree to a full tree.
|
91
|
+
|
92
|
+
Args:
|
93
|
+
prefix_tree: A prefix tree.
|
94
|
+
full_tree: A full tree.
|
95
|
+
prefix_is_leaf: A function that checks if a prefix is a leaf.
|
96
|
+
tree_is_leaf: A function that checks if a tree is a leaf.
|
97
|
+
|
98
|
+
Returns:
|
99
|
+
A list of prefixes.
|
100
|
+
"""
|
101
|
+
# If prefix_tree is not a tree prefix of full_tree, this code can raise a
|
102
|
+
# ValueError; use prefix_errors to find disagreements and raise more precise
|
103
|
+
# error messages.
|
104
|
+
result = []
|
105
|
+
num_leaves = lambda t: jax.tree_util.tree_structure(t, is_leaf=tree_is_leaf).num_leaves
|
106
|
+
add_leaves = lambda x, subtree: result.extend([x] * num_leaves(subtree))
|
107
|
+
jax.tree.map(add_leaves, prefix_tree, full_tree, is_leaf=prefix_is_leaf)
|
108
|
+
return result
|
109
|
+
|
110
|
+
|
111
|
+
class NodeStates(PyTreeNode):
|
112
|
+
_graphdef: GraphDef[Any] | None
|
113
|
+
states: tuple[GraphStateMapping, ...]
|
114
|
+
metadata: Any = field(pytree_node=False)
|
115
|
+
|
116
|
+
@property
|
117
|
+
def graphdef(self) -> GraphDef[Any]:
|
118
|
+
if self._graphdef is None:
|
119
|
+
raise ValueError('No graphdef available')
|
120
|
+
return self._graphdef
|
121
|
+
|
122
|
+
@property
|
123
|
+
def state(self) -> GraphStateMapping:
|
124
|
+
if len(self.states) != 1:
|
125
|
+
raise ValueError(f'Expected exactly one GraphDefState, got {len(self.states)}')
|
126
|
+
return self.states[0]
|
127
|
+
|
128
|
+
@classmethod
|
129
|
+
def from_split(
|
130
|
+
cls,
|
131
|
+
graphdef: GraphDef[Any],
|
132
|
+
state: GraphStateMapping,
|
133
|
+
/,
|
134
|
+
*states: GraphStateMapping,
|
135
|
+
metadata: Any = None,
|
136
|
+
):
|
137
|
+
return cls(_graphdef=graphdef, states=(state, *states), metadata=metadata)
|
138
|
+
|
139
|
+
@classmethod
|
140
|
+
def from_states(cls, state: GraphStateMapping, *states: GraphStateMapping):
|
141
|
+
return cls(_graphdef=None, states=(state, *states), metadata=None)
|
142
|
+
|
143
|
+
@classmethod
|
144
|
+
def from_prefixes(cls, prefixes: Iterable[Any], /, *, metadata: Any = None):
|
145
|
+
return cls(_graphdef=None, states=tuple(prefixes), metadata=metadata)
|
146
|
+
|
147
|
+
|
148
|
+
def _default_split_fn(ctx: SplitContext, path: KeyPath, prefix: Prefix, leaf: Leaf):
|
149
|
+
return NodeStates.from_split(*ctx.treefy_split(leaf))
|
150
|
+
|
151
|
+
|
152
|
+
def graph_to_tree(
|
153
|
+
may_have_graph_nodes,
|
154
|
+
/,
|
155
|
+
*,
|
156
|
+
prefix: Any = Missing,
|
157
|
+
split_fn: Callable[[SplitContext, KeyPath, Prefix, Leaf], Any] = _default_split_fn,
|
158
|
+
map_non_graph_nodes: bool = False,
|
159
|
+
ctxtag: str | None = None,
|
160
|
+
check_aliasing: bool = True,
|
161
|
+
) -> PyTree:
|
162
|
+
"""
|
163
|
+
Convert a tree of pytree objects to a tree of TreeNode objects.
|
164
|
+
"""
|
165
|
+
leaf_prefixes = broadcast_prefix(prefix, may_have_graph_nodes, prefix_is_leaf=lambda x: x is None)
|
166
|
+
leaf_keys, treedef = jax.tree_util.tree_flatten_with_path(may_have_graph_nodes)
|
167
|
+
|
168
|
+
# Check that the number of keys and prefixes match
|
169
|
+
assert len(leaf_keys) == len(leaf_prefixes)
|
170
|
+
|
171
|
+
# Split the tree
|
172
|
+
with split_context(ctxtag) as ctx:
|
173
|
+
leaves_out = []
|
174
|
+
node_prefixes = RefMap[Any, list[tuple[PathParts, Any]]]()
|
175
|
+
for (keypath, leaf), leaf_prefix in zip(leaf_keys, leaf_prefixes):
|
176
|
+
if _is_graph_node(leaf):
|
177
|
+
if check_aliasing:
|
178
|
+
check_consistent_aliasing(leaf, leaf_prefix, node_prefixes=node_prefixes)
|
179
|
+
leaves_out.append(split_fn(ctx, keypath, leaf_prefix, leaf))
|
180
|
+
else:
|
181
|
+
if map_non_graph_nodes:
|
182
|
+
leaf = split_fn(ctx, keypath, leaf_prefix, leaf)
|
183
|
+
leaves_out.append(leaf)
|
184
|
+
|
185
|
+
pytree_out = jax.tree.unflatten(treedef, leaves_out)
|
186
|
+
return pytree_out
|
187
|
+
|
188
|
+
|
189
|
+
def _is_tree_node(x):
|
190
|
+
"""Check if x is a TreeNode."""
|
191
|
+
return isinstance(x, NodeStates)
|
192
|
+
|
193
|
+
|
194
|
+
def _merge_tree_node(ctx: MergeContext, path: KeyPath, prefix: Prefix, leaf: Leaf) -> Any:
|
195
|
+
if not isinstance(leaf, NodeStates):
|
196
|
+
raise ValueError(f'Expected TreeNode, got {type(leaf)} at path {path}')
|
197
|
+
return ctx.treefy_merge(leaf.graphdef, *leaf.states)
|
198
|
+
|
199
|
+
|
200
|
+
def tree_to_graph(
|
201
|
+
tree: Any,
|
202
|
+
/,
|
203
|
+
*,
|
204
|
+
prefix: Any = Missing,
|
205
|
+
merge_fn: Callable[[MergeContext, KeyPath, Prefix, Leaf], Any] = _merge_tree_node,
|
206
|
+
is_node_leaf: Callable[[Leaf], bool] = _is_tree_node,
|
207
|
+
is_leaf: Callable[[Leaf], bool] = _is_tree_node,
|
208
|
+
map_non_graph_nodes: bool = False,
|
209
|
+
ctxtag: str | None = None,
|
210
|
+
) -> Any:
|
211
|
+
"""
|
212
|
+
Convert a tree of TreeNode objects to a tree of pytree objects.
|
213
|
+
|
214
|
+
Args:
|
215
|
+
tree: A tree of TreeNode objects.
|
216
|
+
prefix: A tree of prefixes.
|
217
|
+
merge_fn: A function that merges a TreeNode object.
|
218
|
+
is_node_leaf: A function that checks if a leaf is a TreeNode.
|
219
|
+
is_leaf: A function that checks if a leaf is a TreeNode.
|
220
|
+
map_non_graph_nodes: A boolean indicating whether to map non-graph nodes.
|
221
|
+
|
222
|
+
Returns:
|
223
|
+
A tree of pytree objects.
|
224
|
+
"""
|
225
|
+
_prefix_is_leaf = lambda x: x is None or is_leaf(x)
|
226
|
+
leaf_prefixes = broadcast_prefix(prefix, tree, prefix_is_leaf=_prefix_is_leaf, tree_is_leaf=is_leaf)
|
227
|
+
leaf_keys, treedef = jax.tree_util.tree_flatten_with_path(tree, is_leaf=is_leaf)
|
228
|
+
assert len(leaf_keys) == len(leaf_prefixes), "Mismatched number of keys and prefixes"
|
229
|
+
|
230
|
+
with merge_context(ctxtag) as ctx:
|
231
|
+
leaves_out = []
|
232
|
+
for (keypath, leaf), leaf_prefix in zip(leaf_keys, leaf_prefixes):
|
233
|
+
if is_node_leaf(leaf):
|
234
|
+
leaf_out = merge_fn(ctx, keypath, leaf_prefix, leaf)
|
235
|
+
leaves_out.append(leaf_out)
|
236
|
+
else:
|
237
|
+
if map_non_graph_nodes:
|
238
|
+
leaf = merge_fn(ctx, keypath, leaf_prefix, leaf)
|
239
|
+
leaves_out.append(leaf)
|
240
|
+
|
241
|
+
pytree_out = jax.tree.unflatten(treedef, leaves_out)
|
242
|
+
return pytree_out
|
243
|
+
|
244
|
+
|
245
|
+
def clear_non_graph_nodes(tree):
|
246
|
+
return jax.tree.map(lambda x: x if _is_graph_node(x) else None, tree)
|
@@ -0,0 +1,300 @@
|
|
1
|
+
# The file is adapted from the Flax library (https://github.com/google/flax).
|
2
|
+
# The credit should go to the Flax authors.
|
3
|
+
#
|
4
|
+
# Copyright 2024 The Flax Authors & 2024 BDP Ecosystem.
|
5
|
+
#
|
6
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
7
|
+
# you may not use this file except in compliance with the License.
|
8
|
+
# You may obtain a copy of the License at
|
9
|
+
#
|
10
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
11
|
+
#
|
12
|
+
# Unless required by applicable law or agreed to in writing, software
|
13
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
14
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
15
|
+
# See the License for the specific language governing permissions and
|
16
|
+
# limitations under the License.
|
17
|
+
|
18
|
+
from __future__ import annotations
|
19
|
+
|
20
|
+
from abc import ABCMeta
|
21
|
+
from copy import deepcopy
|
22
|
+
from typing import Any, Callable, Type, TypeVar, Tuple, TYPE_CHECKING, Mapping, Iterator, Sequence
|
23
|
+
|
24
|
+
import brainunit as u
|
25
|
+
import jax
|
26
|
+
import numpy as np
|
27
|
+
|
28
|
+
from brainstate._state import State, TreefyState
|
29
|
+
from brainstate.typing import Key
|
30
|
+
from brainstate.util._error import TraceContextError
|
31
|
+
from brainstate.util._pretty_repr import PrettyRepr, pretty_repr_avoid_duplicate, PrettyType, PrettyAttr
|
32
|
+
from brainstate.util._tracers import StateJaxTracer
|
33
|
+
from ._graph_operation import register_graph_node_type
|
34
|
+
|
35
|
+
__all__ = [
|
36
|
+
'Node', 'Dict', 'List', 'Sequential',
|
37
|
+
]
|
38
|
+
|
39
|
+
G = TypeVar('G', bound='Node')
|
40
|
+
A = TypeVar('A')
|
41
|
+
|
42
|
+
|
43
|
+
class GraphNodeMeta(ABCMeta):
|
44
|
+
if not TYPE_CHECKING:
|
45
|
+
def __call__(cls, *args: Any, **kwargs: Any) -> Any:
|
46
|
+
node = cls.__new__(cls, *args, **kwargs)
|
47
|
+
vars(node)['_trace_state'] = StateJaxTracer()
|
48
|
+
node.__init__(*args, **kwargs)
|
49
|
+
return node
|
50
|
+
|
51
|
+
|
52
|
+
class Node(PrettyRepr, metaclass=GraphNodeMeta):
|
53
|
+
"""
|
54
|
+
Base class for all graph nodes.
|
55
|
+
|
56
|
+
This class provides the following functionalities:
|
57
|
+
- Register the node type with the graph tool.
|
58
|
+
- Prevent mutation of the node from different trace level.
|
59
|
+
- Provide a pretty repr for the node.
|
60
|
+
- Provide a treescope repr for the node.
|
61
|
+
- Deepcopy the node.
|
62
|
+
|
63
|
+
"""
|
64
|
+
if TYPE_CHECKING:
|
65
|
+
_trace_state: StateJaxTracer
|
66
|
+
|
67
|
+
def __init_subclass__(cls) -> None:
|
68
|
+
super().__init_subclass__()
|
69
|
+
|
70
|
+
register_graph_node_type(
|
71
|
+
type=cls,
|
72
|
+
flatten=_node_flatten,
|
73
|
+
set_key=_node_set_key,
|
74
|
+
pop_key=_node_pop_key,
|
75
|
+
create_empty=_node_create_empty,
|
76
|
+
clear=_node_clear,
|
77
|
+
)
|
78
|
+
|
79
|
+
# if not TYPE_CHECKING:
|
80
|
+
# def __setattr__(self, name: str, value: Any) -> None:
|
81
|
+
# self._setattr(name, value)
|
82
|
+
|
83
|
+
# def _setattr(self, name: str, value: Any) -> None:
|
84
|
+
# self.check_valid_context(lambda: f"Cannot mutate '{type(self).__name__}' from different trace level")
|
85
|
+
# object.__setattr__(self, name, value)
|
86
|
+
|
87
|
+
def check_valid_context(self, error_msg: Callable[[], str]) -> None:
|
88
|
+
"""
|
89
|
+
Check if the current context is valid for the object to be mutated.
|
90
|
+
"""
|
91
|
+
if not self._trace_state.is_valid():
|
92
|
+
raise TraceContextError(error_msg())
|
93
|
+
|
94
|
+
def __deepcopy__(self: G, memo=None) -> G:
|
95
|
+
"""
|
96
|
+
Deepcopy the object.
|
97
|
+
"""
|
98
|
+
from ._graph_operation import treefy_split, treefy_merge
|
99
|
+
|
100
|
+
graphdef, state = treefy_split(self)
|
101
|
+
graphdef = deepcopy(graphdef)
|
102
|
+
state = deepcopy(state)
|
103
|
+
return treefy_merge(graphdef, state)
|
104
|
+
|
105
|
+
def __pretty_repr__(self):
|
106
|
+
"""
|
107
|
+
Pretty repr for the object.
|
108
|
+
"""
|
109
|
+
yield from pretty_repr_avoid_duplicate(self, _default_repr_object, _default_repr_attr)
|
110
|
+
|
111
|
+
def __treescope_repr__(self, path, subtree_renderer):
|
112
|
+
"""
|
113
|
+
Treescope repr for the object.
|
114
|
+
"""
|
115
|
+
children = {}
|
116
|
+
for name, value in vars(self).items():
|
117
|
+
name, value = self.__leaf_fn__(name, value)
|
118
|
+
if name.startswith('_'):
|
119
|
+
continue
|
120
|
+
children[name] = value
|
121
|
+
import treescope # type: ignore[import-not-found,import-untyped]
|
122
|
+
return treescope.repr_lib.render_object_constructor(
|
123
|
+
object_type=type(self),
|
124
|
+
attributes=children,
|
125
|
+
path=path,
|
126
|
+
subtree_renderer=subtree_renderer,
|
127
|
+
color=treescope.formatting_util.color_from_string(type(self).__qualname__)
|
128
|
+
)
|
129
|
+
|
130
|
+
def __leaf_fn__(self, leaf, value):
|
131
|
+
return leaf, value
|
132
|
+
|
133
|
+
|
134
|
+
def _default_repr_object(node: Node):
|
135
|
+
yield PrettyType(type=type(node))
|
136
|
+
|
137
|
+
|
138
|
+
def _default_repr_attr(node: Node):
|
139
|
+
for name, value in vars(node).items():
|
140
|
+
name, value = node.__leaf_fn__(name, value)
|
141
|
+
if name.startswith('_'):
|
142
|
+
continue
|
143
|
+
# value = jax.tree.map(_to_shape_dtype, value, is_leaf=lambda x: isinstance(x, u.Quantity))
|
144
|
+
yield PrettyAttr(name, repr(value))
|
145
|
+
|
146
|
+
|
147
|
+
class String:
|
148
|
+
def __init__(self, msg):
|
149
|
+
self.msg = msg
|
150
|
+
|
151
|
+
def __repr__(self):
|
152
|
+
return self.msg
|
153
|
+
|
154
|
+
|
155
|
+
def _to_shape_dtype(value):
|
156
|
+
if isinstance(value, State):
|
157
|
+
return value.replace(jax.tree.map(_to_shape_dtype, value.value))
|
158
|
+
elif isinstance(value, (np.ndarray, jax.Array)):
|
159
|
+
return String(f'Array(shape={value.shape}, dtype={value.dtype.name})')
|
160
|
+
elif isinstance(value, u.Quantity):
|
161
|
+
return String(f'Quantity(mantissa=Array(shape={value.shape}, dtype={value.dtype.name}), unit={value.unit})')
|
162
|
+
return value
|
163
|
+
|
164
|
+
|
165
|
+
# -------------------------------
|
166
|
+
# Graph Definition
|
167
|
+
# -------------------------------
|
168
|
+
|
169
|
+
|
170
|
+
def _node_flatten(
|
171
|
+
node: Node
|
172
|
+
) -> Tuple[Tuple[Tuple[str, Any], ...], Tuple[Type]]:
|
173
|
+
nodes = sorted((key, value) for key, value in vars(node).items() if key != '_trace_state')
|
174
|
+
return nodes, (type(node),)
|
175
|
+
|
176
|
+
|
177
|
+
def _node_set_key(
|
178
|
+
node: Node,
|
179
|
+
key: Key,
|
180
|
+
value: Any
|
181
|
+
) -> None:
|
182
|
+
if not isinstance(key, str):
|
183
|
+
raise KeyError(f'Invalid key: {key!r}')
|
184
|
+
elif (
|
185
|
+
hasattr(node, key)
|
186
|
+
and isinstance(state := getattr(node, key), State)
|
187
|
+
and isinstance(value, TreefyState)
|
188
|
+
):
|
189
|
+
state.update_from_ref(value)
|
190
|
+
else:
|
191
|
+
setattr(node, key, value)
|
192
|
+
|
193
|
+
|
194
|
+
def _node_pop_key(
|
195
|
+
node: Node,
|
196
|
+
key: Key
|
197
|
+
):
|
198
|
+
if not isinstance(key, str):
|
199
|
+
raise KeyError(f'Invalid key: {key!r}')
|
200
|
+
return vars(node).pop(key)
|
201
|
+
|
202
|
+
|
203
|
+
def _node_create_empty(
|
204
|
+
static: tuple[Type[G],]
|
205
|
+
) -> G:
|
206
|
+
node_type, = static
|
207
|
+
node = object.__new__(node_type)
|
208
|
+
vars(node).update(_trace_state=StateJaxTracer())
|
209
|
+
return node
|
210
|
+
|
211
|
+
|
212
|
+
def _node_clear(node: Node):
|
213
|
+
module_state = node._trace_state
|
214
|
+
module_vars = vars(node)
|
215
|
+
module_vars.clear()
|
216
|
+
module_vars['_trace_state'] = module_state
|
217
|
+
|
218
|
+
|
219
|
+
class Dict(Node, Mapping[str, A]):
|
220
|
+
"""
|
221
|
+
A dictionary node.
|
222
|
+
"""
|
223
|
+
|
224
|
+
def __init__(self, *args, **kwargs):
|
225
|
+
for name, value in dict(*args, **kwargs).items():
|
226
|
+
setattr(self, name, value)
|
227
|
+
|
228
|
+
def __getitem__(self, key) -> A:
|
229
|
+
return getattr(self, key)
|
230
|
+
|
231
|
+
def __setitem__(self, key, value):
|
232
|
+
setattr(self, key, value)
|
233
|
+
|
234
|
+
def __getattr__(self, key) -> A:
|
235
|
+
return super().__getattribute__(key)
|
236
|
+
|
237
|
+
def __setattr__(self, key, value):
|
238
|
+
super().__setattr__(key, value)
|
239
|
+
|
240
|
+
def __iter__(self) -> Iterator[str]:
|
241
|
+
return (k for k in vars(self) if k != '_object__state')
|
242
|
+
|
243
|
+
def __len__(self) -> int:
|
244
|
+
return len(vars(self))
|
245
|
+
|
246
|
+
|
247
|
+
class List(Node):
|
248
|
+
"""
|
249
|
+
A list node.
|
250
|
+
"""
|
251
|
+
|
252
|
+
def __init__(self, seq=()):
|
253
|
+
vars(self).update({str(i): item for i, item in enumerate(seq)})
|
254
|
+
|
255
|
+
def __getitem__(self, idx):
|
256
|
+
return getattr(self, str(idx))
|
257
|
+
|
258
|
+
def __setitem__(self, idx, value):
|
259
|
+
setattr(self, str(idx), value)
|
260
|
+
|
261
|
+
def __iter__(self):
|
262
|
+
return iter(vars(self).values())
|
263
|
+
|
264
|
+
def __len__(self):
|
265
|
+
return len(vars(self))
|
266
|
+
|
267
|
+
def __add__(self, other: Sequence[A]) -> List[A]:
|
268
|
+
return List(list(self) + list(other))
|
269
|
+
|
270
|
+
def append(self, value):
|
271
|
+
self[len(vars(self))] = value
|
272
|
+
|
273
|
+
def extend(self, values):
|
274
|
+
for value in values:
|
275
|
+
self.append(value)
|
276
|
+
|
277
|
+
|
278
|
+
class Sequential(Node):
|
279
|
+
def __init__(self, *fns: Callable[..., Any]):
|
280
|
+
self.layers = list(fns)
|
281
|
+
|
282
|
+
def __call__(self, *args, **kwargs) -> Any:
|
283
|
+
output: Any = None
|
284
|
+
|
285
|
+
for i, f in enumerate(self.layers):
|
286
|
+
if not callable(f):
|
287
|
+
raise TypeError(f'Sequence[{i}] is not callable: {f}')
|
288
|
+
if i > 0:
|
289
|
+
if isinstance(output, tuple):
|
290
|
+
args = output
|
291
|
+
kwargs = {}
|
292
|
+
elif isinstance(output, dict):
|
293
|
+
args = ()
|
294
|
+
kwargs = output
|
295
|
+
else:
|
296
|
+
args = (output,)
|
297
|
+
kwargs = {}
|
298
|
+
output = f(*args, **kwargs)
|
299
|
+
|
300
|
+
return output
|
@@ -0,0 +1,75 @@
|
|
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 unittest
|
19
|
+
|
20
|
+
import brainstate as bst
|
21
|
+
|
22
|
+
|
23
|
+
class TestSequential(unittest.TestCase):
|
24
|
+
def test1(self):
|
25
|
+
s = bst.graph.Sequential(bst.nn.Linear(1, 2),
|
26
|
+
bst.nn.Linear(2, 3))
|
27
|
+
graphdef, states = bst.graph.treefy_split(s)
|
28
|
+
print(states)
|
29
|
+
self.assertTrue(len(states.to_flat()) == 2)
|
30
|
+
|
31
|
+
|
32
|
+
class TestStateRetrieve(unittest.TestCase):
|
33
|
+
def test_list_of_states_1(self):
|
34
|
+
class Model(bst.graph.Node):
|
35
|
+
def __init__(self):
|
36
|
+
self.a = [1, 2, 3]
|
37
|
+
self.b = [bst.State(1), bst.State(2), bst.State(3)]
|
38
|
+
|
39
|
+
m = Model()
|
40
|
+
graphdef, states = bst.graph.treefy_split(m)
|
41
|
+
print(states.to_flat())
|
42
|
+
self.assertTrue(len(states.to_flat()) == 3)
|
43
|
+
|
44
|
+
def test_list_of_states_2(self):
|
45
|
+
class Model(bst.graph.Node):
|
46
|
+
def __init__(self):
|
47
|
+
self.a = [1, 2, 3]
|
48
|
+
self.b = [bst.State(1), [bst.State(2), bst.State(3)]]
|
49
|
+
|
50
|
+
m = Model()
|
51
|
+
graphdef, states = bst.graph.treefy_split(m)
|
52
|
+
print(states.to_flat())
|
53
|
+
self.assertTrue(len(states.to_flat()) == 3)
|
54
|
+
|
55
|
+
def test_list_of_node_1(self):
|
56
|
+
class Model(bst.graph.Node):
|
57
|
+
def __init__(self):
|
58
|
+
self.a = [1, 2, 3]
|
59
|
+
self.b = [bst.nn.Linear(1, 2), bst.nn.Linear(2, 3)]
|
60
|
+
|
61
|
+
m = Model()
|
62
|
+
graphdef, states = bst.graph.treefy_split(m)
|
63
|
+
print(states.to_flat())
|
64
|
+
self.assertTrue(len(states.to_flat()) == 2)
|
65
|
+
|
66
|
+
def test_list_of_node_2(self):
|
67
|
+
class Model(bst.graph.Node):
|
68
|
+
def __init__(self):
|
69
|
+
self.a = [1, 2, 3]
|
70
|
+
self.b = [bst.nn.Linear(1, 2), [bst.nn.Linear(2, 3)], (bst.nn.Linear(3, 4), bst.nn.Linear(4, 5))]
|
71
|
+
|
72
|
+
m = Model()
|
73
|
+
graphdef, states = bst.graph.treefy_split(m)
|
74
|
+
print(states.to_flat())
|
75
|
+
self.assertTrue(len(states.to_flat()) == 4)
|