bartz 0.6.0__py3-none-any.whl → 0.7.0__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.
@@ -0,0 +1,238 @@
1
+ # bartz/src/bartz/jaxext/_autobatch.py
2
+ #
3
+ # Copyright (c) 2025, Giacomo Petrillo
4
+ #
5
+ # This file is part of bartz.
6
+ #
7
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ # of this software and associated documentation files (the "Software"), to deal
9
+ # in the Software without restriction, including without limitation the rights
10
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ # copies of the Software, and to permit persons to whom the Software is
12
+ # furnished to do so, subject to the following conditions:
13
+ #
14
+ # The above copyright notice and this permission notice shall be included in all
15
+ # copies or substantial portions of the Software.
16
+ #
17
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
+ # SOFTWARE.
24
+
25
+ """Implementation of `autobatch`."""
26
+
27
+ import math
28
+ from collections.abc import Callable
29
+ from functools import wraps
30
+ from warnings import warn
31
+
32
+ from jax import eval_shape, jit
33
+ from jax import numpy as jnp
34
+ from jax.lax import scan
35
+ from jax.tree import flatten as tree_flatten
36
+ from jax.tree import map as tree_map
37
+ from jax.tree import reduce as tree_reduce
38
+ from jaxtyping import PyTree
39
+
40
+
41
+ def expand_axes(axes, tree):
42
+ """Expand `axes` such that they match the pytreedef of `tree`."""
43
+
44
+ def expand_axis(axis, subtree):
45
+ return tree_map(lambda _: axis, subtree)
46
+
47
+ return tree_map(expand_axis, axes, tree, is_leaf=lambda x: x is None)
48
+
49
+
50
+ def check_no_nones(axes, tree):
51
+ def check_not_none(_, axis):
52
+ assert axis is not None
53
+
54
+ tree_map(check_not_none, tree, axes)
55
+
56
+
57
+ def extract_size(axes, tree):
58
+ def get_size(x, axis):
59
+ if axis is None:
60
+ return None
61
+ else:
62
+ return x.shape[axis]
63
+
64
+ sizes = tree_map(get_size, tree, axes)
65
+ sizes, _ = tree_flatten(sizes)
66
+ assert all(s == sizes[0] for s in sizes)
67
+ return sizes[0]
68
+
69
+
70
+ def sum_nbytes(tree):
71
+ def nbytes(x):
72
+ return math.prod(x.shape) * x.dtype.itemsize
73
+
74
+ return tree_reduce(lambda size, x: size + nbytes(x), tree, 0)
75
+
76
+
77
+ def next_divisor_small(dividend, min_divisor):
78
+ for divisor in range(min_divisor, int(math.sqrt(dividend)) + 1):
79
+ if dividend % divisor == 0:
80
+ return divisor
81
+ return dividend
82
+
83
+
84
+ def next_divisor_large(dividend, min_divisor):
85
+ max_inv_divisor = dividend // min_divisor
86
+ for inv_divisor in range(max_inv_divisor, 0, -1):
87
+ if dividend % inv_divisor == 0:
88
+ return dividend // inv_divisor
89
+ return dividend
90
+
91
+
92
+ def next_divisor(dividend, min_divisor):
93
+ if dividend == 0:
94
+ return min_divisor
95
+ if min_divisor * min_divisor <= dividend:
96
+ return next_divisor_small(dividend, min_divisor)
97
+ return next_divisor_large(dividend, min_divisor)
98
+
99
+
100
+ def pull_nonbatched(axes, tree):
101
+ def pull_nonbatched(x, axis):
102
+ if axis is None:
103
+ return None
104
+ else:
105
+ return x
106
+
107
+ return tree_map(pull_nonbatched, tree, axes), tree
108
+
109
+
110
+ def push_nonbatched(axes, tree, original_tree):
111
+ def push_nonbatched(original_x, x, axis):
112
+ if axis is None:
113
+ return original_x
114
+ else:
115
+ return x
116
+
117
+ return tree_map(push_nonbatched, original_tree, tree, axes)
118
+
119
+
120
+ def move_axes_out(axes, tree):
121
+ def move_axis_out(x, axis):
122
+ return jnp.moveaxis(x, axis, 0)
123
+
124
+ return tree_map(move_axis_out, tree, axes)
125
+
126
+
127
+ def move_axes_in(axes, tree):
128
+ def move_axis_in(x, axis):
129
+ return jnp.moveaxis(x, 0, axis)
130
+
131
+ return tree_map(move_axis_in, tree, axes)
132
+
133
+
134
+ def batch(tree, nbatches):
135
+ def batch(x):
136
+ return x.reshape((nbatches, x.shape[0] // nbatches) + x.shape[1:])
137
+
138
+ return tree_map(batch, tree)
139
+
140
+
141
+ def unbatch(tree):
142
+ def unbatch(x):
143
+ return x.reshape((x.shape[0] * x.shape[1],) + x.shape[2:])
144
+
145
+ return tree_map(unbatch, tree)
146
+
147
+
148
+ def check_same(tree1, tree2):
149
+ def check_same(x1, x2):
150
+ assert x1.shape == x2.shape
151
+ assert x1.dtype == x2.dtype
152
+
153
+ tree_map(check_same, tree1, tree2)
154
+
155
+
156
+ def autobatch(
157
+ func: Callable,
158
+ max_io_nbytes: int,
159
+ in_axes: PyTree[int | None] = 0,
160
+ out_axes: PyTree[int] = 0,
161
+ return_nbatches: bool = False,
162
+ ) -> Callable:
163
+ """
164
+ Batch a function such that each batch is smaller than a threshold.
165
+
166
+ Parameters
167
+ ----------
168
+ func
169
+ A jittable function with positional arguments only, with inputs and
170
+ outputs pytrees of arrays.
171
+ max_io_nbytes
172
+ The maximum number of input + output bytes in each batch (excluding
173
+ unbatched arguments.)
174
+ in_axes
175
+ A tree matching (a prefix of) the structure of the function input,
176
+ indicating along which axes each array should be batched. A `None` axis
177
+ indicates to not batch an argument.
178
+ out_axes
179
+ The same for outputs (but non-batching is not allowed).
180
+ return_nbatches
181
+ If True, the number of batches is returned as a second output.
182
+
183
+ Returns
184
+ -------
185
+ A function with the same signature as `func`, save for the return value if `return_nbatches`.
186
+ """
187
+ initial_in_axes = in_axes
188
+ initial_out_axes = out_axes
189
+
190
+ @jit
191
+ @wraps(func)
192
+ def batched_func(*args):
193
+ example_result = eval_shape(func, *args)
194
+
195
+ in_axes = expand_axes(initial_in_axes, args)
196
+ out_axes = expand_axes(initial_out_axes, example_result)
197
+ check_no_nones(out_axes, example_result)
198
+
199
+ size = extract_size((in_axes, out_axes), (args, example_result))
200
+
201
+ args, nonbatched_args = pull_nonbatched(in_axes, args)
202
+
203
+ total_nbytes = sum_nbytes((args, example_result))
204
+ min_nbatches = total_nbytes // max_io_nbytes + bool(
205
+ total_nbytes % max_io_nbytes
206
+ )
207
+ min_nbatches = max(1, min_nbatches)
208
+ nbatches = next_divisor(size, min_nbatches)
209
+ assert 1 <= nbatches <= max(1, size)
210
+ assert size % nbatches == 0
211
+ assert total_nbytes % nbatches == 0
212
+
213
+ batch_nbytes = total_nbytes // nbatches
214
+ if batch_nbytes > max_io_nbytes:
215
+ assert size == nbatches
216
+ msg = f'batch_nbytes = {batch_nbytes} > max_io_nbytes = {max_io_nbytes}'
217
+ warn(msg)
218
+
219
+ def loop(_, args):
220
+ args = move_axes_in(in_axes, args)
221
+ args = push_nonbatched(in_axes, args, nonbatched_args)
222
+ result = func(*args)
223
+ result = move_axes_out(out_axes, result)
224
+ return None, result
225
+
226
+ args = move_axes_out(in_axes, args)
227
+ args = batch(args, nbatches)
228
+ _, result = scan(loop, None, args)
229
+ result = unbatch(result)
230
+ result = move_axes_in(out_axes, result)
231
+
232
+ check_same(example_result, result)
233
+
234
+ if return_nbatches:
235
+ return result, nbatches
236
+ return result
237
+
238
+ return batched_func
@@ -0,0 +1,25 @@
1
+ # bartz/src/bartz/jaxext/scipy/__init__.py
2
+ #
3
+ # Copyright (c) 2025, Giacomo Petrillo
4
+ #
5
+ # This file is part of bartz.
6
+ #
7
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ # of this software and associated documentation files (the "Software"), to deal
9
+ # in the Software without restriction, including without limitation the rights
10
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ # copies of the Software, and to permit persons to whom the Software is
12
+ # furnished to do so, subject to the following conditions:
13
+ #
14
+ # The above copyright notice and this permission notice shall be included in all
15
+ # copies or substantial portions of the Software.
16
+ #
17
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
+ # SOFTWARE.
24
+
25
+ """Mockup of the :external:py:mod:`scipy` module."""
@@ -0,0 +1,240 @@
1
+ # bartz/src/bartz/jaxext/scipy/special.py
2
+ #
3
+ # Copyright (c) 2025, Giacomo Petrillo
4
+ #
5
+ # This file is part of bartz.
6
+ #
7
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ # of this software and associated documentation files (the "Software"), to deal
9
+ # in the Software without restriction, including without limitation the rights
10
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ # copies of the Software, and to permit persons to whom the Software is
12
+ # furnished to do so, subject to the following conditions:
13
+ #
14
+ # The above copyright notice and this permission notice shall be included in all
15
+ # copies or substantial portions of the Software.
16
+ #
17
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
+ # SOFTWARE.
24
+
25
+ """Mockup of the :external:py:mod:`scipy.special` module."""
26
+
27
+ from functools import wraps
28
+
29
+ from jax import ShapeDtypeStruct, pure_callback
30
+ from jax import numpy as jnp
31
+ from scipy.special import gammainccinv as scipy_gammainccinv
32
+
33
+
34
+ def _float_type(*args):
35
+ """Determine the jax floating point result type given operands/types."""
36
+ t = jnp.result_type(*args)
37
+ return jnp.sin(jnp.empty(0, t)).dtype
38
+
39
+
40
+ def _castto(func, dtype):
41
+ @wraps(func)
42
+ def newfunc(*args, **kw):
43
+ return func(*args, **kw).astype(dtype)
44
+
45
+ return newfunc
46
+
47
+
48
+ def gammainccinv(a, y):
49
+ """Survival function inverse of the Gamma(a, 1) distribution."""
50
+ a = jnp.asarray(a)
51
+ y = jnp.asarray(y)
52
+ shape = jnp.broadcast_shapes(a.shape, y.shape)
53
+ dtype = _float_type(a.dtype, y.dtype)
54
+ dummy = ShapeDtypeStruct(shape, dtype)
55
+ ufunc = _castto(scipy_gammainccinv, dtype)
56
+ return pure_callback(ufunc, dummy, a, y, vmap_method='expand_dims')
57
+
58
+
59
+ ################# COPIED AND ADAPTED FROM JAX ##################
60
+ # Copyright 2018 The JAX Authors.
61
+ #
62
+ # Licensed under the Apache License, Version 2.0 (the "License");
63
+ # you may not use this file except in compliance with the License.
64
+ # You may obtain a copy of the License at
65
+ #
66
+ # https://www.apache.org/licenses/LICENSE-2.0
67
+ #
68
+ # Unless required by applicable law or agreed to in writing, software
69
+ # distributed under the License is distributed on an "AS IS" BASIS,
70
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
71
+ # See the License for the specific language governing permissions and
72
+ # limitations under the License.
73
+
74
+ import numpy as np
75
+ from jax import debug_infs, lax
76
+
77
+
78
+ def ndtri(p):
79
+ """Compute the inverse of the CDF of the Normal distribution function.
80
+
81
+ This is a patch of `jax.scipy.special.ndtri`.
82
+ """
83
+ dtype = lax.dtype(p)
84
+ if dtype not in (jnp.float32, jnp.float64):
85
+ msg = f'x.dtype={dtype} is not supported, see docstring for supported types.'
86
+ raise TypeError(msg)
87
+ return _ndtri(p)
88
+
89
+
90
+ def _ndtri(p):
91
+ # Constants used in piece-wise rational approximations. Taken from the cephes
92
+ # library:
93
+ # https://root.cern.ch/doc/v608/SpecFuncCephesInv_8cxx_source.html
94
+ p0 = list(
95
+ reversed(
96
+ [
97
+ -5.99633501014107895267e1,
98
+ 9.80010754185999661536e1,
99
+ -5.66762857469070293439e1,
100
+ 1.39312609387279679503e1,
101
+ -1.23916583867381258016e0,
102
+ ]
103
+ )
104
+ )
105
+ q0 = list(
106
+ reversed(
107
+ [
108
+ 1.0,
109
+ 1.95448858338141759834e0,
110
+ 4.67627912898881538453e0,
111
+ 8.63602421390890590575e1,
112
+ -2.25462687854119370527e2,
113
+ 2.00260212380060660359e2,
114
+ -8.20372256168333339912e1,
115
+ 1.59056225126211695515e1,
116
+ -1.18331621121330003142e0,
117
+ ]
118
+ )
119
+ )
120
+ p1 = list(
121
+ reversed(
122
+ [
123
+ 4.05544892305962419923e0,
124
+ 3.15251094599893866154e1,
125
+ 5.71628192246421288162e1,
126
+ 4.40805073893200834700e1,
127
+ 1.46849561928858024014e1,
128
+ 2.18663306850790267539e0,
129
+ -1.40256079171354495875e-1,
130
+ -3.50424626827848203418e-2,
131
+ -8.57456785154685413611e-4,
132
+ ]
133
+ )
134
+ )
135
+ q1 = list(
136
+ reversed(
137
+ [
138
+ 1.0,
139
+ 1.57799883256466749731e1,
140
+ 4.53907635128879210584e1,
141
+ 4.13172038254672030440e1,
142
+ 1.50425385692907503408e1,
143
+ 2.50464946208309415979e0,
144
+ -1.42182922854787788574e-1,
145
+ -3.80806407691578277194e-2,
146
+ -9.33259480895457427372e-4,
147
+ ]
148
+ )
149
+ )
150
+ p2 = list(
151
+ reversed(
152
+ [
153
+ 3.23774891776946035970e0,
154
+ 6.91522889068984211695e0,
155
+ 3.93881025292474443415e0,
156
+ 1.33303460815807542389e0,
157
+ 2.01485389549179081538e-1,
158
+ 1.23716634817820021358e-2,
159
+ 3.01581553508235416007e-4,
160
+ 2.65806974686737550832e-6,
161
+ 6.23974539184983293730e-9,
162
+ ]
163
+ )
164
+ )
165
+ q2 = list(
166
+ reversed(
167
+ [
168
+ 1.0,
169
+ 6.02427039364742014255e0,
170
+ 3.67983563856160859403e0,
171
+ 1.37702099489081330271e0,
172
+ 2.16236993594496635890e-1,
173
+ 1.34204006088543189037e-2,
174
+ 3.28014464682127739104e-4,
175
+ 2.89247864745380683936e-6,
176
+ 6.79019408009981274425e-9,
177
+ ]
178
+ )
179
+ )
180
+
181
+ dtype = lax.dtype(p).type
182
+ shape = jnp.shape(p)
183
+
184
+ def _create_polynomial(var, coeffs):
185
+ """Compute n_th order polynomial via Horner's method."""
186
+ coeffs = np.array(coeffs, dtype)
187
+ if not coeffs.size:
188
+ return jnp.zeros_like(var)
189
+ return coeffs[0] + _create_polynomial(var, coeffs[1:]) * var
190
+
191
+ maybe_complement_p = jnp.where(p > dtype(-np.expm1(-2.0)), dtype(1.0) - p, p)
192
+ # Write in an arbitrary value in place of 0 for p since 0 will cause NaNs
193
+ # later on. The result from the computation when p == 0 is not used so any
194
+ # number that doesn't result in NaNs is fine.
195
+ sanitized_mcp = jnp.where(
196
+ maybe_complement_p == dtype(0.0),
197
+ jnp.full(shape, dtype(0.5)),
198
+ maybe_complement_p,
199
+ )
200
+
201
+ # Compute x for p > exp(-2): x/sqrt(2pi) = w + w**3 P0(w**2)/Q0(w**2).
202
+ w = sanitized_mcp - dtype(0.5)
203
+ ww = lax.square(w)
204
+ x_for_big_p = w + w * ww * (_create_polynomial(ww, p0) / _create_polynomial(ww, q0))
205
+ x_for_big_p *= -dtype(np.sqrt(2.0 * np.pi))
206
+
207
+ # Compute x for p <= exp(-2): x = z - log(z)/z - (1/z) P(1/z) / Q(1/z),
208
+ # where z = sqrt(-2. * log(p)), and P/Q are chosen between two different
209
+ # arrays based on whether p < exp(-32).
210
+ z = lax.sqrt(dtype(-2.0) * lax.log(sanitized_mcp))
211
+ first_term = z - lax.log(z) / z
212
+ second_term_small_p = (
213
+ _create_polynomial(dtype(1.0) / z, p2)
214
+ / _create_polynomial(dtype(1.0) / z, q2)
215
+ / z
216
+ )
217
+ second_term_otherwise = (
218
+ _create_polynomial(dtype(1.0) / z, p1)
219
+ / _create_polynomial(dtype(1.0) / z, q1)
220
+ / z
221
+ )
222
+ x_for_small_p = first_term - second_term_small_p
223
+ x_otherwise = first_term - second_term_otherwise
224
+
225
+ x = jnp.where(
226
+ sanitized_mcp > dtype(np.exp(-2.0)),
227
+ x_for_big_p,
228
+ jnp.where(z >= dtype(8.0), x_for_small_p, x_otherwise),
229
+ )
230
+
231
+ x = jnp.where(p > dtype(1.0 - np.exp(-2.0)), x, -x)
232
+ with debug_infs(False):
233
+ infinity = jnp.full(shape, dtype(np.inf))
234
+ neg_infinity = -infinity
235
+ return jnp.where(
236
+ p == dtype(0.0), neg_infinity, jnp.where(p == dtype(1.0), infinity, x)
237
+ )
238
+
239
+
240
+ ################################################################
@@ -0,0 +1,36 @@
1
+ # bartz/src/bartz/jaxext/scipy/stats.py
2
+ #
3
+ # Copyright (c) 2025, Giacomo Petrillo
4
+ #
5
+ # This file is part of bartz.
6
+ #
7
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ # of this software and associated documentation files (the "Software"), to deal
9
+ # in the Software without restriction, including without limitation the rights
10
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ # copies of the Software, and to permit persons to whom the Software is
12
+ # furnished to do so, subject to the following conditions:
13
+ #
14
+ # The above copyright notice and this permission notice shall be included in all
15
+ # copies or substantial portions of the Software.
16
+ #
17
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
+ # SOFTWARE.
24
+
25
+ """Mockup of the :external:py:mod:`scipy.stats` module."""
26
+
27
+ from bartz.jaxext.scipy.special import gammainccinv
28
+
29
+
30
+ class invgamma:
31
+ """Class that represents the distribution InvGamma(a, 1)."""
32
+
33
+ @staticmethod
34
+ def ppf(q, a):
35
+ """Percentile point function."""
36
+ return 1 / gammainccinv(a, q)