brainstate 0.1.8__py2.py3-none-any.whl → 0.1.10__py2.py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- brainstate/__init__.py +58 -51
- brainstate/_compatible_import.py +148 -148
- brainstate/_state.py +1605 -1663
- brainstate/_state_test.py +52 -52
- brainstate/_utils.py +47 -47
- brainstate/augment/__init__.py +30 -30
- brainstate/augment/_autograd.py +778 -778
- brainstate/augment/_autograd_test.py +1289 -1289
- brainstate/augment/_eval_shape.py +99 -99
- brainstate/augment/_eval_shape_test.py +38 -38
- brainstate/augment/_mapping.py +1060 -1060
- brainstate/augment/_mapping_test.py +597 -597
- brainstate/augment/_random.py +151 -151
- brainstate/compile/__init__.py +38 -38
- brainstate/compile/_ad_checkpoint.py +204 -204
- brainstate/compile/_ad_checkpoint_test.py +49 -49
- brainstate/compile/_conditions.py +256 -256
- brainstate/compile/_conditions_test.py +220 -220
- brainstate/compile/_error_if.py +92 -92
- brainstate/compile/_error_if_test.py +52 -52
- brainstate/compile/_jit.py +346 -346
- brainstate/compile/_jit_test.py +143 -143
- brainstate/compile/_loop_collect_return.py +536 -536
- brainstate/compile/_loop_collect_return_test.py +58 -58
- brainstate/compile/_loop_no_collection.py +184 -184
- brainstate/compile/_loop_no_collection_test.py +50 -50
- brainstate/compile/_make_jaxpr.py +888 -888
- brainstate/compile/_make_jaxpr_test.py +156 -156
- brainstate/compile/_progress_bar.py +202 -202
- brainstate/compile/_unvmap.py +159 -159
- brainstate/compile/_util.py +147 -147
- brainstate/environ.py +563 -563
- brainstate/environ_test.py +62 -62
- brainstate/functional/__init__.py +27 -26
- brainstate/graph/__init__.py +29 -29
- brainstate/graph/_graph_node.py +244 -244
- brainstate/graph/_graph_node_test.py +73 -73
- brainstate/graph/_graph_operation.py +1738 -1738
- brainstate/graph/_graph_operation_test.py +563 -563
- brainstate/init/__init__.py +26 -26
- brainstate/init/_base.py +52 -52
- brainstate/init/_generic.py +244 -244
- brainstate/init/_random_inits.py +553 -553
- brainstate/init/_random_inits_test.py +149 -149
- brainstate/init/_regular_inits.py +105 -105
- brainstate/init/_regular_inits_test.py +50 -50
- brainstate/mixin.py +365 -363
- brainstate/mixin_test.py +77 -73
- brainstate/nn/__init__.py +135 -131
- brainstate/{functional → nn}/_activations.py +808 -813
- brainstate/{functional → nn}/_activations_test.py +331 -331
- brainstate/nn/_collective_ops.py +514 -514
- brainstate/nn/_collective_ops_test.py +43 -43
- brainstate/nn/_common.py +178 -178
- brainstate/nn/_conv.py +501 -501
- brainstate/nn/_conv_test.py +238 -238
- brainstate/nn/_delay.py +588 -502
- brainstate/nn/_delay_test.py +238 -184
- brainstate/nn/_dropout.py +426 -426
- brainstate/nn/_dropout_test.py +100 -100
- brainstate/nn/_dynamics.py +1343 -1343
- brainstate/nn/_dynamics_test.py +78 -78
- brainstate/nn/_elementwise.py +1119 -1119
- brainstate/nn/_elementwise_test.py +169 -169
- brainstate/nn/_embedding.py +58 -58
- brainstate/nn/_exp_euler.py +92 -92
- brainstate/nn/_exp_euler_test.py +35 -35
- brainstate/nn/_fixedprob.py +239 -239
- brainstate/nn/_fixedprob_test.py +114 -114
- brainstate/nn/_inputs.py +608 -608
- brainstate/nn/_linear.py +424 -424
- brainstate/nn/_linear_mv.py +83 -83
- brainstate/nn/_linear_mv_test.py +120 -120
- brainstate/nn/_linear_test.py +107 -107
- brainstate/nn/_ltp.py +28 -28
- brainstate/nn/_module.py +377 -377
- brainstate/nn/_module_test.py +40 -40
- brainstate/nn/_neuron.py +705 -705
- brainstate/nn/_neuron_test.py +161 -161
- brainstate/nn/_normalizations.py +975 -918
- brainstate/nn/_normalizations_test.py +73 -73
- brainstate/{functional → nn}/_others.py +46 -46
- brainstate/nn/_poolings.py +1177 -1177
- brainstate/nn/_poolings_test.py +217 -217
- brainstate/nn/_projection.py +486 -486
- brainstate/nn/_rate_rnns.py +554 -554
- brainstate/nn/_rate_rnns_test.py +63 -63
- brainstate/nn/_readout.py +209 -209
- brainstate/nn/_readout_test.py +53 -53
- brainstate/nn/_stp.py +236 -236
- brainstate/nn/_synapse.py +505 -505
- brainstate/nn/_synapse_test.py +131 -131
- brainstate/nn/_synaptic_projection.py +423 -423
- brainstate/nn/_synouts.py +162 -162
- brainstate/nn/_synouts_test.py +57 -57
- brainstate/nn/_utils.py +89 -89
- brainstate/nn/metrics.py +388 -388
- brainstate/optim/__init__.py +38 -38
- brainstate/optim/_base.py +64 -64
- brainstate/optim/_lr_scheduler.py +448 -448
- brainstate/optim/_lr_scheduler_test.py +50 -50
- brainstate/optim/_optax_optimizer.py +152 -152
- brainstate/optim/_optax_optimizer_test.py +53 -53
- brainstate/optim/_sgd_optimizer.py +1104 -1104
- brainstate/random/__init__.py +24 -24
- brainstate/random/_rand_funs.py +3616 -3616
- brainstate/random/_rand_funs_test.py +567 -567
- brainstate/random/_rand_seed.py +210 -210
- brainstate/random/_rand_seed_test.py +48 -48
- brainstate/random/_rand_state.py +1409 -1409
- brainstate/random/_random_for_unit.py +52 -52
- brainstate/surrogate.py +1957 -1957
- brainstate/transform.py +23 -23
- brainstate/typing.py +304 -304
- brainstate/util/__init__.py +50 -50
- brainstate/util/caller.py +98 -98
- brainstate/util/error.py +55 -55
- brainstate/util/filter.py +469 -469
- brainstate/util/others.py +540 -540
- brainstate/util/pretty_pytree.py +945 -945
- brainstate/util/pretty_pytree_test.py +159 -159
- brainstate/util/pretty_repr.py +328 -328
- brainstate/util/pretty_table.py +2954 -2954
- brainstate/util/scaling.py +258 -258
- brainstate/util/struct.py +523 -523
- {brainstate-0.1.8.dist-info → brainstate-0.1.10.dist-info}/METADATA +91 -99
- brainstate-0.1.10.dist-info/RECORD +130 -0
- {brainstate-0.1.8.dist-info → brainstate-0.1.10.dist-info}/WHEEL +1 -1
- {brainstate-0.1.8.dist-info → brainstate-0.1.10.dist-info/licenses}/LICENSE +202 -202
- brainstate/functional/_normalization.py +0 -81
- brainstate/functional/_spikes.py +0 -204
- brainstate-0.1.8.dist-info/RECORD +0 -132
- {brainstate-0.1.8.dist-info → brainstate-0.1.10.dist-info}/top_level.txt +0 -0
@@ -1,256 +1,256 @@
|
|
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 collections.abc import Callable, Sequence
|
17
|
-
|
18
|
-
import jax
|
19
|
-
import jax.numpy as jnp
|
20
|
-
import numpy as np
|
21
|
-
|
22
|
-
from brainstate._compatible_import import to_concrete_aval, Tracer
|
23
|
-
from brainstate._utils import set_module_as
|
24
|
-
from ._error_if import jit_error_if
|
25
|
-
from ._make_jaxpr import StatefulFunction
|
26
|
-
from ._util import wrap_single_fun_in_multi_branches, write_back_state_values
|
27
|
-
|
28
|
-
__all__ = [
|
29
|
-
'cond', 'switch', 'ifelse',
|
30
|
-
]
|
31
|
-
|
32
|
-
|
33
|
-
@set_module_as('brainstate.compile')
|
34
|
-
def cond(pred, true_fun: Callable, false_fun: Callable, *operands):
|
35
|
-
"""
|
36
|
-
Conditionally apply ``true_fun`` or ``false_fun``.
|
37
|
-
|
38
|
-
Provided arguments are correctly typed, ``cond()`` has equivalent
|
39
|
-
semantics to this Python implementation, where ``pred`` must be a
|
40
|
-
scalar type::
|
41
|
-
|
42
|
-
def cond(pred, true_fun, false_fun, *operands):
|
43
|
-
if pred:
|
44
|
-
return true_fun(*operands)
|
45
|
-
else:
|
46
|
-
return false_fun(*operands)
|
47
|
-
|
48
|
-
|
49
|
-
In contrast with :func:`jax.lax.select`, using ``cond`` indicates that only one of
|
50
|
-
the two branches is executed (up to compiler rewrites and optimizations).
|
51
|
-
However, when transformed with :func:`~jax.vmap` to operate over a batch of
|
52
|
-
predicates, ``cond`` is converted to :func:`~jax.lax.select`.
|
53
|
-
|
54
|
-
Args:
|
55
|
-
pred: Boolean scalar type, indicating which branch function to apply.
|
56
|
-
true_fun: Function (A -> B), to be applied if ``pred`` is True.
|
57
|
-
false_fun: Function (A -> B), to be applied if ``pred`` is False.
|
58
|
-
operands: Operands (A) input to either branch depending on ``pred``. The
|
59
|
-
type can be a scalar, array, or any pytree (nested Python tuple/list/dict)
|
60
|
-
thereof.
|
61
|
-
|
62
|
-
Returns:
|
63
|
-
Value (B) of either ``true_fun(*operands)`` or ``false_fun(*operands)``,
|
64
|
-
depending on the value of ``pred``. The type can be a scalar, array, or any
|
65
|
-
pytree (nested Python tuple/list/dict) thereof.
|
66
|
-
"""
|
67
|
-
if not (callable(true_fun) and callable(false_fun)):
|
68
|
-
raise TypeError("true_fun and false_fun arguments should be callable.")
|
69
|
-
|
70
|
-
if pred is None:
|
71
|
-
raise TypeError("cond predicate is None")
|
72
|
-
if isinstance(pred, Sequence) or np.ndim(pred) != 0:
|
73
|
-
raise TypeError(f"Pred must be a scalar, got {pred} of " +
|
74
|
-
(f"type {type(pred)}" if isinstance(pred, Sequence)
|
75
|
-
else f"shape {np.shape(pred)}."))
|
76
|
-
|
77
|
-
# check pred
|
78
|
-
try:
|
79
|
-
pred_dtype = jax.dtypes.result_type(pred)
|
80
|
-
except TypeError as err:
|
81
|
-
raise TypeError("Pred type must be either boolean or number, got {}.".format(pred)) from err
|
82
|
-
if pred_dtype.kind != 'b':
|
83
|
-
if pred_dtype.kind in 'iuf':
|
84
|
-
pred = pred != 0
|
85
|
-
else:
|
86
|
-
raise TypeError("Pred type must be either boolean or number, got {}.".format(pred_dtype))
|
87
|
-
|
88
|
-
# not jit
|
89
|
-
if jax.config.jax_disable_jit and not isinstance(to_concrete_aval(pred), Tracer):
|
90
|
-
if pred:
|
91
|
-
return true_fun(*operands)
|
92
|
-
else:
|
93
|
-
return false_fun(*operands)
|
94
|
-
|
95
|
-
# evaluate jaxpr
|
96
|
-
stateful_true = StatefulFunction(true_fun, name='cond:true').make_jaxpr(*operands)
|
97
|
-
stateful_false = StatefulFunction(false_fun, name='conda:false').make_jaxpr(*operands)
|
98
|
-
|
99
|
-
# state trace and state values
|
100
|
-
state_trace = stateful_true.get_state_trace() + stateful_false.get_state_trace()
|
101
|
-
read_state_vals = state_trace.get_read_state_values(True)
|
102
|
-
write_state_vals = state_trace.get_write_state_values(True)
|
103
|
-
|
104
|
-
# wrap the functions
|
105
|
-
true_fun = wrap_single_fun_in_multi_branches(stateful_true, state_trace, read_state_vals, True)
|
106
|
-
false_fun = wrap_single_fun_in_multi_branches(stateful_false, state_trace, read_state_vals, True)
|
107
|
-
|
108
|
-
# cond
|
109
|
-
write_state_vals, out = jax.lax.cond(pred, true_fun, false_fun, write_state_vals, *operands)
|
110
|
-
|
111
|
-
# assign the written state values and restore the read state values
|
112
|
-
write_back_state_values(state_trace, read_state_vals, write_state_vals)
|
113
|
-
return out
|
114
|
-
|
115
|
-
|
116
|
-
@set_module_as('brainstate.compile')
|
117
|
-
def switch(index, branches: Sequence[Callable], *operands):
|
118
|
-
"""
|
119
|
-
Apply exactly one of ``branches`` given by ``index``.
|
120
|
-
|
121
|
-
If ``index`` is out of bounds, it is clamped to within bounds.
|
122
|
-
|
123
|
-
Has the semantics of the following Python::
|
124
|
-
|
125
|
-
def switch(index, branches, *operands):
|
126
|
-
index = clamp(0, index, len(branches) - 1)
|
127
|
-
return branches[index](*operands)
|
128
|
-
|
129
|
-
Internally this wraps XLA's `Conditional
|
130
|
-
<https://www.tensorflow.org/xla/operation_semantics#conditional>`_
|
131
|
-
operator. However, when transformed with :func:`~jax.vmap` to operate over a
|
132
|
-
batch of predicates, ``cond`` is converted to :func:`~jax.lax.select`.
|
133
|
-
|
134
|
-
Args:
|
135
|
-
index: Integer scalar type, indicating which branch function to apply.
|
136
|
-
branches: Sequence of functions (A -> B) to be applied based on ``index``.
|
137
|
-
operands: Operands (A) input to whichever branch is applied.
|
138
|
-
|
139
|
-
Returns:
|
140
|
-
Value (B) of ``branch(*operands)`` for the branch that was selected based
|
141
|
-
on ``index``.
|
142
|
-
"""
|
143
|
-
# check branches
|
144
|
-
if not all(callable(branch) for branch in branches):
|
145
|
-
raise TypeError("branches argument should be a sequence of callables.")
|
146
|
-
|
147
|
-
# check index
|
148
|
-
if len(np.shape(index)) != 0:
|
149
|
-
raise TypeError(f"Branch index must be scalar, got {index} of shape {np.shape(index)}.")
|
150
|
-
try:
|
151
|
-
index_dtype = jax.dtypes.result_type(index)
|
152
|
-
except TypeError as err:
|
153
|
-
msg = f"Index type must be an integer, got {index}."
|
154
|
-
raise TypeError(msg) from err
|
155
|
-
if index_dtype.kind not in 'iu':
|
156
|
-
raise TypeError(f"Index type must be an integer, got {index} as {index_dtype}")
|
157
|
-
|
158
|
-
# format branches
|
159
|
-
branches = tuple(branches)
|
160
|
-
if len(branches) == 0:
|
161
|
-
raise ValueError("Empty branch sequence")
|
162
|
-
elif len(branches) == 1:
|
163
|
-
return branches[0](*operands)
|
164
|
-
|
165
|
-
# format index
|
166
|
-
index = jax.lax.convert_element_type(index, np.int32)
|
167
|
-
lo = np.array(0, np.int32)
|
168
|
-
hi = np.array(len(branches) - 1, np.int32)
|
169
|
-
index = jax.lax.clamp(lo, index, hi)
|
170
|
-
|
171
|
-
# not jit
|
172
|
-
if jax.config.jax_disable_jit and isinstance(jax.core.core.get_aval(index), jax.core.ConcreteArray):
|
173
|
-
return branches[int(index)](*operands)
|
174
|
-
|
175
|
-
# evaluate jaxpr
|
176
|
-
wrapped_branches = [StatefulFunction(branch, name='switch') for branch in branches]
|
177
|
-
for wrapped_branch in wrapped_branches:
|
178
|
-
wrapped_branch.make_jaxpr(*operands)
|
179
|
-
|
180
|
-
# wrap the functions
|
181
|
-
state_trace = wrapped_branches[0].get_state_trace() + wrapped_branches[1].get_state_trace()
|
182
|
-
state_trace.merge(*[wrapped_branch.get_state_trace() for wrapped_branch in wrapped_branches[2:]])
|
183
|
-
read_state_vals = state_trace.get_read_state_values(True)
|
184
|
-
write_state_vals = state_trace.get_write_state_values(True)
|
185
|
-
branches = [
|
186
|
-
wrap_single_fun_in_multi_branches(wrapped_branch, state_trace, read_state_vals, True)
|
187
|
-
for wrapped_branch in wrapped_branches
|
188
|
-
]
|
189
|
-
|
190
|
-
# switch
|
191
|
-
write_state_vals, out = jax.lax.switch(index, branches, write_state_vals, *operands)
|
192
|
-
|
193
|
-
# write back state values or restore them
|
194
|
-
write_back_state_values(state_trace, read_state_vals, write_state_vals)
|
195
|
-
return out
|
196
|
-
|
197
|
-
|
198
|
-
@set_module_as('brainstate.compile')
|
199
|
-
def ifelse(conditions, branches, *operands, check_cond: bool = True):
|
200
|
-
"""
|
201
|
-
``If-else`` control flows looks like native Pythonic programming.
|
202
|
-
|
203
|
-
Examples
|
204
|
-
--------
|
205
|
-
|
206
|
-
>>> import brainstate
|
207
|
-
>>> def f(a):
|
208
|
-
>>> return brainstate.compile.ifelse(conditions=[a > 10, a > 5, a > 2, a > 0],
|
209
|
-
>>> branches=[lambda: 1,
|
210
|
-
>>> lambda: 2,
|
211
|
-
>>> lambda: 3,
|
212
|
-
>>> lambda: 4,
|
213
|
-
>>> lambda: 5])
|
214
|
-
>>> f(1)
|
215
|
-
4
|
216
|
-
>>> f(0)
|
217
|
-
5
|
218
|
-
|
219
|
-
Parameters
|
220
|
-
----------
|
221
|
-
conditions: bool, sequence of bool, Array
|
222
|
-
The boolean conditions.
|
223
|
-
branches: Any
|
224
|
-
The branches, at least has two elements. Elements can be functions,
|
225
|
-
arrays, or numbers. The number of ``branches`` and ``conditions`` has
|
226
|
-
the relationship of `len(branches) == len(conditions) + 1`.
|
227
|
-
Each branch should receive one arguement for ``operands``.
|
228
|
-
*operands: optional, Any
|
229
|
-
The operands for each branch.
|
230
|
-
check_cond: bool
|
231
|
-
Whether to check the conditions. Default is True.
|
232
|
-
|
233
|
-
Returns
|
234
|
-
-------
|
235
|
-
res: Any
|
236
|
-
The results of the control flow.
|
237
|
-
"""
|
238
|
-
# check branches
|
239
|
-
if not all(callable(branch) for branch in branches):
|
240
|
-
raise TypeError("branches argument should be a sequence of callables.")
|
241
|
-
|
242
|
-
# format branches
|
243
|
-
branches = tuple(branches)
|
244
|
-
if len(branches) == 0:
|
245
|
-
raise ValueError("Empty branch sequence")
|
246
|
-
elif len(branches) == 1:
|
247
|
-
return branches[0](*operands)
|
248
|
-
if len(conditions) != len(branches):
|
249
|
-
raise ValueError("The number of conditions should be equal to the number of branches.")
|
250
|
-
|
251
|
-
# format index
|
252
|
-
conditions = jnp.asarray(conditions, np.int32)
|
253
|
-
if check_cond:
|
254
|
-
jit_error_if(jnp.sum(conditions) != 1, "Only one condition can be True. But got {}.", err_arg=conditions)
|
255
|
-
index = jnp.where(conditions, size=1, fill_value=len(conditions) - 1)[0][0]
|
256
|
-
return switch(index, branches, *operands)
|
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 collections.abc import Callable, Sequence
|
17
|
+
|
18
|
+
import jax
|
19
|
+
import jax.numpy as jnp
|
20
|
+
import numpy as np
|
21
|
+
|
22
|
+
from brainstate._compatible_import import to_concrete_aval, Tracer
|
23
|
+
from brainstate._utils import set_module_as
|
24
|
+
from ._error_if import jit_error_if
|
25
|
+
from ._make_jaxpr import StatefulFunction
|
26
|
+
from ._util import wrap_single_fun_in_multi_branches, write_back_state_values
|
27
|
+
|
28
|
+
__all__ = [
|
29
|
+
'cond', 'switch', 'ifelse',
|
30
|
+
]
|
31
|
+
|
32
|
+
|
33
|
+
@set_module_as('brainstate.compile')
|
34
|
+
def cond(pred, true_fun: Callable, false_fun: Callable, *operands):
|
35
|
+
"""
|
36
|
+
Conditionally apply ``true_fun`` or ``false_fun``.
|
37
|
+
|
38
|
+
Provided arguments are correctly typed, ``cond()`` has equivalent
|
39
|
+
semantics to this Python implementation, where ``pred`` must be a
|
40
|
+
scalar type::
|
41
|
+
|
42
|
+
def cond(pred, true_fun, false_fun, *operands):
|
43
|
+
if pred:
|
44
|
+
return true_fun(*operands)
|
45
|
+
else:
|
46
|
+
return false_fun(*operands)
|
47
|
+
|
48
|
+
|
49
|
+
In contrast with :func:`jax.lax.select`, using ``cond`` indicates that only one of
|
50
|
+
the two branches is executed (up to compiler rewrites and optimizations).
|
51
|
+
However, when transformed with :func:`~jax.vmap` to operate over a batch of
|
52
|
+
predicates, ``cond`` is converted to :func:`~jax.lax.select`.
|
53
|
+
|
54
|
+
Args:
|
55
|
+
pred: Boolean scalar type, indicating which branch function to apply.
|
56
|
+
true_fun: Function (A -> B), to be applied if ``pred`` is True.
|
57
|
+
false_fun: Function (A -> B), to be applied if ``pred`` is False.
|
58
|
+
operands: Operands (A) input to either branch depending on ``pred``. The
|
59
|
+
type can be a scalar, array, or any pytree (nested Python tuple/list/dict)
|
60
|
+
thereof.
|
61
|
+
|
62
|
+
Returns:
|
63
|
+
Value (B) of either ``true_fun(*operands)`` or ``false_fun(*operands)``,
|
64
|
+
depending on the value of ``pred``. The type can be a scalar, array, or any
|
65
|
+
pytree (nested Python tuple/list/dict) thereof.
|
66
|
+
"""
|
67
|
+
if not (callable(true_fun) and callable(false_fun)):
|
68
|
+
raise TypeError("true_fun and false_fun arguments should be callable.")
|
69
|
+
|
70
|
+
if pred is None:
|
71
|
+
raise TypeError("cond predicate is None")
|
72
|
+
if isinstance(pred, Sequence) or np.ndim(pred) != 0:
|
73
|
+
raise TypeError(f"Pred must be a scalar, got {pred} of " +
|
74
|
+
(f"type {type(pred)}" if isinstance(pred, Sequence)
|
75
|
+
else f"shape {np.shape(pred)}."))
|
76
|
+
|
77
|
+
# check pred
|
78
|
+
try:
|
79
|
+
pred_dtype = jax.dtypes.result_type(pred)
|
80
|
+
except TypeError as err:
|
81
|
+
raise TypeError("Pred type must be either boolean or number, got {}.".format(pred)) from err
|
82
|
+
if pred_dtype.kind != 'b':
|
83
|
+
if pred_dtype.kind in 'iuf':
|
84
|
+
pred = pred != 0
|
85
|
+
else:
|
86
|
+
raise TypeError("Pred type must be either boolean or number, got {}.".format(pred_dtype))
|
87
|
+
|
88
|
+
# not jit
|
89
|
+
if jax.config.jax_disable_jit and not isinstance(to_concrete_aval(pred), Tracer):
|
90
|
+
if pred:
|
91
|
+
return true_fun(*operands)
|
92
|
+
else:
|
93
|
+
return false_fun(*operands)
|
94
|
+
|
95
|
+
# evaluate jaxpr
|
96
|
+
stateful_true = StatefulFunction(true_fun, name='cond:true').make_jaxpr(*operands)
|
97
|
+
stateful_false = StatefulFunction(false_fun, name='conda:false').make_jaxpr(*operands)
|
98
|
+
|
99
|
+
# state trace and state values
|
100
|
+
state_trace = stateful_true.get_state_trace() + stateful_false.get_state_trace()
|
101
|
+
read_state_vals = state_trace.get_read_state_values(True)
|
102
|
+
write_state_vals = state_trace.get_write_state_values(True)
|
103
|
+
|
104
|
+
# wrap the functions
|
105
|
+
true_fun = wrap_single_fun_in_multi_branches(stateful_true, state_trace, read_state_vals, True)
|
106
|
+
false_fun = wrap_single_fun_in_multi_branches(stateful_false, state_trace, read_state_vals, True)
|
107
|
+
|
108
|
+
# cond
|
109
|
+
write_state_vals, out = jax.lax.cond(pred, true_fun, false_fun, write_state_vals, *operands)
|
110
|
+
|
111
|
+
# assign the written state values and restore the read state values
|
112
|
+
write_back_state_values(state_trace, read_state_vals, write_state_vals)
|
113
|
+
return out
|
114
|
+
|
115
|
+
|
116
|
+
@set_module_as('brainstate.compile')
|
117
|
+
def switch(index, branches: Sequence[Callable], *operands):
|
118
|
+
"""
|
119
|
+
Apply exactly one of ``branches`` given by ``index``.
|
120
|
+
|
121
|
+
If ``index`` is out of bounds, it is clamped to within bounds.
|
122
|
+
|
123
|
+
Has the semantics of the following Python::
|
124
|
+
|
125
|
+
def switch(index, branches, *operands):
|
126
|
+
index = clamp(0, index, len(branches) - 1)
|
127
|
+
return branches[index](*operands)
|
128
|
+
|
129
|
+
Internally this wraps XLA's `Conditional
|
130
|
+
<https://www.tensorflow.org/xla/operation_semantics#conditional>`_
|
131
|
+
operator. However, when transformed with :func:`~jax.vmap` to operate over a
|
132
|
+
batch of predicates, ``cond`` is converted to :func:`~jax.lax.select`.
|
133
|
+
|
134
|
+
Args:
|
135
|
+
index: Integer scalar type, indicating which branch function to apply.
|
136
|
+
branches: Sequence of functions (A -> B) to be applied based on ``index``.
|
137
|
+
operands: Operands (A) input to whichever branch is applied.
|
138
|
+
|
139
|
+
Returns:
|
140
|
+
Value (B) of ``branch(*operands)`` for the branch that was selected based
|
141
|
+
on ``index``.
|
142
|
+
"""
|
143
|
+
# check branches
|
144
|
+
if not all(callable(branch) for branch in branches):
|
145
|
+
raise TypeError("branches argument should be a sequence of callables.")
|
146
|
+
|
147
|
+
# check index
|
148
|
+
if len(np.shape(index)) != 0:
|
149
|
+
raise TypeError(f"Branch index must be scalar, got {index} of shape {np.shape(index)}.")
|
150
|
+
try:
|
151
|
+
index_dtype = jax.dtypes.result_type(index)
|
152
|
+
except TypeError as err:
|
153
|
+
msg = f"Index type must be an integer, got {index}."
|
154
|
+
raise TypeError(msg) from err
|
155
|
+
if index_dtype.kind not in 'iu':
|
156
|
+
raise TypeError(f"Index type must be an integer, got {index} as {index_dtype}")
|
157
|
+
|
158
|
+
# format branches
|
159
|
+
branches = tuple(branches)
|
160
|
+
if len(branches) == 0:
|
161
|
+
raise ValueError("Empty branch sequence")
|
162
|
+
elif len(branches) == 1:
|
163
|
+
return branches[0](*operands)
|
164
|
+
|
165
|
+
# format index
|
166
|
+
index = jax.lax.convert_element_type(index, np.int32)
|
167
|
+
lo = np.array(0, np.int32)
|
168
|
+
hi = np.array(len(branches) - 1, np.int32)
|
169
|
+
index = jax.lax.clamp(lo, index, hi)
|
170
|
+
|
171
|
+
# not jit
|
172
|
+
if jax.config.jax_disable_jit and isinstance(jax.core.core.get_aval(index), jax.core.ConcreteArray):
|
173
|
+
return branches[int(index)](*operands)
|
174
|
+
|
175
|
+
# evaluate jaxpr
|
176
|
+
wrapped_branches = [StatefulFunction(branch, name='switch') for branch in branches]
|
177
|
+
for wrapped_branch in wrapped_branches:
|
178
|
+
wrapped_branch.make_jaxpr(*operands)
|
179
|
+
|
180
|
+
# wrap the functions
|
181
|
+
state_trace = wrapped_branches[0].get_state_trace() + wrapped_branches[1].get_state_trace()
|
182
|
+
state_trace.merge(*[wrapped_branch.get_state_trace() for wrapped_branch in wrapped_branches[2:]])
|
183
|
+
read_state_vals = state_trace.get_read_state_values(True)
|
184
|
+
write_state_vals = state_trace.get_write_state_values(True)
|
185
|
+
branches = [
|
186
|
+
wrap_single_fun_in_multi_branches(wrapped_branch, state_trace, read_state_vals, True)
|
187
|
+
for wrapped_branch in wrapped_branches
|
188
|
+
]
|
189
|
+
|
190
|
+
# switch
|
191
|
+
write_state_vals, out = jax.lax.switch(index, branches, write_state_vals, *operands)
|
192
|
+
|
193
|
+
# write back state values or restore them
|
194
|
+
write_back_state_values(state_trace, read_state_vals, write_state_vals)
|
195
|
+
return out
|
196
|
+
|
197
|
+
|
198
|
+
@set_module_as('brainstate.compile')
|
199
|
+
def ifelse(conditions, branches, *operands, check_cond: bool = True):
|
200
|
+
"""
|
201
|
+
``If-else`` control flows looks like native Pythonic programming.
|
202
|
+
|
203
|
+
Examples
|
204
|
+
--------
|
205
|
+
|
206
|
+
>>> import brainstate
|
207
|
+
>>> def f(a):
|
208
|
+
>>> return brainstate.compile.ifelse(conditions=[a > 10, a > 5, a > 2, a > 0],
|
209
|
+
>>> branches=[lambda: 1,
|
210
|
+
>>> lambda: 2,
|
211
|
+
>>> lambda: 3,
|
212
|
+
>>> lambda: 4,
|
213
|
+
>>> lambda: 5])
|
214
|
+
>>> f(1)
|
215
|
+
4
|
216
|
+
>>> f(0)
|
217
|
+
5
|
218
|
+
|
219
|
+
Parameters
|
220
|
+
----------
|
221
|
+
conditions: bool, sequence of bool, Array
|
222
|
+
The boolean conditions.
|
223
|
+
branches: Any
|
224
|
+
The branches, at least has two elements. Elements can be functions,
|
225
|
+
arrays, or numbers. The number of ``branches`` and ``conditions`` has
|
226
|
+
the relationship of `len(branches) == len(conditions) + 1`.
|
227
|
+
Each branch should receive one arguement for ``operands``.
|
228
|
+
*operands: optional, Any
|
229
|
+
The operands for each branch.
|
230
|
+
check_cond: bool
|
231
|
+
Whether to check the conditions. Default is True.
|
232
|
+
|
233
|
+
Returns
|
234
|
+
-------
|
235
|
+
res: Any
|
236
|
+
The results of the control flow.
|
237
|
+
"""
|
238
|
+
# check branches
|
239
|
+
if not all(callable(branch) for branch in branches):
|
240
|
+
raise TypeError("branches argument should be a sequence of callables.")
|
241
|
+
|
242
|
+
# format branches
|
243
|
+
branches = tuple(branches)
|
244
|
+
if len(branches) == 0:
|
245
|
+
raise ValueError("Empty branch sequence")
|
246
|
+
elif len(branches) == 1:
|
247
|
+
return branches[0](*operands)
|
248
|
+
if len(conditions) != len(branches):
|
249
|
+
raise ValueError("The number of conditions should be equal to the number of branches.")
|
250
|
+
|
251
|
+
# format index
|
252
|
+
conditions = jnp.asarray(conditions, np.int32)
|
253
|
+
if check_cond:
|
254
|
+
jit_error_if(jnp.sum(conditions) != 1, "Only one condition can be True. But got {}.", err_arg=conditions)
|
255
|
+
index = jnp.where(conditions, size=1, fill_value=len(conditions) - 1)[0][0]
|
256
|
+
return switch(index, branches, *operands)
|