brainstate 0.0.2.post20240825__py2.py3-none-any.whl → 0.0.2.post20240910__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.
@@ -1,180 +0,0 @@
1
- # Copyright 2024 BDP Ecosystem Limited. All Rights Reserved.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing, software
10
- # distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
- # ==============================================================================
15
-
16
- from __future__ import annotations
17
-
18
- import functools
19
- from functools import partial
20
- from typing import Callable, Union
21
-
22
- import jax
23
- from jax import numpy as jnp
24
- from jax.core import Primitive, ShapedArray
25
- from jax.interpreters import batching, mlir
26
-
27
- from brainstate._utils import set_module_as
28
-
29
- __all__ = [
30
- 'jit_error',
31
- ]
32
-
33
-
34
- @set_module_as('brainstate.transform')
35
- def remove_vmap(x, op: str = 'any'):
36
- if op == 'any':
37
- return _any_without_vmap(x)
38
- elif op == 'all':
39
- return _all_without_vmap(x)
40
- elif op == 'none':
41
- return _without_vmap(x)
42
- else:
43
- raise ValueError(f'Do not support type: {op}')
44
-
45
-
46
- def _without_vmap(x):
47
- return _no_vmap_prim.bind(x)
48
-
49
-
50
- def _without_vmap_imp(x):
51
- return x
52
-
53
-
54
- def _without_vmap_abs(x):
55
- return x
56
-
57
-
58
- def _without_vmap_batch(x, batch_axes):
59
- (x,) = x
60
- return _without_vmap(x), batching.not_mapped
61
-
62
-
63
- _no_vmap_prim = Primitive('no_vmap')
64
- _no_vmap_prim.def_impl(_without_vmap_imp)
65
- _no_vmap_prim.def_abstract_eval(_without_vmap_abs)
66
- batching.primitive_batchers[_no_vmap_prim] = _without_vmap_batch
67
- mlir.register_lowering(_no_vmap_prim, mlir.lower_fun(_without_vmap_imp, multiple_results=False))
68
-
69
-
70
- def _any_without_vmap(x):
71
- return _any_no_vmap_prim.bind(x)
72
-
73
-
74
- def _any_without_vmap_imp(x):
75
- return jnp.any(x)
76
-
77
-
78
- def _any_without_vmap_abs(x):
79
- return ShapedArray(shape=(), dtype=jnp.bool_)
80
-
81
-
82
- def _any_without_vmap_batch(x, batch_axes):
83
- (x,) = x
84
- return _any_without_vmap(x), batching.not_mapped
85
-
86
-
87
- _any_no_vmap_prim = Primitive('any_no_vmap')
88
- _any_no_vmap_prim.def_impl(_any_without_vmap_imp)
89
- _any_no_vmap_prim.def_abstract_eval(_any_without_vmap_abs)
90
- batching.primitive_batchers[_any_no_vmap_prim] = _any_without_vmap_batch
91
- mlir.register_lowering(_any_no_vmap_prim, mlir.lower_fun(_any_without_vmap_imp, multiple_results=False))
92
-
93
-
94
- def _all_without_vmap(x):
95
- return _all_no_vmap_prim.bind(x)
96
-
97
-
98
- def _all_without_vmap_imp(x):
99
- return jnp.all(x)
100
-
101
-
102
- def _all_without_vmap_abs(x):
103
- return ShapedArray(shape=(), dtype=jnp.bool_)
104
-
105
-
106
- def _all_without_vmap_batch(x, batch_axes):
107
- (x,) = x
108
- return _all_without_vmap(x), batching.not_mapped
109
-
110
-
111
- _all_no_vmap_prim = Primitive('all_no_vmap')
112
- _all_no_vmap_prim.def_impl(_all_without_vmap_imp)
113
- _all_no_vmap_prim.def_abstract_eval(_all_without_vmap_abs)
114
- batching.primitive_batchers[_all_no_vmap_prim] = _all_without_vmap_batch
115
- mlir.register_lowering(_all_no_vmap_prim, mlir.lower_fun(_all_without_vmap_imp, multiple_results=False))
116
-
117
-
118
- def _err_jit_true_branch(err_fun, args, kwargs):
119
- jax.debug.callback(err_fun, *args, **kwargs)
120
-
121
-
122
- def _err_jit_false_branch(args, kwargs):
123
- pass
124
-
125
-
126
- def _error_msg(msg, *arg, **kwargs):
127
- if len(arg):
128
- msg = msg % arg
129
- if len(kwargs):
130
- msg = msg.format(**kwargs)
131
- raise ValueError(msg)
132
-
133
-
134
- @set_module_as('brainstate.transform')
135
- def jit_error(
136
- pred,
137
- err_fun: Union[Callable, str],
138
- *err_args,
139
- **err_kwargs,
140
- ):
141
- """
142
- Check errors in a jit function.
143
-
144
- Examples
145
- --------
146
-
147
- It can give a function which receive arguments that passed from the JIT variables and raise errors.
148
-
149
- >>> def error(x):
150
- >>> raise ValueError(f'error {x}')
151
- >>> x = jax.random.uniform(jax.random.PRNGKey(0), (10,))
152
- >>> jit_error(x.sum() < 5., error, x)
153
-
154
- Or, it can be a simple string message.
155
-
156
- >>> x = jax.random.uniform(jax.random.PRNGKey(0), (10,))
157
- >>> jit_error(x.sum() < 5., "Error: the sum is less than 5. Got {s}", s=x.sum())
158
-
159
-
160
- Parameters
161
- ----------
162
- pred: bool, Array
163
- The boolean prediction.
164
- err_fun: callable
165
- The error function, which raise errors.
166
- err_args:
167
- The arguments which passed into `err_f`.
168
- err_kwargs:
169
- The keywords which passed into `err_f`.
170
- """
171
- if isinstance(err_fun, str):
172
- err_fun = partial(_error_msg, err_fun)
173
-
174
- jax.lax.cond(
175
- remove_vmap(pred, op='any'),
176
- partial(_err_jit_true_branch, err_fun),
177
- _err_jit_false_branch,
178
- jax.tree.map(functools.partial(remove_vmap, op='none'), err_args),
179
- jax.tree.map(functools.partial(remove_vmap, op='none'), err_kwargs),
180
- )