From 8f48f503e552b3ac6df55b3bb49fde2aa36e10a2 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Sat, 14 Nov 2026 17:49:31 +0000 Subject: [PATCH] fix: tolerate a class already registered as a JAX pytree elsewhere Building a JAX Fitness registers Galaxy via autofit.jax.register_model; autolens.jax.register_tracer_classes then reaches register_instance_pytree for the same class and JAX raised "Duplicate custom PyTreeDef type registration for Galaxy". Both autoarray registration helpers now keep the existing registration and record the class as registered; any other ValueError still raises. Fixes #693 Co-Authored-By: Claude Opus 5.5 --- autoarray/abstract_ndarray.py | 31 +++++++-- .../test_abstract_ndarray_pytree_duplicate.py | 67 +++++++++++++++++++ 2 files changed, 93 insertions(+), 5 deletions(-) create mode 100644 test_autoarray/test_abstract_ndarray_pytree_duplicate.py diff --git a/autoarray/abstract_ndarray.py b/autoarray/abstract_ndarray.py index 559d0d8b7..aa4470b9d 100644 --- a/autoarray/abstract_ndarray.py +++ b/autoarray/abstract_ndarray.py @@ -65,6 +65,26 @@ def wrapper(self, other): _pytree_registered_classes: set = set() +def _register_pytree_node_once(cls, flatten, unflatten) -> None: + """Register ``cls`` with ``jax.tree_util``, tolerating a prior registration. + + JAX allows one registration per class and has no way to undo one. Several + routes register the same classes: ``autofit.jax.register_model`` registers + every model class (``Galaxy`` included) when a JAX ``Fitness`` is built, + and ``autolens.jax.register_tracer_classes`` reaches + :func:`register_instance_pytree` for the same ``Galaxy``. When JAX reports + the class is already registered, the existing registration is kept (the + first route wins) and this call is a no-op. Any other error still raises. + """ + from autonerves.jax_wrapper import register_pytree_node + + try: + register_pytree_node(cls, flatten, unflatten) + except ValueError as exc: + if "Duplicate custom PyTreeDef" not in str(exc): + raise + + def _register_as_pytree(cls): """Register ``cls`` with ``jax.tree_util`` via the lazy autonerves wrapper. @@ -75,9 +95,8 @@ def _register_as_pytree(cls): """ if cls in _pytree_registered_classes: return - from autonerves.jax_wrapper import register_pytree_node - register_pytree_node(cls, cls.instance_flatten, cls.instance_unflatten) + _register_pytree_node_once(cls, cls.instance_flatten, cls.instance_unflatten) _pytree_registered_classes.add(cls) @@ -97,11 +116,13 @@ def register_instance_pytree(cls, no_flatten=()): cosmology, adapt images). Reconstructs via ``cls.__new__`` + ``setattr`` (side-effect-free — no - ``__init__`` re-entry). Idempotent. + ``__init__`` re-entry). Idempotent, including across registration routes: + if ``cls`` was already registered elsewhere (e.g. ``Galaxy`` by + ``autofit.jax.register_model`` when a JAX ``Fitness`` was built), that + registration is kept and this call does nothing. """ if cls in _pytree_registered_classes: return - from autonerves.jax_wrapper import register_pytree_node from autonerves.tools.decorators import cached_property_names # Extend the caller-supplied no_flatten set with every @@ -133,7 +154,7 @@ def unflatten(aux, children): setattr(new, key, value) return new - register_pytree_node(cls, flatten, unflatten) + _register_pytree_node_once(cls, flatten, unflatten) _pytree_registered_classes.add(cls) diff --git a/test_autoarray/test_abstract_ndarray_pytree_duplicate.py b/test_autoarray/test_abstract_ndarray_pytree_duplicate.py new file mode 100644 index 000000000..cc52a6271 --- /dev/null +++ b/test_autoarray/test_abstract_ndarray_pytree_duplicate.py @@ -0,0 +1,67 @@ +"""Regression: registering a class that another route already registered +with JAX must not raise. + +Building a JAX ``Fitness`` registers ``Galaxy`` through +``autofit.jax.register_model``; ``autolens.jax.register_tracer_classes`` then +reaches ``register_instance_pytree(Galaxy)``. JAX raises +``ValueError: Duplicate custom PyTreeDef type registration`` on the second +registration, which broke every static-lattice JAX test run after a JAX +``Fitness`` in the same process (PyAutoArray#693). + +NumPy-only per the project rule [[feedback_no_jax_in_unit_tests]]: the JAX +registration call is replaced with a stub that raises the error JAX raises. +""" + +import pytest + +import autonerves.jax_wrapper as jax_wrapper + +from autoarray import abstract_ndarray + + +def _duplicate(cls, *args, **kwargs): + raise ValueError(f"Duplicate custom PyTreeDef type registration for {cls}.") + + +def _other_error(cls, *args, **kwargs): + raise ValueError("some other registration failure") + + +def test__register_instance_pytree__class_registered_elsewhere__no_error(monkeypatch): + class _RegisteredElsewhere: + pass + + monkeypatch.setattr(jax_wrapper, "register_pytree_node", _duplicate) + + abstract_ndarray.register_instance_pytree(_RegisteredElsewhere) + + assert _RegisteredElsewhere in abstract_ndarray._pytree_registered_classes + + +def test__register_as_pytree__class_registered_elsewhere__no_error(monkeypatch): + class _RegisteredElsewhere: + @classmethod + def instance_flatten(cls, instance): + return (), () + + @classmethod + def instance_unflatten(cls, aux, children): + return cls() + + monkeypatch.setattr(jax_wrapper, "register_pytree_node", _duplicate) + + abstract_ndarray._register_as_pytree(_RegisteredElsewhere) + + assert _RegisteredElsewhere in abstract_ndarray._pytree_registered_classes + + +def test__register_instance_pytree__other_value_error__raises(monkeypatch): + class _Broken: + pass + + monkeypatch.setattr(jax_wrapper, "register_pytree_node", _other_error) + + with pytest.raises(ValueError, match="some other registration failure"): + abstract_ndarray.register_instance_pytree(_Broken) + + assert _Broken not in abstract_ndarray._pytree_registered_classes