diff --git a/autofit/mapper/prior/arithmetic/assertion.py b/autofit/mapper/prior/arithmetic/assertion.py index 996c77a1f..20b1a20e5 100644 --- a/autofit/mapper/prior/arithmetic/assertion.py +++ b/autofit/mapper/prior/arithmetic/assertion.py @@ -43,10 +43,12 @@ def _instance_for_arguments(self, arguments, ignore_assertions=False, xp=np): lower = self.left_for_arguments( arguments, ignore_assertions=ignore_assertions, + xp=xp, ) greater = self.right_for_arguments( arguments, ignore_assertions=ignore_assertions, + xp=xp, ) return lower < greater @@ -75,9 +77,11 @@ def _instance_for_arguments( return self.left_for_arguments( arguments, ignore_assertions=ignore_assertions, + xp=xp, ) <= self.right_for_arguments( arguments, ignore_assertions=ignore_assertions, + xp=xp, ) @@ -94,12 +98,43 @@ def _instance_for_arguments( ignore_assertions=False, xp=np, ): - return self.assertion_1.instance_for_arguments( - arguments, - ignore_assertions, - ) and self.assertion_2.instance_for_arguments( - arguments, - ignore_assertions, + """ + Both sub-assertions must hold. + + The numpy path keeps the Python ``and``, which **short-circuits**: a false first half + means the second is never realised. That is load-bearing rather than incidental — a + chained assertion's second half can be undefined exactly where the first one fails + (``(0 < p) < (1 / p)`` at ``p = 0``), and the user's contract there is a ``FitException`` + (resample), not a ``ZeroDivisionError`` out of the likelihood. + + The JAX path cannot use ``and``: each half is a tracer, and ``and`` coerces its operands + to Python bools, raising ``TracerBoolConversionError``. ``xp.logical_and`` evaluates both + halves, which is safe there because the arithmetic that raises on numpy is ``inf`` or + ``nan`` under JAX rather than an exception. + + The branch is on the *module identity* of ``xp``, which is a static Python value even + inside a trace, so it is legal under ``jit`` and ``vmap``. + """ + if xp is np: + return self.assertion_1.instance_for_arguments( + arguments, + ignore_assertions, + ) and self.assertion_2.instance_for_arguments( + arguments, + ignore_assertions, + ) + + return xp.logical_and( + self.assertion_1.instance_for_arguments( + arguments, + ignore_assertions, + xp=xp, + ), + self.assertion_2.instance_for_arguments( + arguments, + ignore_assertions, + xp=xp, + ), ) def dict(self) -> dict: diff --git a/autofit/mapper/prior_model/abstract.py b/autofit/mapper/prior_model/abstract.py index 3ec277036..73547e510 100644 --- a/autofit/mapper/prior_model/abstract.py +++ b/autofit/mapper/prior_model/abstract.py @@ -190,14 +190,21 @@ def assertions(self): def assertions(self, assertions): self._assertions = assertions - def check_assertions(self, arguments: Dict[Prior, float]): + def check_assertions(self, arguments: Dict[Prior, float], xp=np): """ Check that all assertions are satisfied by the given arguments. + This is the **exception** form of the assertion check, and therefore the numpy form: it + applies a Python ``not`` to each assertion's value, which is illegal on a traced value. + The traced form is `assertions_satisfied_for_arguments`. + Parameters ---------- arguments A dictionary mapping priors to values + xp + The array module (``numpy`` or ``jax.numpy``) used to realise the values the + assertions compare. Raises ------ @@ -211,6 +218,7 @@ def check_assertions(self, arguments: Dict[Prior, float]): or assertion is not True and not assertion.instance_for_arguments( arguments, + xp=xp, ) ] number_of_failed_assertions = len(failed_assertions) @@ -226,6 +234,166 @@ def check_assertions(self, arguments: Dict[Prior, float]): f"{number_of_failed_assertions} assertions failed!\n{name_string}" ) + def gathered_assertions(self) -> list: + """ + Every assertion attached anywhere in this model's tree. + + Assertions are attached to whichever model object the user happened to hold -- a child + `Model` as often as the top-level `Collection` -- and on the numpy path that does not + matter, because each model checks its own assertions as its own instance is built. The + traced path has no such recursion to hook into: it is handed one model and one parameter + vector, so it must find the assertions itself or silently enforce fewer of them than + numpy does. + + Returns + ------- + This model's own assertions first, then those of every `AbstractPriorModel` reachable + beneath it in walk order, then those attached to the assertions' own operands. A component + reachable by more than one path (a shared component) contributes its assertions once. + """ + assertions = list(self._assertions) + + # `_assertions` itself is never walked into by the tree walk below: + # `path_instances_of_class` skips attributes whose name starts with an underscore, so the + # assertion objects -- which are themselves `AbstractPriorModel`s -- are not mistaken for + # components of the model. Their operands are picked up separately, afterwards. + seen = {id(self)} + + for _, model in self.attribute_tuples_with_type( + AbstractPriorModel, + ignore_children=False, + ): + if id(model) in seen: + continue + seen.add(id(model)) + assertions.extend(getattr(model, "_assertions", [])) + + # An assertion's operand can itself be a model carrying assertions -- `derived = p + 1` is + # a `CompoundPrior`, and `derived.add_assertion(...)` attaches to it. On numpy those fire + # when the operand is realised, so they are part of the model's contract; the tree walk + # cannot see them, because the operand hangs off the assertion rather than off the model. + collected = {id(assertion) for assertion in assertions} + visited = set() + queue = list(assertions) + + while queue: + node = queue.pop(0) + + if id(node) in visited: + continue + visited.add(id(node)) + + if isinstance(node, AbstractPriorModel) and id(node) not in seen: + for assertion in node._assertions: + if id(assertion) not in collected: + collected.add(id(assertion)) + assertions.append(assertion) + queue.append(assertion) + + for attribute in ("_left", "_right", "assertion_1", "assertion_2"): + operand = getattr(node, attribute, None) + if operand is not None: + queue.append(operand) + + return assertions + + def assertions_satisfied_for_arguments( + self, + arguments: Dict[Prior, float], + xp=np, + assertions=None, + ): + """ + Whether every assertion attached to this model is satisfied, returned as a **value** + rather than signalled by an exception. + + This is the traced sibling of `check_assertions`. It never applies a Python ``not``, + ``and`` or ``if`` to an assertion's value, so under ``jax.jit`` / ``jax.vmap`` -- where + each value is a tracer -- it returns a traced boolean instead of raising + ``TracerBoolConversionError``. `Fitness` applies that boolean with ``xp.where``, + mapping a violating model to the resample figure of merit. + + Parameters + ---------- + arguments + A dictionary mapping priors to physical values. + xp + The array module (``numpy`` or ``jax.numpy``) used to realise and combine the + assertion values. + assertions + The assertions to evaluate. Defaults to `gathered_assertions`, i.e. every assertion + in the model tree; a caller that gathers them once (as `Fitness` does, in its + constructor) passes them in so the walk is not repeated per likelihood evaluation. + + Returns + ------- + A boolean array which is ``True`` when every assertion holds. A model with no assertions + returns ``True``. + """ + if assertions is None: + assertions = self.gathered_assertions() + + satisfied = xp.asarray(True) + + for assertion in assertions: + if assertion is True: + continue + if assertion is False: + value = xp.asarray(False) + else: + value = assertion.instance_for_arguments( + arguments, + ignore_assertions=True, + xp=xp, + ) + satisfied = xp.logical_and(satisfied, value) + + return satisfied + + def assertions_satisfied_from_vector(self, vector, xp=np, assertions=None): + """ + Whether every assertion attached to this model is satisfied by a physical parameter + vector, returned as a **value** rather than signalled by an exception. + + The vector is mapped to arguments exactly as `instance_from_vector` maps it, so the + assertions are evaluated against the same physical values the instance would be built + from. + + Parameters + ---------- + vector: [float] + A vector of physical parameter values, ordered by prior id. + xp + The array module (``numpy`` or ``jax.numpy``) used to realise and combine the + assertion values. + assertions + The assertions to evaluate. Defaults to `gathered_assertions` (see + `assertions_satisfied_for_arguments`). + + Returns + ------- + A boolean array which is ``True`` when every assertion holds. A model with no assertions + returns ``True``. + """ + if len(vector) != self.prior_count: + raise AssertionError( + f"Vector length {len(vector)} != prior count {self.prior_count}" + ) + + arguments = dict( + map( + lambda prior_tuple, physical_unit: (prior_tuple.prior, physical_unit), + self.prior_tuples_ordered_by_id, + vector, + ) + ) + + return self.assertions_satisfied_for_arguments( + arguments, + xp=xp, + assertions=assertions, + ) + def set_item_at_path(self, path: Tuple[str, ...], value): """ Set an item at a path in the model. @@ -441,8 +609,24 @@ def from_json(cls, file: str): def add_assertion(self, assertion, name=""): """ Assert that some relationship holds between physical values associated with - priors at the point an instance is created. If this fails a FitException is - raised causing the model to be re-sampled. + priors at the point an instance is created. + + The assertion is enforced differently on the two array backends, but with the same + outcome -- the non-linear search never selects a violating model: + + - **numpy**: `check_assertions` raises a ``FitException`` when the assertion fails, which + :class:`~autofit.non_linear.fitness.Fitness` catches and turns into the resample figure + of merit. + - **JAX**: raising is impossible inside a trace, so the assertion is instead evaluated as + a traced boolean by `assertions_satisfied_from_vector` and applied by + :class:`~autofit.non_linear.fitness.Fitness` with ``xp.where``, mapping a violating + model to the resample figure of merit. This is a **value-only** penalty, carrying the + same gradient caveat as the NaN guards documented on `Fitness.call`. + + Both paths enforce assertions attached anywhere in the model tree: numpy because each + model checks its own as its instance is built, JAX because `gathered_assertions` collects + them from the whole tree. + Parameters ---------- assertion @@ -1620,7 +1804,7 @@ def instance_for_arguments( if not ( conf.instance["general"]["test"]["exception_override"] or ignore_assertions ): - self.check_assertions(arguments) + self.check_assertions(arguments, xp=xp) return self._instance_for_arguments( arguments, diff --git a/autofit/mapper/prior_model/constraint.py b/autofit/mapper/prior_model/constraint.py index a38ebb221..4ff2c7ea4 100644 --- a/autofit/mapper/prior_model/constraint.py +++ b/autofit/mapper/prior_model/constraint.py @@ -2,21 +2,27 @@ Class-declared model constraints, evaluated as traced values. This is the differentiable sibling of :meth:`AbstractPriorModel.add_assertion`. -Assertions are attached to a *model instance* by the user and signal failure by -raising :class:`FitException`; that works on the NumPy path, where -:class:`Fitness` catches the exception and returns the resample sentinel, but it -cannot work under JAX. A ``raise`` needs a concrete boolean, and inside a trace -the condition is a tracer — attempting it gives ``TracerBoolConversionError``. -That is why guards such as ``autogalaxy.profiles.validate.validate_ell_comps`` -return early for non-concrete scalars rather than raising: the escape hatch is -load-bearing, or every jitted likelihood would crash instead of sampling. +Assertions are attached to a *model instance* by the user. On the NumPy path they +signal failure by raising :class:`FitException`, which :class:`Fitness` catches, +returning the resample sentinel. A ``raise`` cannot happen inside a JAX trace — it +needs a concrete boolean, and the condition there is a tracer, which gives +``TracerBoolConversionError`` — so under JAX the assertion is instead evaluated as +a **traced boolean** and applied by :class:`Fitness` as an ``xp.where`` penalty +that maps a violating model to the resample sentinel. Assertions therefore survive +``jit`` and ``vmap``, but as a *value-only* rejection: reverse-mode +differentiates both branches of that ``where``, so the penalty carries no usable +gradient back into the valid region. This is also why guards such as +``autogalaxy.profiles.validate.validate_ell_comps`` return early for non-concrete +scalars rather than raising: the escape hatch is load-bearing, or every jitted +likelihood would crash instead of sampling. A model constraint differs in exactly two ways: - it is declared **on the class**, so every model built from that class carries it without the user remembering to attach anything; -- it is evaluated as a **traced non-negative violation measure** rather than - raising, so it survives ``jit``, ``vmap`` and ``grad``. +- it is evaluated as a **traced non-negative violation measure** rather than a + boolean, so it survives ``jit``, ``vmap`` and ``grad`` — a magnitude carries a + gradient back into the valid region where the assertion ``where`` cannot. Declaring one ------------- diff --git a/autofit/non_linear/fitness.py b/autofit/non_linear/fitness.py index c87f361b0..524619e96 100644 --- a/autofit/non_linear/fitness.py +++ b/autofit/non_linear/fitness.py @@ -31,6 +31,20 @@ def get_timeout_seconds(): logger = logging.getLogger(__name__) timeout_seconds = get_timeout_seconds() + +def _exception_override() -> bool: + """ + Whether `general.test.exception_override` is set, which disables assertion checking. + + Read once per `Fitness` rather than per call: the traced assertion penalty branches on this + with a Python `if`, which must resolve at trace time. A config that never mentions the key + means no override. + """ + try: + return bool(conf.instance["general"]["test"]["exception_override"]) + except KeyError: + return False + #: Ceiling used when ``general.test.log_likelihood_ceiling`` is absent from the config (e.g. a #: workspace whose ``general.yaml`` pre-dates the key). ``inf`` -- i.e. the guard is **off** -- #: because the packaged default is off, and a config that never mentions the key must inherit @@ -232,6 +246,9 @@ def __init__( # traced value under `jax.jit` / `jax.vmap`, which requires the ceiling to be a compile-time # constant. self.log_likelihood_ceiling = get_log_likelihood_ceiling() + + self._set_traced_assertions() + self.convert_to_chi_squared = convert_to_chi_squared self.store_history = store_history @@ -336,6 +353,21 @@ def call(self, parameters): A private method that calls the fitness function with the given parameters and additional keyword arguments. This method is intended for internal use only. + Model assertions (`AbstractPriorModel.add_assertion`) are enforced here too, and how + depends on the backend. On numpy `instance_from_vector` raises a `FitException` and the + `except` below returns `resample_figure_of_merit`. Under JAX a `raise` cannot happen + inside a trace, so the instance is built with `ignore_assertions=True` and the assertions + -- gathered from the whole model tree once, in `__init__`, so a child-attached assertion + is enforced exactly as it is on numpy -- are instead evaluated as a **traced boolean** by + `assertions_satisfied_from_vector` and applied with an `xp.where` to the **final figure of + merit**, mapping a violating model to `resample_figure_of_merit`. Applying it at the end + is what makes the two backends agree exactly: numpy returns its sentinel from an early + `return`, before the log prior is added and before the chi-squared multiply. That + makes the JAX path exception-free as required, at the cost of the same **value-only** + caveat the NaN guards carry below: under `jax.grad` the `where` still differentiates the + rejected branch. Whether the penalty is applied at all is a static Python bool decided in + `__init__`, so the branch resolves at trace time under `jax.jit` / `jax.vmap`. + The NaN/inf/magnitude guards below protect the **value only, never the gradient**. A model whose likelihood is NaN, inf, or larger in magnitude than `self.log_likelihood_ceiling` is mapped @@ -377,14 +409,28 @@ def call(self, parameters): ------- The figure of merit returned to the non-linear search, which is either the log likelihood or log posterior. """ + # `None` on the numpy path, and on the JAX path when the model has no assertions: a Python + # `is None` on it below is therefore a static branch, legal under `jax.jit` / `jax.vmap`. + assertions_satisfied = None + if self._is_jax: - # Get instance from model (must be side-effect free and exception-free under JAX) - instance = self.model.instance_from_vector(vector=parameters, xp=self._xp) + # Get instance from model. Assertions are skipped here because they signal failure by + # raising, which is illegal inside a trace; they are applied below as a traced value. + instance = self.model.instance_from_vector( + vector=parameters, ignore_assertions=True, xp=self._xp + ) # Evaluate log likelihood (must be side-effect free and exception-free) log_likelihood = self.analysis.log_likelihood_function(instance=instance) + if self._apply_assertions_traced: + assertions_satisfied = self.model.assertions_satisfied_from_vector( + parameters, + xp=self._xp, + assertions=self._traced_assertions, + ) + else: try: @@ -443,6 +489,19 @@ def call(self, parameters): if self.convert_to_chi_squared: figure_of_merit *= -2.0 + # Reject models that violate an assertion, *after* the conversions above. The numpy path + # returns `resample_figure_of_merit` from an early `return`, so neither the log prior nor + # the chi-squared multiply ever touches its sentinel; applying this to the log likelihood + # instead would let both rewrite it here, and `convert_to_chi_squared` flips its sign -- + # turning the most-rejected point in the space into the most attractive one for a + # minimizer. Same value-only caveat as the guards above. + if assertions_satisfied is not None: + figure_of_merit = self._xp.where( + assertions_satisfied, + figure_of_merit, + self.resample_figure_of_merit, + ) + return figure_of_merit def log_likelihood_from(self, figure_of_merit, parameters): @@ -720,6 +779,34 @@ def __call__(self, parameters, *kwargs): """ return self.call_wrap(parameters) + def _set_traced_assertions(self): + """ + Gather the model's assertions and decide, once, whether the traced penalty applies. + + Both are static by construction. The walk over the model tree is a Python loop over Python + objects, so it cannot happen inside a trace, and there is no reason to repeat it per + likelihood evaluation; `_apply_assertions_traced` is read by `call` as a Python `if`, which + must resolve at trace time under `jax.jit` / `jax.vmap`. + + It is `False` when the model tree carries no assertions (the `where` would be a no-op) or + when `general.test.exception_override` is set, which is what disables assertions on the + numpy path too. + + Called from `__init__` **and** from `__setstate__`: a `Fitness` pickled before the traced + penalty existed carries neither attribute, and defaulting them to "no assertions" would + leave a resumed JAX search quietly sampling models the user forbade. The assertions live + on the restored model either way, so they are recomputed rather than defaulted. + """ + # `hasattr` because some tests pass a stand-in for the model rather than a real one. + self._traced_assertions = ( + self.model.gathered_assertions() + if hasattr(self.model, "gathered_assertions") + else [] + ) + self._apply_assertions_traced = ( + bool(self._traced_assertions) and not _exception_override() + ) + def __getstate__(self): state = self.__dict__.copy() # Strip JAX-compiled callables: jax.jit / jax.vmap / jax.grad return @@ -734,6 +821,14 @@ def __setstate__(self, state): # Fitness objects pickled before the magnitude guard existed carry no ceiling; give them the # configured one rather than letting `call` raise `AttributeError` on resume. self.__dict__.setdefault("log_likelihood_ceiling", get_log_likelihood_ceiling()) + # `Fitness` objects pickled before the traced assertion penalty existed carry neither + # assertion attribute. Recompute them from the restored model rather than defaulting to + # "no assertions", which would silently stop enforcing them on resume. + if ( + "_traced_assertions" not in self.__dict__ + or "_apply_assertions_traced" not in self.__dict__ + ): + self._set_traced_assertions() self._call = self.call if getattr(self, "use_jax_vmap", False): self._call = self._vmap diff --git a/test_autofit/mapper/prior/test_assertion.py b/test_autofit/mapper/prior/test_assertion.py index 95dc61f10..12ed77afe 100644 --- a/test_autofit/mapper/prior/test_assertion.py +++ b/test_autofit/mapper/prior/test_assertion.py @@ -1,3 +1,4 @@ +import numpy as np import pytest import autofit as af @@ -118,3 +119,373 @@ def test_numerical(self): model.add_assertion(False) with pytest.raises(exc.FitException): model.instance_from_unit_vector([]) + + +class TestAssertionsSatisfiedFromVector: + """ + The **value** form of the assertion check, which is what makes assertions work under JAX. + + `check_assertions` signals a violation by raising, and a `raise` cannot happen inside a + trace. `assertions_satisfied_from_vector` returns the same verdict as a boolean array + instead, which `Fitness` applies with an `xp.where`. These tests pin it on numpy, where the + verdict must match what `instance_from_vector` does or does not raise; the traced behaviour + is pinned in `test_autofit/non_linear/test_fitness_assertions_jax.py`. + """ + + @staticmethod + def _collection(*names): + return af.Collection(**{name: af.Model(af.ex.Gaussian) for name in names}) + + def test_greater_than_assertion(self): + model = self._collection("gaussian_0", "gaussian_1") + model.add_assertion(model.gaussian_0.centre > model.gaussian_1.centre) + + # The vector is ordered by prior id: centre, normalization, sigma for each Gaussian in + # turn, so index 0 is `gaussian_0.centre` and index 3 is `gaussian_1.centre`. + satisfied = model.assertions_satisfied_from_vector( + [20.0, 1.0, 1.0, 10.0, 1.0, 1.0] + ) + violated = model.assertions_satisfied_from_vector( + [10.0, 1.0, 1.0, 20.0, 1.0, 1.0] + ) + + assert np.asarray(satisfied).dtype == bool + assert bool(satisfied) is True + assert bool(violated) is False + + def test_greater_than_equal_assertion(self): + """ + The `>=` assertion is a different class to `>`, and the equal case is the one that + distinguishes them. + """ + model = self._collection("gaussian_0", "gaussian_1") + model.add_assertion(model.gaussian_0.centre >= model.gaussian_1.centre) + + equal = model.assertions_satisfied_from_vector( + [10.0, 1.0, 1.0, 10.0, 1.0, 1.0] + ) + + assert bool(equal) is True + assert ( + bool( + model.assertions_satisfied_from_vector( + [20.0, 1.0, 1.0, 10.0, 1.0, 1.0] + ) + ) + is True + ) + assert ( + bool( + model.assertions_satisfied_from_vector( + [10.0, 1.0, 1.0, 20.0, 1.0, 1.0] + ) + ) + is False + ) + + def test_compound_assertion(self): + """ + `(a > b) > c` chains to `a > b and b > c`, a `CompoundAssertion`. Both halves must hold, + and the combination must not go through a Python `and`. + """ + model = self._collection("gaussian_0", "gaussian_1", "gaussian_2") + model.add_assertion( + (model.gaussian_0.centre > model.gaussian_1.centre) + > model.gaussian_2.centre + ) + + ordered = [3.0, 1.0, 1.0, 2.0, 1.0, 1.0, 1.0, 1.0, 1.0] + second_half_violated = [3.0, 1.0, 1.0, 1.0, 1.0, 1.0, 2.0, 1.0, 1.0] + first_half_violated = [1.0, 1.0, 1.0, 2.0, 1.0, 1.0, 0.5, 1.0, 1.0] + + assert bool(model.assertions_satisfied_from_vector(ordered)) is True + assert ( + bool(model.assertions_satisfied_from_vector(second_half_violated)) is False + ) + assert ( + bool(model.assertions_satisfied_from_vector(first_half_violated)) is False + ) + + def test_compound_prior_assertion(self): + """ + The motivating case: an ordering between two *derived* quantities rather than two bare + priors -- here the squared radius of each component's (centre, normalization) pair, which + is the 1D stand-in for the MGE `ell_comps` label degeneracy the assertion was added to + break. The assertion adds no free parameters, so the vector length is unchanged. + """ + model = self._collection("gaussian_0", "gaussian_1") + + prior_count = model.prior_count + model.add_assertion( + (model.gaussian_0.centre**2 + model.gaussian_0.normalization**2) + > (model.gaussian_1.centre**2 + model.gaussian_1.normalization**2) + ) + + assert model.prior_count == prior_count + + # |(0.4, 0.3)|^2 = 0.25 > |(0.05, 0.05)|^2 = 0.005 + satisfied = [0.4, 0.3, 1.0, 0.05, 0.05, 1.0] + violated = [0.05, 0.05, 1.0, 0.4, 0.3, 1.0] + + assert bool(model.assertions_satisfied_from_vector(satisfied)) is True + assert bool(model.assertions_satisfied_from_vector(violated)) is False + + def test_model_without_assertions_is_always_satisfied(self): + """ + A model with nothing attached must return `True` rather than an empty reduction, so + `Fitness` can call this unconditionally. + """ + model = self._collection("gaussian_0") + + satisfied = model.assertions_satisfied_from_vector([1.0, 1.0, 1.0]) + + assert np.asarray(satisfied).dtype == bool + assert bool(satisfied) is True + + def test_vector_length_is_checked(self): + """ + The same guard `instance_from_vector` applies, since the two must map a vector to + arguments identically or the assertion would be evaluated against the wrong parameters. + """ + model = self._collection("gaussian_0") + model.add_assertion(model.gaussian_0.centre > 0.0) + + with pytest.raises(AssertionError): + model.assertions_satisfied_from_vector([1.0, 1.0]) + + def test_agrees_with_check_assertions(self): + """ + The value form and the exception form are two statements of one rule, so a vector that + `instance_from_vector` rejects must be exactly the vector this returns `False` for. + """ + model = self._collection("gaussian_0", "gaussian_1") + model.add_assertion(model.gaussian_0.centre > model.gaussian_1.centre) + + satisfied = [20.0, 1.0, 1.0, 10.0, 1.0, 1.0] + violated = [10.0, 1.0, 1.0, 20.0, 1.0, 1.0] + + model.instance_from_vector(satisfied) + assert bool(model.assertions_satisfied_from_vector(satisfied)) is True + + with pytest.raises(exc.FitException): + model.instance_from_vector(violated) + assert bool(model.assertions_satisfied_from_vector(violated)) is False + + +class TestGatheredAssertions: + """ + Assertions are attached to whichever model object the user held, which is very often a child + component rather than the model the search is handed. `check_assertions` never had to care -- + every model checks its own as its instance is built -- but the traced path is handed one model + and has to find them itself, so a walk that missed a child would enforce fewer assertions + under JAX than under numpy. That asymmetry is what these pin against. + """ + + def test_own_assertions(self): + model = af.Collection(gaussian=af.Model(af.ex.Gaussian)) + assertion = model.gaussian.centre > 0.0 + model.add_assertion(assertion) + + assert model.gathered_assertions() == [assertion] + + def test_child_assertions(self): + """ + The form the pre-existing numpy regression test uses: attached to the child `Model`, and + the `Collection` is what the search sees. + """ + gaussian_0 = af.Model(af.ex.Gaussian) + gaussian_1 = af.Model(af.ex.Gaussian) + assertion = gaussian_0.centre > gaussian_1.centre + gaussian_0.add_assertion(assertion) + + model = af.Collection(gaussian_0=gaussian_0, gaussian_1=gaussian_1) + + assert model._assertions == [] + assert model.gathered_assertions() == [assertion] + + def test_nested_collections_and_own_assertions_first(self): + gaussian_0 = af.Model(af.ex.Gaussian) + gaussian_1 = af.Model(af.ex.Gaussian) + child_assertion = gaussian_0.centre > gaussian_1.centre + gaussian_0.add_assertion(child_assertion) + + inner = af.Collection(gaussian_0=gaussian_0, gaussian_1=gaussian_1) + inner_assertion = inner.gaussian_1.sigma > 0.5 + inner.add_assertion(inner_assertion) + + model = af.Collection(inner=inner) + own_assertion = model.inner.gaussian_0.normalization > 0.0 + model.add_assertion(own_assertion) + + gathered = model.gathered_assertions() + + assert gathered[0] is own_assertion + assert set(map(id, gathered)) == { + id(own_assertion), + id(inner_assertion), + id(child_assertion), + } + + def test_model_without_assertions(self): + model = af.Collection(gaussian=af.Model(af.ex.Gaussian)) + + assert model.gathered_assertions() == [] + + def test_a_shared_component_contributes_once(self): + """ + The same `Model` reachable by two paths is one component with one set of assertions, so + its assertion must not be evaluated (or counted) twice. + """ + gaussian = af.Model(af.ex.Gaussian) + assertion = gaussian.centre > 0.0 + gaussian.add_assertion(assertion) + + model = af.Collection(first=gaussian, second=gaussian) + + assert model.gathered_assertions() == [assertion] + + def test_child_assertions_are_evaluated_from_a_vector(self): + """ + The verdict, not just the gathering: a child-attached assertion must make + `assertions_satisfied_from_vector` on the *parent* return `False`, matching the + `FitException` `instance_from_vector` raises for the same vector. + """ + gaussian_0 = af.Model(af.ex.Gaussian) + gaussian_1 = af.Model(af.ex.Gaussian) + gaussian_0.add_assertion(gaussian_0.centre > gaussian_1.centre) + model = af.Collection(gaussian_0=gaussian_0, gaussian_1=gaussian_1) + + satisfied = [20.0, 1.0, 1.0, 10.0, 1.0, 1.0] + violated = [10.0, 1.0, 1.0, 20.0, 1.0, 1.0] + + assert bool(model.assertions_satisfied_from_vector(satisfied)) is True + assert bool(model.assertions_satisfied_from_vector(violated)) is False + + with pytest.raises(exc.FitException): + model.instance_from_vector(violated) + + def test_explicit_assertions_argument_is_used_verbatim(self): + """ + `Fitness` gathers once in its constructor and passes the list back in, so the per-call + cost is the evaluation rather than a fresh walk of the model tree. + """ + gaussian_0 = af.Model(af.ex.Gaussian) + gaussian_1 = af.Model(af.ex.Gaussian) + gaussian_0.add_assertion(gaussian_0.centre > gaussian_1.centre) + model = af.Collection(gaussian_0=gaussian_0, gaussian_1=gaussian_1) + + violated = [10.0, 1.0, 1.0, 20.0, 1.0, 1.0] + + assert ( + bool( + model.assertions_satisfied_from_vector( + violated, assertions=model.gathered_assertions() + ) + ) + is False + ) + # An empty list is not "no list": it means evaluate nothing. + assert ( + bool(model.assertions_satisfied_from_vector(violated, assertions=[])) + is True + ) + + +class TestCompoundAssertionShortCircuits: + """ + `CompoundAssertion` combines its halves with a Python `and` on numpy, which **short-circuits**: + a false first half means the second is never realised. That is load-bearing, not incidental -- + a chained assertion's second half can be undefined exactly where the first one fails, and the + user's contract is a `FitException` (resample), not whatever exception the arithmetic raises. + + Only the JAX path uses `xp.logical_and`, which evaluates both halves; there it has to, since a + Python `and` on a tracer is illegal, and division by zero is `inf` rather than an exception. + """ + + def test_numpy_and_short_circuits_a_singular_second_half(self): + prior = af.UniformPrior(lower_limit=0.0, upper_limit=2.0) + model = af.Collection(p=prior) + model.add_assertion((0 < prior) < (1 / prior)) + + # `0 < 0.0` is False, so `1 / 0.0` must never be evaluated. + with pytest.raises(exc.FitException): + model.instance_from_vector([0.0]) + + # The value form short-circuits the same way, returning `False` rather than dividing. + assert bool(model.assertions_satisfied_from_vector([0.0])) is False + + def test_numpy_compound_result_is_a_python_bool(self): + """ + The numpy half returns the `True`/`False` singletons, unchanged from before the JAX work: + `np.logical_and` would return an `np.bool_`, and code (and tests) downstream compare with + `is`. + """ + prior = af.UniformPrior() + assertion = (0.2 < prior) < 0.5 + + assert assertion.instance_for_arguments({prior: 0.3}) is True + + +class TestAssertionBoundaries: + """ + `>` and `>=` are different classes, and the equality boundary is the only input that tells + them apart -- so it is the one that would catch the two being wired to the same comparison. + """ + + @staticmethod + def _model(operator): + model = af.Collection( + gaussian_0=af.Model(af.ex.Gaussian), + gaussian_1=af.Model(af.ex.Gaussian), + ) + if operator == ">": + model.add_assertion(model.gaussian_0.centre > model.gaussian_1.centre) + else: + model.add_assertion(model.gaussian_0.centre >= model.gaussian_1.centre) + return model + + EQUAL = [10.0, 1.0, 1.0, 10.0, 1.0, 1.0] + + def test_greater_than_rejects_equality(self): + assert bool(self._model(">").assertions_satisfied_from_vector(self.EQUAL)) is False + + def test_greater_than_equal_accepts_equality(self): + assert bool(self._model(">=").assertions_satisfied_from_vector(self.EQUAL)) is True + + +class TestAssertionsOnAssertionOperands: + """ + An assertion's operand can itself be a model carrying assertions -- `derived = p + 1` is a + `CompoundPrior`, and `derived.add_assertion(...)` attaches to it. On numpy those fire when the + operand is realised, so they are part of the model's contract; a gather that walked only the + model tree would miss them (the operand hangs off the assertion, and `_assertions` is not + walked into), and JAX would accept a vector numpy rejects. + """ + + @staticmethod + def _model(): + prior = af.UniformPrior(lower_limit=0.0, upper_limit=2.0) + derived = prior + 1 + derived.add_assertion(prior > 0.5) + + model = af.Collection(p=prior) + model.add_assertion(derived < 2) + return model + + def test_operand_assertions_are_gathered(self): + model = self._model() + + assert len(model._assertions) == 1 + assert len(model.gathered_assertions()) == 2 + + def test_operand_assertion_rejects_the_same_vector_numpy_does(self): + model = self._model() + + # p = 0.25 satisfies the outer assertion (0.25 + 1 < 2) but violates the operand's own + # (0.25 > 0.5 is False), which is what numpy rejects it for. + with pytest.raises(exc.FitException): + model.instance_from_vector([0.25]) + assert bool(model.assertions_satisfied_from_vector([0.25])) is False + + model.instance_from_vector([0.75]) + assert bool(model.assertions_satisfied_from_vector([0.75])) is True diff --git a/test_autofit/non_linear/test_fitness_assertions.py b/test_autofit/non_linear/test_fitness_assertions.py index 7ebd26fe0..306770023 100644 --- a/test_autofit/non_linear/test_fitness_assertions.py +++ b/test_autofit/non_linear/test_fitness_assertions.py @@ -1,4 +1,5 @@ import logging +import pickle import numpy as np import pytest @@ -37,6 +38,174 @@ def test_fitness_returns_resample_fom_on_assertion_failure(): assert fitness.call(satisfying) != fitness.resample_figure_of_merit +def test_numpy_path_is_unchanged_by_the_traced_assertion_penalty(): + """ + The traced penalty is JAX-only: on numpy the `FitException` raised by `instance_from_vector` + is still what produces `resample_figure_of_merit`, and the `xp.where` added for JAX must not + run here at all. `_apply_assertions_traced` is nonetheless `True` — it is a property of the + *model*, decided once in `__init__` so it is a compile-time constant under `jax.jit` — so + this pins that the flag being set does not perturb a numpy fit. + """ + gaussian_0 = af.Model(af.ex.Gaussian) + gaussian_1 = af.Model(af.ex.Gaussian) + model = af.Collection(gaussian_0=gaussian_0, gaussian_1=gaussian_1) + model.add_assertion(model.gaussian_0.centre > model.gaussian_1.centre) + + data = np.ones(20) + noise_map = np.ones(20) * 0.1 + analysis = af.ex.Analysis(data=data, noise_map=noise_map) + + fitness = Fitness(model=model, analysis=analysis) + + assert fitness._is_jax is False + assert fitness._apply_assertions_traced is True + + violating = [10.0, 1.0, 1.0, 20.0, 1.0, 1.0] + assert fitness.call(violating) == fitness.resample_figure_of_merit + + satisfying = [20.0, 1.0, 1.0, 10.0, 1.0, 1.0] + instance = model.instance_from_vector(satisfying) + assert fitness.call(satisfying) == pytest.approx( + analysis.log_likelihood_function(instance=instance) + ) + + +def test_apply_assertions_traced_is_false_without_assertions(): + """ + With nothing attached the `where` would be a no-op, so it is not emitted at all — one fewer + traced operation in every likelihood evaluation of the (overwhelmingly common) unconstrained + model. + """ + data = np.ones(20) + noise_map = np.ones(20) * 0.1 + fitness = Fitness( + model=af.Model(af.ex.Gaussian), + analysis=af.ex.Analysis(data=data, noise_map=noise_map), + ) + + assert fitness._apply_assertions_traced is False + + +def test_gathered_assertions_survive_a_pickle_roundtrip(): + """ + A search pickles its `Fitness` (parallel workers, resume). The gathered assertion list is + plain model objects, so it pickles -- and the priors inside it are the same objects as those + in the pickled model, since pickle preserves identity within one blob, so the restored + assertions still key into the restored model's arguments. + """ + gaussian_0 = af.Model(af.ex.Gaussian) + gaussian_1 = af.Model(af.ex.Gaussian) + gaussian_0.add_assertion(gaussian_0.centre > gaussian_1.centre) + model = af.Collection(gaussian_0=gaussian_0, gaussian_1=gaussian_1) + + data = np.ones(20) + noise_map = np.ones(20) * 0.1 + fitness = Fitness( + model=model, + analysis=af.ex.Analysis(data=data, noise_map=noise_map), + resample_figure_of_merit=-1.0e99, + ) + + restored = pickle.loads(pickle.dumps(fitness)) + + assert restored._apply_assertions_traced is True + assert len(restored._traced_assertions) == 1 + assert restored.call([10.0, 1.0, 1.0, 20.0, 1.0, 1.0]) == -1.0e99 + assert ( + bool( + restored.model.assertions_satisfied_from_vector( + [10.0, 1.0, 1.0, 20.0, 1.0, 1.0], + assertions=restored._traced_assertions, + ) + ) + is False + ) + + +def test_unpickling_an_old_fitness_recomputes_the_gathered_assertions(): + """ + A `Fitness` pickled before the traced penalty existed carries neither `_traced_assertions` nor + `_apply_assertions_traced`. Defaulting them to "no assertions" would mean a search *resumed* + from such a pickle silently stops enforcing its model's assertions under JAX -- the failure is + invisible, since the fit runs happily and simply samples models the user forbade. The state is + recomputed from the restored model instead, which is where the assertions live anyway. + """ + gaussian_0 = af.Model(af.ex.Gaussian) + gaussian_1 = af.Model(af.ex.Gaussian) + gaussian_0.add_assertion(gaussian_0.centre > gaussian_1.centre) + model = af.Collection(gaussian_0=gaussian_0, gaussian_1=gaussian_1) + + data = np.ones(20) + noise_map = np.ones(20) * 0.1 + fitness = Fitness( + model=model, + analysis=af.ex.Analysis(data=data, noise_map=noise_map), + resample_figure_of_merit=-1.0e99, + ) + + state = fitness.__getstate__() + del state["_traced_assertions"] + del state["_apply_assertions_traced"] + + restored = Fitness.__new__(Fitness) + restored.__setstate__(state) + + assert restored._apply_assertions_traced is True + assert len(restored._traced_assertions) == 1 + assert restored.call([10.0, 1.0, 1.0, 20.0, 1.0, 1.0]) == -1.0e99 + + +def test_numpy_short_circuit_assertion_returns_the_sentinel(): + """ + The numpy `and` short-circuit is part of the user contract: a chained assertion whose second + half is singular exactly where the first fails must reach the search as a resample, not as a + `ZeroDivisionError` out of the likelihood. + """ + prior = af.UniformPrior(lower_limit=0.0, upper_limit=2.0) + model = af.Collection(p=prior) + model.add_assertion((0 < prior) < (1 / prior)) + + data = np.ones(20) + noise_map = np.ones(20) * 0.1 + fitness = Fitness( + model=model, + analysis=af.ex.Analysis(data=data, noise_map=noise_map), + resample_figure_of_merit=-1.0e99, + ) + + assert fitness.call([0.0]) == -1.0e99 + + +@pytest.mark.parametrize( + "kwargs", + [ + {"convert_to_chi_squared": True}, + {"fom_is_log_likelihood": False}, + {"convert_to_chi_squared": True, "fom_is_log_likelihood": False}, + ], +) +def test_numpy_returns_the_raw_sentinel_whatever_the_conversion(kwargs): + """ + The reference the JAX path must match: numpy returns `resample_figure_of_merit` from an early + `return`, so neither the log-prior addition nor the chi-squared multiply touches it. + """ + gaussian_0 = af.Model(af.ex.Gaussian) + gaussian_1 = af.Model(af.ex.Gaussian) + model = af.Collection(gaussian_0=gaussian_0, gaussian_1=gaussian_1) + model.add_assertion(model.gaussian_0.centre > model.gaussian_1.centre) + + data = np.ones(20) + noise_map = np.ones(20) * 0.1 + fitness = Fitness( + model=model, + analysis=af.ex.Analysis(data=data, noise_map=noise_map), + resample_figure_of_merit=-1.0e99, + **kwargs, + ) + + assert fitness.call([10.0, 1.0, 1.0, 20.0, 1.0, 1.0]) == -1.0e99 + + def _ceiling_fitness(log_likelihood, ceiling=None, **kwargs): """ A `Fitness` whose analysis returns `log_likelihood` for any instance. diff --git a/test_autofit/non_linear/test_fitness_assertions_jax.py b/test_autofit/non_linear/test_fitness_assertions_jax.py new file mode 100644 index 000000000..be6798ef9 --- /dev/null +++ b/test_autofit/non_linear/test_fitness_assertions_jax.py @@ -0,0 +1,478 @@ +""" +Model assertions on the JAX paths. + +An assertion signals failure by raising `FitException`, and a `raise` cannot happen inside a +trace: `check_assertions` applies a Python `not` to the assertion's value, and `CompoundAssertion` +combined its halves with a Python `and`, both of which coerce a tracer to a bool and raise +`TracerBoolConversionError`. So a JAX analysis either let the exception escape into the search +(non-vmapped) or failed to trace at all (`use_jax_vmap=True`, which is the Nautilus default for a +JAX analysis). + +`Fitness` now builds the instance with `ignore_assertions=True` and applies the assertions as a +traced boolean through `xp.where`, mapping a violating model to `resample_figure_of_merit` — the +same value the numpy path reaches by catching the exception. These tests pin that equivalence on +all three JAX call surfaces (`call`, `_jit`, `_vmap`), the last being the strict one: under `vmap` +every parameter is a tracer, so an assertion that had kept any Python branch would fail there even +where jit-on-concrete passed. + +JAX is an optional dependency and unit tests are the always-green numpy layer, so the file skips +whole rather than importing `jax` unconditionally (the numpy half is covered in +`test_fitness_assertions.py`). +""" + +import numpy as np +import pytest + +import autofit as af +from autofit.non_linear import fitness as fitness_module +from autofit.non_linear.fitness import Fitness + +jax = pytest.importorskip("jax") +jnp = pytest.importorskip("jax.numpy") + + +#: `gaussian_0.centre` is index 0 and `gaussian_1.centre` is index 3: the vector is ordered by +#: prior id, which is centre, normalization, sigma for each Gaussian in turn. +SATISFYING = [20.0, 1.0, 1.0, 10.0, 1.0, 1.0] +VIOLATING = [10.0, 1.0, 1.0, 20.0, 1.0, 1.0] + +#: The finite sentinel Nautilus and dynesty pass, rather than `-inf`, so a rejection is +#: distinguishable from a merely terrible likelihood in the assertions below. +RESAMPLE = -1.0e99 + + +def _model(assertion="ordering"): + """ + Two Gaussians in a `Collection`. `child` attaches the assertion to `gaussian_0` rather than to + the `Collection` — the form the pre-existing numpy regression test uses, and the one the + traced path has to gather from the tree rather than read off the model it is handed. + """ + gaussian_0 = af.Model(af.ex.Gaussian) + gaussian_1 = af.Model(af.ex.Gaussian) + + if assertion == "child": + gaussian_0.add_assertion(gaussian_0.centre > gaussian_1.centre) + + model = af.Collection(gaussian_0=gaussian_0, gaussian_1=gaussian_1) + + if assertion == "ordering": + model.add_assertion(model.gaussian_0.centre > model.gaussian_1.centre) + elif assertion == "compound_prior": + model.add_assertion( + (model.gaussian_0.centre**2 + model.gaussian_0.normalization**2) + > (model.gaussian_1.centre**2 + model.gaussian_1.normalization**2) + ) + + return model + + +def _fitness(model, use_jax, **kwargs): + data = np.ones(20) + noise_map = np.ones(20) * 0.1 + return Fitness( + model=model, + analysis=af.ex.Analysis(data=data, noise_map=noise_map, use_jax=use_jax), + resample_figure_of_merit=RESAMPLE, + **kwargs, + ) + + +def _numpy_figure_of_merit(model, vector): + """The value the numpy path returns for the same model and vector — the reference.""" + return _fitness(model, use_jax=False).call(vector) + + +def test_jax_call_rejects_a_violating_vector(): + """ + The non-vmapped JAX path. Before the traced penalty this raised `FitException` out of + `instance_from_vector`, since only the numpy branch of `call` has a `try/except`. + """ + model = _model() + fitness = _fitness(model, use_jax=True) + + assert fitness._is_jax is True + assert fitness._apply_assertions_traced is True + assert float(fitness.call(jnp.array(VIOLATING))) == RESAMPLE + + +def test_jax_call_passes_a_satisfying_vector(): + model = _model() + fitness = _fitness(model, use_jax=True) + + figure_of_merit = float(fitness.call(jnp.array(SATISFYING))) + + assert figure_of_merit != RESAMPLE + assert figure_of_merit == pytest.approx( + _numpy_figure_of_merit(model, SATISFYING), abs=1.0e-8 + ) + + +def test_jit_path_rejects_a_violating_vector_and_passes_a_satisfying_one(): + """ + Under `jit` the assertion must trace: whether the penalty is applied at all is a static + Python bool set in `__init__`, and the verdict itself is a traced boolean fed to `xp.where`. + """ + model = _model() + fitness = _fitness(model, use_jax=True, use_jax_jit=True) + + assert fitness._call is fitness._jit + assert float(fitness._call(jnp.array(VIOLATING))) == RESAMPLE + assert float(fitness._call(jnp.array(SATISFYING))) == pytest.approx( + _numpy_figure_of_merit(model, SATISFYING), abs=1.0e-8 + ) + + +def test_vmap_path_rejects_only_the_violating_member_of_a_batch(): + """ + The strict check, and the configuration Nautilus actually builds for a JAX analysis. Both + vectors are traced together, so the rejection has to be a value selected per batch member + rather than a branch taken once. + """ + model = _model() + fitness = _fitness(model, use_jax=True, use_jax_vmap=True) + + assert fitness._call is fitness._vmap + + figures_of_merit = np.asarray( + fitness._call(jnp.array([VIOLATING, SATISFYING])) + ) + + assert figures_of_merit.shape == (2,) + assert figures_of_merit[0] == RESAMPLE + assert figures_of_merit[1] == pytest.approx( + _numpy_figure_of_merit(model, SATISFYING), abs=1.0e-8 + ) + + +@pytest.mark.parametrize("use_jax_jit, use_jax_vmap", [(False, False), (True, False), (False, True)]) +def test_compound_prior_assertion_on_every_jax_surface(use_jax_jit, use_jax_vmap): + """ + The motivating case is an ordering between two *derived* quantities — the squared radius of a + pair of shared priors, the 1D stand-in for the MGE `ell_comps` label degeneracy. That routes + through `SumPrior` and `PowerPrior`, which must realise their operands with the same `xp` as + the rest of the trace. + """ + model = _model(assertion="compound_prior") + fitness = _fitness( + model, use_jax=True, use_jax_jit=use_jax_jit, use_jax_vmap=use_jax_vmap + ) + + # |(0.4, 0.3)|^2 = 0.25 > |(0.05, 0.05)|^2 = 0.005 + satisfying = [0.4, 0.3, 1.0, 0.05, 0.05, 1.0] + violating = [0.05, 0.05, 1.0, 0.4, 0.3, 1.0] + + if use_jax_vmap: + values = np.asarray(fitness._call(jnp.array([violating, satisfying]))) + else: + values = np.array( + [ + float(fitness._call(jnp.array(violating))), + float(fitness._call(jnp.array(satisfying))), + ] + ) + + assert values[0] == RESAMPLE + assert values[1] == pytest.approx( + _numpy_figure_of_merit(model, satisfying), abs=1.0e-8 + ) + + +@pytest.mark.parametrize("use_jax_jit, use_jax_vmap", [(False, False), (True, False), (False, True)]) +def test_model_without_assertions_is_unaffected(use_jax_jit, use_jax_vmap): + """ + With nothing attached the `where` is not emitted at all, and the figure of merit must be the + likelihood untouched — the penalty must not cost the common unconstrained model anything. + """ + model = _model(assertion=None) + fitness = _fitness( + model, use_jax=True, use_jax_jit=use_jax_jit, use_jax_vmap=use_jax_vmap + ) + + assert fitness._apply_assertions_traced is False + + if use_jax_vmap: + values = np.asarray(fitness._call(jnp.array([VIOLATING, SATISFYING]))) + else: + values = np.array( + [ + float(fitness._call(jnp.array(VIOLATING))), + float(fitness._call(jnp.array(SATISFYING))), + ] + ) + + assert np.all(values != RESAMPLE) + assert values[0] == pytest.approx( + _numpy_figure_of_merit(model, VIOLATING), abs=1.0e-8 + ) + assert values[1] == pytest.approx( + _numpy_figure_of_merit(model, SATISFYING), abs=1.0e-8 + ) + + +@pytest.mark.parametrize("use_jax_jit, use_jax_vmap", [(False, False), (True, False), (False, True)]) +def test_child_attached_assertion_is_enforced_on_every_jax_surface( + use_jax_jit, use_jax_vmap +): + """ + The trap this closes: an assertion attached to a child `Model` is enforced on numpy, because + that child checks its own assertions as its instance is built, but the traced path is handed + only the top-level `Collection`. Reading that model's own `_assertions` would find nothing and + silently sample violating models under JAX while rejecting them on numpy. + """ + model = _model(assertion="child") + fitness = _fitness( + model, use_jax=True, use_jax_jit=use_jax_jit, use_jax_vmap=use_jax_vmap + ) + + assert model._assertions == [] + assert fitness._apply_assertions_traced is True + + if use_jax_vmap: + values = np.asarray(fitness._call(jnp.array([VIOLATING, SATISFYING]))) + else: + values = np.array( + [ + float(fitness._call(jnp.array(VIOLATING))), + float(fitness._call(jnp.array(SATISFYING))), + ] + ) + + assert values[0] == RESAMPLE + assert values[1] == pytest.approx( + _numpy_figure_of_merit(model, SATISFYING), abs=1.0e-8 + ) + + +# --------------------------------------------------------------------------- +# The figure-of-merit conversions must not touch the sentinel. +# --------------------------------------------------------------------------- + +#: The three JAX call surfaces, as (use_jax_jit, use_jax_vmap) pairs. +SURFACES = [(False, False), (True, False), (False, True)] + + +def _values(fitness, vectors): + """Evaluate `vectors` on whichever surface `fitness` dispatches to, as a numpy array.""" + if fitness.use_jax_vmap: + return np.asarray(fitness._call(jnp.array(vectors))) + return np.array([float(fitness._call(jnp.array(v))) for v in vectors]) + + +@pytest.mark.parametrize("use_jax_jit, use_jax_vmap", SURFACES) +@pytest.mark.parametrize( + "kwargs", + [ + {"convert_to_chi_squared": True}, + {"fom_is_log_likelihood": False}, + {"convert_to_chi_squared": True, "fom_is_log_likelihood": False}, + ], +) +def test_the_sentinel_survives_the_figure_of_merit_conversions( + use_jax_jit, use_jax_vmap, kwargs +): + """ + numpy returns `resample_figure_of_merit` from an early `return`, *before* the log prior is + added and before the chi-squared multiply. A `where` applied to the log likelihood instead of + to the final figure of merit would let both conversions rewrite the sentinel -- and + `convert_to_chi_squared` flips its sign, so a rejected model would come back as `+2e99`: the + single most attractive point in the space for a minimizer. The two backends must return the + same number. + """ + model = _model() + fitness = _fitness( + model, use_jax=True, use_jax_jit=use_jax_jit, use_jax_vmap=use_jax_vmap, **kwargs + ) + numpy_fitness = _fitness(model, use_jax=False, **kwargs) + + values = _values(fitness, [VIOLATING, SATISFYING]) + + assert values[0] == RESAMPLE + assert values[0] == numpy_fitness.call(VIOLATING) + assert values[1] == pytest.approx(numpy_fitness.call(SATISFYING), abs=1.0e-8) + + +def test_the_sentinel_survives_a_log_prior_that_is_not_zero(): + """ + The posterior-mode half of the check needs a model whose summed log prior is non-zero -- with + the default `UniformPrior`s it is exactly `0.0`, so adding it to the sentinel would be + invisible. + """ + gaussian_0 = af.Model(af.ex.Gaussian) + gaussian_1 = af.Model(af.ex.Gaussian) + gaussian_0.centre = af.GaussianPrior(mean=0.0, sigma=30.0) + gaussian_1.centre = af.GaussianPrior(mean=0.0, sigma=30.0) + model = af.Collection(gaussian_0=gaussian_0, gaussian_1=gaussian_1) + model.add_assertion(model.gaussian_0.centre > model.gaussian_1.centre) + + assert np.sum(model.log_prior_list_from_vector(vector=VIOLATING)) != 0.0 + + fitness = _fitness(model, use_jax=True, fom_is_log_likelihood=False) + + assert float(fitness.call(jnp.array(VIOLATING))) == RESAMPLE + + +# --------------------------------------------------------------------------- +# State restored from a pickle. +# --------------------------------------------------------------------------- + + +def test_unpickling_without_the_assertion_state_still_enforces_assertions(): + """ + A `Fitness` pickled before the traced penalty existed carries neither key. Defaulting them to + "no assertions" would leave a *resumed* JAX search quietly sampling models the user forbade, + so they are recomputed from the restored model. + """ + model = _model() + fitness = _fitness(model, use_jax=True) + + state = fitness.__getstate__() + del state["_traced_assertions"] + del state["_apply_assertions_traced"] + + restored = Fitness.__new__(Fitness) + restored.__setstate__(state) + + assert restored._apply_assertions_traced is True + assert len(restored._traced_assertions) == 1 + assert float(restored.call(jnp.array(VIOLATING))) == RESAMPLE + assert float(restored.call(jnp.array(SATISFYING))) == pytest.approx( + _numpy_figure_of_merit(model, SATISFYING), abs=1.0e-8 + ) + + +# --------------------------------------------------------------------------- +# Compound chaining, boundaries, singular operands and the config override. +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize("use_jax_jit, use_jax_vmap", SURFACES) +def test_compound_assertion_chain_on_every_jax_surface(use_jax_jit, use_jax_vmap): + """ + `(a > b) > c` chains to two comparisons combined by `CompoundAssertion`, which is the class + that had to give up its Python `and` to trace at all. + """ + model = af.Collection( + gaussian_0=af.Model(af.ex.Gaussian), + gaussian_1=af.Model(af.ex.Gaussian), + gaussian_2=af.Model(af.ex.Gaussian), + ) + model.add_assertion( + (model.gaussian_0.centre > model.gaussian_1.centre) > model.gaussian_2.centre + ) + + ordered = [3.0, 1.0, 1.0, 2.0, 1.0, 1.0, 1.0, 1.0, 1.0] + second_half_violated = [3.0, 1.0, 1.0, 1.0, 1.0, 1.0, 2.0, 1.0, 1.0] + + fitness = _fitness( + model, use_jax=True, use_jax_jit=use_jax_jit, use_jax_vmap=use_jax_vmap + ) + + values = _values(fitness, [second_half_violated, ordered]) + + assert values[0] == RESAMPLE + assert values[1] == pytest.approx( + _numpy_figure_of_merit(model, ordered), abs=1.0e-8 + ) + + +@pytest.mark.parametrize("operator, expected_resample", [(">", True), (">=", False)]) +def test_equality_boundary(operator, expected_resample): + """ + The equality boundary is the only input that distinguishes `>` from `>=`, so it is what would + catch the two being wired to the same comparison when `xp` was threaded through them. + """ + model = af.Collection( + gaussian_0=af.Model(af.ex.Gaussian), + gaussian_1=af.Model(af.ex.Gaussian), + ) + if operator == ">": + model.add_assertion(model.gaussian_0.centre > model.gaussian_1.centre) + else: + model.add_assertion(model.gaussian_0.centre >= model.gaussian_1.centre) + + equal = [10.0, 1.0, 1.0, 10.0, 1.0, 1.0] + fitness = _fitness(model, use_jax=True) + + value = float(fitness.call(jnp.array(equal))) + + if expected_resample: + assert value == RESAMPLE + else: + assert value == pytest.approx( + _numpy_figure_of_merit(model, equal), abs=1.0e-8 + ) + + +def test_a_singular_second_half_traces_rather_than_raising(): + """ + The numpy path short-circuits `(0 < p) < (1 / p)` so `1 / 0` is never evaluated. JAX cannot: + `logical_and` evaluates both halves. That is safe there -- `1 / 0` is `inf`, not an exception — + so the trace must simply complete, and a violating vector must still reach the sentinel. + """ + prior = af.UniformPrior(lower_limit=0.0, upper_limit=2.0) + model = af.Collection(p=prior) + model.add_assertion((0.5 < prior) < (1 / prior)) + + fitness = _fitness(model, use_jax=True) + + # p = 0.25 fails the first half (0.5 < 0.25 is False). + assert float(fitness.call(jnp.array([0.25]))) == RESAMPLE + # p = 0.75 satisfies both (0.5 < 0.75 < 1.333). + assert float(fitness.call(jnp.array([0.75]))) != RESAMPLE + + +def test_assertions_on_an_assertion_operand_are_enforced(): + """ + `derived = p + 1` carries its own assertion, which numpy fires when the operand is realised. + The gather has to follow the assertion's operand graph to find it, or JAX accepts a vector + numpy rejects. + """ + prior = af.UniformPrior(lower_limit=0.0, upper_limit=2.0) + derived = prior + 1 + derived.add_assertion(prior > 0.5) + + model = af.Collection(p=prior) + model.add_assertion(derived < 2) + + fitness = _fitness(model, use_jax=True) + + assert fitness._apply_assertions_traced is True + assert float(fitness.call(jnp.array([0.25]))) == RESAMPLE + assert float(fitness.call(jnp.array([0.75]))) != RESAMPLE + + +class _ExceptionOverrideConf: + """ + Stands in for `autonerves.conf` with `general.test.exception_override` set, the switch that + turns assertion checking off wholesale on the numpy path. + """ + + instance = {"general": {"test": {"exception_override": True}}} + + +def test_exception_override_disables_the_traced_penalty(monkeypatch): + """ + `exception_override` exists so a test run can push a model through a search without its + assertions rejecting anything. It disables `check_assertions` on numpy, so it has to disable + the traced penalty too -- otherwise a JAX run under the override rejects models a numpy run + accepts. + """ + monkeypatch.setattr(fitness_module, "conf", _ExceptionOverrideConf()) + + model = _model() + fitness = _fitness(model, use_jax=True) + + assert fitness._apply_assertions_traced is False + + value = float(fitness.call(jnp.array(VIOLATING))) + + assert value != RESAMPLE + + # The reference is the same model without the assertion: the override is read from + # `autofit.mapper.prior_model.abstract`'s own `conf` on the numpy path, which this + # monkeypatch does not reach, so a numpy `Fitness` on the asserting model would still + # resample. The likelihood depends only on the vector, so the assertion-free twin gives the + # value the override is supposed to let through. + assert value == pytest.approx( + _numpy_figure_of_merit(_model(assertion=None), VIOLATING), abs=1.0e-8 + )