brainstate 0.1.10__py2.py3-none-any.whl → 0.2.1__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 +169 -58
- brainstate/_compatible_import.py +340 -148
- brainstate/_compatible_import_test.py +681 -0
- brainstate/_deprecation.py +210 -0
- brainstate/_deprecation_test.py +2319 -0
- brainstate/{util/error.py → _error.py} +45 -55
- brainstate/_state.py +1652 -1605
- brainstate/_state_test.py +52 -52
- brainstate/_utils.py +47 -47
- brainstate/environ.py +1495 -563
- brainstate/environ_test.py +1223 -62
- brainstate/graph/__init__.py +22 -29
- brainstate/graph/_node.py +240 -0
- brainstate/graph/_node_test.py +589 -0
- brainstate/graph/{_graph_operation.py → _operation.py} +1624 -1738
- brainstate/graph/_operation_test.py +1147 -0
- brainstate/mixin.py +1433 -365
- brainstate/mixin_test.py +1017 -77
- brainstate/nn/__init__.py +137 -135
- brainstate/nn/_activations.py +1100 -808
- brainstate/nn/_activations_test.py +354 -331
- brainstate/nn/_collective_ops.py +633 -514
- brainstate/nn/_collective_ops_test.py +774 -43
- brainstate/nn/_common.py +226 -178
- brainstate/nn/_common_test.py +154 -0
- brainstate/nn/_conv.py +2010 -501
- brainstate/nn/_conv_test.py +849 -238
- brainstate/nn/_delay.py +575 -588
- brainstate/nn/_delay_test.py +243 -238
- brainstate/nn/_dropout.py +618 -426
- brainstate/nn/_dropout_test.py +477 -100
- brainstate/nn/_dynamics.py +1267 -1343
- brainstate/nn/_dynamics_test.py +67 -78
- brainstate/nn/_elementwise.py +1298 -1119
- brainstate/nn/_elementwise_test.py +830 -169
- brainstate/nn/_embedding.py +408 -58
- brainstate/nn/_embedding_test.py +156 -0
- brainstate/nn/{_fixedprob.py → _event_fixedprob.py} +233 -239
- brainstate/nn/{_fixedprob_test.py → _event_fixedprob_test.py} +115 -114
- brainstate/nn/{_linear_mv.py → _event_linear.py} +83 -83
- brainstate/nn/{_linear_mv_test.py → _event_linear_test.py} +121 -120
- brainstate/nn/_exp_euler.py +254 -92
- brainstate/nn/_exp_euler_test.py +377 -35
- brainstate/nn/_linear.py +744 -424
- brainstate/nn/_linear_test.py +475 -107
- brainstate/nn/_metrics.py +1070 -0
- brainstate/nn/_metrics_test.py +611 -0
- brainstate/nn/_module.py +384 -377
- brainstate/nn/_module_test.py +40 -40
- brainstate/nn/_normalizations.py +1334 -975
- brainstate/nn/_normalizations_test.py +699 -73
- brainstate/nn/_paddings.py +1020 -0
- brainstate/nn/_paddings_test.py +723 -0
- brainstate/nn/_poolings.py +2239 -1177
- brainstate/nn/_poolings_test.py +953 -217
- brainstate/nn/{_rate_rnns.py → _rnns.py} +946 -554
- brainstate/nn/_rnns_test.py +593 -0
- brainstate/nn/_utils.py +216 -89
- brainstate/nn/_utils_test.py +402 -0
- brainstate/{init/_random_inits.py → nn/init.py} +809 -553
- brainstate/{init/_random_inits_test.py → nn/init_test.py} +180 -149
- brainstate/random/__init__.py +270 -24
- brainstate/random/_rand_funs.py +3938 -3616
- brainstate/random/_rand_funs_test.py +640 -567
- brainstate/random/_rand_seed.py +675 -210
- brainstate/random/_rand_seed_test.py +48 -48
- brainstate/random/_rand_state.py +1617 -1409
- brainstate/random/_rand_state_test.py +551 -0
- brainstate/transform/__init__.py +59 -0
- brainstate/transform/_ad_checkpoint.py +176 -0
- brainstate/{compile → transform}/_ad_checkpoint_test.py +49 -49
- brainstate/{augment → transform}/_autograd.py +1025 -778
- brainstate/{augment → transform}/_autograd_test.py +1289 -1289
- brainstate/transform/_conditions.py +316 -0
- brainstate/{compile → transform}/_conditions_test.py +220 -220
- brainstate/{compile → transform}/_error_if.py +94 -92
- brainstate/{compile → transform}/_error_if_test.py +52 -52
- brainstate/transform/_eval_shape.py +145 -0
- brainstate/{augment → transform}/_eval_shape_test.py +38 -38
- brainstate/{compile → transform}/_jit.py +399 -346
- brainstate/{compile → transform}/_jit_test.py +143 -143
- brainstate/{compile → transform}/_loop_collect_return.py +675 -536
- brainstate/{compile → transform}/_loop_collect_return_test.py +58 -58
- brainstate/{compile → transform}/_loop_no_collection.py +283 -184
- brainstate/{compile → transform}/_loop_no_collection_test.py +50 -50
- brainstate/transform/_make_jaxpr.py +2016 -0
- brainstate/transform/_make_jaxpr_test.py +1510 -0
- brainstate/transform/_mapping.py +529 -0
- brainstate/transform/_mapping_test.py +194 -0
- brainstate/{compile → transform}/_progress_bar.py +255 -202
- brainstate/{augment → transform}/_random.py +171 -151
- brainstate/{compile → transform}/_unvmap.py +256 -159
- brainstate/transform/_util.py +286 -0
- brainstate/typing.py +837 -304
- brainstate/typing_test.py +780 -0
- brainstate/util/__init__.py +27 -50
- brainstate/util/_others.py +1025 -0
- brainstate/util/_others_test.py +962 -0
- brainstate/util/_pretty_pytree.py +1301 -0
- brainstate/util/_pretty_pytree_test.py +675 -0
- brainstate/util/{pretty_repr.py → _pretty_repr.py} +462 -328
- brainstate/util/_pretty_repr_test.py +696 -0
- brainstate/util/filter.py +945 -469
- brainstate/util/filter_test.py +912 -0
- brainstate/util/struct.py +910 -523
- brainstate/util/struct_test.py +602 -0
- {brainstate-0.1.10.dist-info → brainstate-0.2.1.dist-info}/METADATA +108 -91
- brainstate-0.2.1.dist-info/RECORD +111 -0
- {brainstate-0.1.10.dist-info → brainstate-0.2.1.dist-info}/licenses/LICENSE +202 -202
- brainstate/augment/__init__.py +0 -30
- brainstate/augment/_eval_shape.py +0 -99
- brainstate/augment/_mapping.py +0 -1060
- brainstate/augment/_mapping_test.py +0 -597
- brainstate/compile/__init__.py +0 -38
- brainstate/compile/_ad_checkpoint.py +0 -204
- brainstate/compile/_conditions.py +0 -256
- brainstate/compile/_make_jaxpr.py +0 -888
- brainstate/compile/_make_jaxpr_test.py +0 -156
- brainstate/compile/_util.py +0 -147
- brainstate/functional/__init__.py +0 -27
- brainstate/graph/_graph_node.py +0 -244
- brainstate/graph/_graph_node_test.py +0 -73
- brainstate/graph/_graph_operation_test.py +0 -563
- brainstate/init/__init__.py +0 -26
- brainstate/init/_base.py +0 -52
- brainstate/init/_generic.py +0 -244
- brainstate/init/_regular_inits.py +0 -105
- brainstate/init/_regular_inits_test.py +0 -50
- brainstate/nn/_inputs.py +0 -608
- brainstate/nn/_ltp.py +0 -28
- brainstate/nn/_neuron.py +0 -705
- brainstate/nn/_neuron_test.py +0 -161
- brainstate/nn/_others.py +0 -46
- brainstate/nn/_projection.py +0 -486
- brainstate/nn/_rate_rnns_test.py +0 -63
- brainstate/nn/_readout.py +0 -209
- brainstate/nn/_readout_test.py +0 -53
- brainstate/nn/_stp.py +0 -236
- brainstate/nn/_synapse.py +0 -505
- brainstate/nn/_synapse_test.py +0 -131
- brainstate/nn/_synaptic_projection.py +0 -423
- brainstate/nn/_synouts.py +0 -162
- brainstate/nn/_synouts_test.py +0 -57
- brainstate/nn/metrics.py +0 -388
- brainstate/optim/__init__.py +0 -38
- brainstate/optim/_base.py +0 -64
- brainstate/optim/_lr_scheduler.py +0 -448
- brainstate/optim/_lr_scheduler_test.py +0 -50
- brainstate/optim/_optax_optimizer.py +0 -152
- brainstate/optim/_optax_optimizer_test.py +0 -53
- brainstate/optim/_sgd_optimizer.py +0 -1104
- brainstate/random/_random_for_unit.py +0 -52
- brainstate/surrogate.py +0 -1957
- brainstate/transform.py +0 -23
- brainstate/util/caller.py +0 -98
- brainstate/util/others.py +0 -540
- brainstate/util/pretty_pytree.py +0 -945
- brainstate/util/pretty_pytree_test.py +0 -159
- brainstate/util/pretty_table.py +0 -2954
- brainstate/util/scaling.py +0 -258
- brainstate-0.1.10.dist-info/RECORD +0 -130
- {brainstate-0.1.10.dist-info → brainstate-0.2.1.dist-info}/WHEEL +0 -0
- {brainstate-0.1.10.dist-info → brainstate-0.2.1.dist-info}/top_level.txt +0 -0
@@ -1,156 +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
|
-
|
17
|
-
import unittest
|
18
|
-
|
19
|
-
import jax
|
20
|
-
import jax.numpy as jnp
|
21
|
-
import pytest
|
22
|
-
|
23
|
-
import brainstate
|
24
|
-
from brainstate._compatible_import import jaxpr_as_fun
|
25
|
-
|
26
|
-
|
27
|
-
class TestMakeJaxpr(unittest.TestCase):
|
28
|
-
def test_compar_jax_make_jaxpr(self):
|
29
|
-
def func4(arg): # Arg is a pair
|
30
|
-
temp = arg[0] + jnp.sin(arg[1]) * 3.
|
31
|
-
c = brainstate.random.rand_like(arg[0])
|
32
|
-
return jnp.sum(temp + c)
|
33
|
-
|
34
|
-
key = brainstate.random.DEFAULT.value
|
35
|
-
jaxpr = jax.make_jaxpr(func4)((jnp.zeros(8), jnp.ones(8)))
|
36
|
-
print(jaxpr)
|
37
|
-
self.assertTrue(len(jaxpr.in_avals) == 2)
|
38
|
-
self.assertTrue(len(jaxpr.consts) == 1)
|
39
|
-
self.assertTrue(len(jaxpr.out_avals) == 1)
|
40
|
-
self.assertTrue(jnp.allclose(jaxpr.consts[0], key))
|
41
|
-
|
42
|
-
brainstate.random.seed(1)
|
43
|
-
print(brainstate.random.DEFAULT.value)
|
44
|
-
|
45
|
-
jaxpr2, states = brainstate.compile.make_jaxpr(func4)((jnp.zeros(8), jnp.ones(8)))
|
46
|
-
print(jaxpr2)
|
47
|
-
self.assertTrue(len(jaxpr2.in_avals) == 3)
|
48
|
-
self.assertTrue(len(jaxpr2.out_avals) == 2)
|
49
|
-
self.assertTrue(len(jaxpr2.consts) == 0)
|
50
|
-
print(brainstate.random.DEFAULT.value)
|
51
|
-
|
52
|
-
def test_StatefulFunction_1(self):
|
53
|
-
def func4(arg): # Arg is a pair
|
54
|
-
temp = arg[0] + jnp.sin(arg[1]) * 3.
|
55
|
-
c = brainstate.random.rand_like(arg[0])
|
56
|
-
return jnp.sum(temp + c)
|
57
|
-
|
58
|
-
fun = brainstate.compile.StatefulFunction(func4).make_jaxpr((jnp.zeros(8), jnp.ones(8)))
|
59
|
-
print(fun.get_states())
|
60
|
-
print(fun.get_jaxpr())
|
61
|
-
|
62
|
-
def test_StatefulFunction_2(self):
|
63
|
-
st1 = brainstate.State(jnp.ones(10))
|
64
|
-
|
65
|
-
def f1(x):
|
66
|
-
st1.value = x + st1.value
|
67
|
-
|
68
|
-
def f2(x):
|
69
|
-
jaxpr = brainstate.compile.make_jaxpr(f1)(x)
|
70
|
-
c = 1. + x
|
71
|
-
return c
|
72
|
-
|
73
|
-
def f3(x):
|
74
|
-
jaxpr = brainstate.compile.make_jaxpr(f1)(x)
|
75
|
-
c = 1.
|
76
|
-
return c
|
77
|
-
|
78
|
-
print()
|
79
|
-
jaxpr = brainstate.compile.make_jaxpr(f1)(jnp.zeros(1))
|
80
|
-
print(jaxpr)
|
81
|
-
jaxpr = jax.make_jaxpr(f2)(jnp.zeros(1))
|
82
|
-
print(jaxpr)
|
83
|
-
jaxpr = jax.make_jaxpr(f3)(jnp.zeros(1))
|
84
|
-
print(jaxpr)
|
85
|
-
jaxpr, _ = brainstate.compile.make_jaxpr(f3)(jnp.zeros(1))
|
86
|
-
print(jaxpr)
|
87
|
-
self.assertTrue(jnp.allclose(jaxpr_as_fun(jaxpr)(jnp.zeros(1), st1.value)[0],
|
88
|
-
f3(jnp.zeros(1))))
|
89
|
-
|
90
|
-
def test_compare_jax_make_jaxpr2(self):
|
91
|
-
st1 = brainstate.State(jnp.ones(10))
|
92
|
-
|
93
|
-
def fa(x):
|
94
|
-
st1.value = x + st1.value
|
95
|
-
|
96
|
-
def ffa(x):
|
97
|
-
jaxpr, states = brainstate.compile.make_jaxpr(fa)(x)
|
98
|
-
c = 1. + x
|
99
|
-
return c
|
100
|
-
|
101
|
-
jaxpr, states = brainstate.compile.make_jaxpr(ffa)(jnp.zeros(1))
|
102
|
-
print()
|
103
|
-
print(jaxpr)
|
104
|
-
print(states)
|
105
|
-
print(jaxpr_as_fun(jaxpr)(jnp.zeros(1), st1.value))
|
106
|
-
jaxpr = jax.make_jaxpr(ffa)(jnp.zeros(1))
|
107
|
-
print(jaxpr)
|
108
|
-
print(jaxpr_as_fun(jaxpr)(jnp.zeros(1)))
|
109
|
-
|
110
|
-
def test_compare_jax_make_jaxpr3(self):
|
111
|
-
def fa(x):
|
112
|
-
return 1.
|
113
|
-
|
114
|
-
jaxpr, states = brainstate.compile.make_jaxpr(fa)(jnp.zeros(1))
|
115
|
-
print()
|
116
|
-
print(jaxpr)
|
117
|
-
print(states)
|
118
|
-
# print(jaxpr_as_fun(jaxpr)(jnp.zeros(1)))
|
119
|
-
jaxpr = jax.make_jaxpr(fa)(jnp.zeros(1))
|
120
|
-
print(jaxpr)
|
121
|
-
# print(jaxpr_as_fun(jaxpr)(jnp.zeros(1)))
|
122
|
-
|
123
|
-
def test_static_argnames(self):
|
124
|
-
def func4(a, b): # Arg is a pair
|
125
|
-
temp = a + jnp.sin(b) * 3.
|
126
|
-
c = brainstate.random.rand_like(a)
|
127
|
-
return jnp.sum(temp + c)
|
128
|
-
|
129
|
-
jaxpr, states = brainstate.compile.make_jaxpr(func4, static_argnames='b')(jnp.zeros(8), 1.)
|
130
|
-
print()
|
131
|
-
print(jaxpr)
|
132
|
-
print(states)
|
133
|
-
|
134
|
-
def test_state_in(self):
|
135
|
-
def f(a):
|
136
|
-
return a.value
|
137
|
-
|
138
|
-
with pytest.raises(ValueError):
|
139
|
-
brainstate.compile.StatefulFunction(f).make_jaxpr(brainstate.State(1.))
|
140
|
-
|
141
|
-
def test_state_out(self):
|
142
|
-
def f(a):
|
143
|
-
return brainstate.State(a)
|
144
|
-
|
145
|
-
with pytest.raises(ValueError):
|
146
|
-
brainstate.compile.StatefulFunction(f).make_jaxpr(1.)
|
147
|
-
|
148
|
-
def test_return_states(self):
|
149
|
-
a = brainstate.State(jnp.ones(3))
|
150
|
-
|
151
|
-
@brainstate.compile.jit
|
152
|
-
def f():
|
153
|
-
return a
|
154
|
-
|
155
|
-
with pytest.raises(ValueError):
|
156
|
-
f()
|
brainstate/compile/_util.py
DELETED
@@ -1,147 +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 functools import wraps
|
17
|
-
from typing import Sequence, Tuple
|
18
|
-
|
19
|
-
from brainstate._state import StateTraceStack
|
20
|
-
from brainstate.typing import PyTree
|
21
|
-
from ._make_jaxpr import StatefulFunction
|
22
|
-
|
23
|
-
|
24
|
-
def write_back_state_values(
|
25
|
-
state_trace: StateTraceStack,
|
26
|
-
read_state_vals: Sequence[PyTree],
|
27
|
-
write_state_vals: Sequence[PyTree],
|
28
|
-
):
|
29
|
-
assert len(state_trace.states) == len(state_trace.been_writen) == len(read_state_vals) == len(write_state_vals)
|
30
|
-
for st, write, val_r, val_w in zip(state_trace.states, state_trace.been_writen, read_state_vals, write_state_vals):
|
31
|
-
if write:
|
32
|
-
st.value = val_w
|
33
|
-
else:
|
34
|
-
st.restore_value(val_r)
|
35
|
-
|
36
|
-
|
37
|
-
def wrap_single_fun_in_multi_branches(
|
38
|
-
stateful_fun: StatefulFunction,
|
39
|
-
merged_state_trace: StateTraceStack,
|
40
|
-
read_state_vals: Sequence[PyTree | None],
|
41
|
-
return_states: bool = True
|
42
|
-
):
|
43
|
-
state_ids_belong_to_this_fun = {id(st): st for st in stateful_fun.get_states()}
|
44
|
-
|
45
|
-
@wraps(stateful_fun.fun)
|
46
|
-
def wrapped_branch(write_state_vals, *operands):
|
47
|
-
# "write_state_vals" should have the same length as "merged_state_trace.states"
|
48
|
-
assert len(merged_state_trace.states) == len(write_state_vals) == len(read_state_vals)
|
49
|
-
|
50
|
-
# get all state values needed for this function, which is a subset of "write_state_vals"
|
51
|
-
st_vals_for_this_fun = []
|
52
|
-
for write, st, val_w, val_r in zip(merged_state_trace.been_writen,
|
53
|
-
merged_state_trace.states,
|
54
|
-
write_state_vals,
|
55
|
-
read_state_vals):
|
56
|
-
if id(st) in state_ids_belong_to_this_fun:
|
57
|
-
st_vals_for_this_fun.append(val_w if write else val_r)
|
58
|
-
|
59
|
-
# call this function
|
60
|
-
new_state_vals, out = stateful_fun.jaxpr_call(st_vals_for_this_fun, *operands)
|
61
|
-
assert len(new_state_vals) == len(st_vals_for_this_fun)
|
62
|
-
|
63
|
-
if return_states:
|
64
|
-
# get all written state values
|
65
|
-
new_state_vals = {id(st): val for st, val in zip(stateful_fun.get_states(), new_state_vals)}
|
66
|
-
write_state_vals = tuple([
|
67
|
-
(new_state_vals[id(st)] if id(st) in state_ids_belong_to_this_fun else w_val)
|
68
|
-
if write else None
|
69
|
-
for write, st, w_val in zip(merged_state_trace.been_writen,
|
70
|
-
merged_state_trace.states,
|
71
|
-
write_state_vals)
|
72
|
-
])
|
73
|
-
return write_state_vals, out
|
74
|
-
return out
|
75
|
-
|
76
|
-
return wrapped_branch
|
77
|
-
|
78
|
-
|
79
|
-
def wrap_single_fun_in_multi_branches_while_loop(
|
80
|
-
stateful_fun: StatefulFunction,
|
81
|
-
merged_state_trace: StateTraceStack,
|
82
|
-
read_state_vals: Sequence[PyTree | None],
|
83
|
-
return_states: bool = True
|
84
|
-
):
|
85
|
-
state_ids_belong_to_this_fun = {id(st): st for st in stateful_fun.get_states()}
|
86
|
-
|
87
|
-
@wraps(stateful_fun.fun)
|
88
|
-
def wrapped_branch(init_val):
|
89
|
-
write_state_vals, init_val = init_val
|
90
|
-
# "write_state_vals" should have the same length as "merged_state_trace.states"
|
91
|
-
assert len(merged_state_trace.states) == len(write_state_vals) == len(read_state_vals)
|
92
|
-
|
93
|
-
# get all state values needed for this function, which is a subset of "write_state_vals"
|
94
|
-
st_vals_for_this_fun = []
|
95
|
-
for write, st, val_w, val_r in zip(merged_state_trace.been_writen,
|
96
|
-
merged_state_trace.states,
|
97
|
-
write_state_vals,
|
98
|
-
read_state_vals):
|
99
|
-
if id(st) in state_ids_belong_to_this_fun:
|
100
|
-
st_vals_for_this_fun.append(val_w if write else val_r)
|
101
|
-
|
102
|
-
# call this function
|
103
|
-
new_state_vals, out = stateful_fun.jaxpr_call(st_vals_for_this_fun, init_val)
|
104
|
-
assert len(new_state_vals) == len(st_vals_for_this_fun)
|
105
|
-
|
106
|
-
if return_states:
|
107
|
-
# get all written state values
|
108
|
-
new_state_vals = {id(st): val for st, val in zip(stateful_fun.get_states(), new_state_vals)}
|
109
|
-
write_state_vals = tuple([
|
110
|
-
(new_state_vals[id(st)] if id(st) in state_ids_belong_to_this_fun else w_val)
|
111
|
-
if write else None
|
112
|
-
for write, st, w_val in zip(merged_state_trace.been_writen,
|
113
|
-
merged_state_trace.states,
|
114
|
-
write_state_vals)
|
115
|
-
])
|
116
|
-
return write_state_vals, out
|
117
|
-
return out
|
118
|
-
|
119
|
-
return wrapped_branch
|
120
|
-
|
121
|
-
|
122
|
-
def wrap_single_fun(
|
123
|
-
stateful_fun: StatefulFunction,
|
124
|
-
been_writen: Tuple[bool],
|
125
|
-
read_state_vals: Tuple[PyTree | None],
|
126
|
-
):
|
127
|
-
@wraps(stateful_fun.fun)
|
128
|
-
def wrapped_fun(new_carry, inputs):
|
129
|
-
writen_state_vals, carry = new_carry
|
130
|
-
assert len(been_writen) == len(writen_state_vals) == len(read_state_vals)
|
131
|
-
|
132
|
-
# collect all written and read states
|
133
|
-
state_vals = [
|
134
|
-
written_val if written else read_val
|
135
|
-
for written, written_val, read_val in zip(been_writen, writen_state_vals, read_state_vals)
|
136
|
-
]
|
137
|
-
|
138
|
-
# call the jaxpr
|
139
|
-
state_vals, (carry, out) = stateful_fun.jaxpr_call(state_vals, carry, inputs)
|
140
|
-
|
141
|
-
# only return the written states
|
142
|
-
writen_state_vals = tuple([val if written else None for written, val in zip(been_writen, state_vals)])
|
143
|
-
|
144
|
-
# return
|
145
|
-
return (writen_state_vals, carry), out
|
146
|
-
|
147
|
-
return wrapped_fun
|
@@ -1,27 +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 brainstate.nn._activations import *
|
17
|
-
from brainstate.nn._activations import __all__ as act_all
|
18
|
-
from brainstate.nn._normalizations import weight_standardization
|
19
|
-
from brainstate.nn._others import clip_grad_norm
|
20
|
-
|
21
|
-
__all__ = ['weight_standardization', 'clip_grad_norm'] + act_all
|
22
|
-
del act_all
|
23
|
-
|
24
|
-
if __name__ == '__main__':
|
25
|
-
relu
|
26
|
-
clip_grad_norm
|
27
|
-
weight_standardization
|
brainstate/graph/_graph_node.py
DELETED
@@ -1,244 +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.
|
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 +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
|
-
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)
|