From d49275c3387b08bfedae9377aff6482125e97e18 Mon Sep 17 00:00:00 2001 From: James Nightingale Date: Mon, 24 Aug 2026 17:43:08 +0000 Subject: [PATCH] fix: TEST_MODE bypass must evaluate a point the model's assertions accept MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The `PYAUTO_TEST_MODE=2/3` bypass has no sampler, so it picks its own evaluation point: the prior medians. A model whose components share priors and carry an ordering assertion — the standard idiom for breaking exchange degeneracy, e.g. PyAutoCTI trap models with `trap_0.release_timescale < trap_1.release_timescale` — ties exactly there, so `check_assertions` rejects it with `FitException` and the run hard-fails on an artifact of the bypass's own choice of point. A real search absorbs this by resampling. The failure had three sites, not one: - `_fit_bypass_test_mode` instantiated the model outside the `try` that catches `FitException`, so the assertion rejection escaped that guard; - every fake sample is the median vector scaled uniformly, which preserves an ordering tie, so no stored sample was reconstructible either; - `SamplesSummary.max_log_likelihood` is `@to_instance()` with `recover="raise"`, so `result.max_log_likelihood_instance` raised `SamplesException` — meaning `PYAUTO_TEST_MODE=3` was broken too, even though it never calls the likelihood. Fix all three at the source by making the bypass evaluate *and store* a vector the model accepts. `_test_mode_valid_parameter_vector` factors out the deterministic search TEST_MODE=1 recovery already used — prior medians first, then `default_rng(seed=0)` prior draws, each candidate validated — and both call sites now share it. The fixed seed keeps smoke runs reproducible. Mode 1's stronger per-sample validation is preserved via the `validate` hook. The likelihood-call guard is untouched: a pathological likelihood is a different contract from an invalid instance, and both are now covered. Closes #1519 --- autofit/non_linear/search/abstract_search.py | 185 +++++++++++++----- .../non_linear/search/test_abstract_search.py | 119 +++++++++++ 2 files changed, 255 insertions(+), 49 deletions(-) diff --git a/autofit/non_linear/search/abstract_search.py b/autofit/non_linear/search/abstract_search.py index 9a00c0df7..f258208ef 100644 --- a/autofit/non_linear/search/abstract_search.py +++ b/autofit/non_linear/search/abstract_search.py @@ -11,7 +11,7 @@ from collections import Counter from functools import wraps from pathlib import Path -from typing import TYPE_CHECKING, Optional, Union, Tuple, List, Dict +from typing import TYPE_CHECKING, Any, Callable, Optional, Union, Tuple, List, Dict import psutil @@ -783,6 +783,96 @@ def start_resume_fit(self, analysis: Analysis, model: AbstractPriorModel) -> Res return result + def _test_mode_valid_parameter_vector( + self, + model: AbstractPriorModel, + failure_prefix: str, + validate: Optional[Callable[[List[float]], Any]] = None, + ) -> Tuple[List[float], Any]: + """The first deterministically-drawn parameter vector the model accepts. + + Test mode has no sampler, so it evaluates the model at a point it picks + itself — the prior medians. A model whose components share priors and + carry an ordering assertion (``trap_0.release_timescale < + trap_1.release_timescale``, the standard idiom for breaking exchange + degeneracy) ties *exactly* there, so ``check_assertions`` rejects the + medians with :class:`FitException`. A production search absorbs that by + resampling, and test mode must do the same rather than hard-fail on an + artifact of its own choice of point. + + Try the prior medians first, then a deterministic sequence of prior + draws, returning the first candidate ``validate`` accepts. The fixed + seed keeps smoke runs reproducible without touching the application's + global random state. + + Parameters + ---------- + model + The model the vector must be valid for. + failure_prefix + Opening of the :class:`FitException` message raised once the attempt + budget is spent; the attempt count is appended to it. + validate + Called with each candidate vector. Raising `FitException` rejects + that candidate and moves on to the next draw; the return value is + handed back alongside the accepted vector, so a caller that must + build something in order to validate it does not build it twice. + Defaults to instantiating the vector. + + Returns + ------- + The accepted parameter vector, and whatever ``validate`` returned for it. + + Raises + ------ + FitException + If no candidate is accepted within + ``TEST_MODE_REPRESENTATIVE_MAX_ATTEMPTS`` attempts, chained to the + final rejection. + """ + if validate is None: + + def validate(candidate: List[float]): + return model.instance_from_vector(vector=candidate) + + rng = np.random.default_rng(seed=0) + last_error = None + + for attempt in range(TEST_MODE_REPRESENTATIVE_MAX_ATTEMPTS): + unit_vector = ( + [0.5] * model.prior_count + if attempt == 0 + else rng.random(model.prior_count).tolist() + ) + + try: + parameter_vector = [ + float(value) + for value in model.vector_from_unit_vector( + unit_vector=unit_vector, + ) + ] + validated = validate(parameter_vector) + except exc.FitException as candidate_error: + last_error = candidate_error + continue + + if attempt > 0: + logger.warning( + "TEST MODE: the prior medians are not a valid model " + f"instance ({last_error.__cause__ or last_error!r}); using " + f"deterministic prior draw {attempt} instead. A model whose " + "components share priors and carry an ordering assertion " + "ties at its medians, which a real search resamples past." + ) + + return parameter_vector, validated + + raise exc.FitException( + f"{failure_prefix} after " + f"{TEST_MODE_REPRESENTATIVE_MAX_ATTEMPTS} attempts." + ) from last_error + def _test_mode_samples_after_rejected_fit( self, samples: Samples, @@ -808,56 +898,44 @@ def _test_mode_samples_after_rejected_fit( "a valid representative sample for result construction." ) - rng = np.random.default_rng(seed=0) - last_error = error model = samples.model - for attempt in range(TEST_MODE_REPRESENTATIVE_MAX_ATTEMPTS): - unit_vector = ( - [0.5] * model.prior_count - if attempt == 0 - else rng.random(model.prior_count).tolist() + def validate(parameter_vector: List[float]): + """Every synthetic sample, not just the first, must reconstruct.""" + sample_list = self._build_fake_samples( + model=model, + parameter_vector=parameter_vector, + log_likelihood=-1.0e99, ) - try: - parameter_vector = [ - float(value) - for value in model.vector_from_unit_vector( - unit_vector=unit_vector, - ) - ] - sample_list = self._build_fake_samples( - model=model, - parameter_vector=parameter_vector, - log_likelihood=-1.0e99, + for sample in sample_list: + model.instance_from_vector( + vector=sample.parameter_lists_for_model(model) ) - for sample in sample_list: - model.instance_from_vector( - vector=sample.parameter_lists_for_model(model) - ) - except exc.FitException as candidate_error: - last_error = candidate_error - continue + return sample_list - samples_info = { - **(samples.samples_info or {}), - "total_iterations": 1, - "time": 0.0, - "log_evidence": -1.0e99, - } - samples_info.update(self._test_mode_samples_info()) + _, sample_list = self._test_mode_valid_parameter_vector( + model=model, + failure_prefix=( + "TEST MODE 1 could not construct a valid representative result" + ), + validate=validate, + ) - return samples.from_list_info_and_model( - model=model, - sample_list=sample_list, - samples_info=samples_info, - ) + samples_info = { + **(samples.samples_info or {}), + "total_iterations": 1, + "time": 0.0, + "log_evidence": -1.0e99, + } + samples_info.update(self._test_mode_samples_info()) - raise exc.FitException( - "TEST MODE 1 could not construct a valid representative result " - f"after {TEST_MODE_REPRESENTATIVE_MAX_ATTEMPTS} attempts." - ) from last_error + return samples.from_list_info_and_model( + model=model, + sample_list=sample_list, + samples_info=samples_info, + ) def result_via_completed_fit( self, @@ -996,16 +1074,25 @@ def _fit_bypass_test_mode( model.freeze() - unit_vector = [0.5] * model.prior_count - parameter_vector = [ - float(v) for v in model.vector_from_unit_vector( - unit_vector=unit_vector, - ) - ] + # The bypass has no sampler, so it chooses its own evaluation point and + # must choose one the model accepts. A model whose components share + # priors and carry an ordering assertion ties exactly at the prior + # medians, and `check_assertions` rejects that tie with `FitException`. + # The vector chosen here is also the one written into the fake samples + # below, so picking a valid one is what keeps + # `result.max_log_likelihood_instance` reconstructible — which is why + # mode 3 needs this too, not just mode 2's likelihood call + # (PyAutoFit #1519). + parameter_vector, instance = self._test_mode_valid_parameter_vector( + model=model, + failure_prefix=( + "TEST MODE could not find a parameter vector satisfying the " + "model's assertions" + ), + ) log_likelihood = -1.0e99 if call_likelihood: - instance = model.instance_from_vector(vector=parameter_vector) try: log_likelihood = float( analysis.log_likelihood_function(instance) diff --git a/test_autofit/non_linear/search/test_abstract_search.py b/test_autofit/non_linear/search/test_abstract_search.py index 46d3ca092..0d105c880 100644 --- a/test_autofit/non_linear/search/test_abstract_search.py +++ b/test_autofit/non_linear/search/test_abstract_search.py @@ -476,6 +476,125 @@ def log_likelihood_function(self, instance): search.fit(model=af.Model(af.m.MockClassx2), analysis=_BrokenAnalysis()) +class _ConstantLikelihoodAnalysis(af.m.MockAnalysis): + """`MockAnalysis` maps its likelihood over the model, which returns a list + for the collections below; the bypass wants a single float.""" + + def log_likelihood_function(self, instance): + return 1.0 + + +class _Ordered: + """A one-parameter component; two of them plus an ordering assertion is the + standard idiom for breaking an exchange degeneracy.""" + + def __init__(self, value=1.0): + self.value = value + + +def _tied_assertion_model(): + """Identical priors either side of an ordering assertion — so the two + parameters tie *exactly* at the prior medians the bypass evaluates at.""" + model = af.Collection( + first=af.Model(_Ordered, value=af.UniformPrior(0.1, 10.0)), + second=af.Model(_Ordered, value=af.UniformPrior(0.1, 10.0)), + ) + model.add_assertion(model.first.value < model.second.value) + return model + + +def _impossible_assertion_model(): + """Disjoint priors ordered the wrong way round: no draw can satisfy it.""" + model = af.Collection( + first=af.Model(_Ordered, value=af.UniformPrior(5.0, 10.0)), + second=af.Model(_Ordered, value=af.UniformPrior(0.1, 1.0)), + ) + model.add_assertion(model.first.value < model.second.value) + return model + + +class TestBypassToleratesAssertionTies: + """ + The bypass has no sampler, so it evaluates the model at a point it picks + itself — the prior medians. A model whose components share priors and carry + an ordering assertion (e.g. PyAutoCTI trap models with + `trap_0.release_timescale < trap_1.release_timescale`) ties exactly there, + so `check_assertions` rejects it and the run hard-fails on an artifact of + the bypass's own choice of point. A real search resamples past this + (PyAutoFit #1519). + + Mode 3 is affected as well as mode 2. It never calls the likelihood, but the + vector the bypass *stores* is the one `result.max_log_likelihood_instance` + reconstructs, and `SamplesSummary.max_log_likelihood` raises rather than + falling back to another stored sample — every fake sample is the same point + scaled uniformly, which preserves the tie anyway. + """ + + @pytest.mark.parametrize("mode", ["2", "3"]) + def test__tied_assertion__fit_completes_and_result_instance_reconstructs( + self, monkeypatch, mode + ): + monkeypatch.setenv("PYAUTO_TEST_MODE", mode) + + result = af.DynestyStatic( + name=f"bypass_assertion_tie_{mode}", + unique_tag=f"bypass_assertion_tie_{mode}_test", + ).fit(model=_tied_assertion_model(), analysis=_ConstantLikelihoodAnalysis()) + + # The result must be constructible, not just the fit survivable: the + # stored vector is re-instantiated here, assertions and all. + instance = result.max_log_likelihood_instance + + assert instance.first.value < instance.second.value + + def test__tied_assertion__chosen_point_is_deterministic_across_modes( + self, monkeypatch + ): + values = [] + + for mode in ("2", "3"): + monkeypatch.setenv("PYAUTO_TEST_MODE", mode) + result = af.DynestyStatic( + name=f"bypass_assertion_seed_{mode}", + unique_tag=f"bypass_assertion_seed_{mode}_test", + ).fit(model=_tied_assertion_model(), analysis=_ConstantLikelihoodAnalysis()) + instance = result.max_log_likelihood_instance + values.append([instance.first.value, instance.second.value]) + + # A fixed seed, so smoke runs stay reproducible and the two modes agree. + assert values[0] == pytest.approx(values[1]) + + @pytest.mark.parametrize("mode", ["2", "3"]) + def test__unsatisfiable_assertion__bounded_failure_is_clear( + self, monkeypatch, mode + ): + from autofit.non_linear.search import abstract_search + + monkeypatch.setenv("PYAUTO_TEST_MODE", mode) + monkeypatch.setattr( + abstract_search, + "TEST_MODE_REPRESENTATIVE_MAX_ATTEMPTS", + 2, + ) + + with pytest.raises( + af.exc.FitException, + match=( + "could not find a parameter vector satisfying the model's " + "assertions after 2 attempts" + ), + ) as error: + af.DynestyStatic( + name=f"bypass_assertion_impossible_{mode}", + unique_tag=f"bypass_assertion_impossible_{mode}_test", + ).fit( + model=_impossible_assertion_model(), + analysis=_ConstantLikelihoodAnalysis(), + ) + + assert isinstance(error.value.__cause__, af.exc.FitException) + + class _RejectsLowValue: def __init__(self, value): if value < 0.75: