brainstate 0.1.8__py2.py3-none-any.whl → 0.1.9__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 +509 -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.9.dist-info}/METADATA +91 -99
- brainstate-0.1.9.dist-info/RECORD +130 -0
- {brainstate-0.1.8.dist-info → brainstate-0.1.9.dist-info}/WHEEL +1 -1
- {brainstate-0.1.8.dist-info → brainstate-0.1.9.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.9.dist-info}/top_level.txt +0 -0
brainstate/random/_rand_seed.py
CHANGED
@@ -1,210 +1,210 @@
|
|
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 contextlib import contextmanager
|
17
|
-
from typing import Optional
|
18
|
-
|
19
|
-
import jax
|
20
|
-
import numpy as np
|
21
|
-
|
22
|
-
from brainstate.typing import SeedOrKey
|
23
|
-
from ._rand_state import RandomState, DEFAULT, use_prng_key
|
24
|
-
|
25
|
-
__all__ = [
|
26
|
-
'seed', 'set_key', 'get_key', 'default_rng', 'split_key', 'split_keys', 'seed_context', 'restore_key',
|
27
|
-
'self_assign_multi_keys',
|
28
|
-
]
|
29
|
-
|
30
|
-
|
31
|
-
def restore_key():
|
32
|
-
"""Restore the default random key."""
|
33
|
-
DEFAULT.restore_key()
|
34
|
-
|
35
|
-
|
36
|
-
def split_key(n: Optional[int] = None, backup: bool = False):
|
37
|
-
"""Create a new seed from the current seed.
|
38
|
-
|
39
|
-
This function is useful for the consistency with JAX's random paradigm.
|
40
|
-
|
41
|
-
Parameters
|
42
|
-
----------
|
43
|
-
n : int, optional
|
44
|
-
The number of seeds to generate.
|
45
|
-
backup : bool, optional
|
46
|
-
Whether to backup the current key.
|
47
|
-
|
48
|
-
Returns
|
49
|
-
-------
|
50
|
-
key : jax.random.PRNGKey
|
51
|
-
A new random key.
|
52
|
-
|
53
|
-
"""
|
54
|
-
return DEFAULT.split_key(n=n, backup=backup)
|
55
|
-
|
56
|
-
|
57
|
-
def split_keys(n: int, backup: bool = False):
|
58
|
-
"""Create multiple seeds from the current seed. This is used
|
59
|
-
internally by `pmap` and `vmap` to ensure that random numbers
|
60
|
-
are different in parallel threads.
|
61
|
-
|
62
|
-
Parameters
|
63
|
-
----------
|
64
|
-
n : int
|
65
|
-
The number of seeds to generate.
|
66
|
-
backup : bool, optional
|
67
|
-
Whether to backup the current key
|
68
|
-
|
69
|
-
Returns
|
70
|
-
-------
|
71
|
-
keys : jax.random.PRNGKey
|
72
|
-
A tuple of JAX random keys.
|
73
|
-
|
74
|
-
"""
|
75
|
-
return split_key(n, backup=backup)
|
76
|
-
|
77
|
-
|
78
|
-
def self_assign_multi_keys(n: int, backup: bool = True):
|
79
|
-
"""
|
80
|
-
Assign multiple keys to the current key.
|
81
|
-
"""
|
82
|
-
DEFAULT.self_assign_multi_keys(n, backup=backup)
|
83
|
-
|
84
|
-
|
85
|
-
def clone_rng(seed_or_key=None, clone: bool = True) -> RandomState:
|
86
|
-
"""Clone the random state according to the given setting.
|
87
|
-
|
88
|
-
Args:
|
89
|
-
seed_or_key: The seed (an integer) or the random key.
|
90
|
-
clone: Bool. Whether clone the default random state.
|
91
|
-
|
92
|
-
Returns:
|
93
|
-
The random state.
|
94
|
-
"""
|
95
|
-
if seed_or_key is None:
|
96
|
-
return DEFAULT.clone() if clone else DEFAULT
|
97
|
-
else:
|
98
|
-
return RandomState(seed_or_key)
|
99
|
-
|
100
|
-
|
101
|
-
def default_rng(seed_or_key=None) -> RandomState:
|
102
|
-
"""
|
103
|
-
Get the default random state.
|
104
|
-
|
105
|
-
Args:
|
106
|
-
seed_or_key: The seed (an integer) or the jax random key.
|
107
|
-
|
108
|
-
Returns:
|
109
|
-
The random state.
|
110
|
-
"""
|
111
|
-
if seed_or_key is None:
|
112
|
-
return DEFAULT
|
113
|
-
else:
|
114
|
-
return RandomState(seed_or_key)
|
115
|
-
|
116
|
-
|
117
|
-
def set_key(seed_or_key: SeedOrKey):
|
118
|
-
"""Sets a new random key.
|
119
|
-
|
120
|
-
Parameters
|
121
|
-
----------
|
122
|
-
seed_or_key: int
|
123
|
-
The random key.
|
124
|
-
"""
|
125
|
-
if isinstance(seed_or_key, int):
|
126
|
-
# key = jax.random.key(seed_or_key)
|
127
|
-
key = jax.random.PRNGKey(seed_or_key) if use_prng_key else jrjax.random.key(seed_or_key)
|
128
|
-
elif isinstance(seed_or_key, (jax.numpy.ndarray, np.ndarray)):
|
129
|
-
if jax.numpy.issubdtype(seed_or_key.dtype, jax.dtypes.prng_key):
|
130
|
-
key = seed_or_key
|
131
|
-
elif seed_or_key.size == 2 and seed_or_key.dtype == jax.numpy.uint32:
|
132
|
-
key = seed_or_key
|
133
|
-
else:
|
134
|
-
raise ValueError(f"seed_or_key should be an integer or a tuple of two integers.")
|
135
|
-
DEFAULT.set_key(key)
|
136
|
-
|
137
|
-
|
138
|
-
def get_key():
|
139
|
-
"""Get a new random key.
|
140
|
-
|
141
|
-
Returns
|
142
|
-
-------
|
143
|
-
seed_or_key: int
|
144
|
-
The random key.
|
145
|
-
"""
|
146
|
-
return DEFAULT.value
|
147
|
-
|
148
|
-
|
149
|
-
def seed(seed_or_key: SeedOrKey = None):
|
150
|
-
"""Sets a new random seed.
|
151
|
-
|
152
|
-
Parameters
|
153
|
-
----------
|
154
|
-
seed_or_key: int, optional
|
155
|
-
The random seed (an integer) or jax random key.
|
156
|
-
"""
|
157
|
-
with jax.ensure_compile_time_eval():
|
158
|
-
_set_numpy_seed = True
|
159
|
-
if seed_or_key is None:
|
160
|
-
seed_or_key = np.random.randint(0, 100000)
|
161
|
-
_set_numpy_seed = False
|
162
|
-
|
163
|
-
# numpy random seed
|
164
|
-
if _set_numpy_seed:
|
165
|
-
try:
|
166
|
-
if np.size(seed_or_key) == 1: # seed
|
167
|
-
np.random.seed(seed_or_key)
|
168
|
-
elif np.size(seed_or_key) == 2: # jax random key
|
169
|
-
np.random.seed(seed_or_key[0])
|
170
|
-
else:
|
171
|
-
raise ValueError(f"seed_or_key should be an integer or a tuple of two integers.")
|
172
|
-
except jax.errors.TracerArrayConversionError:
|
173
|
-
pass
|
174
|
-
|
175
|
-
# jax random seed
|
176
|
-
DEFAULT.seed(seed_or_key)
|
177
|
-
|
178
|
-
|
179
|
-
@contextmanager
|
180
|
-
def seed_context(seed_or_key: SeedOrKey):
|
181
|
-
"""
|
182
|
-
A context manager that sets the random seed for the duration of the block.
|
183
|
-
|
184
|
-
Examples:
|
185
|
-
|
186
|
-
>>> import brainstate as brainstate
|
187
|
-
>>> print(brainstate.random.rand(2))
|
188
|
-
[0.57721865 0.9820676 ]
|
189
|
-
>>> print(brainstate.random.rand(2))
|
190
|
-
[0.8511752 0.95312667]
|
191
|
-
>>> with brainstate.random.seed_context(42):
|
192
|
-
... print(brainstate.random.rand(2))
|
193
|
-
[0.95598125 0.4032725 ]
|
194
|
-
>>> with brainstate.random.seed_context(42):
|
195
|
-
... print(brainstate.random.rand(2))
|
196
|
-
[0.95598125 0.4032725 ]
|
197
|
-
|
198
|
-
Args:
|
199
|
-
seed_or_key: The seed (an integer) or jax random key.
|
200
|
-
|
201
|
-
"""
|
202
|
-
# get the old random key
|
203
|
-
old_jrand_key = DEFAULT.value
|
204
|
-
try:
|
205
|
-
# set the seed of jax random state
|
206
|
-
DEFAULT.seed(seed_or_key)
|
207
|
-
yield
|
208
|
-
finally:
|
209
|
-
# restore the random state
|
210
|
-
DEFAULT.seed(old_jrand_key)
|
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 contextlib import contextmanager
|
17
|
+
from typing import Optional
|
18
|
+
|
19
|
+
import jax
|
20
|
+
import numpy as np
|
21
|
+
|
22
|
+
from brainstate.typing import SeedOrKey
|
23
|
+
from ._rand_state import RandomState, DEFAULT, use_prng_key
|
24
|
+
|
25
|
+
__all__ = [
|
26
|
+
'seed', 'set_key', 'get_key', 'default_rng', 'split_key', 'split_keys', 'seed_context', 'restore_key',
|
27
|
+
'self_assign_multi_keys',
|
28
|
+
]
|
29
|
+
|
30
|
+
|
31
|
+
def restore_key():
|
32
|
+
"""Restore the default random key."""
|
33
|
+
DEFAULT.restore_key()
|
34
|
+
|
35
|
+
|
36
|
+
def split_key(n: Optional[int] = None, backup: bool = False):
|
37
|
+
"""Create a new seed from the current seed.
|
38
|
+
|
39
|
+
This function is useful for the consistency with JAX's random paradigm.
|
40
|
+
|
41
|
+
Parameters
|
42
|
+
----------
|
43
|
+
n : int, optional
|
44
|
+
The number of seeds to generate.
|
45
|
+
backup : bool, optional
|
46
|
+
Whether to backup the current key.
|
47
|
+
|
48
|
+
Returns
|
49
|
+
-------
|
50
|
+
key : jax.random.PRNGKey
|
51
|
+
A new random key.
|
52
|
+
|
53
|
+
"""
|
54
|
+
return DEFAULT.split_key(n=n, backup=backup)
|
55
|
+
|
56
|
+
|
57
|
+
def split_keys(n: int, backup: bool = False):
|
58
|
+
"""Create multiple seeds from the current seed. This is used
|
59
|
+
internally by `pmap` and `vmap` to ensure that random numbers
|
60
|
+
are different in parallel threads.
|
61
|
+
|
62
|
+
Parameters
|
63
|
+
----------
|
64
|
+
n : int
|
65
|
+
The number of seeds to generate.
|
66
|
+
backup : bool, optional
|
67
|
+
Whether to backup the current key
|
68
|
+
|
69
|
+
Returns
|
70
|
+
-------
|
71
|
+
keys : jax.random.PRNGKey
|
72
|
+
A tuple of JAX random keys.
|
73
|
+
|
74
|
+
"""
|
75
|
+
return split_key(n, backup=backup)
|
76
|
+
|
77
|
+
|
78
|
+
def self_assign_multi_keys(n: int, backup: bool = True):
|
79
|
+
"""
|
80
|
+
Assign multiple keys to the current key.
|
81
|
+
"""
|
82
|
+
DEFAULT.self_assign_multi_keys(n, backup=backup)
|
83
|
+
|
84
|
+
|
85
|
+
def clone_rng(seed_or_key=None, clone: bool = True) -> RandomState:
|
86
|
+
"""Clone the random state according to the given setting.
|
87
|
+
|
88
|
+
Args:
|
89
|
+
seed_or_key: The seed (an integer) or the random key.
|
90
|
+
clone: Bool. Whether clone the default random state.
|
91
|
+
|
92
|
+
Returns:
|
93
|
+
The random state.
|
94
|
+
"""
|
95
|
+
if seed_or_key is None:
|
96
|
+
return DEFAULT.clone() if clone else DEFAULT
|
97
|
+
else:
|
98
|
+
return RandomState(seed_or_key)
|
99
|
+
|
100
|
+
|
101
|
+
def default_rng(seed_or_key=None) -> RandomState:
|
102
|
+
"""
|
103
|
+
Get the default random state.
|
104
|
+
|
105
|
+
Args:
|
106
|
+
seed_or_key: The seed (an integer) or the jax random key.
|
107
|
+
|
108
|
+
Returns:
|
109
|
+
The random state.
|
110
|
+
"""
|
111
|
+
if seed_or_key is None:
|
112
|
+
return DEFAULT
|
113
|
+
else:
|
114
|
+
return RandomState(seed_or_key)
|
115
|
+
|
116
|
+
|
117
|
+
def set_key(seed_or_key: SeedOrKey):
|
118
|
+
"""Sets a new random key.
|
119
|
+
|
120
|
+
Parameters
|
121
|
+
----------
|
122
|
+
seed_or_key: int
|
123
|
+
The random key.
|
124
|
+
"""
|
125
|
+
if isinstance(seed_or_key, int):
|
126
|
+
# key = jax.random.key(seed_or_key)
|
127
|
+
key = jax.random.PRNGKey(seed_or_key) if use_prng_key else jrjax.random.key(seed_or_key)
|
128
|
+
elif isinstance(seed_or_key, (jax.numpy.ndarray, np.ndarray)):
|
129
|
+
if jax.numpy.issubdtype(seed_or_key.dtype, jax.dtypes.prng_key):
|
130
|
+
key = seed_or_key
|
131
|
+
elif seed_or_key.size == 2 and seed_or_key.dtype == jax.numpy.uint32:
|
132
|
+
key = seed_or_key
|
133
|
+
else:
|
134
|
+
raise ValueError(f"seed_or_key should be an integer or a tuple of two integers.")
|
135
|
+
DEFAULT.set_key(key)
|
136
|
+
|
137
|
+
|
138
|
+
def get_key():
|
139
|
+
"""Get a new random key.
|
140
|
+
|
141
|
+
Returns
|
142
|
+
-------
|
143
|
+
seed_or_key: int
|
144
|
+
The random key.
|
145
|
+
"""
|
146
|
+
return DEFAULT.value
|
147
|
+
|
148
|
+
|
149
|
+
def seed(seed_or_key: SeedOrKey = None):
|
150
|
+
"""Sets a new random seed.
|
151
|
+
|
152
|
+
Parameters
|
153
|
+
----------
|
154
|
+
seed_or_key: int, optional
|
155
|
+
The random seed (an integer) or jax random key.
|
156
|
+
"""
|
157
|
+
with jax.ensure_compile_time_eval():
|
158
|
+
_set_numpy_seed = True
|
159
|
+
if seed_or_key is None:
|
160
|
+
seed_or_key = np.random.randint(0, 100000)
|
161
|
+
_set_numpy_seed = False
|
162
|
+
|
163
|
+
# numpy random seed
|
164
|
+
if _set_numpy_seed:
|
165
|
+
try:
|
166
|
+
if np.size(seed_or_key) == 1: # seed
|
167
|
+
np.random.seed(seed_or_key)
|
168
|
+
elif np.size(seed_or_key) == 2: # jax random key
|
169
|
+
np.random.seed(seed_or_key[0])
|
170
|
+
else:
|
171
|
+
raise ValueError(f"seed_or_key should be an integer or a tuple of two integers.")
|
172
|
+
except jax.errors.TracerArrayConversionError:
|
173
|
+
pass
|
174
|
+
|
175
|
+
# jax random seed
|
176
|
+
DEFAULT.seed(seed_or_key)
|
177
|
+
|
178
|
+
|
179
|
+
@contextmanager
|
180
|
+
def seed_context(seed_or_key: SeedOrKey):
|
181
|
+
"""
|
182
|
+
A context manager that sets the random seed for the duration of the block.
|
183
|
+
|
184
|
+
Examples:
|
185
|
+
|
186
|
+
>>> import brainstate as brainstate
|
187
|
+
>>> print(brainstate.random.rand(2))
|
188
|
+
[0.57721865 0.9820676 ]
|
189
|
+
>>> print(brainstate.random.rand(2))
|
190
|
+
[0.8511752 0.95312667]
|
191
|
+
>>> with brainstate.random.seed_context(42):
|
192
|
+
... print(brainstate.random.rand(2))
|
193
|
+
[0.95598125 0.4032725 ]
|
194
|
+
>>> with brainstate.random.seed_context(42):
|
195
|
+
... print(brainstate.random.rand(2))
|
196
|
+
[0.95598125 0.4032725 ]
|
197
|
+
|
198
|
+
Args:
|
199
|
+
seed_or_key: The seed (an integer) or jax random key.
|
200
|
+
|
201
|
+
"""
|
202
|
+
# get the old random key
|
203
|
+
old_jrand_key = DEFAULT.value
|
204
|
+
try:
|
205
|
+
# set the seed of jax random state
|
206
|
+
DEFAULT.seed(seed_or_key)
|
207
|
+
yield
|
208
|
+
finally:
|
209
|
+
# restore the random state
|
210
|
+
DEFAULT.seed(old_jrand_key)
|
@@ -1,48 +1,48 @@
|
|
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 jax.numpy as jnp
|
19
|
-
import jax.random
|
20
|
-
|
21
|
-
import brainstate
|
22
|
-
|
23
|
-
|
24
|
-
class TestRandom(unittest.TestCase):
|
25
|
-
|
26
|
-
def test_seed2(self):
|
27
|
-
test_seed = 299
|
28
|
-
key = jax.random.PRNGKey(test_seed)
|
29
|
-
brainstate.random.seed(key)
|
30
|
-
|
31
|
-
@jax.jit
|
32
|
-
def jit_seed(key):
|
33
|
-
brainstate.random.seed(key)
|
34
|
-
with brainstate.random.seed_context(key):
|
35
|
-
print(brainstate.random.DEFAULT.value)
|
36
|
-
|
37
|
-
jit_seed(key)
|
38
|
-
jit_seed(1)
|
39
|
-
jit_seed(None)
|
40
|
-
brainstate.random.seed(1)
|
41
|
-
|
42
|
-
def test_seed(self):
|
43
|
-
test_seed = 299
|
44
|
-
brainstate.random.seed(test_seed)
|
45
|
-
a = brainstate.random.rand(3)
|
46
|
-
brainstate.random.seed(test_seed)
|
47
|
-
b = brainstate.random.rand(3)
|
48
|
-
self.assertTrue(jnp.array_equal(a, b))
|
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 jax.numpy as jnp
|
19
|
+
import jax.random
|
20
|
+
|
21
|
+
import brainstate
|
22
|
+
|
23
|
+
|
24
|
+
class TestRandom(unittest.TestCase):
|
25
|
+
|
26
|
+
def test_seed2(self):
|
27
|
+
test_seed = 299
|
28
|
+
key = jax.random.PRNGKey(test_seed)
|
29
|
+
brainstate.random.seed(key)
|
30
|
+
|
31
|
+
@jax.jit
|
32
|
+
def jit_seed(key):
|
33
|
+
brainstate.random.seed(key)
|
34
|
+
with brainstate.random.seed_context(key):
|
35
|
+
print(brainstate.random.DEFAULT.value)
|
36
|
+
|
37
|
+
jit_seed(key)
|
38
|
+
jit_seed(1)
|
39
|
+
jit_seed(None)
|
40
|
+
brainstate.random.seed(1)
|
41
|
+
|
42
|
+
def test_seed(self):
|
43
|
+
test_seed = 299
|
44
|
+
brainstate.random.seed(test_seed)
|
45
|
+
a = brainstate.random.rand(3)
|
46
|
+
brainstate.random.seed(test_seed)
|
47
|
+
b = brainstate.random.rand(3)
|
48
|
+
self.assertTrue(jnp.array_equal(a, b))
|