Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 26 additions & 5 deletions autoarray/abstract_ndarray.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand All @@ -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)


Expand All @@ -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
Expand Down Expand Up @@ -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)


Expand Down
67 changes: 67 additions & 0 deletions test_autoarray/test_abstract_ndarray_pytree_duplicate.py
Original file line number Diff line number Diff line change
@@ -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
Loading