brainstate 0.1.8__py2.py3-none-any.whl → 0.1.10__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/__init__.py +58 -51
- brainstate/_compatible_import.py +148 -148
- brainstate/_state.py +1605 -1663
- brainstate/_state_test.py +52 -52
- brainstate/_utils.py +47 -47
- brainstate/augment/__init__.py +30 -30
- brainstate/augment/_autograd.py +778 -778
- brainstate/augment/_autograd_test.py +1289 -1289
- brainstate/augment/_eval_shape.py +99 -99
- brainstate/augment/_eval_shape_test.py +38 -38
- brainstate/augment/_mapping.py +1060 -1060
- brainstate/augment/_mapping_test.py +597 -597
- brainstate/augment/_random.py +151 -151
- brainstate/compile/__init__.py +38 -38
- brainstate/compile/_ad_checkpoint.py +204 -204
- brainstate/compile/_ad_checkpoint_test.py +49 -49
- brainstate/compile/_conditions.py +256 -256
- brainstate/compile/_conditions_test.py +220 -220
- brainstate/compile/_error_if.py +92 -92
- brainstate/compile/_error_if_test.py +52 -52
- brainstate/compile/_jit.py +346 -346
- brainstate/compile/_jit_test.py +143 -143
- brainstate/compile/_loop_collect_return.py +536 -536
- brainstate/compile/_loop_collect_return_test.py +58 -58
- brainstate/compile/_loop_no_collection.py +184 -184
- brainstate/compile/_loop_no_collection_test.py +50 -50
- brainstate/compile/_make_jaxpr.py +888 -888
- brainstate/compile/_make_jaxpr_test.py +156 -156
- brainstate/compile/_progress_bar.py +202 -202
- brainstate/compile/_unvmap.py +159 -159
- brainstate/compile/_util.py +147 -147
- brainstate/environ.py +563 -563
- brainstate/environ_test.py +62 -62
- brainstate/functional/__init__.py +27 -26
- brainstate/graph/__init__.py +29 -29
- brainstate/graph/_graph_node.py +244 -244
- brainstate/graph/_graph_node_test.py +73 -73
- brainstate/graph/_graph_operation.py +1738 -1738
- brainstate/graph/_graph_operation_test.py +563 -563
- brainstate/init/__init__.py +26 -26
- brainstate/init/_base.py +52 -52
- brainstate/init/_generic.py +244 -244
- brainstate/init/_random_inits.py +553 -553
- brainstate/init/_random_inits_test.py +149 -149
- brainstate/init/_regular_inits.py +105 -105
- brainstate/init/_regular_inits_test.py +50 -50
- brainstate/mixin.py +365 -363
- brainstate/mixin_test.py +77 -73
- brainstate/nn/__init__.py +135 -131
- brainstate/{functional → nn}/_activations.py +808 -813
- brainstate/{functional → nn}/_activations_test.py +331 -331
- brainstate/nn/_collective_ops.py +514 -514
- brainstate/nn/_collective_ops_test.py +43 -43
- brainstate/nn/_common.py +178 -178
- brainstate/nn/_conv.py +501 -501
- brainstate/nn/_conv_test.py +238 -238
- brainstate/nn/_delay.py +588 -502
- brainstate/nn/_delay_test.py +238 -184
- brainstate/nn/_dropout.py +426 -426
- brainstate/nn/_dropout_test.py +100 -100
- brainstate/nn/_dynamics.py +1343 -1343
- brainstate/nn/_dynamics_test.py +78 -78
- brainstate/nn/_elementwise.py +1119 -1119
- brainstate/nn/_elementwise_test.py +169 -169
- brainstate/nn/_embedding.py +58 -58
- brainstate/nn/_exp_euler.py +92 -92
- brainstate/nn/_exp_euler_test.py +35 -35
- brainstate/nn/_fixedprob.py +239 -239
- brainstate/nn/_fixedprob_test.py +114 -114
- brainstate/nn/_inputs.py +608 -608
- brainstate/nn/_linear.py +424 -424
- brainstate/nn/_linear_mv.py +83 -83
- brainstate/nn/_linear_mv_test.py +120 -120
- brainstate/nn/_linear_test.py +107 -107
- brainstate/nn/_ltp.py +28 -28
- brainstate/nn/_module.py +377 -377
- brainstate/nn/_module_test.py +40 -40
- brainstate/nn/_neuron.py +705 -705
- brainstate/nn/_neuron_test.py +161 -161
- brainstate/nn/_normalizations.py +975 -918
- brainstate/nn/_normalizations_test.py +73 -73
- brainstate/{functional → nn}/_others.py +46 -46
- brainstate/nn/_poolings.py +1177 -1177
- brainstate/nn/_poolings_test.py +217 -217
- brainstate/nn/_projection.py +486 -486
- brainstate/nn/_rate_rnns.py +554 -554
- brainstate/nn/_rate_rnns_test.py +63 -63
- brainstate/nn/_readout.py +209 -209
- brainstate/nn/_readout_test.py +53 -53
- brainstate/nn/_stp.py +236 -236
- brainstate/nn/_synapse.py +505 -505
- brainstate/nn/_synapse_test.py +131 -131
- brainstate/nn/_synaptic_projection.py +423 -423
- brainstate/nn/_synouts.py +162 -162
- brainstate/nn/_synouts_test.py +57 -57
- brainstate/nn/_utils.py +89 -89
- brainstate/nn/metrics.py +388 -388
- brainstate/optim/__init__.py +38 -38
- brainstate/optim/_base.py +64 -64
- brainstate/optim/_lr_scheduler.py +448 -448
- brainstate/optim/_lr_scheduler_test.py +50 -50
- brainstate/optim/_optax_optimizer.py +152 -152
- brainstate/optim/_optax_optimizer_test.py +53 -53
- brainstate/optim/_sgd_optimizer.py +1104 -1104
- brainstate/random/__init__.py +24 -24
- brainstate/random/_rand_funs.py +3616 -3616
- brainstate/random/_rand_funs_test.py +567 -567
- brainstate/random/_rand_seed.py +210 -210
- brainstate/random/_rand_seed_test.py +48 -48
- brainstate/random/_rand_state.py +1409 -1409
- brainstate/random/_random_for_unit.py +52 -52
- brainstate/surrogate.py +1957 -1957
- brainstate/transform.py +23 -23
- brainstate/typing.py +304 -304
- brainstate/util/__init__.py +50 -50
- brainstate/util/caller.py +98 -98
- brainstate/util/error.py +55 -55
- brainstate/util/filter.py +469 -469
- brainstate/util/others.py +540 -540
- brainstate/util/pretty_pytree.py +945 -945
- brainstate/util/pretty_pytree_test.py +159 -159
- brainstate/util/pretty_repr.py +328 -328
- brainstate/util/pretty_table.py +2954 -2954
- brainstate/util/scaling.py +258 -258
- brainstate/util/struct.py +523 -523
- {brainstate-0.1.8.dist-info → brainstate-0.1.10.dist-info}/METADATA +91 -99
- brainstate-0.1.10.dist-info/RECORD +130 -0
- {brainstate-0.1.8.dist-info → brainstate-0.1.10.dist-info}/WHEEL +1 -1
- {brainstate-0.1.8.dist-info → brainstate-0.1.10.dist-info/licenses}/LICENSE +202 -202
- brainstate/functional/_normalization.py +0 -81
- brainstate/functional/_spikes.py +0 -204
- brainstate-0.1.8.dist-info/RECORD +0 -132
- {brainstate-0.1.8.dist-info → brainstate-0.1.10.dist-info}/top_level.txt +0 -0
brainstate/graph/_graph_node.py
CHANGED
@@ -1,244 +1,244 @@
|
|
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.
|
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 abc import ABCMeta
|
19
|
-
from copy import deepcopy
|
20
|
-
from typing import Any, Callable, Type, TypeVar, Tuple, TYPE_CHECKING, Mapping, Iterator, Sequence
|
21
|
-
|
22
|
-
import brainunit as u
|
23
|
-
import jax
|
24
|
-
import numpy as np
|
25
|
-
|
26
|
-
from brainstate._state import State, TreefyState
|
27
|
-
from brainstate.typing import Key
|
28
|
-
from brainstate.util.pretty_pytree import PrettyObject
|
29
|
-
from ._graph_operation import register_graph_node_type
|
30
|
-
|
31
|
-
__all__ = [
|
32
|
-
'Node', 'Dict', 'List', 'Sequential',
|
33
|
-
]
|
34
|
-
|
35
|
-
G = TypeVar('G', bound='Node')
|
36
|
-
A = TypeVar('A')
|
37
|
-
|
38
|
-
|
39
|
-
class GraphNodeMeta(ABCMeta):
|
40
|
-
if not TYPE_CHECKING:
|
41
|
-
def __call__(cls, *args: Any, **kwargs: Any) -> Any:
|
42
|
-
node = cls.__new__(cls, *args, **kwargs)
|
43
|
-
node.__init__(*args, **kwargs)
|
44
|
-
return node
|
45
|
-
|
46
|
-
|
47
|
-
class Node(PrettyObject, metaclass=GraphNodeMeta):
|
48
|
-
"""
|
49
|
-
Base class for all graph nodes.
|
50
|
-
|
51
|
-
This class provides the following functionalities:
|
52
|
-
- Register the node type with the graph tool.
|
53
|
-
- Prevent mutation of the node from different trace level.
|
54
|
-
- Provide a pretty repr for the node.
|
55
|
-
- Provide a treescope repr for the node.
|
56
|
-
- Deepcopy the node.
|
57
|
-
|
58
|
-
"""
|
59
|
-
|
60
|
-
graph_invisible_attrs = ()
|
61
|
-
|
62
|
-
def __init_subclass__(cls) -> None:
|
63
|
-
super().__init_subclass__()
|
64
|
-
|
65
|
-
register_graph_node_type(
|
66
|
-
type=cls,
|
67
|
-
flatten=_node_flatten,
|
68
|
-
set_key=_node_set_key,
|
69
|
-
pop_key=_node_pop_key,
|
70
|
-
create_empty=_node_create_empty,
|
71
|
-
clear=_node_clear,
|
72
|
-
)
|
73
|
-
|
74
|
-
def __deepcopy__(self: G, memo=None) -> G:
|
75
|
-
"""
|
76
|
-
Deepcopy the object.
|
77
|
-
"""
|
78
|
-
from ._graph_operation import treefy_split, treefy_merge
|
79
|
-
|
80
|
-
graphdef, state = treefy_split(self)
|
81
|
-
graphdef = deepcopy(graphdef)
|
82
|
-
state = deepcopy(state)
|
83
|
-
return treefy_merge(graphdef, state)
|
84
|
-
|
85
|
-
|
86
|
-
class String:
|
87
|
-
def __init__(self, msg):
|
88
|
-
self.msg = msg
|
89
|
-
|
90
|
-
def __repr__(self):
|
91
|
-
return self.msg
|
92
|
-
|
93
|
-
|
94
|
-
def _to_shape_dtype(value):
|
95
|
-
if isinstance(value, State):
|
96
|
-
return value.replace(jax.tree.map(_to_shape_dtype, value.value))
|
97
|
-
elif isinstance(value, (np.ndarray, jax.Array)):
|
98
|
-
return String(f'Array(shape={value.shape}, dtype={value.dtype.name})')
|
99
|
-
elif isinstance(value, u.Quantity):
|
100
|
-
return String(f'Quantity(mantissa=Array(shape={value.shape}, dtype={value.dtype.name}), unit={value.unit})')
|
101
|
-
return value
|
102
|
-
|
103
|
-
|
104
|
-
# -------------------------------
|
105
|
-
# Graph Definition
|
106
|
-
# -------------------------------
|
107
|
-
|
108
|
-
|
109
|
-
def _node_flatten(
|
110
|
-
node: Node
|
111
|
-
) -> Tuple[Tuple[Tuple[str, Any], ...], Tuple[Type]]:
|
112
|
-
# graph_invisible_attrs = getattr(node, 'graph_invisible_attrs', ())
|
113
|
-
# graph_invisible_attrs = tuple(graph_invisible_attrs) + ('_trace_state',)
|
114
|
-
graph_invisible_attrs = ('_trace_state',)
|
115
|
-
nodes = sorted(
|
116
|
-
(key, value) for key, value in vars(node).items()
|
117
|
-
if (key not in graph_invisible_attrs)
|
118
|
-
)
|
119
|
-
return nodes, (type(node),)
|
120
|
-
|
121
|
-
|
122
|
-
def _node_set_key(
|
123
|
-
node: Node,
|
124
|
-
key: Key,
|
125
|
-
value: Any
|
126
|
-
) -> None:
|
127
|
-
if not isinstance(key, str):
|
128
|
-
raise KeyError(f'Invalid key: {key!r}')
|
129
|
-
elif (
|
130
|
-
hasattr(node, key)
|
131
|
-
and isinstance(state := getattr(node, key), State)
|
132
|
-
and isinstance(value, TreefyState)
|
133
|
-
):
|
134
|
-
state.update_from_ref(value)
|
135
|
-
else:
|
136
|
-
setattr(node, key, value)
|
137
|
-
|
138
|
-
|
139
|
-
def _node_pop_key(
|
140
|
-
node: Node,
|
141
|
-
key: Key
|
142
|
-
):
|
143
|
-
if not isinstance(key, str):
|
144
|
-
raise KeyError(f'Invalid key: {key!r}')
|
145
|
-
return vars(node).pop(key)
|
146
|
-
|
147
|
-
|
148
|
-
def _node_create_empty(
|
149
|
-
static: tuple[Type[G],]
|
150
|
-
) -> G:
|
151
|
-
node_type, = static
|
152
|
-
node = object.__new__(node_type)
|
153
|
-
return node
|
154
|
-
|
155
|
-
|
156
|
-
def _node_clear(node: Node):
|
157
|
-
module_state = node._trace_state
|
158
|
-
module_vars = vars(node)
|
159
|
-
module_vars.clear()
|
160
|
-
module_vars['_trace_state'] = module_state
|
161
|
-
|
162
|
-
|
163
|
-
class Dict(Node, Mapping[str, A]):
|
164
|
-
"""
|
165
|
-
A dictionary node.
|
166
|
-
"""
|
167
|
-
|
168
|
-
def __init__(self, *args, **kwargs):
|
169
|
-
for name, value in dict(*args, **kwargs).items():
|
170
|
-
setattr(self, name, value)
|
171
|
-
|
172
|
-
def __getitem__(self, key) -> A:
|
173
|
-
return getattr(self, key)
|
174
|
-
|
175
|
-
def __setitem__(self, key, value):
|
176
|
-
setattr(self, key, value)
|
177
|
-
|
178
|
-
def __getattr__(self, key) -> A:
|
179
|
-
return super().__getattribute__(key)
|
180
|
-
|
181
|
-
def __setattr__(self, key, value):
|
182
|
-
super().__setattr__(key, value)
|
183
|
-
|
184
|
-
def __iter__(self) -> Iterator[str]:
|
185
|
-
return (k for k in vars(self) if k != '_object__state')
|
186
|
-
|
187
|
-
def __len__(self) -> int:
|
188
|
-
return len(vars(self))
|
189
|
-
|
190
|
-
|
191
|
-
class List(Node):
|
192
|
-
"""
|
193
|
-
A list node.
|
194
|
-
"""
|
195
|
-
|
196
|
-
def __init__(self, seq=()):
|
197
|
-
vars(self).update({str(i): item for i, item in enumerate(seq)})
|
198
|
-
|
199
|
-
def __getitem__(self, idx):
|
200
|
-
return getattr(self, str(idx))
|
201
|
-
|
202
|
-
def __setitem__(self, idx, value):
|
203
|
-
setattr(self, str(idx), value)
|
204
|
-
|
205
|
-
def __iter__(self):
|
206
|
-
return iter(vars(self).values())
|
207
|
-
|
208
|
-
def __len__(self):
|
209
|
-
return len(vars(self))
|
210
|
-
|
211
|
-
def __add__(self, other: Sequence[A]) -> 'List[A]':
|
212
|
-
return List(list(self) + list(other))
|
213
|
-
|
214
|
-
def append(self, value):
|
215
|
-
self[len(vars(self))] = value
|
216
|
-
|
217
|
-
def extend(self, values):
|
218
|
-
for value in values:
|
219
|
-
self.append(value)
|
220
|
-
|
221
|
-
|
222
|
-
class Sequential(Node):
|
223
|
-
def __init__(self, *fns: Callable[..., Any]):
|
224
|
-
self.layers = list(fns)
|
225
|
-
|
226
|
-
def __call__(self, *args, **kwargs) -> Any:
|
227
|
-
output: Any = None
|
228
|
-
|
229
|
-
for i, f in enumerate(self.layers):
|
230
|
-
if not callable(f):
|
231
|
-
raise TypeError(f'Sequence[{i}] is not callable: {f}')
|
232
|
-
if i > 0:
|
233
|
-
if isinstance(output, tuple):
|
234
|
-
args = output
|
235
|
-
kwargs = {}
|
236
|
-
elif isinstance(output, dict):
|
237
|
-
args = ()
|
238
|
-
kwargs = output
|
239
|
-
else:
|
240
|
-
args = (output,)
|
241
|
-
kwargs = {}
|
242
|
-
output = f(*args, **kwargs)
|
243
|
-
|
244
|
-
return output
|
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.
|
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 abc import ABCMeta
|
19
|
+
from copy import deepcopy
|
20
|
+
from typing import Any, Callable, Type, TypeVar, Tuple, TYPE_CHECKING, Mapping, Iterator, Sequence
|
21
|
+
|
22
|
+
import brainunit as u
|
23
|
+
import jax
|
24
|
+
import numpy as np
|
25
|
+
|
26
|
+
from brainstate._state import State, TreefyState
|
27
|
+
from brainstate.typing import Key
|
28
|
+
from brainstate.util.pretty_pytree import PrettyObject
|
29
|
+
from ._graph_operation import register_graph_node_type
|
30
|
+
|
31
|
+
__all__ = [
|
32
|
+
'Node', 'Dict', 'List', 'Sequential',
|
33
|
+
]
|
34
|
+
|
35
|
+
G = TypeVar('G', bound='Node')
|
36
|
+
A = TypeVar('A')
|
37
|
+
|
38
|
+
|
39
|
+
class GraphNodeMeta(ABCMeta):
|
40
|
+
if not TYPE_CHECKING:
|
41
|
+
def __call__(cls, *args: Any, **kwargs: Any) -> Any:
|
42
|
+
node = cls.__new__(cls, *args, **kwargs)
|
43
|
+
node.__init__(*args, **kwargs)
|
44
|
+
return node
|
45
|
+
|
46
|
+
|
47
|
+
class Node(PrettyObject, metaclass=GraphNodeMeta):
|
48
|
+
"""
|
49
|
+
Base class for all graph nodes.
|
50
|
+
|
51
|
+
This class provides the following functionalities:
|
52
|
+
- Register the node type with the graph tool.
|
53
|
+
- Prevent mutation of the node from different trace level.
|
54
|
+
- Provide a pretty repr for the node.
|
55
|
+
- Provide a treescope repr for the node.
|
56
|
+
- Deepcopy the node.
|
57
|
+
|
58
|
+
"""
|
59
|
+
|
60
|
+
graph_invisible_attrs = ()
|
61
|
+
|
62
|
+
def __init_subclass__(cls) -> None:
|
63
|
+
super().__init_subclass__()
|
64
|
+
|
65
|
+
register_graph_node_type(
|
66
|
+
type=cls,
|
67
|
+
flatten=_node_flatten,
|
68
|
+
set_key=_node_set_key,
|
69
|
+
pop_key=_node_pop_key,
|
70
|
+
create_empty=_node_create_empty,
|
71
|
+
clear=_node_clear,
|
72
|
+
)
|
73
|
+
|
74
|
+
def __deepcopy__(self: G, memo=None) -> G:
|
75
|
+
"""
|
76
|
+
Deepcopy the object.
|
77
|
+
"""
|
78
|
+
from ._graph_operation import treefy_split, treefy_merge
|
79
|
+
|
80
|
+
graphdef, state = treefy_split(self)
|
81
|
+
graphdef = deepcopy(graphdef)
|
82
|
+
state = deepcopy(state)
|
83
|
+
return treefy_merge(graphdef, state)
|
84
|
+
|
85
|
+
|
86
|
+
class String:
|
87
|
+
def __init__(self, msg):
|
88
|
+
self.msg = msg
|
89
|
+
|
90
|
+
def __repr__(self):
|
91
|
+
return self.msg
|
92
|
+
|
93
|
+
|
94
|
+
def _to_shape_dtype(value):
|
95
|
+
if isinstance(value, State):
|
96
|
+
return value.replace(jax.tree.map(_to_shape_dtype, value.value))
|
97
|
+
elif isinstance(value, (np.ndarray, jax.Array)):
|
98
|
+
return String(f'Array(shape={value.shape}, dtype={value.dtype.name})')
|
99
|
+
elif isinstance(value, u.Quantity):
|
100
|
+
return String(f'Quantity(mantissa=Array(shape={value.shape}, dtype={value.dtype.name}), unit={value.unit})')
|
101
|
+
return value
|
102
|
+
|
103
|
+
|
104
|
+
# -------------------------------
|
105
|
+
# Graph Definition
|
106
|
+
# -------------------------------
|
107
|
+
|
108
|
+
|
109
|
+
def _node_flatten(
|
110
|
+
node: Node
|
111
|
+
) -> Tuple[Tuple[Tuple[str, Any], ...], Tuple[Type]]:
|
112
|
+
# graph_invisible_attrs = getattr(node, 'graph_invisible_attrs', ())
|
113
|
+
# graph_invisible_attrs = tuple(graph_invisible_attrs) + ('_trace_state',)
|
114
|
+
graph_invisible_attrs = ('_trace_state',)
|
115
|
+
nodes = sorted(
|
116
|
+
(key, value) for key, value in vars(node).items()
|
117
|
+
if (key not in graph_invisible_attrs)
|
118
|
+
)
|
119
|
+
return nodes, (type(node),)
|
120
|
+
|
121
|
+
|
122
|
+
def _node_set_key(
|
123
|
+
node: Node,
|
124
|
+
key: Key,
|
125
|
+
value: Any
|
126
|
+
) -> None:
|
127
|
+
if not isinstance(key, str):
|
128
|
+
raise KeyError(f'Invalid key: {key!r}')
|
129
|
+
elif (
|
130
|
+
hasattr(node, key)
|
131
|
+
and isinstance(state := getattr(node, key), State)
|
132
|
+
and isinstance(value, TreefyState)
|
133
|
+
):
|
134
|
+
state.update_from_ref(value)
|
135
|
+
else:
|
136
|
+
setattr(node, key, value)
|
137
|
+
|
138
|
+
|
139
|
+
def _node_pop_key(
|
140
|
+
node: Node,
|
141
|
+
key: Key
|
142
|
+
):
|
143
|
+
if not isinstance(key, str):
|
144
|
+
raise KeyError(f'Invalid key: {key!r}')
|
145
|
+
return vars(node).pop(key)
|
146
|
+
|
147
|
+
|
148
|
+
def _node_create_empty(
|
149
|
+
static: tuple[Type[G],]
|
150
|
+
) -> G:
|
151
|
+
node_type, = static
|
152
|
+
node = object.__new__(node_type)
|
153
|
+
return node
|
154
|
+
|
155
|
+
|
156
|
+
def _node_clear(node: Node):
|
157
|
+
module_state = node._trace_state
|
158
|
+
module_vars = vars(node)
|
159
|
+
module_vars.clear()
|
160
|
+
module_vars['_trace_state'] = module_state
|
161
|
+
|
162
|
+
|
163
|
+
class Dict(Node, Mapping[str, A]):
|
164
|
+
"""
|
165
|
+
A dictionary node.
|
166
|
+
"""
|
167
|
+
|
168
|
+
def __init__(self, *args, **kwargs):
|
169
|
+
for name, value in dict(*args, **kwargs).items():
|
170
|
+
setattr(self, name, value)
|
171
|
+
|
172
|
+
def __getitem__(self, key) -> A:
|
173
|
+
return getattr(self, key)
|
174
|
+
|
175
|
+
def __setitem__(self, key, value):
|
176
|
+
setattr(self, key, value)
|
177
|
+
|
178
|
+
def __getattr__(self, key) -> A:
|
179
|
+
return super().__getattribute__(key)
|
180
|
+
|
181
|
+
def __setattr__(self, key, value):
|
182
|
+
super().__setattr__(key, value)
|
183
|
+
|
184
|
+
def __iter__(self) -> Iterator[str]:
|
185
|
+
return (k for k in vars(self) if k != '_object__state')
|
186
|
+
|
187
|
+
def __len__(self) -> int:
|
188
|
+
return len(vars(self))
|
189
|
+
|
190
|
+
|
191
|
+
class List(Node):
|
192
|
+
"""
|
193
|
+
A list node.
|
194
|
+
"""
|
195
|
+
|
196
|
+
def __init__(self, seq=()):
|
197
|
+
vars(self).update({str(i): item for i, item in enumerate(seq)})
|
198
|
+
|
199
|
+
def __getitem__(self, idx):
|
200
|
+
return getattr(self, str(idx))
|
201
|
+
|
202
|
+
def __setitem__(self, idx, value):
|
203
|
+
setattr(self, str(idx), value)
|
204
|
+
|
205
|
+
def __iter__(self):
|
206
|
+
return iter(vars(self).values())
|
207
|
+
|
208
|
+
def __len__(self):
|
209
|
+
return len(vars(self))
|
210
|
+
|
211
|
+
def __add__(self, other: Sequence[A]) -> 'List[A]':
|
212
|
+
return List(list(self) + list(other))
|
213
|
+
|
214
|
+
def append(self, value):
|
215
|
+
self[len(vars(self))] = value
|
216
|
+
|
217
|
+
def extend(self, values):
|
218
|
+
for value in values:
|
219
|
+
self.append(value)
|
220
|
+
|
221
|
+
|
222
|
+
class Sequential(Node):
|
223
|
+
def __init__(self, *fns: Callable[..., Any]):
|
224
|
+
self.layers = list(fns)
|
225
|
+
|
226
|
+
def __call__(self, *args, **kwargs) -> Any:
|
227
|
+
output: Any = None
|
228
|
+
|
229
|
+
for i, f in enumerate(self.layers):
|
230
|
+
if not callable(f):
|
231
|
+
raise TypeError(f'Sequence[{i}] is not callable: {f}')
|
232
|
+
if i > 0:
|
233
|
+
if isinstance(output, tuple):
|
234
|
+
args = output
|
235
|
+
kwargs = {}
|
236
|
+
elif isinstance(output, dict):
|
237
|
+
args = ()
|
238
|
+
kwargs = output
|
239
|
+
else:
|
240
|
+
args = (output,)
|
241
|
+
kwargs = {}
|
242
|
+
output = f(*args, **kwargs)
|
243
|
+
|
244
|
+
return output
|
@@ -1,73 +1,73 @@
|
|
1
|
-
# Copyright 2024 BDP Ecosystem Limited. All Rights Reserved.
|
2
|
-
#
|
3
|
-
# Licensed under the Apache License, Version 2.0 (the "License");
|
4
|
-
# you may not use this file except in compliance with the License.
|
5
|
-
# You may obtain a copy of the License at
|
6
|
-
#
|
7
|
-
# http://www.apache.org/licenses/LICENSE-2.0
|
8
|
-
#
|
9
|
-
# Unless required by applicable law or agreed to in writing, software
|
10
|
-
# distributed under the License is distributed on an "AS IS" BASIS,
|
11
|
-
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12
|
-
# See the License for the specific language governing permissions and
|
13
|
-
# limitations under the License.
|
14
|
-
# ==============================================================================
|
15
|
-
|
16
|
-
import unittest
|
17
|
-
|
18
|
-
import brainstate
|
19
|
-
|
20
|
-
|
21
|
-
class TestSequential(unittest.TestCase):
|
22
|
-
def test1(self):
|
23
|
-
s = brainstate.graph.Sequential(brainstate.nn.Linear(1, 2),
|
24
|
-
brainstate.nn.Linear(2, 3))
|
25
|
-
graphdef, states = brainstate.graph.treefy_split(s)
|
26
|
-
print(states)
|
27
|
-
self.assertTrue(len(states.to_flat()) == 2)
|
28
|
-
|
29
|
-
|
30
|
-
class TestStateRetrieve(unittest.TestCase):
|
31
|
-
def test_list_of_states_1(self):
|
32
|
-
class Model(brainstate.graph.Node):
|
33
|
-
def __init__(self):
|
34
|
-
self.a = [1, 2, 3]
|
35
|
-
self.b = [brainstate.State(1), brainstate.State(2), brainstate.State(3)]
|
36
|
-
|
37
|
-
m = Model()
|
38
|
-
graphdef, states = brainstate.graph.treefy_split(m)
|
39
|
-
print(states.to_flat())
|
40
|
-
self.assertTrue(len(states.to_flat()) == 3)
|
41
|
-
|
42
|
-
def test_list_of_states_2(self):
|
43
|
-
class Model(brainstate.graph.Node):
|
44
|
-
def __init__(self):
|
45
|
-
self.a = [1, 2, 3]
|
46
|
-
self.b = [brainstate.State(1), [brainstate.State(2), brainstate.State(3)]]
|
47
|
-
|
48
|
-
m = Model()
|
49
|
-
graphdef, states = brainstate.graph.treefy_split(m)
|
50
|
-
print(states.to_flat())
|
51
|
-
self.assertTrue(len(states.to_flat()) == 3)
|
52
|
-
|
53
|
-
def test_list_of_node_1(self):
|
54
|
-
class Model(brainstate.graph.Node):
|
55
|
-
def __init__(self):
|
56
|
-
self.a = [1, 2, 3]
|
57
|
-
self.b = [brainstate.nn.Linear(1, 2), brainstate.nn.Linear(2, 3)]
|
58
|
-
|
59
|
-
m = Model()
|
60
|
-
graphdef, states = brainstate.graph.treefy_split(m)
|
61
|
-
print(states.to_flat())
|
62
|
-
self.assertTrue(len(states.to_flat()) == 2)
|
63
|
-
|
64
|
-
def test_list_of_node_2(self):
|
65
|
-
class Model(brainstate.graph.Node):
|
66
|
-
def __init__(self):
|
67
|
-
self.a = [1, 2, 3]
|
68
|
-
self.b = [brainstate.nn.Linear(1, 2), [brainstate.nn.Linear(2, 3)], (brainstate.nn.Linear(3, 4), brainstate.nn.Linear(4, 5))]
|
69
|
-
|
70
|
-
m = Model()
|
71
|
-
graphdef, states = brainstate.graph.treefy_split(m)
|
72
|
-
print(states.to_flat())
|
73
|
-
self.assertTrue(len(states.to_flat()) == 4)
|
1
|
+
# Copyright 2024 BDP Ecosystem Limited. All Rights Reserved.
|
2
|
+
#
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
4
|
+
# you may not use this file except in compliance with the License.
|
5
|
+
# You may obtain a copy of the License at
|
6
|
+
#
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
8
|
+
#
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12
|
+
# See the License for the specific language governing permissions and
|
13
|
+
# limitations under the License.
|
14
|
+
# ==============================================================================
|
15
|
+
|
16
|
+
import unittest
|
17
|
+
|
18
|
+
import brainstate
|
19
|
+
|
20
|
+
|
21
|
+
class TestSequential(unittest.TestCase):
|
22
|
+
def test1(self):
|
23
|
+
s = brainstate.graph.Sequential(brainstate.nn.Linear(1, 2),
|
24
|
+
brainstate.nn.Linear(2, 3))
|
25
|
+
graphdef, states = brainstate.graph.treefy_split(s)
|
26
|
+
print(states)
|
27
|
+
self.assertTrue(len(states.to_flat()) == 2)
|
28
|
+
|
29
|
+
|
30
|
+
class TestStateRetrieve(unittest.TestCase):
|
31
|
+
def test_list_of_states_1(self):
|
32
|
+
class Model(brainstate.graph.Node):
|
33
|
+
def __init__(self):
|
34
|
+
self.a = [1, 2, 3]
|
35
|
+
self.b = [brainstate.State(1), brainstate.State(2), brainstate.State(3)]
|
36
|
+
|
37
|
+
m = Model()
|
38
|
+
graphdef, states = brainstate.graph.treefy_split(m)
|
39
|
+
print(states.to_flat())
|
40
|
+
self.assertTrue(len(states.to_flat()) == 3)
|
41
|
+
|
42
|
+
def test_list_of_states_2(self):
|
43
|
+
class Model(brainstate.graph.Node):
|
44
|
+
def __init__(self):
|
45
|
+
self.a = [1, 2, 3]
|
46
|
+
self.b = [brainstate.State(1), [brainstate.State(2), brainstate.State(3)]]
|
47
|
+
|
48
|
+
m = Model()
|
49
|
+
graphdef, states = brainstate.graph.treefy_split(m)
|
50
|
+
print(states.to_flat())
|
51
|
+
self.assertTrue(len(states.to_flat()) == 3)
|
52
|
+
|
53
|
+
def test_list_of_node_1(self):
|
54
|
+
class Model(brainstate.graph.Node):
|
55
|
+
def __init__(self):
|
56
|
+
self.a = [1, 2, 3]
|
57
|
+
self.b = [brainstate.nn.Linear(1, 2), brainstate.nn.Linear(2, 3)]
|
58
|
+
|
59
|
+
m = Model()
|
60
|
+
graphdef, states = brainstate.graph.treefy_split(m)
|
61
|
+
print(states.to_flat())
|
62
|
+
self.assertTrue(len(states.to_flat()) == 2)
|
63
|
+
|
64
|
+
def test_list_of_node_2(self):
|
65
|
+
class Model(brainstate.graph.Node):
|
66
|
+
def __init__(self):
|
67
|
+
self.a = [1, 2, 3]
|
68
|
+
self.b = [brainstate.nn.Linear(1, 2), [brainstate.nn.Linear(2, 3)], (brainstate.nn.Linear(3, 4), brainstate.nn.Linear(4, 5))]
|
69
|
+
|
70
|
+
m = Model()
|
71
|
+
graphdef, states = brainstate.graph.treefy_split(m)
|
72
|
+
print(states.to_flat())
|
73
|
+
self.assertTrue(len(states.to_flat()) == 4)
|