Coverage for src/lsqfitgp/_patch_jax.py: 88%
30 statements
« prev ^ index » next coverage.py v7.16.1, created at 2026-10-04 11:43 +0000
« prev ^ index » next coverage.py v7.16.1, created at 2026-10-04 11:43 +0000
1# lsqfitgp/_patch_jax.py
2#
3# Copyright (c) 2022, 2023, 2026, Giacomo Petrillo
4#
5# This file is part of lsqfitgp.
6#
7# lsqfitgp is free software: you can redistribute it and/or modify
8# it under the terms of the GNU General Public License as published by
9# the Free Software Foundation, either version 3 of the License, or
10# (at your option) any later version.
11#
12# lsqfitgp is distributed in the hope that it will be useful,
13# but WITHOUT ANY WARRANTY; without even the implied warranty of
14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15# GNU General Public License for more details.
16#
17# You should have received a copy of the GNU General Public License
18# along with lsqfitgp. If not, see <http://www.gnu.org/licenses/>.
20"""Modifications to the global state of jax."""
22import gvar 1cab
23import numpy 1cab
24from jax import config, tree_util 1cab
26config.update('jax_enable_x64', True) 1cab
29class BufferDictPyTreeDef: 1cab
30 @staticmethod 1cab
31 def _skeleton(bd): 1cab
32 """Return a memoryless BufferDict with the same layout as `bd`."""
33 return gvar.BufferDict(bd, buf=numpy.empty(bd.buf.shape, [])) 1ab
34 # BufferDict mirrors the data type of the _buf attribute, so we do not
35 # need to preserve it to maintain consistency. buf is not copied.
37 def __init__(self, bd): 1cab
38 self.skeleton = self._skeleton(bd) 1ab
39 self.layout = {k: tuple(bd.slice_shape(k)) for k in bd} 1ab
40 # it is not necessary to save the data type because that's in buf
42 def __eq__(self, other): 1cab
43 if not isinstance(other, __class__): 43 ↛ 44line 43 didn't jump to line 44 because the condition on line 43 was never true1ab
44 return NotImplemented
45 return self.layout == other.layout 1ab
47 def __hash__(self): 1cab
48 return hash(self.layout)
50 def __repr__(self): 1cab
51 return repr(self.layout)
53 @classmethod 1cab
54 def flatten(cls, bd): 1cab
55 return (bd.buf,), cls(bd) 1ab
57 @classmethod 1cab
58 def unflatten(cls, self, children): 1cab
59 (buf,) = children 1ab
60 new = cls._skeleton(self.skeleton) 1ab
61 # copy the skeleton to permit multiple unflattening
62 new._extension = {} 1ab
63 new._buf = buf 1ab
64 return new 1ab
67# register BufferDict as a pytree
68tree_util.register_pytree_node( 1cab
69 gvar.BufferDict, BufferDictPyTreeDef.flatten, BufferDictPyTreeDef.unflatten
70)