brainstate 0.1.0.post20250105__py2.py3-none-any.whl → 0.1.0.post20250120__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.
- brainstate/_state.py +77 -44
- brainstate/_state_test.py +0 -17
- brainstate/augment/_eval_shape.py +9 -10
- brainstate/augment/_eval_shape_test.py +1 -1
- brainstate/augment/_mapping.py +265 -277
- brainstate/augment/_mapping_test.py +147 -175
- brainstate/compile/_ad_checkpoint.py +6 -4
- brainstate/compile/_jit.py +37 -28
- brainstate/compile/_loop_collect_return.py +6 -3
- brainstate/compile/_loop_no_collection.py +2 -0
- brainstate/compile/_make_jaxpr.py +7 -3
- brainstate/compile/_progress_bar.py +68 -40
- brainstate/compile/_unvmap.py +6 -3
- brainstate/event/__init__.py +0 -2
- brainstate/event/_csr.py +266 -23
- brainstate/event/_csr_test.py +187 -0
- brainstate/event/_xla_custom_op.py +7 -3
- brainstate/graph/__init__.py +8 -12
- brainstate/graph/_graph_node.py +1 -23
- brainstate/graph/_graph_operation.py +1 -1
- brainstate/graph/_graph_operation_test.py +0 -159
- brainstate/nn/_dyn_impl/_inputs.py +124 -39
- brainstate/nn/_interaction/_conv.py +4 -2
- brainstate/nn/_interaction/_linear.py +84 -10
- brainstate/random/_rand_funs.py +9 -2
- brainstate/random/_rand_seed.py +12 -2
- brainstate/random/_rand_state.py +50 -179
- brainstate/surrogate.py +5 -1
- brainstate/util/__init__.py +0 -4
- brainstate/util/_caller.py +1 -1
- brainstate/util/_dict.py +4 -1
- brainstate/util/_filter.py +1 -1
- brainstate/util/_pretty_repr.py +1 -1
- brainstate/util/_struct.py +1 -1
- {brainstate-0.1.0.post20250105.dist-info → brainstate-0.1.0.post20250120.dist-info}/METADATA +2 -1
- {brainstate-0.1.0.post20250105.dist-info → brainstate-0.1.0.post20250120.dist-info}/RECORD +40 -46
- brainstate/event/_csr_mv_test.py +0 -118
- brainstate/graph/_graph_context.py +0 -443
- brainstate/graph/_graph_context_test.py +0 -65
- brainstate/graph/_graph_convert.py +0 -246
- brainstate/util/_tracers.py +0 -68
- brainstate/util/_visualization.py +0 -47
- /brainstate/event/{_csr_mv_benchmark.py → _csr_benchmark.py} +0 -0
- {brainstate-0.1.0.post20250105.dist-info → brainstate-0.1.0.post20250120.dist-info}/LICENSE +0 -0
- {brainstate-0.1.0.post20250105.dist-info → brainstate-0.1.0.post20250120.dist-info}/WHEEL +0 -0
- {brainstate-0.1.0.post20250105.dist-info → brainstate-0.1.0.post20250120.dist-info}/top_level.txt +0 -0
@@ -1,246 +0,0 @@
|
|
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)
|
brainstate/util/_tracers.py
DELETED
@@ -1,68 +0,0 @@
|
|
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
|
-
from __future__ import annotations
|
16
|
-
|
17
|
-
import jax
|
18
|
-
import jax.core
|
19
|
-
|
20
|
-
from ._pretty_repr import PrettyRepr, PrettyType, PrettyAttr
|
21
|
-
|
22
|
-
__all__ = [
|
23
|
-
'StateJaxTracer',
|
24
|
-
]
|
25
|
-
|
26
|
-
|
27
|
-
|
28
|
-
def current_jax_trace():
|
29
|
-
"""Returns the Jax tracing state."""
|
30
|
-
if jax.__version_info__ <= (0, 4, 33):
|
31
|
-
return jax.core.thread_local_state.trace_state.trace_stack.dynamic
|
32
|
-
return jax.core.get_opaque_trace_state(convention="nnx")
|
33
|
-
|
34
|
-
|
35
|
-
class StateJaxTracer(PrettyRepr):
|
36
|
-
__slots__ = ['_jax_trace']
|
37
|
-
|
38
|
-
def __init__(self):
|
39
|
-
self._jax_trace = current_jax_trace()
|
40
|
-
|
41
|
-
@property
|
42
|
-
def jax_trace(self):
|
43
|
-
return self._jax_trace
|
44
|
-
|
45
|
-
def is_valid(self) -> bool:
|
46
|
-
if jax.__version_info__ <= (0, 4, 33):
|
47
|
-
return self._jax_trace is current_jax_trace()
|
48
|
-
else:
|
49
|
-
return self._jax_trace == current_jax_trace()
|
50
|
-
|
51
|
-
def __eq__(self, other):
|
52
|
-
if jax.__version_info__ <= (0, 4, 33):
|
53
|
-
return isinstance(other, StateJaxTracer) and self._jax_trace is other._jax_trace
|
54
|
-
else:
|
55
|
-
return isinstance(other, StateJaxTracer) and self._jax_trace == other._jax_trace
|
56
|
-
|
57
|
-
def __pretty_repr__(self):
|
58
|
-
yield PrettyType(f'{type(self).__name__}')
|
59
|
-
yield PrettyAttr('jax_trace', self._jax_trace)
|
60
|
-
|
61
|
-
def __treescope_repr__(self, path, subtree_renderer):
|
62
|
-
import treescope # type: ignore[import-not-found,import-untyped]
|
63
|
-
return treescope.repr_lib.render_object_constructor(
|
64
|
-
object_type=type(self),
|
65
|
-
attributes={'jax_trace': self._jax_trace},
|
66
|
-
path=path,
|
67
|
-
subtree_renderer=subtree_renderer,
|
68
|
-
)
|
@@ -1,47 +0,0 @@
|
|
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
|
-
__all__ = [
|
19
|
-
'display',
|
20
|
-
]
|
21
|
-
|
22
|
-
import importlib.util
|
23
|
-
|
24
|
-
treescope_installed = importlib.util.find_spec('treescope') is not None
|
25
|
-
try:
|
26
|
-
from IPython import get_ipython
|
27
|
-
|
28
|
-
in_ipython = get_ipython() is not None
|
29
|
-
except ImportError:
|
30
|
-
in_ipython = False
|
31
|
-
|
32
|
-
|
33
|
-
def display(*args):
|
34
|
-
"""Display the given objects using the Treescope pretty-printer.
|
35
|
-
|
36
|
-
If treescope is not installed or the code is not running in IPython,
|
37
|
-
``display`` will print the objects instead.
|
38
|
-
"""
|
39
|
-
if not treescope_installed or not in_ipython:
|
40
|
-
for x in args:
|
41
|
-
print(x)
|
42
|
-
return
|
43
|
-
|
44
|
-
import treescope # type: ignore[import-not-found,import-untyped]
|
45
|
-
|
46
|
-
for x in args:
|
47
|
-
treescope.display(x, ignore_exceptions=True, autovisualize=True)
|
File without changes
|
File without changes
|
File without changes
|
{brainstate-0.1.0.post20250105.dist-info → brainstate-0.1.0.post20250120.dist-info}/top_level.txt
RENAMED
File without changes
|