Skip to content

Commit 05a5baf

Browse files
Jammy2211claude
authored andcommitted
feat: add lazy register_pytree_node helpers for opt-in JAX pytree registration
Library code can now register classes as JAX pytree nodes without forcing jax.tree_util to import at module load. Both helpers no-op if JAX is missing, so they're safe to call from code paths that may run without JAX installed. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
1 parent 368d425 commit 05a5baf

1 file changed

Lines changed: 34 additions & 2 deletions

File tree

autoconf/jax_wrapper.py

Lines changed: 34 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,8 +47,40 @@
4747
""""
4848
JAX 64-bit precision has been automatically enabled for you (JAX_ENABLE_X64=True),
4949
as double precision is required for most scientific computing applications.
50-
51-
To enable 64 precision as default in JAX, set the environment variable
50+
51+
To enable 64 precision as default in JAX, set the environment variable
5252
JAX_ENABLE_X64=true before running your script.
5353
"""
5454
)
55+
56+
57+
def register_pytree_node_class(cls):
58+
"""Opt-in JAX pytree class registration that defers the JAX import.
59+
60+
The previous eager registration in ``autofit.mapper.prior_model.prior_model``
61+
forced ``jax.tree_util`` to load whenever ``import autofit`` ran. To keep
62+
JAX an optional dependency, library code now exposes ``tree_flatten`` /
63+
``tree_unflatten`` methods but does NOT register the class itself; callers
64+
that want JAX integration call this helper explicitly (typically via
65+
``autofit.jax.enable_pytrees()``).
66+
67+
No-ops if JAX is not installed.
68+
"""
69+
try:
70+
from jax.tree_util import register_pytree_node_class as _r
71+
except ImportError:
72+
return cls
73+
return _r(cls)
74+
75+
76+
def register_pytree_node(nodetype, flatten_func, unflatten_func):
77+
"""Opt-in JAX pytree registration for an externally-defined class.
78+
79+
Lazy counterpart to :func:`register_pytree_node_class` for the case where
80+
the class cannot be decorated directly. No-ops if JAX is not installed.
81+
"""
82+
try:
83+
from jax.tree_util import register_pytree_node as _r
84+
except ImportError:
85+
return None
86+
return _r(nodetype, flatten_func, unflatten_func)

0 commit comments

Comments
 (0)