From 734bf96b53876c5dbb269a9b6d7eca6449fa631f Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Wed, 18 Nov 2026 13:14:08 +0000 Subject: [PATCH] fix: Model.tree_flatten handles zero direct priors and keeps TuplePrior children Model.tree_flatten built its pytree from direct_prior_tuples alone, so a Model with no direct priors (a DatasetModel shape, whose grid_offset priors sit under a TuplePrior) raised "not enough values to unpack", and a model with a free TuplePrior plus a scalar lost the tuple priors on round-trip. - Model.tree_flatten carries direct priors and direct TuplePrior attributes as children, and returns empty children when there are none. - TuplePrior gains tree_flatten/tree_unflatten (prior members as children, fixed members in aux) and is registered in enable_pytrees. - New round-trip test over a DatasetModel-shaped Model: prior_count 0, 2, 3 survives tree_flatten/tree_unflatten. Closes #1777 Co-Authored-By: Claude Opus 5.5 --- autofit/jax/pytrees.py | 2 + autofit/mapper/prior/tuple_prior.py | 26 +++++++ autofit/mapper/prior_model/prior_model.py | 11 ++- .../mapper/test_model_pytree_tuple_prior.py | 71 +++++++++++++++++++ 4 files changed, 108 insertions(+), 2 deletions(-) create mode 100644 test_autofit/mapper/test_model_pytree_tuple_prior.py diff --git a/autofit/jax/pytrees.py b/autofit/jax/pytrees.py index 7a705396e..8afdd86ee 100644 --- a/autofit/jax/pytrees.py +++ b/autofit/jax/pytrees.py @@ -55,6 +55,7 @@ def enable_pytrees() -> bool: import autofit as af from autofit.mapper.prior_model.prior_model import Model from autofit.mapper.prior_model.collection import Collection + from autofit.mapper.prior.tuple_prior import TuplePrior for cls in ( af.GaussianPrior, @@ -64,6 +65,7 @@ def enable_pytrees() -> bool: af.TruncatedGaussianPrior, Model, Collection, + TuplePrior, af.ModelInstance, ): try: diff --git a/autofit/mapper/prior/tuple_prior.py b/autofit/mapper/prior/tuple_prior.py index a3937b4a6..79cae561d 100644 --- a/autofit/mapper/prior/tuple_prior.py +++ b/autofit/mapper/prior/tuple_prior.py @@ -23,6 +23,32 @@ def __init__(self, **kwargs): for key, value in kwargs.items(): setattr(self, key, value) + def tree_flatten(self): + """ + Flatten this tuple prior as a JAX PyTree. + + The prior members are the children; their names and any fixed + (non-prior) members go in the aux data, so ``tree_unflatten`` + rebuilds the same mix of free and fixed tuple entries. + """ + prior_tuples = self.prior_tuples + names = tuple(name for name, _ in prior_tuples) + children = tuple(prior for _, prior in prior_tuples) + fixed = tuple( + (key, value) + for key, value in self.__dict__.items() + if key != "id" and not isinstance(value, Prior) + ) + return children, (names, fixed) + + @classmethod + def tree_unflatten(cls, aux_data, children): + """ + Rebuild a tuple prior from its flattened PyTree. + """ + names, fixed = aux_data + return cls(**dict(zip(names, children)), **dict(fixed)) + @property @cast_collection(PriorNameValue) def prior_tuples(self): diff --git a/autofit/mapper/prior_model/prior_model.py b/autofit/mapper/prior_model/prior_model.py index 3a603ea27..05f88916d 100644 --- a/autofit/mapper/prior_model/prior_model.py +++ b/autofit/mapper/prior_model/prior_model.py @@ -329,9 +329,16 @@ def instance_unflatten(self, aux_data, children): def tree_flatten(self): """ Flatten this model as a PyTree. + + The children are the model's direct priors and its direct + ``TuplePrior`` attributes (e.g. a ``grid_offset`` tuple), so both + survive ``tree_unflatten``. A model with neither flattens to empty + children. """ - names, priors = zip(*self.direct_prior_tuples) - return priors, (names, self.cls) + tuples = list(self.direct_prior_tuples) + list(self.direct_tuple_priors) + names = tuple(name for name, _ in tuples) + children = tuple(value for _, value in tuples) + return children, (names, self.cls) @classmethod def tree_unflatten(cls, aux_data, children): diff --git a/test_autofit/mapper/test_model_pytree_tuple_prior.py b/test_autofit/mapper/test_model_pytree_tuple_prior.py new file mode 100644 index 000000000..1841ff48f --- /dev/null +++ b/test_autofit/mapper/test_model_pytree_tuple_prior.py @@ -0,0 +1,71 @@ +import pytest + +import autofit as af +from autofit.mapper.prior.tuple_prior import TuplePrior + +jax = pytest.importorskip("jax") + +from autofit.jax import register_model + + +class DatasetModel: + """ + The shape of autoarray's ``DatasetModel``: a scalar plus a 2-tuple, so + the model has no direct priors when the scalar is fixed and its tuple + priors sit under a ``TuplePrior``. + """ + + def __init__(self, background_sky_level=0.0, grid_offset=(0.0, 0.0)): + self.background_sky_level = background_sky_level + self.grid_offset = grid_offset + + +def _make_model(free_grid_offset, free_sky): + model = af.Model(DatasetModel) + model.background_sky_level = 0.0 + model.grid_offset.grid_offset_0 = 0.0 + model.grid_offset.grid_offset_1 = 0.0 + if free_grid_offset: + model.grid_offset.grid_offset_0 = af.UniformPrior(-1.0, 1.0) + model.grid_offset.grid_offset_1 = af.UniformPrior(-1.0, 1.0) + if free_sky: + model.background_sky_level = af.UniformPrior(0.0, 1.0) + return model + + +@pytest.mark.parametrize( + "free_grid_offset, free_sky, prior_count", + [ + (False, False, 0), + (True, False, 2), + (True, True, 3), + ], +) +def test_model_with_tuple_prior_round_trips(free_grid_offset, free_sky, prior_count): + model = _make_model(free_grid_offset, free_sky) + register_model(model) + + assert model.prior_count == prior_count + + leaves, treedef = jax.tree_util.tree_flatten(model) + rebuilt = jax.tree_util.tree_unflatten(treedef, leaves) + + assert rebuilt.prior_count == prior_count + assert isinstance(rebuilt.grid_offset, TuplePrior) + + +def test_tuple_prior_round_trips_free_and_fixed_members(): + register_model(af.Model(DatasetModel)) + + tuple_prior = TuplePrior( + grid_offset_0=af.UniformPrior(-1.0, 1.0), + grid_offset_1=0.5, + ) + + leaves, treedef = jax.tree_util.tree_flatten(tuple_prior) + rebuilt = jax.tree_util.tree_unflatten(treedef, leaves) + + assert isinstance(rebuilt, TuplePrior) + assert len(rebuilt.priors) == 1 + assert rebuilt.grid_offset_1 == 0.5 + assert rebuilt.value_for_arguments({rebuilt.grid_offset_0: 0.25}) == (0.25, 0.5)