diff --git a/autofit/config/general.yaml b/autofit/config/general.yaml index 0ba95f8a4..a854e2a90 100644 --- a/autofit/config/general.yaml +++ b/autofit/config/general.yaml @@ -31,5 +31,5 @@ test: check_likelihood_function: true # if True, when a search is resumed the likelihood of a previous sample is recalculated to ensure it is consistent with the previous run. exception_override: false lh_timeout_seconds: # If a float is input, the log_likelihood_function call is timed out after this many seconds, to diagnose infinite loops. Default is None, meaning no timeout. - log_likelihood_ceiling: 1.0e+20 # If a float is input, log likelihoods whose magnitude exceeds it are treated as numerical garbage and replaced by the resample figure of merit. Blank (null) or inf disables the guard. + log_likelihood_ceiling: # If a float is input, log likelihoods whose magnitude exceeds it are treated as numerical garbage and replaced by the resample figure of merit. Blank (null) or inf disables the guard, which is the default: a log likelihood scales with the noise-map units, so a fixed magnitude can reject a legitimate fit on a badly-scaled dataset. Opt in where the units are known (e.g. autolens_profiling sets 1.0e+20). parallel_profile: false diff --git a/autofit/non_linear/fitness.py b/autofit/non_linear/fitness.py index d1e3ab902..157bd87ac 100644 --- a/autofit/non_linear/fitness.py +++ b/autofit/non_linear/fitness.py @@ -32,9 +32,53 @@ def get_timeout_seconds(): timeout_seconds = get_timeout_seconds() #: Ceiling used when ``general.test.log_likelihood_ceiling`` is absent from the config (e.g. a -#: workspace whose ``general.yaml`` pre-dates the key). Chosen far above any physically meaningful -#: log likelihood, so it only ever catches numerical garbage. -LOG_LIKELIHOOD_CEILING_DEFAULT = 1.0e20 +#: 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 +#: today's default rather than the one that shipped in PyAutoFit 2025.x. +LOG_LIKELIHOOD_CEILING_DEFAULT = float("inf") + +#: Set the first time the magnitude guard actually rejects a log likelihood on the numpy path, so +#: the warning below is emitted once per process rather than once per sample. Module level, not +#: per-`Fitness`: a search rebuilds its fitness object on resume, and one warning per run is the +#: point. +_log_likelihood_ceiling_warning_emitted = False + + +def _warn_log_likelihood_ceiling_fired(log_likelihood, ceiling: float): + """ + Warn, once per process, that the magnitude guard has rejected a log likelihood. + + The guard is deliberately silent about *which* of the two things it caught: numerical garbage + (what it exists for), or a legitimate likelihood on a dataset whose noise-map units make + ``|log_likelihood|`` genuinely enormous (what makes the ceiling unsafe as a default -- see + `get_log_likelihood_ceiling`). Only the user knows their units, so the warning names the value + and the ceiling and leaves the judgement to them. + + **Numpy path only.** `Fitness.call` also runs under ``jax.jit`` / ``jax.vmap``, where the + rejection is an ``xp.where`` on a *tracer*: there is no Python-visible moment at which the guard + "fires", so this cannot be called, and those paths reject silently by construction. Nor is a + fire *counter* offered for them -- incrementing one from traced code needs a host callback or a + donated buffer, which perturbs the very code being profiled and does not survive ``vmap`` / + ``grad``. A counter that only ever counted the numpy path would read ``0`` on a jitted run that + rejected every sample, which is worse than no counter at all. + """ + global _log_likelihood_ceiling_warning_emitted + + if _log_likelihood_ceiling_warning_emitted: + return + + _log_likelihood_ceiling_warning_emitted = True + + logger.warning( + f"A log likelihood of {log_likelihood} exceeded the configured magnitude ceiling of " + f"{ceiling} and was replaced by the resample figure of merit, so the search will not " + "sample this model. This is usually numerical garbage (e.g. an fp64 Cholesky on a " + "non-positive-definite matrix), but a log likelihood scales with the noise-map units, so a " + "badly-scaled dataset can exceed the ceiling legitimately -- check the units before " + "trusting the rejection. Set general.test.log_likelihood_ceiling higher, or blank to " + "disable the guard. This warning is issued once per run; JAX-traced runs (jit / vmap) " + "cannot issue it at all." + ) def get_log_likelihood_ceiling() -> float: @@ -42,14 +86,25 @@ def get_log_likelihood_ceiling() -> float: The largest ``|log_likelihood|`` a fitness function accepts before treating the value as numerical garbage and substituting the resample figure of merit. - `Fitness.call` maps ``NaN`` and ``inf`` log likelihoods to ``resample_figure_of_merit``, but a - *finite* value of, say, ``3e+303`` passes straight through and the search accepts it as its best - point. That is not hypothetical: a non-positive-definite regularization matrix makes an fp64 - Cholesky return finite garbage, a nested sampler treats it as the peak of the posterior, its - shell log evidence explodes to ``~1e56`` and the termination criterion never fires -- the run - burns its wall clock without ever converging. - - The ceiling closes that hole. It is read **once** from + **Off by default.** The packaged ``general.yaml`` ships this blank, so the guard is disabled + unless a config opts in. It is off because the ceiling is a bare magnitude in *unspecified + units*: a log likelihood is ``-0.5 * chi_squared - 0.5 * noise_normalization``, and both terms + scale with the noise map -- ``chi_squared`` as ``noise ** -2``, ``noise_normalization`` + linearly in the number of pixels. A dataset whose noise map is expressed in a small unit can + therefore produce a *legitimate* log likelihood above any fixed threshold, and every model + would be silently rejected, leaving the search nothing but the resample sentinel. The guard + cannot tell that case from the one below, because a magnitude is the only signal it reads. + + What it exists for, when a config does opt in: `Fitness.call` maps ``NaN`` and ``inf`` log + likelihoods to ``resample_figure_of_merit``, but a *finite* value of, say, ``3e+303`` passes + straight through and the search accepts it as its best point. That is not hypothetical: a + non-positive-definite regularization matrix makes an fp64 Cholesky return finite garbage, a + nested sampler treats it as the peak of the posterior, its shell log evidence explodes to + ``~1e56`` and the termination criterion never fires -- the run burns its wall clock without ever + converging. `autolens_profiling` enables the ceiling for exactly this reason (run ``341908_5``); + a science analysis should enable it only once its own units are known to be safe. + + The value is read **once** from ``conf.instance["general"]["test"]["log_likelihood_ceiling"]`` and returned as a static Python float, because the guard it feeds runs inside JAX-traced code, where a Python ``if`` on a traced value is illegal and the comparison must be a static-vs-traced ``xp.where``. @@ -59,8 +114,8 @@ def get_log_likelihood_ceiling() -> float: Returns ------- - The ceiling as a float. ``inf`` disables the guard, which is what a ``null``, non-positive or - unparseable config entry maps to, since ``abs(x) > inf`` is never true. + The ceiling as a float. ``inf`` disables the guard, which is what an absent, ``null``, + non-positive or unparseable config entry maps to, since ``abs(x) > inf`` is never true. """ try: ceiling = conf.instance["general"]["test"]["log_likelihood_ceiling"] @@ -266,6 +321,16 @@ def _warmup_visualization(self): def _xp(self): return self.analysis._xp + @property + def _is_jax(self) -> bool: + """ + Whether the array backend is JAX, and therefore whether `call` may be running on tracers. + + Read by the log-likelihood magnitude guard, which warns from Python and so must stay on the + numpy path — under `jax.jit` / `jax.vmap` a Python branch on a traced value is illegal. + """ + return self._xp.__name__.startswith("jax") + def call(self, parameters): """ A private method that calls the fitness function with the given parameters and additional keyword arguments. @@ -278,8 +343,11 @@ def call(self, parameters): the resample sentinel and never select the point. The magnitude ceiling exists because the NaN/inf checks miss the failure mode that actually kills long runs: an fp64 Cholesky on a non-positive-definite matrix returns *finite* garbage (log likelihoods up to `3e+303`), which a nested sampler happily accepts as its - best point and then never terminates on. It is a static Python float (see `get_log_likelihood_ceiling`), - so `inf` makes the `where` a no-op and the comparison stays legal under `jax.jit` / `jax.vmap`. Gradient + best point and then never terminates on. It is **off unless a config opts in** — the threshold is a bare + magnitude and a log likelihood scales with the noise-map units, so a fixed ceiling can reject a legitimate + fit (`get_log_likelihood_ceiling` carries the argument). It is a static Python float, so the default `inf` + makes the `where` a no-op and the comparison stays legal under `jax.jit` / `jax.vmap`. When it does fire, + the numpy path warns once per process; the traced paths cannot warn at all. Gradient consumers get no such protection: under `jax.grad`, reverse-mode differentiates *both* branches of an `xp.where` and multiplies the unselected one by zero, so if the likelihood's derivative is also non-finite the guard yields `0 * NaN = NaN` and the returned gradient is NaN even though the value looks handled. @@ -309,7 +377,7 @@ def call(self, parameters): ------- The figure of merit returned to the non-linear search, which is either the log likelihood or log posterior. """ - if self._xp.__name__.startswith("jax"): + 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) @@ -333,14 +401,36 @@ def call(self, parameters): # Penalize finite-but-impossible log-likelihoods (e.g. 3e+303 out of an fp64 Cholesky on a # non-positive-definite matrix), which the isnan/isinf guards above let through. Same - # value-only caveat. The ceiling is a static float, so `inf` makes this a no-op and the + # value-only caveat. The ceiling is a static float, and it is `inf` unless a config opts in + # (see `get_log_likelihood_ceiling`), so by default this is a no-op; when it is set, the # resample sentinels (-inf, -1e99, -1e30) map to themselves. + raw_log_likelihood = log_likelihood + + over_ceiling = self._xp.abs(log_likelihood) > self.log_likelihood_ceiling + log_likelihood = self._xp.where( - self._xp.abs(log_likelihood) > self.log_likelihood_ceiling, + over_ceiling, self.resample_figure_of_merit, log_likelihood, ) + # Tell the user the first time the guard actually rejects something, because a rejection is + # indistinguishable from "the model is bad" from inside the search. Numpy path only: + # `over_ceiling` is a tracer under jit / vmap, so a Python `if` on it is illegal there and + # those runs reject silently (documented in `_warn_log_likelihood_ceiling_fired`). The + # ceiling test comes first so the default (disabled) config short-circuits before touching + # the array at all, and `_warning_emitted` takes this off the hot path after the first fire. + if ( + self.log_likelihood_ceiling != np.inf + and not _log_likelihood_ceiling_warning_emitted + and not self._is_jax + ): + if bool(np.any(over_ceiling)): + _warn_log_likelihood_ceiling_fired( + log_likelihood=raw_log_likelihood, + ceiling=self.log_likelihood_ceiling, + ) + # Determine final figure of merit if self.fom_is_log_likelihood: figure_of_merit = log_likelihood diff --git a/autofit/non_linear/search/nest/nss/search.py b/autofit/non_linear/search/nest/nss/search.py index 8e39aa069..e086096fd 100644 --- a/autofit/non_linear/search/nest/nss/search.py +++ b/autofit/non_linear/search/nest/nss/search.py @@ -56,11 +56,18 @@ def nss_log_likelihood_from(model, analysis, log_likelihood_ceiling=None): Two things are rejected, both mapped to `NSS_INVALID_LOG_LIKELIHOOD`: - - non-finite values (``NaN`` / ``inf``), as before; - - finite values whose magnitude exceeds the configured ceiling. An fp64 Cholesky on a - non-positive-definite matrix returns finite garbage (log likelihoods up to ``3e+303``), which - a nested sampler otherwise accepts as its highest-likelihood live point; the shell log - evidence then explodes and the termination criterion never fires. + - non-finite values (``NaN`` / ``inf``), always; + - finite values whose magnitude exceeds the configured ceiling, **if** a config has opted in. + An fp64 Cholesky on a non-positive-definite matrix returns finite garbage (log likelihoods up + to ``3e+303``), which a nested sampler otherwise accepts as its highest-likelihood live point; + the shell log evidence then explodes and the termination criterion never fires. The ceiling is + off in the packaged config, because a log likelihood scales with the noise-map units and a + fixed magnitude can therefore reject a legitimate fit + (`autofit.non_linear.fitness.get_log_likelihood_ceiling` carries the full argument). + + This closure is JAX-only, so it cannot warn when the ceiling fires — the rejection is an + ``jnp.where`` on a tracer. `Fitness.call`'s numpy path warns once per process; ``af.NSS`` does + not sample through it. Parameters ---------- @@ -70,8 +77,9 @@ def nss_log_likelihood_from(model, analysis, log_likelihood_ceiling=None): The analysis supplying `log_likelihood_function`. log_likelihood_ceiling The magnitude ceiling. Defaults to the configured value - (`autofit.non_linear.fitness.get_log_likelihood_ceiling`); ``inf`` disables the check. It - must be a static Python float, because JAX traces the comparison it feeds. + (`autofit.non_linear.fitness.get_log_likelihood_ceiling`), which is ``inf`` — the check + disabled — unless a config opts in. It must be a static Python float, because JAX traces + the comparison it feeds. Returns ------- diff --git a/test_autofit/config/general.yaml b/test_autofit/config/general.yaml index 2d77aa866..ed2f15e2a 100644 --- a/test_autofit/config/general.yaml +++ b/test_autofit/config/general.yaml @@ -28,5 +28,5 @@ test: preloads_check_threshold: 1.0 # If the figure of merit of a fit with and without preloads is greater than this threshold, the check preload test fails and an exception raised for a model-fit. # If True, perform a sanity check that the likelihood using preloads is identical to the likelihood not using preloads. exception_override: false lh_timeout_seconds: # If a float is input, the log_likelihood_function call is timed out after this many seconds, to diagnose infinite loops. Default is None, meaning no timeout. - log_likelihood_ceiling: 1.0e+20 # If a float is input, log likelihoods whose magnitude exceeds it are treated as numerical garbage and replaced by the resample figure of merit. Blank (null) or inf disables the guard. + log_likelihood_ceiling: # If a float is input, log likelihoods whose magnitude exceeds it are treated as numerical garbage and replaced by the resample figure of merit. Blank (null) or inf disables the guard, which is the default: a log likelihood scales with the noise-map units, so a fixed magnitude can reject a legitimate fit on a badly-scaled dataset. Opt in where the units are known (e.g. autolens_profiling sets 1.0e+20). parallel_profile: false diff --git a/test_autofit/non_linear/search/nest/nss/test_log_likelihood_ceiling.py b/test_autofit/non_linear/search/nest/nss/test_log_likelihood_ceiling.py index bae0a371c..1623b6f73 100644 --- a/test_autofit/non_linear/search/nest/nss/test_log_likelihood_ceiling.py +++ b/test_autofit/non_linear/search/nest/nss/test_log_likelihood_ceiling.py @@ -25,6 +25,10 @@ PARAMETERS = [1.0, 1.0, 1.0] +#: The ceiling `autolens_profiling` opts into. PyAutoFit ships the guard off, so every +#: enabled-path test below passes it explicitly. +CEILING = 1.0e20 + #: Above the 1e20 ceiling, inside float32 range — so the value is rejected by the magnitude guard #: and not by the isfinite guard that precedes it. OVER_CEILING = 1.0e30 @@ -45,13 +49,13 @@ def test_nss_closure_rejects_a_log_likelihood_above_the_ceiling(): The failure this exists for: a finite `3e+303` out of an fp64 Cholesky becomes the highest-likelihood live point, the shell log evidence explodes and the run never terminates. """ - log_likelihood = _log_likelihood_from(OVER_CEILING, log_likelihood_ceiling=1.0e20) + log_likelihood = _log_likelihood_from(OVER_CEILING, log_likelihood_ceiling=CEILING) assert float(log_likelihood(jnp.array(PARAMETERS))) == NSS_INVALID_LOG_LIKELIHOOD def test_nss_closure_passes_a_log_likelihood_below_the_ceiling(): - log_likelihood = _log_likelihood_from(UNDER_CEILING, log_likelihood_ceiling=1.0e20) + log_likelihood = _log_likelihood_from(UNDER_CEILING, log_likelihood_ceiling=CEILING) assert float(log_likelihood(jnp.array(PARAMETERS))) == pytest.approx( UNDER_CEILING, rel=1.0e-5 @@ -64,7 +68,7 @@ def test_nss_closure_still_rejects_non_finite_log_likelihoods(log_likelihood): The magnitude guard is added *after* the isfinite guard; the pre-existing behaviour must be unchanged. """ - closure = _log_likelihood_from(log_likelihood, log_likelihood_ceiling=1.0e20) + closure = _log_likelihood_from(log_likelihood, log_likelihood_ceiling=CEILING) assert float(closure(jnp.array(PARAMETERS))) == NSS_INVALID_LOG_LIKELIHOOD @@ -75,7 +79,7 @@ def test_nss_closure_sentinel_maps_to_itself(): idempotent against the value it substitutes. """ closure = _log_likelihood_from( - NSS_INVALID_LOG_LIKELIHOOD, log_likelihood_ceiling=1.0e20 + NSS_INVALID_LOG_LIKELIHOOD, log_likelihood_ceiling=CEILING ) assert float(closure(jnp.array(PARAMETERS))) == NSS_INVALID_LOG_LIKELIHOOD @@ -89,11 +93,26 @@ def test_nss_closure_with_the_ceiling_disabled_passes_any_finite_value(): ) -def test_nss_closure_defaults_to_the_configured_ceiling(): +def test_nss_closure_defaults_to_the_configured_ceiling_which_is_disabled(): """ - With no explicit ceiling the closure reads the config, so `af.NSS` picks the guard up without - the search having to thread it. + With no explicit ceiling the closure reads the config — and the packaged config ships the guard + **off**, because the threshold is a bare magnitude and a log likelihood scales with the + noise-map units. So `af.NSS` picks up "disabled" by default and an enormous finite value passes + through, exactly as it did before the guard existed. A config that opts in (as + `autolens_profiling` does) is what turns the tests above into the live behaviour. """ closure = _log_likelihood_from(OVER_CEILING) + assert float(closure(jnp.array(PARAMETERS))) == pytest.approx( + OVER_CEILING, rel=1.0e-5 + ) + + +def test_nss_closure_still_rejects_non_finite_values_with_the_ceiling_disabled(): + """ + Turning the magnitude guard off must not turn the isfinite guard off with it — blackjax's + nested-sampler arithmetic still cannot see a `NaN`. + """ + closure = _log_likelihood_from(np.nan) + assert float(closure(jnp.array(PARAMETERS))) == NSS_INVALID_LOG_LIKELIHOOD diff --git a/test_autofit/non_linear/test_fitness_assertions.py b/test_autofit/non_linear/test_fitness_assertions.py index 2af34df64..7ebd26fe0 100644 --- a/test_autofit/non_linear/test_fitness_assertions.py +++ b/test_autofit/non_linear/test_fitness_assertions.py @@ -1,3 +1,5 @@ +import logging + import numpy as np import pytest @@ -35,41 +37,79 @@ def test_fitness_returns_resample_fom_on_assertion_failure(): assert fitness.call(satisfying) != fitness.resample_figure_of_merit -def _ceiling_fitness(log_likelihood, **kwargs): +def _ceiling_fitness(log_likelihood, ceiling=None, **kwargs): """ A `Fitness` whose analysis returns `log_likelihood` for any instance. + + `ceiling` is set on the built object rather than pushed through the config, because the + packaged default is now *disabled* — every test of the enabled path has to opt in, exactly as a + user's `general.yaml` would. """ - return Fitness( + fitness = Fitness( model=af.Model(af.ex.Gaussian), analysis=ConstantAnalysis(log_likelihood=log_likelihood), **kwargs, ) + if ceiling is not None: + fitness.log_likelihood_ceiling = ceiling + + return fitness + PARAMETERS = [1.0, 1.0, 1.0] +#: The ceiling PyAutoFit used to ship enabled, and the one `autolens_profiling` opts into. Every +#: enabled-path test below sets it explicitly. +CEILING = 1.0e20 + + +@pytest.fixture(autouse=True) +def _reset_ceiling_warning(monkeypatch): + """ + The first-fire warning is a module-level latch, so a test that fires the guard would otherwise + silence every test that runs after it. `monkeypatch` restores the flag on teardown. + """ + monkeypatch.setattr(fitness_module, "_log_likelihood_ceiling_warning_emitted", False) + -def test_fitness_ceiling_defaults_to_the_configured_value(): +def test_fitness_ceiling_defaults_to_disabled(): """ - The ceiling is read once, in `__init__`, and is a static Python float — `Fitness.call` compares - it against a traced value under `jax.jit` / `jax.vmap`, which a config lookup per call could - not do. + The packaged `general.yaml` ships the ceiling blank, so the guard is **off** unless a config + opts in. The threshold is a bare magnitude, and a log likelihood scales with the noise-map + units (`chi_squared` as `noise ** -2`, `noise_normalization` linearly in the pixel count), so a + fixed value can reject a legitimate fit on a badly-scaled dataset. + + It is still read once, in `__init__`, and is still a static Python float — `Fitness.call` + compares it against a traced value under `jax.jit` / `jax.vmap`, which a config lookup per call + could not do. """ fitness = _ceiling_fitness(log_likelihood=1.0) - assert fitness.log_likelihood_ceiling == 1.0e20 + assert fitness.log_likelihood_ceiling == float("inf") assert type(fitness.log_likelihood_ceiling) is float +def test_fitness_with_the_default_ceiling_passes_an_enormous_finite_value(): + """ + The consequence of the default being off: a `1e266` log likelihood is returned untouched. That + is the deliberate trade — the fp64-Cholesky garbage this guard was built for is let through + unless a config opts in, so that a legitimately huge likelihood is never silently rejected. + """ + fitness = _ceiling_fitness(log_likelihood=1.0e266) + + assert fitness.call(PARAMETERS) == 1.0e266 + + @pytest.mark.parametrize("log_likelihood", [1.0e266, -1.0e266, 1.0e21]) def test_fitness_rejects_log_likelihoods_above_the_ceiling(log_likelihood): """ - A finite log likelihood above the ceiling is numerical garbage — an fp64 Cholesky on a - non-positive-definite matrix returns values up to `3e+303` — and must be mapped to - `resample_figure_of_merit` rather than accepted as the search's best point. Both signs are - rejected, since the guard is on the magnitude. + With the guard enabled, a finite log likelihood above the ceiling is numerical garbage — an + fp64 Cholesky on a non-positive-definite matrix returns values up to `3e+303` — and must be + mapped to `resample_figure_of_merit` rather than accepted as the search's best point. Both + signs are rejected, since the guard is on the magnitude. """ - fitness = _ceiling_fitness(log_likelihood=log_likelihood) + fitness = _ceiling_fitness(log_likelihood=log_likelihood, ceiling=CEILING) assert fitness.call(PARAMETERS) == fitness.resample_figure_of_merit @@ -80,7 +120,7 @@ def test_fitness_passes_log_likelihoods_below_the_ceiling(log_likelihood): Anything of a plausible magnitude is returned untouched — the guard must not perturb ordinary likelihoods, including the ~3e4 values a real lens fit reaches. """ - fitness = _ceiling_fitness(log_likelihood=log_likelihood) + fitness = _ceiling_fitness(log_likelihood=log_likelihood, ceiling=CEILING) assert fitness.call(PARAMETERS) == log_likelihood @@ -90,8 +130,7 @@ def test_fitness_ceiling_disabled_passes_any_finite_value(): A `null` ceiling in the config disables the guard, which `get_log_likelihood_ceiling` expresses as `inf` — `abs(x) > inf` is never true, so the `where` becomes a no-op rather than a branch. """ - fitness = _ceiling_fitness(log_likelihood=1.0e266) - fitness.log_likelihood_ceiling = float("inf") + fitness = _ceiling_fitness(log_likelihood=1.0e266, ceiling=float("inf")) assert fitness.call(PARAMETERS) == 1.0e266 @@ -99,12 +138,13 @@ def test_fitness_ceiling_disabled_passes_any_finite_value(): def test_fitness_ceiling_leaves_the_nan_and_inf_guards_intact(): """ The magnitude guard sits after the isnan/isinf `where`s, so the sentinel those produce must - survive it rather than being re-flagged into something else. + survive it rather than being re-flagged into something else. The NaN/inf guards are + unconditional — unlike the ceiling, they are not config-gated. """ - assert _ceiling_fitness(log_likelihood=np.nan).call( + assert _ceiling_fitness(log_likelihood=np.nan, ceiling=CEILING).call( PARAMETERS ) == _ceiling_fitness(log_likelihood=1.0).resample_figure_of_merit - assert _ceiling_fitness(log_likelihood=np.inf).call( + assert _ceiling_fitness(log_likelihood=np.inf, ceiling=CEILING).call( PARAMETERS ) == _ceiling_fitness(log_likelihood=1.0).resample_figure_of_merit @@ -115,11 +155,58 @@ def test_fitness_ceiling_is_idempotent_against_a_finite_resample_sentinel(): as `resample_figure_of_merit`. Its own magnitude is above the ceiling, so the guard must map it to itself rather than oscillating. """ - fitness = _ceiling_fitness(log_likelihood=1.0e266, resample_figure_of_merit=-1.0e99) + fitness = _ceiling_fitness( + log_likelihood=1.0e266, ceiling=CEILING, resample_figure_of_merit=-1.0e99 + ) assert fitness.call(PARAMETERS) == -1.0e99 +def test_fitness_warns_the_first_time_the_ceiling_fires(caplog): + """ + A rejection is invisible from inside the search — it looks exactly like a bad model — so the + numpy path says so once. The message names the value, the ceiling, and the units caveat, since + only the user can tell garbage from a legitimately enormous likelihood. + """ + fitness = _ceiling_fitness(log_likelihood=1.0e266, ceiling=CEILING) + + with caplog.at_level(logging.WARNING, logger=fitness_module.__name__): + fitness.call(PARAMETERS) + + assert len(caplog.records) == 1 + assert "1e+266" in caplog.text + assert "noise-map units" in caplog.text + + +def test_fitness_warns_only_once_per_process(caplog): + """ + A nested sampler can reject millions of samples in a run; one warning is information, one per + sample is a wall of text that hides everything else. The latch is module-level, so a fitness + object rebuilt on resume does not re-warn either. + """ + fitness = _ceiling_fitness(log_likelihood=1.0e266, ceiling=CEILING) + + with caplog.at_level(logging.WARNING, logger=fitness_module.__name__): + fitness.call(PARAMETERS) + fitness.call(PARAMETERS) + _ceiling_fitness(log_likelihood=1.0e266, ceiling=CEILING).call(PARAMETERS) + + assert len(caplog.records) == 1 + + +def test_fitness_does_not_warn_when_nothing_is_rejected(caplog): + """ + The warning is tied to an actual rejection, not to the guard being configured — an enabled + ceiling that never fires must stay silent. + """ + fitness = _ceiling_fitness(log_likelihood=30701.3, ceiling=CEILING) + + with caplog.at_level(logging.WARNING, logger=fitness_module.__name__): + fitness.call(PARAMETERS) + + assert caplog.records == [] + + class _StubConf: """ Stands in for `autonerves.conf`, so the config-reading half of the guard can be tested without @@ -154,12 +241,15 @@ def test_get_log_likelihood_ceiling_reads_the_config(monkeypatch, value, expecte assert fitness_module.get_log_likelihood_ceiling() == expected -def test_get_log_likelihood_ceiling_falls_back_when_the_key_is_absent(monkeypatch): +def test_get_log_likelihood_ceiling_is_disabled_when_the_key_is_absent(monkeypatch): """ - A workspace whose `general.yaml` pre-dates the key must still get the guard, not lose it. + A workspace whose `general.yaml` pre-dates the key must inherit **today's** default, which is + disabled — not the `1e20` that shipped with the guard's first release. A missing key is silence + about the guard, and silence means off. """ monkeypatch.setattr(fitness_module, "conf", _StubConf(present=False)) + assert fitness_module.LOG_LIKELIHOOD_CEILING_DEFAULT == float("inf") assert ( fitness_module.get_log_likelihood_ceiling() == fitness_module.LOG_LIKELIHOOD_CEILING_DEFAULT diff --git a/test_autofit/non_linear/test_fitness_ceiling_jax.py b/test_autofit/non_linear/test_fitness_ceiling_jax.py index e789fcb3e..4f06d7dd1 100644 --- a/test_autofit/non_linear/test_fitness_ceiling_jax.py +++ b/test_autofit/non_linear/test_fitness_ceiling_jax.py @@ -5,15 +5,23 @@ is a static Python float. A traced ceiling, or a Python `if` on the traced likelihood, would raise at trace time rather than silently degrade, and these tests are what would catch that. +The ceiling is **off** in the packaged config, so every enabled-path test here sets it explicitly, +the way a user's `general.yaml` would. The last test pins the other half of the contract: the +first-fire warning is numpy-only, so a jitted run that rejects a sample must trace and reject +without attempting a Python `logger` call on a tracer. + 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 of the guard is covered in `test_fitness_assertions.py`). """ +import logging + 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 from test_autofit.non_linear.constant_analysis import ConstantAnalysis @@ -31,12 +39,18 @@ PARAMETERS = [1.0, 1.0, 1.0] -def _jax_fitness(log_likelihood, **kwargs): - return Fitness( +#: The ceiling `autolens_profiling` opts into. Set explicitly here — PyAutoFit ships the guard off. +CEILING = 1.0e20 + + +def _jax_fitness(log_likelihood, ceiling=CEILING, **kwargs): + fitness = Fitness( model=af.Model(af.ex.Gaussian), analysis=ConstantAnalysis(log_likelihood=log_likelihood, use_jax=True), **kwargs, ) + fitness.log_likelihood_ceiling = ceiling + return fitness def test_jit_path_rejects_a_log_likelihood_above_the_ceiling(): @@ -81,12 +95,33 @@ def test_vmap_path_passes_a_log_likelihood_below_the_ceiling(): def test_disabled_ceiling_traces_and_passes_any_finite_value(): """ - With the guard disabled the `where` must still trace (it is not compiled away by a Python - branch), and must return the value untouched. + With the guard disabled — the shipped default — the `where` must still trace (it is not + compiled away by a Python branch), and must return the value untouched. """ - fitness = _jax_fitness(log_likelihood=OVER_CEILING, use_jax_jit=True) - fitness.log_likelihood_ceiling = float("inf") + fitness = _jax_fitness( + log_likelihood=OVER_CEILING, ceiling=float("inf"), use_jax_jit=True + ) figure_of_merit = float(fitness._call(jnp.array(PARAMETERS))) assert figure_of_merit == pytest.approx(OVER_CEILING, rel=1.0e-5) + + +def test_jit_path_rejects_without_warning(monkeypatch, caplog): + """ + The first-fire warning is numpy-only by construction: under `jax.jit` the rejection mask is a + tracer, so a Python `if` on it would raise `TracerBoolConversionError` rather than warn. The + jitted path must therefore reject *silently*, and the module-level latch must be untouched so a + later numpy run can still warn. + """ + monkeypatch.setattr( + fitness_module, "_log_likelihood_ceiling_warning_emitted", False + ) + + fitness = _jax_fitness(log_likelihood=OVER_CEILING, use_jax_jit=True) + + with caplog.at_level(logging.WARNING, logger=fitness_module.__name__): + assert float(fitness._call(jnp.array(PARAMETERS))) == fitness.resample_figure_of_merit + + assert caplog.records == [] + assert fitness_module._log_likelihood_ceiling_warning_emitted is False