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.
Files changed (133) hide show
  1. brainstate/__init__.py +58 -51
  2. brainstate/_compatible_import.py +148 -148
  3. brainstate/_state.py +1605 -1663
  4. brainstate/_state_test.py +52 -52
  5. brainstate/_utils.py +47 -47
  6. brainstate/augment/__init__.py +30 -30
  7. brainstate/augment/_autograd.py +778 -778
  8. brainstate/augment/_autograd_test.py +1289 -1289
  9. brainstate/augment/_eval_shape.py +99 -99
  10. brainstate/augment/_eval_shape_test.py +38 -38
  11. brainstate/augment/_mapping.py +1060 -1060
  12. brainstate/augment/_mapping_test.py +597 -597
  13. brainstate/augment/_random.py +151 -151
  14. brainstate/compile/__init__.py +38 -38
  15. brainstate/compile/_ad_checkpoint.py +204 -204
  16. brainstate/compile/_ad_checkpoint_test.py +49 -49
  17. brainstate/compile/_conditions.py +256 -256
  18. brainstate/compile/_conditions_test.py +220 -220
  19. brainstate/compile/_error_if.py +92 -92
  20. brainstate/compile/_error_if_test.py +52 -52
  21. brainstate/compile/_jit.py +346 -346
  22. brainstate/compile/_jit_test.py +143 -143
  23. brainstate/compile/_loop_collect_return.py +536 -536
  24. brainstate/compile/_loop_collect_return_test.py +58 -58
  25. brainstate/compile/_loop_no_collection.py +184 -184
  26. brainstate/compile/_loop_no_collection_test.py +50 -50
  27. brainstate/compile/_make_jaxpr.py +888 -888
  28. brainstate/compile/_make_jaxpr_test.py +156 -156
  29. brainstate/compile/_progress_bar.py +202 -202
  30. brainstate/compile/_unvmap.py +159 -159
  31. brainstate/compile/_util.py +147 -147
  32. brainstate/environ.py +563 -563
  33. brainstate/environ_test.py +62 -62
  34. brainstate/functional/__init__.py +27 -26
  35. brainstate/graph/__init__.py +29 -29
  36. brainstate/graph/_graph_node.py +244 -244
  37. brainstate/graph/_graph_node_test.py +73 -73
  38. brainstate/graph/_graph_operation.py +1738 -1738
  39. brainstate/graph/_graph_operation_test.py +563 -563
  40. brainstate/init/__init__.py +26 -26
  41. brainstate/init/_base.py +52 -52
  42. brainstate/init/_generic.py +244 -244
  43. brainstate/init/_random_inits.py +553 -553
  44. brainstate/init/_random_inits_test.py +149 -149
  45. brainstate/init/_regular_inits.py +105 -105
  46. brainstate/init/_regular_inits_test.py +50 -50
  47. brainstate/mixin.py +365 -363
  48. brainstate/mixin_test.py +77 -73
  49. brainstate/nn/__init__.py +135 -131
  50. brainstate/{functional → nn}/_activations.py +808 -813
  51. brainstate/{functional → nn}/_activations_test.py +331 -331
  52. brainstate/nn/_collective_ops.py +514 -514
  53. brainstate/nn/_collective_ops_test.py +43 -43
  54. brainstate/nn/_common.py +178 -178
  55. brainstate/nn/_conv.py +501 -501
  56. brainstate/nn/_conv_test.py +238 -238
  57. brainstate/nn/_delay.py +588 -502
  58. brainstate/nn/_delay_test.py +238 -184
  59. brainstate/nn/_dropout.py +426 -426
  60. brainstate/nn/_dropout_test.py +100 -100
  61. brainstate/nn/_dynamics.py +1343 -1343
  62. brainstate/nn/_dynamics_test.py +78 -78
  63. brainstate/nn/_elementwise.py +1119 -1119
  64. brainstate/nn/_elementwise_test.py +169 -169
  65. brainstate/nn/_embedding.py +58 -58
  66. brainstate/nn/_exp_euler.py +92 -92
  67. brainstate/nn/_exp_euler_test.py +35 -35
  68. brainstate/nn/_fixedprob.py +239 -239
  69. brainstate/nn/_fixedprob_test.py +114 -114
  70. brainstate/nn/_inputs.py +608 -608
  71. brainstate/nn/_linear.py +424 -424
  72. brainstate/nn/_linear_mv.py +83 -83
  73. brainstate/nn/_linear_mv_test.py +120 -120
  74. brainstate/nn/_linear_test.py +107 -107
  75. brainstate/nn/_ltp.py +28 -28
  76. brainstate/nn/_module.py +377 -377
  77. brainstate/nn/_module_test.py +40 -40
  78. brainstate/nn/_neuron.py +705 -705
  79. brainstate/nn/_neuron_test.py +161 -161
  80. brainstate/nn/_normalizations.py +975 -918
  81. brainstate/nn/_normalizations_test.py +73 -73
  82. brainstate/{functional → nn}/_others.py +46 -46
  83. brainstate/nn/_poolings.py +1177 -1177
  84. brainstate/nn/_poolings_test.py +217 -217
  85. brainstate/nn/_projection.py +486 -486
  86. brainstate/nn/_rate_rnns.py +554 -554
  87. brainstate/nn/_rate_rnns_test.py +63 -63
  88. brainstate/nn/_readout.py +209 -209
  89. brainstate/nn/_readout_test.py +53 -53
  90. brainstate/nn/_stp.py +236 -236
  91. brainstate/nn/_synapse.py +505 -505
  92. brainstate/nn/_synapse_test.py +131 -131
  93. brainstate/nn/_synaptic_projection.py +423 -423
  94. brainstate/nn/_synouts.py +162 -162
  95. brainstate/nn/_synouts_test.py +57 -57
  96. brainstate/nn/_utils.py +89 -89
  97. brainstate/nn/metrics.py +388 -388
  98. brainstate/optim/__init__.py +38 -38
  99. brainstate/optim/_base.py +64 -64
  100. brainstate/optim/_lr_scheduler.py +448 -448
  101. brainstate/optim/_lr_scheduler_test.py +50 -50
  102. brainstate/optim/_optax_optimizer.py +152 -152
  103. brainstate/optim/_optax_optimizer_test.py +53 -53
  104. brainstate/optim/_sgd_optimizer.py +1104 -1104
  105. brainstate/random/__init__.py +24 -24
  106. brainstate/random/_rand_funs.py +3616 -3616
  107. brainstate/random/_rand_funs_test.py +567 -567
  108. brainstate/random/_rand_seed.py +210 -210
  109. brainstate/random/_rand_seed_test.py +48 -48
  110. brainstate/random/_rand_state.py +1409 -1409
  111. brainstate/random/_random_for_unit.py +52 -52
  112. brainstate/surrogate.py +1957 -1957
  113. brainstate/transform.py +23 -23
  114. brainstate/typing.py +304 -304
  115. brainstate/util/__init__.py +50 -50
  116. brainstate/util/caller.py +98 -98
  117. brainstate/util/error.py +55 -55
  118. brainstate/util/filter.py +469 -469
  119. brainstate/util/others.py +540 -540
  120. brainstate/util/pretty_pytree.py +945 -945
  121. brainstate/util/pretty_pytree_test.py +159 -159
  122. brainstate/util/pretty_repr.py +328 -328
  123. brainstate/util/pretty_table.py +2954 -2954
  124. brainstate/util/scaling.py +258 -258
  125. brainstate/util/struct.py +523 -523
  126. {brainstate-0.1.8.dist-info → brainstate-0.1.10.dist-info}/METADATA +91 -99
  127. brainstate-0.1.10.dist-info/RECORD +130 -0
  128. {brainstate-0.1.8.dist-info → brainstate-0.1.10.dist-info}/WHEEL +1 -1
  129. {brainstate-0.1.8.dist-info → brainstate-0.1.10.dist-info/licenses}/LICENSE +202 -202
  130. brainstate/functional/_normalization.py +0 -81
  131. brainstate/functional/_spikes.py +0 -204
  132. brainstate-0.1.8.dist-info/RECORD +0 -132
  133. {brainstate-0.1.8.dist-info → brainstate-0.1.10.dist-info}/top_level.txt +0 -0
@@ -1,563 +1,563 @@
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
- from collections.abc import Callable
18
- from threading import Thread
19
-
20
- import jax
21
- import jax.numpy as jnp
22
- from absl.testing import absltest, parameterized
23
-
24
- import brainstate
25
-
26
-
27
- class TestIter(unittest.TestCase):
28
- def test1(self):
29
- class Model(brainstate.nn.Module):
30
- def __init__(self):
31
- super().__init__()
32
- self.a = brainstate.nn.Linear(1, 2)
33
- self.b = brainstate.nn.Linear(2, 3)
34
- self.c = [brainstate.nn.Linear(3, 4), brainstate.nn.Linear(4, 5)]
35
- self.d = {'x': brainstate.nn.Linear(5, 6), 'y': brainstate.nn.Linear(6, 7)}
36
- self.b.a = brainstate.nn.LIF(2)
37
-
38
- for path, node in brainstate.graph.iter_leaf(Model()):
39
- print(path, node)
40
- for path, node in brainstate.graph.iter_node(Model()):
41
- print(path, node)
42
- for path, node in brainstate.graph.iter_node(Model(), allowed_hierarchy=(1, 1)):
43
- print(path, node)
44
- for path, node in brainstate.graph.iter_node(Model(), allowed_hierarchy=(2, 2)):
45
- print(path, node)
46
-
47
- def test_iter_leaf_v1(self):
48
- class Linear(brainstate.nn.Module):
49
- def __init__(self, din, dout):
50
- super().__init__()
51
- self.weight = brainstate.ParamState(brainstate.random.randn(din, dout))
52
- self.bias = brainstate.ParamState(brainstate.random.randn(dout))
53
- self.a = 1
54
-
55
- module = Linear(3, 4)
56
- graph = [module, module]
57
-
58
- num = 0
59
- for path, value in brainstate.graph.iter_leaf(graph):
60
- print(path, type(value).__name__)
61
- num += 1
62
-
63
- assert num == 3
64
-
65
- def test_iter_node_v1(self):
66
- class Model(brainstate.nn.Module):
67
- def __init__(self):
68
- super().__init__()
69
- self.a = brainstate.nn.Linear(1, 2)
70
- self.b = brainstate.nn.Linear(2, 3)
71
- self.c = [brainstate.nn.Linear(3, 4), brainstate.nn.Linear(4, 5)]
72
- self.d = {'x': brainstate.nn.Linear(5, 6), 'y': brainstate.nn.Linear(6, 7)}
73
- self.b.a = brainstate.nn.LIF(2)
74
-
75
- model = Model()
76
-
77
- num = 0
78
- for path, node in brainstate.graph.iter_node([model, model]):
79
- print(path, node.__class__.__name__)
80
- num += 1
81
- assert num == 8
82
-
83
-
84
- class List(brainstate.nn.Module):
85
- def __init__(self, items):
86
- super().__init__()
87
- self.items = list(items)
88
-
89
- def __getitem__(self, idx):
90
- return self.items[idx]
91
-
92
- def __setitem__(self, idx, value):
93
- self.items[idx] = value
94
-
95
-
96
- class Dict(brainstate.nn.Module):
97
- def __init__(self, *args, **kwargs):
98
- super().__init__()
99
- self.items = dict(*args, **kwargs)
100
-
101
- def __getitem__(self, key):
102
- return self.items[key]
103
-
104
- def __setitem__(self, key, value):
105
- self.items[key] = value
106
-
107
-
108
- class StatefulLinear(brainstate.nn.Module):
109
- def __init__(self, din, dout):
110
- super().__init__()
111
- self.w = brainstate.ParamState(brainstate.random.rand(din, dout))
112
- self.b = brainstate.ParamState(jnp.zeros((dout,)))
113
- self.count = brainstate.State(jnp.array(0, dtype=jnp.uint32))
114
-
115
- def increment(self):
116
- self.count.value += 1
117
-
118
- def __call__(self, x):
119
- self.count.value += 1
120
- return x @ self.w.value + self.b.value
121
-
122
-
123
- class TestGraphUtils(absltest.TestCase):
124
- def test_flatten_treey_state(self):
125
- a = {'a': 1, 'b': brainstate.ParamState(2)}
126
- g = [a, 3, a, brainstate.ParamState(4)]
127
-
128
- refmap = brainstate.graph.RefMap()
129
- graphdef, states = brainstate.graph.flatten(g, ref_index=refmap, treefy_state=True)
130
-
131
- states[0]['b'].value = 2
132
- states[3].value = 4
133
-
134
- assert isinstance(states[0]['b'], brainstate.TreefyState)
135
- assert isinstance(states[3], brainstate.TreefyState)
136
- assert isinstance(states, brainstate.util.NestedDict)
137
- assert len(refmap) == 2
138
- assert a['b'] in refmap
139
- assert g[3] in refmap
140
-
141
- def test_flatten(self):
142
- a = {'a': 1, 'b': brainstate.ParamState(2)}
143
- g = [a, 3, a, brainstate.ParamState(4)]
144
-
145
- refmap = brainstate.graph.RefMap()
146
- graphdef, states = brainstate.graph.flatten(g, ref_index=refmap, treefy_state=False)
147
-
148
- states[0]['b'].value = 2
149
- states[3].value = 4
150
-
151
- assert isinstance(states[0]['b'], brainstate.State)
152
- assert isinstance(states[3], brainstate.State)
153
- assert len(refmap) == 2
154
- assert a['b'] in refmap
155
- assert g[3] in refmap
156
-
157
- def test_unflatten_treey_state(self):
158
- a = brainstate.graph.Dict(a=1, b=brainstate.ParamState(2))
159
- g1 = brainstate.graph.List([a, 3, a, brainstate.ParamState(4)])
160
-
161
- graphdef, references = brainstate.graph.flatten(g1, treefy_state=True)
162
- g = brainstate.graph.unflatten(graphdef, references)
163
-
164
- print(graphdef)
165
- print(references)
166
- assert g[0] is g[2]
167
- assert g1[3] is not g[3]
168
- assert g1[0]['b'] is not g[0]['b']
169
-
170
- def test_unflatten(self):
171
- a = brainstate.graph.Dict(a=1, b=brainstate.ParamState(2))
172
- g1 = brainstate.graph.List([a, 3, a, brainstate.ParamState(4)])
173
-
174
- graphdef, references = brainstate.graph.flatten(g1, treefy_state=False)
175
- g = brainstate.graph.unflatten(graphdef, references)
176
-
177
- print(graphdef)
178
- print(references)
179
- assert g[0] is g[2]
180
- assert g1[3] is g[3]
181
- assert g1[0]['b'] is g[0]['b']
182
-
183
- def test_unflatten_pytree(self):
184
- a = {'a': 1, 'b': brainstate.ParamState(2)}
185
- g = [a, 3, a, brainstate.ParamState(4)]
186
-
187
- graphdef, references = brainstate.graph.treefy_split(g)
188
- g = brainstate.graph.treefy_merge(graphdef, references)
189
-
190
- assert g[0] is not g[2]
191
-
192
- def test_unflatten_empty(self):
193
- a = Dict({'a': 1, 'b': brainstate.ParamState(2)})
194
- g = List([a, 3, a, brainstate.ParamState(4)])
195
-
196
- graphdef, references = brainstate.graph.treefy_split(g)
197
-
198
- with self.assertRaisesRegex(ValueError, 'Expected key'):
199
- brainstate.graph.unflatten(graphdef, brainstate.util.NestedDict({}))
200
-
201
- def test_module_list(self):
202
- ls = [
203
- brainstate.nn.Linear(2, 2),
204
- brainstate.nn.BatchNorm1d([10, 2]),
205
- ]
206
- graphdef, statetree = brainstate.graph.treefy_split(ls)
207
-
208
- assert statetree[0]['weight'].value['weight'].shape == (2, 2)
209
- assert statetree[0]['weight'].value['bias'].shape == (2,)
210
- assert statetree[1]['weight'].value['scale'].shape == (1, 2,)
211
- assert statetree[1]['weight'].value['bias'].shape == (1, 2,)
212
- assert statetree[1]['running_mean'].value.shape == (1, 2,)
213
- assert statetree[1]['running_var'].value.shape == (1, 2)
214
-
215
- def test_shared_variables(self):
216
- v = brainstate.ParamState(1)
217
- g = [v, v]
218
-
219
- graphdef, statetree = brainstate.graph.treefy_split(g)
220
- assert len(statetree.to_flat()) == 1
221
-
222
- g2 = brainstate.graph.treefy_merge(graphdef, statetree)
223
- assert g2[0] is g2[1]
224
-
225
- def test_tied_weights(self):
226
- class Foo(brainstate.nn.Module):
227
- def __init__(self) -> None:
228
- super().__init__()
229
- self.bar = brainstate.nn.Linear(2, 2)
230
- self.baz = brainstate.nn.Linear(2, 2)
231
-
232
- # tie the weights
233
- self.baz.weight = self.bar.weight
234
-
235
- node = Foo()
236
- graphdef, state = brainstate.graph.treefy_split(node)
237
-
238
- assert len(state.to_flat()) == 1
239
-
240
- node2 = brainstate.graph.treefy_merge(graphdef, state)
241
-
242
- assert node2.bar.weight is node2.baz.weight
243
-
244
- def test_tied_weights_example(self):
245
- class LinearTranspose(brainstate.nn.Module):
246
- def __init__(self, dout: int, din: int, ) -> None:
247
- super().__init__()
248
- self.kernel = brainstate.ParamState(brainstate.init.LecunNormal()((dout, din)))
249
-
250
- def __call__(self, x):
251
- return x @ self.kernel.value.T
252
-
253
- class Encoder(brainstate.nn.Module):
254
- def __init__(self, ) -> None:
255
- super().__init__()
256
- self.embed = brainstate.nn.Embedding(10, 2)
257
- self.linear_out = LinearTranspose(10, 2)
258
-
259
- # tie the weights
260
- self.linear_out.kernel = self.embed.weight
261
-
262
- def __call__(self, x):
263
- x = self.embed(x)
264
- return self.linear_out(x)
265
-
266
- model = Encoder()
267
- graphdef, state = brainstate.graph.treefy_split(model)
268
-
269
- assert len(state.to_flat()) == 1
270
-
271
- x = jax.random.randint(jax.random.key(0), (2,), 0, 10)
272
- y = model(x)
273
-
274
- assert y.shape == (2, 10)
275
-
276
- def test_state_variables_not_shared_with_graph(self):
277
- class Foo(brainstate.graph.Node):
278
- def __init__(self):
279
- self.a = brainstate.ParamState(1)
280
-
281
- m = Foo()
282
- graphdef, statetree = brainstate.graph.treefy_split(m)
283
-
284
- assert isinstance(m.a, brainstate.ParamState)
285
- assert issubclass(statetree.a.type, brainstate.ParamState)
286
- assert m.a is not statetree.a
287
- assert m.a.value == statetree.a.value
288
-
289
- m2 = brainstate.graph.treefy_merge(graphdef, statetree)
290
-
291
- assert isinstance(m2.a, brainstate.ParamState)
292
- assert issubclass(statetree.a.type, brainstate.ParamState)
293
- assert m2.a is not statetree.a
294
- assert m2.a.value == statetree.a.value
295
-
296
- def test_shared_state_variables_not_shared_with_graph(self):
297
- class Foo(brainstate.graph.Node):
298
- def __init__(self):
299
- p = brainstate.ParamState(1)
300
- self.a = p
301
- self.b = p
302
-
303
- m = Foo()
304
- graphdef, state = brainstate.graph.treefy_split(m)
305
-
306
- assert isinstance(m.a, brainstate.ParamState)
307
- assert isinstance(m.b, brainstate.ParamState)
308
- assert issubclass(state.a.type, brainstate.ParamState)
309
- assert 'b' not in state
310
- assert m.a is not state.a
311
- assert m.b is not state.a
312
- assert m.a.value == state.a.value
313
- assert m.b.value == state.a.value
314
-
315
- m2 = brainstate.graph.treefy_merge(graphdef, state)
316
-
317
- assert isinstance(m2.a, brainstate.ParamState)
318
- assert isinstance(m2.b, brainstate.ParamState)
319
- assert issubclass(state.a.type, brainstate.ParamState)
320
- assert m2.a is not state.a
321
- assert m2.b is not state.a
322
- assert m2.a.value == state.a.value
323
- assert m2.b.value == state.a.value
324
- assert m2.a is m2.b
325
-
326
- def test_pytree_node(self):
327
- @brainstate.util.dataclass
328
- class Tree:
329
- a: brainstate.ParamState
330
- b: str = brainstate.util.field(pytree_node=False)
331
-
332
- class Foo(brainstate.graph.Node):
333
- def __init__(self):
334
- self.tree = Tree(brainstate.ParamState(1), 'a')
335
-
336
- m = Foo()
337
-
338
- graphdef, state = brainstate.graph.treefy_split(m)
339
-
340
- assert 'tree' in state
341
- assert 'a' in state.tree
342
- assert graphdef.subgraphs['tree'].type.__name__ == 'PytreeType'
343
-
344
- m2 = brainstate.graph.treefy_merge(graphdef, state)
345
-
346
- assert isinstance(m2.tree, Tree)
347
- assert m2.tree.a.value == 1
348
- assert m2.tree.b == 'a'
349
- assert m2.tree.a is not m.tree.a
350
- assert m2.tree is not m.tree
351
-
352
- def test_call_jit_update(self):
353
- class Counter(brainstate.graph.Node):
354
- def __init__(self):
355
- self.count = brainstate.ParamState(jnp.zeros(()))
356
-
357
- def inc(self):
358
- self.count.value += 1
359
- return 1
360
-
361
- graph_state = brainstate.graph.treefy_split(Counter())
362
-
363
- @jax.jit
364
- def update(graph_state):
365
- out, graph_state = brainstate.graph.call(graph_state).inc()
366
- self.assertEqual(out, 1)
367
- return graph_state
368
-
369
- graph_state = update(graph_state)
370
- graph_state = update(graph_state)
371
-
372
- counter = brainstate.graph.treefy_merge(*graph_state)
373
-
374
- self.assertEqual(counter.count.value, 2)
375
-
376
- def test_stateful_linear(self):
377
- linear = StatefulLinear(3, 2)
378
- linear_state = brainstate.graph.treefy_split(linear)
379
-
380
- @jax.jit
381
- def forward(x, pure_linear):
382
- y, pure_linear = brainstate.graph.call(pure_linear)(x)
383
- return y, pure_linear
384
-
385
- x = jnp.ones((1, 3))
386
- y, linear_state = forward(x, linear_state)
387
- y, linear_state = forward(x, linear_state)
388
-
389
- self.assertEqual(linear.count.value, 0)
390
- new_linear = brainstate.graph.treefy_merge(*linear_state)
391
- self.assertEqual(new_linear.count.value, 2)
392
-
393
- def test_getitem(self):
394
- nodes = dict(
395
- a=StatefulLinear(3, 2),
396
- b=StatefulLinear(2, 1),
397
- )
398
- node_state = brainstate.graph.treefy_split(nodes)
399
- _, node_state = brainstate.graph.call(node_state)['b'].increment()
400
-
401
- nodes = brainstate.graph.treefy_merge(*node_state)
402
-
403
- self.assertEqual(nodes['a'].count.value, 0)
404
- self.assertEqual(nodes['b'].count.value, 1)
405
-
406
-
407
- class SimpleModule(brainstate.nn.Module):
408
- pass
409
-
410
-
411
- class SimplePyTreeModule(brainstate.nn.Module):
412
- pass
413
-
414
-
415
- class TestThreading(parameterized.TestCase):
416
-
417
- @parameterized.parameters(
418
- (SimpleModule,),
419
- (SimplePyTreeModule,),
420
- )
421
- def test_threading(self, module_fn: Callable[[], brainstate.nn.Module]):
422
- x = module_fn()
423
-
424
- class MyThread(Thread):
425
-
426
- def run(self) -> None:
427
- brainstate.graph.treefy_split(x)
428
-
429
- thread = MyThread()
430
- thread.start()
431
- thread.join()
432
-
433
-
434
- class TestGraphOperation(unittest.TestCase):
435
- def test1(self):
436
- class MyNode(brainstate.graph.Node):
437
- def __init__(self):
438
- self.a = brainstate.nn.Linear(2, 3)
439
- self.b = brainstate.nn.Linear(3, 2)
440
- self.c = [brainstate.nn.Linear(1, 2), brainstate.nn.Linear(1, 3)]
441
- self.d = {'x': brainstate.nn.Linear(1, 3), 'y': brainstate.nn.Linear(1, 4)}
442
-
443
- graphdef, statetree = brainstate.graph.flatten(MyNode())
444
- # print(graphdef)
445
- print(statetree)
446
- # print(brainstate.graph.unflatten(graphdef, statetree))
447
-
448
- def test_split(self):
449
- class Foo(brainstate.graph.Node):
450
- def __init__(self):
451
- self.a = brainstate.nn.Linear(2, 2)
452
- self.b = brainstate.nn.BatchNorm1d([10, 2])
453
-
454
- node = Foo()
455
- graphdef, params, others = brainstate.graph.treefy_split(node, brainstate.ParamState, ...)
456
-
457
- print(params)
458
- print(jax.tree.map(jnp.shape, params))
459
-
460
- print(jax.tree.map(jnp.shape, others))
461
-
462
- def test_merge(self):
463
- class Foo(brainstate.graph.Node):
464
- def __init__(self):
465
- self.a = brainstate.nn.Linear(2, 2)
466
- self.b = brainstate.nn.BatchNorm1d([10, 2])
467
-
468
- node = Foo()
469
- graphdef, params, others = brainstate.graph.treefy_split(node, brainstate.ParamState, ...)
470
-
471
- new_node = brainstate.graph.treefy_merge(graphdef, params, others)
472
-
473
- assert isinstance(new_node, Foo)
474
- assert isinstance(new_node.b, brainstate.nn.BatchNorm1d)
475
- assert isinstance(new_node.a, brainstate.nn.Linear)
476
-
477
- def test_update_states(self):
478
- x = jnp.ones((1, 2))
479
- y = jnp.ones((1, 3))
480
- model = brainstate.nn.Linear(2, 3)
481
-
482
- def loss_fn(x, y):
483
- return jnp.mean((y - model(x)) ** 2)
484
-
485
- def sgd(ps, gs):
486
- updates = jax.tree.map(lambda p, g: p - 0.1 * g, ps.value, gs)
487
- ps.value = updates
488
-
489
- prev_loss = loss_fn(x, y)
490
- weights = model.states()
491
- grads = brainstate.augment.grad(loss_fn, weights)(x, y)
492
- for key, val in grads.items():
493
- sgd(weights[key], val)
494
- assert loss_fn(x, y) < prev_loss
495
-
496
- def test_pop_states(self):
497
- class Model(brainstate.nn.Module):
498
- def __init__(self):
499
- super().__init__()
500
- self.a = brainstate.nn.Linear(2, 3)
501
- self.b = brainstate.nn.LIF([10, 2])
502
-
503
- model = Model()
504
- with brainstate.catch_new_states('new'):
505
- brainstate.nn.init_all_states(model)
506
- # print(model.states())
507
- self.assertTrue(len(model.states()) == 2)
508
- model_states = brainstate.graph.pop_states(model, 'new')
509
- print(model_states)
510
- self.assertTrue(len(model.states()) == 1)
511
- assert not hasattr(model.b, 'V')
512
- # print(model.states())
513
-
514
- def test_treefy_split(self):
515
- class MLP(brainstate.graph.Node):
516
- def __init__(self, din: int, dmid: int, dout: int, n_layer: int = 3):
517
- self.input = brainstate.nn.Linear(din, dmid)
518
- self.layers = [brainstate.nn.Linear(dmid, dmid) for _ in range(n_layer)]
519
- self.output = brainstate.nn.Linear(dmid, dout)
520
-
521
- def __call__(self, x):
522
- x = brainstate.functional.relu(self.input(x))
523
- for layer in self.layers:
524
- x = brainstate.functional.relu(layer(x))
525
- return self.output(x)
526
-
527
- model = MLP(2, 1, 3)
528
- graph_def, treefy_states = brainstate.graph.treefy_split(model)
529
-
530
- print(graph_def)
531
- print(treefy_states)
532
-
533
- # states = brainstate.graph.states(model)
534
- # print(states)
535
- # nest_states = states.to_nest()
536
- # print(nest_states)
537
-
538
- def test_states(self):
539
- class MLP(brainstate.graph.Node):
540
- def __init__(self, din: int, dmid: int, dout: int, n_layer: int = 3):
541
- self.input = brainstate.nn.Linear(din, dmid)
542
- self.layers = [brainstate.nn.Linear(dmid, dmid) for _ in range(n_layer)]
543
- self.output = brainstate.nn.LIF(dout)
544
-
545
- def __call__(self, x):
546
- x = brainstate.functional.relu(self.input(x))
547
- for layer in self.layers:
548
- x = brainstate.functional.relu(layer(x))
549
- return self.output(x)
550
-
551
- model = brainstate.nn.init_all_states(MLP(2, 1, 3))
552
- states = brainstate.graph.states(model)
553
- print(states)
554
- nest_states = states.to_nest()
555
- print(nest_states)
556
-
557
- params, others = brainstate.graph.states(model, brainstate.ParamState, brainstate.ShortTermState)
558
- print(params)
559
- print(others)
560
-
561
-
562
- if __name__ == '__main__':
563
- absltest.main()
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
+ from collections.abc import Callable
18
+ from threading import Thread
19
+
20
+ import jax
21
+ import jax.numpy as jnp
22
+ from absl.testing import absltest, parameterized
23
+
24
+ import brainstate
25
+
26
+
27
+ class TestIter(unittest.TestCase):
28
+ def test1(self):
29
+ class Model(brainstate.nn.Module):
30
+ def __init__(self):
31
+ super().__init__()
32
+ self.a = brainstate.nn.Linear(1, 2)
33
+ self.b = brainstate.nn.Linear(2, 3)
34
+ self.c = [brainstate.nn.Linear(3, 4), brainstate.nn.Linear(4, 5)]
35
+ self.d = {'x': brainstate.nn.Linear(5, 6), 'y': brainstate.nn.Linear(6, 7)}
36
+ self.b.a = brainstate.nn.LIF(2)
37
+
38
+ for path, node in brainstate.graph.iter_leaf(Model()):
39
+ print(path, node)
40
+ for path, node in brainstate.graph.iter_node(Model()):
41
+ print(path, node)
42
+ for path, node in brainstate.graph.iter_node(Model(), allowed_hierarchy=(1, 1)):
43
+ print(path, node)
44
+ for path, node in brainstate.graph.iter_node(Model(), allowed_hierarchy=(2, 2)):
45
+ print(path, node)
46
+
47
+ def test_iter_leaf_v1(self):
48
+ class Linear(brainstate.nn.Module):
49
+ def __init__(self, din, dout):
50
+ super().__init__()
51
+ self.weight = brainstate.ParamState(brainstate.random.randn(din, dout))
52
+ self.bias = brainstate.ParamState(brainstate.random.randn(dout))
53
+ self.a = 1
54
+
55
+ module = Linear(3, 4)
56
+ graph = [module, module]
57
+
58
+ num = 0
59
+ for path, value in brainstate.graph.iter_leaf(graph):
60
+ print(path, type(value).__name__)
61
+ num += 1
62
+
63
+ assert num == 3
64
+
65
+ def test_iter_node_v1(self):
66
+ class Model(brainstate.nn.Module):
67
+ def __init__(self):
68
+ super().__init__()
69
+ self.a = brainstate.nn.Linear(1, 2)
70
+ self.b = brainstate.nn.Linear(2, 3)
71
+ self.c = [brainstate.nn.Linear(3, 4), brainstate.nn.Linear(4, 5)]
72
+ self.d = {'x': brainstate.nn.Linear(5, 6), 'y': brainstate.nn.Linear(6, 7)}
73
+ self.b.a = brainstate.nn.LIF(2)
74
+
75
+ model = Model()
76
+
77
+ num = 0
78
+ for path, node in brainstate.graph.iter_node([model, model]):
79
+ print(path, node.__class__.__name__)
80
+ num += 1
81
+ assert num == 8
82
+
83
+
84
+ class List(brainstate.nn.Module):
85
+ def __init__(self, items):
86
+ super().__init__()
87
+ self.items = list(items)
88
+
89
+ def __getitem__(self, idx):
90
+ return self.items[idx]
91
+
92
+ def __setitem__(self, idx, value):
93
+ self.items[idx] = value
94
+
95
+
96
+ class Dict(brainstate.nn.Module):
97
+ def __init__(self, *args, **kwargs):
98
+ super().__init__()
99
+ self.items = dict(*args, **kwargs)
100
+
101
+ def __getitem__(self, key):
102
+ return self.items[key]
103
+
104
+ def __setitem__(self, key, value):
105
+ self.items[key] = value
106
+
107
+
108
+ class StatefulLinear(brainstate.nn.Module):
109
+ def __init__(self, din, dout):
110
+ super().__init__()
111
+ self.w = brainstate.ParamState(brainstate.random.rand(din, dout))
112
+ self.b = brainstate.ParamState(jnp.zeros((dout,)))
113
+ self.count = brainstate.State(jnp.array(0, dtype=jnp.uint32))
114
+
115
+ def increment(self):
116
+ self.count.value += 1
117
+
118
+ def __call__(self, x):
119
+ self.count.value += 1
120
+ return x @ self.w.value + self.b.value
121
+
122
+
123
+ class TestGraphUtils(absltest.TestCase):
124
+ def test_flatten_treey_state(self):
125
+ a = {'a': 1, 'b': brainstate.ParamState(2)}
126
+ g = [a, 3, a, brainstate.ParamState(4)]
127
+
128
+ refmap = brainstate.graph.RefMap()
129
+ graphdef, states = brainstate.graph.flatten(g, ref_index=refmap, treefy_state=True)
130
+
131
+ states[0]['b'].value = 2
132
+ states[3].value = 4
133
+
134
+ assert isinstance(states[0]['b'], brainstate.TreefyState)
135
+ assert isinstance(states[3], brainstate.TreefyState)
136
+ assert isinstance(states, brainstate.util.NestedDict)
137
+ assert len(refmap) == 2
138
+ assert a['b'] in refmap
139
+ assert g[3] in refmap
140
+
141
+ def test_flatten(self):
142
+ a = {'a': 1, 'b': brainstate.ParamState(2)}
143
+ g = [a, 3, a, brainstate.ParamState(4)]
144
+
145
+ refmap = brainstate.graph.RefMap()
146
+ graphdef, states = brainstate.graph.flatten(g, ref_index=refmap, treefy_state=False)
147
+
148
+ states[0]['b'].value = 2
149
+ states[3].value = 4
150
+
151
+ assert isinstance(states[0]['b'], brainstate.State)
152
+ assert isinstance(states[3], brainstate.State)
153
+ assert len(refmap) == 2
154
+ assert a['b'] in refmap
155
+ assert g[3] in refmap
156
+
157
+ def test_unflatten_treey_state(self):
158
+ a = brainstate.graph.Dict(a=1, b=brainstate.ParamState(2))
159
+ g1 = brainstate.graph.List([a, 3, a, brainstate.ParamState(4)])
160
+
161
+ graphdef, references = brainstate.graph.flatten(g1, treefy_state=True)
162
+ g = brainstate.graph.unflatten(graphdef, references)
163
+
164
+ print(graphdef)
165
+ print(references)
166
+ assert g[0] is g[2]
167
+ assert g1[3] is not g[3]
168
+ assert g1[0]['b'] is not g[0]['b']
169
+
170
+ def test_unflatten(self):
171
+ a = brainstate.graph.Dict(a=1, b=brainstate.ParamState(2))
172
+ g1 = brainstate.graph.List([a, 3, a, brainstate.ParamState(4)])
173
+
174
+ graphdef, references = brainstate.graph.flatten(g1, treefy_state=False)
175
+ g = brainstate.graph.unflatten(graphdef, references)
176
+
177
+ print(graphdef)
178
+ print(references)
179
+ assert g[0] is g[2]
180
+ assert g1[3] is g[3]
181
+ assert g1[0]['b'] is g[0]['b']
182
+
183
+ def test_unflatten_pytree(self):
184
+ a = {'a': 1, 'b': brainstate.ParamState(2)}
185
+ g = [a, 3, a, brainstate.ParamState(4)]
186
+
187
+ graphdef, references = brainstate.graph.treefy_split(g)
188
+ g = brainstate.graph.treefy_merge(graphdef, references)
189
+
190
+ assert g[0] is not g[2]
191
+
192
+ def test_unflatten_empty(self):
193
+ a = Dict({'a': 1, 'b': brainstate.ParamState(2)})
194
+ g = List([a, 3, a, brainstate.ParamState(4)])
195
+
196
+ graphdef, references = brainstate.graph.treefy_split(g)
197
+
198
+ with self.assertRaisesRegex(ValueError, 'Expected key'):
199
+ brainstate.graph.unflatten(graphdef, brainstate.util.NestedDict({}))
200
+
201
+ def test_module_list(self):
202
+ ls = [
203
+ brainstate.nn.Linear(2, 2),
204
+ brainstate.nn.BatchNorm1d([10, 2]),
205
+ ]
206
+ graphdef, statetree = brainstate.graph.treefy_split(ls)
207
+
208
+ assert statetree[0]['weight'].value['weight'].shape == (2, 2)
209
+ assert statetree[0]['weight'].value['bias'].shape == (2,)
210
+ assert statetree[1]['weight'].value['scale'].shape == (1, 2,)
211
+ assert statetree[1]['weight'].value['bias'].shape == (1, 2,)
212
+ assert statetree[1]['running_mean'].value.shape == (1, 2,)
213
+ assert statetree[1]['running_var'].value.shape == (1, 2)
214
+
215
+ def test_shared_variables(self):
216
+ v = brainstate.ParamState(1)
217
+ g = [v, v]
218
+
219
+ graphdef, statetree = brainstate.graph.treefy_split(g)
220
+ assert len(statetree.to_flat()) == 1
221
+
222
+ g2 = brainstate.graph.treefy_merge(graphdef, statetree)
223
+ assert g2[0] is g2[1]
224
+
225
+ def test_tied_weights(self):
226
+ class Foo(brainstate.nn.Module):
227
+ def __init__(self) -> None:
228
+ super().__init__()
229
+ self.bar = brainstate.nn.Linear(2, 2)
230
+ self.baz = brainstate.nn.Linear(2, 2)
231
+
232
+ # tie the weights
233
+ self.baz.weight = self.bar.weight
234
+
235
+ node = Foo()
236
+ graphdef, state = brainstate.graph.treefy_split(node)
237
+
238
+ assert len(state.to_flat()) == 1
239
+
240
+ node2 = brainstate.graph.treefy_merge(graphdef, state)
241
+
242
+ assert node2.bar.weight is node2.baz.weight
243
+
244
+ def test_tied_weights_example(self):
245
+ class LinearTranspose(brainstate.nn.Module):
246
+ def __init__(self, dout: int, din: int, ) -> None:
247
+ super().__init__()
248
+ self.kernel = brainstate.ParamState(brainstate.init.LecunNormal()((dout, din)))
249
+
250
+ def __call__(self, x):
251
+ return x @ self.kernel.value.T
252
+
253
+ class Encoder(brainstate.nn.Module):
254
+ def __init__(self, ) -> None:
255
+ super().__init__()
256
+ self.embed = brainstate.nn.Embedding(10, 2)
257
+ self.linear_out = LinearTranspose(10, 2)
258
+
259
+ # tie the weights
260
+ self.linear_out.kernel = self.embed.weight
261
+
262
+ def __call__(self, x):
263
+ x = self.embed(x)
264
+ return self.linear_out(x)
265
+
266
+ model = Encoder()
267
+ graphdef, state = brainstate.graph.treefy_split(model)
268
+
269
+ assert len(state.to_flat()) == 1
270
+
271
+ x = jax.random.randint(jax.random.key(0), (2,), 0, 10)
272
+ y = model(x)
273
+
274
+ assert y.shape == (2, 10)
275
+
276
+ def test_state_variables_not_shared_with_graph(self):
277
+ class Foo(brainstate.graph.Node):
278
+ def __init__(self):
279
+ self.a = brainstate.ParamState(1)
280
+
281
+ m = Foo()
282
+ graphdef, statetree = brainstate.graph.treefy_split(m)
283
+
284
+ assert isinstance(m.a, brainstate.ParamState)
285
+ assert issubclass(statetree.a.type, brainstate.ParamState)
286
+ assert m.a is not statetree.a
287
+ assert m.a.value == statetree.a.value
288
+
289
+ m2 = brainstate.graph.treefy_merge(graphdef, statetree)
290
+
291
+ assert isinstance(m2.a, brainstate.ParamState)
292
+ assert issubclass(statetree.a.type, brainstate.ParamState)
293
+ assert m2.a is not statetree.a
294
+ assert m2.a.value == statetree.a.value
295
+
296
+ def test_shared_state_variables_not_shared_with_graph(self):
297
+ class Foo(brainstate.graph.Node):
298
+ def __init__(self):
299
+ p = brainstate.ParamState(1)
300
+ self.a = p
301
+ self.b = p
302
+
303
+ m = Foo()
304
+ graphdef, state = brainstate.graph.treefy_split(m)
305
+
306
+ assert isinstance(m.a, brainstate.ParamState)
307
+ assert isinstance(m.b, brainstate.ParamState)
308
+ assert issubclass(state.a.type, brainstate.ParamState)
309
+ assert 'b' not in state
310
+ assert m.a is not state.a
311
+ assert m.b is not state.a
312
+ assert m.a.value == state.a.value
313
+ assert m.b.value == state.a.value
314
+
315
+ m2 = brainstate.graph.treefy_merge(graphdef, state)
316
+
317
+ assert isinstance(m2.a, brainstate.ParamState)
318
+ assert isinstance(m2.b, brainstate.ParamState)
319
+ assert issubclass(state.a.type, brainstate.ParamState)
320
+ assert m2.a is not state.a
321
+ assert m2.b is not state.a
322
+ assert m2.a.value == state.a.value
323
+ assert m2.b.value == state.a.value
324
+ assert m2.a is m2.b
325
+
326
+ def test_pytree_node(self):
327
+ @brainstate.util.dataclass
328
+ class Tree:
329
+ a: brainstate.ParamState
330
+ b: str = brainstate.util.field(pytree_node=False)
331
+
332
+ class Foo(brainstate.graph.Node):
333
+ def __init__(self):
334
+ self.tree = Tree(brainstate.ParamState(1), 'a')
335
+
336
+ m = Foo()
337
+
338
+ graphdef, state = brainstate.graph.treefy_split(m)
339
+
340
+ assert 'tree' in state
341
+ assert 'a' in state.tree
342
+ assert graphdef.subgraphs['tree'].type.__name__ == 'PytreeType'
343
+
344
+ m2 = brainstate.graph.treefy_merge(graphdef, state)
345
+
346
+ assert isinstance(m2.tree, Tree)
347
+ assert m2.tree.a.value == 1
348
+ assert m2.tree.b == 'a'
349
+ assert m2.tree.a is not m.tree.a
350
+ assert m2.tree is not m.tree
351
+
352
+ def test_call_jit_update(self):
353
+ class Counter(brainstate.graph.Node):
354
+ def __init__(self):
355
+ self.count = brainstate.ParamState(jnp.zeros(()))
356
+
357
+ def inc(self):
358
+ self.count.value += 1
359
+ return 1
360
+
361
+ graph_state = brainstate.graph.treefy_split(Counter())
362
+
363
+ @jax.jit
364
+ def update(graph_state):
365
+ out, graph_state = brainstate.graph.call(graph_state).inc()
366
+ self.assertEqual(out, 1)
367
+ return graph_state
368
+
369
+ graph_state = update(graph_state)
370
+ graph_state = update(graph_state)
371
+
372
+ counter = brainstate.graph.treefy_merge(*graph_state)
373
+
374
+ self.assertEqual(counter.count.value, 2)
375
+
376
+ def test_stateful_linear(self):
377
+ linear = StatefulLinear(3, 2)
378
+ linear_state = brainstate.graph.treefy_split(linear)
379
+
380
+ @jax.jit
381
+ def forward(x, pure_linear):
382
+ y, pure_linear = brainstate.graph.call(pure_linear)(x)
383
+ return y, pure_linear
384
+
385
+ x = jnp.ones((1, 3))
386
+ y, linear_state = forward(x, linear_state)
387
+ y, linear_state = forward(x, linear_state)
388
+
389
+ self.assertEqual(linear.count.value, 0)
390
+ new_linear = brainstate.graph.treefy_merge(*linear_state)
391
+ self.assertEqual(new_linear.count.value, 2)
392
+
393
+ def test_getitem(self):
394
+ nodes = dict(
395
+ a=StatefulLinear(3, 2),
396
+ b=StatefulLinear(2, 1),
397
+ )
398
+ node_state = brainstate.graph.treefy_split(nodes)
399
+ _, node_state = brainstate.graph.call(node_state)['b'].increment()
400
+
401
+ nodes = brainstate.graph.treefy_merge(*node_state)
402
+
403
+ self.assertEqual(nodes['a'].count.value, 0)
404
+ self.assertEqual(nodes['b'].count.value, 1)
405
+
406
+
407
+ class SimpleModule(brainstate.nn.Module):
408
+ pass
409
+
410
+
411
+ class SimplePyTreeModule(brainstate.nn.Module):
412
+ pass
413
+
414
+
415
+ class TestThreading(parameterized.TestCase):
416
+
417
+ @parameterized.parameters(
418
+ (SimpleModule,),
419
+ (SimplePyTreeModule,),
420
+ )
421
+ def test_threading(self, module_fn: Callable[[], brainstate.nn.Module]):
422
+ x = module_fn()
423
+
424
+ class MyThread(Thread):
425
+
426
+ def run(self) -> None:
427
+ brainstate.graph.treefy_split(x)
428
+
429
+ thread = MyThread()
430
+ thread.start()
431
+ thread.join()
432
+
433
+
434
+ class TestGraphOperation(unittest.TestCase):
435
+ def test1(self):
436
+ class MyNode(brainstate.graph.Node):
437
+ def __init__(self):
438
+ self.a = brainstate.nn.Linear(2, 3)
439
+ self.b = brainstate.nn.Linear(3, 2)
440
+ self.c = [brainstate.nn.Linear(1, 2), brainstate.nn.Linear(1, 3)]
441
+ self.d = {'x': brainstate.nn.Linear(1, 3), 'y': brainstate.nn.Linear(1, 4)}
442
+
443
+ graphdef, statetree = brainstate.graph.flatten(MyNode())
444
+ # print(graphdef)
445
+ print(statetree)
446
+ # print(brainstate.graph.unflatten(graphdef, statetree))
447
+
448
+ def test_split(self):
449
+ class Foo(brainstate.graph.Node):
450
+ def __init__(self):
451
+ self.a = brainstate.nn.Linear(2, 2)
452
+ self.b = brainstate.nn.BatchNorm1d([10, 2])
453
+
454
+ node = Foo()
455
+ graphdef, params, others = brainstate.graph.treefy_split(node, brainstate.ParamState, ...)
456
+
457
+ print(params)
458
+ print(jax.tree.map(jnp.shape, params))
459
+
460
+ print(jax.tree.map(jnp.shape, others))
461
+
462
+ def test_merge(self):
463
+ class Foo(brainstate.graph.Node):
464
+ def __init__(self):
465
+ self.a = brainstate.nn.Linear(2, 2)
466
+ self.b = brainstate.nn.BatchNorm1d([10, 2])
467
+
468
+ node = Foo()
469
+ graphdef, params, others = brainstate.graph.treefy_split(node, brainstate.ParamState, ...)
470
+
471
+ new_node = brainstate.graph.treefy_merge(graphdef, params, others)
472
+
473
+ assert isinstance(new_node, Foo)
474
+ assert isinstance(new_node.b, brainstate.nn.BatchNorm1d)
475
+ assert isinstance(new_node.a, brainstate.nn.Linear)
476
+
477
+ def test_update_states(self):
478
+ x = jnp.ones((1, 2))
479
+ y = jnp.ones((1, 3))
480
+ model = brainstate.nn.Linear(2, 3)
481
+
482
+ def loss_fn(x, y):
483
+ return jnp.mean((y - model(x)) ** 2)
484
+
485
+ def sgd(ps, gs):
486
+ updates = jax.tree.map(lambda p, g: p - 0.1 * g, ps.value, gs)
487
+ ps.value = updates
488
+
489
+ prev_loss = loss_fn(x, y)
490
+ weights = model.states()
491
+ grads = brainstate.augment.grad(loss_fn, weights)(x, y)
492
+ for key, val in grads.items():
493
+ sgd(weights[key], val)
494
+ assert loss_fn(x, y) < prev_loss
495
+
496
+ def test_pop_states(self):
497
+ class Model(brainstate.nn.Module):
498
+ def __init__(self):
499
+ super().__init__()
500
+ self.a = brainstate.nn.Linear(2, 3)
501
+ self.b = brainstate.nn.LIF([10, 2])
502
+
503
+ model = Model()
504
+ with brainstate.catch_new_states('new'):
505
+ brainstate.nn.init_all_states(model)
506
+ # print(model.states())
507
+ self.assertTrue(len(model.states()) == 2)
508
+ model_states = brainstate.graph.pop_states(model, 'new')
509
+ print(model_states)
510
+ self.assertTrue(len(model.states()) == 1)
511
+ assert not hasattr(model.b, 'V')
512
+ # print(model.states())
513
+
514
+ def test_treefy_split(self):
515
+ class MLP(brainstate.graph.Node):
516
+ def __init__(self, din: int, dmid: int, dout: int, n_layer: int = 3):
517
+ self.input = brainstate.nn.Linear(din, dmid)
518
+ self.layers = [brainstate.nn.Linear(dmid, dmid) for _ in range(n_layer)]
519
+ self.output = brainstate.nn.Linear(dmid, dout)
520
+
521
+ def __call__(self, x):
522
+ x = brainstate.functional.relu(self.input(x))
523
+ for layer in self.layers:
524
+ x = brainstate.functional.relu(layer(x))
525
+ return self.output(x)
526
+
527
+ model = MLP(2, 1, 3)
528
+ graph_def, treefy_states = brainstate.graph.treefy_split(model)
529
+
530
+ print(graph_def)
531
+ print(treefy_states)
532
+
533
+ # states = brainstate.graph.states(model)
534
+ # print(states)
535
+ # nest_states = states.to_nest()
536
+ # print(nest_states)
537
+
538
+ def test_states(self):
539
+ class MLP(brainstate.graph.Node):
540
+ def __init__(self, din: int, dmid: int, dout: int, n_layer: int = 3):
541
+ self.input = brainstate.nn.Linear(din, dmid)
542
+ self.layers = [brainstate.nn.Linear(dmid, dmid) for _ in range(n_layer)]
543
+ self.output = brainstate.nn.LIF(dout)
544
+
545
+ def __call__(self, x):
546
+ x = brainstate.functional.relu(self.input(x))
547
+ for layer in self.layers:
548
+ x = brainstate.functional.relu(layer(x))
549
+ return self.output(x)
550
+
551
+ model = brainstate.nn.init_all_states(MLP(2, 1, 3))
552
+ states = brainstate.graph.states(model)
553
+ print(states)
554
+ nest_states = states.to_nest()
555
+ print(nest_states)
556
+
557
+ params, others = brainstate.graph.states(model, brainstate.ParamState, brainstate.ShortTermState)
558
+ print(params)
559
+ print(others)
560
+
561
+
562
+ if __name__ == '__main__':
563
+ absltest.main()