diff --git a/autofit/config/general.yaml b/autofit/config/general.yaml index 156a07fb8..0ba95f8a4 100644 --- a/autofit/config/general.yaml +++ b/autofit/config/general.yaml @@ -31,4 +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. parallel_profile: false diff --git a/autofit/non_linear/fitness.py b/autofit/non_linear/fitness.py index 878b83d1f..d1e3ab902 100644 --- a/autofit/non_linear/fitness.py +++ b/autofit/non_linear/fitness.py @@ -31,6 +31,65 @@ def get_timeout_seconds(): logger = logging.getLogger(__name__) 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 + + +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 + ``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``. + + A bare ``1e20`` in YAML parses as a *string*, not a float (PyYAML requires a decimal point or a + signed exponent), so the value is coerced with ``float`` rather than trusted as read. + + 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. + """ + try: + ceiling = conf.instance["general"]["test"]["log_likelihood_ceiling"] + except KeyError: + return LOG_LIKELIHOOD_CEILING_DEFAULT + + if ceiling is None: + return float("inf") + + try: + ceiling = float(ceiling) + except (TypeError, ValueError): + logger.warning( + f"general.test.log_likelihood_ceiling = {ceiling!r} could not be read as a float. " + "The log likelihood magnitude guard is disabled for this run." + ) + return float("inf") + + if not ceiling > 0.0: + logger.warning( + f"general.test.log_likelihood_ceiling = {ceiling} is not positive, so every log " + "likelihood would be rejected. The log likelihood magnitude guard is disabled for " + "this run." + ) + return float("inf") + + return ceiling + + class Fitness: def __init__( self, @@ -113,6 +172,11 @@ def __init__( self.fom_is_log_likelihood = fom_is_log_likelihood self.resample_figure_of_merit = resample_figure_of_merit or -self._xp.inf + + # Static Python float, read once here rather than per-call: `call` compares it against a + # 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.convert_to_chi_squared = convert_to_chi_squared self.store_history = store_history @@ -207,10 +271,15 @@ 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. - The NaN/inf guard below protects the **value only, never the gradient**. + The NaN/inf/magnitude guards below protect the **value only, never the gradient**. - A model whose likelihood is NaN or inf is mapped to `resample_figure_of_merit`, so searches that read only - the figure of merit (nested samplers, MCMC) get the resample sentinel and never select the point. Gradient + A model whose likelihood is NaN, inf, or larger in magnitude than `self.log_likelihood_ceiling` is mapped + to `resample_figure_of_merit`, so searches that read only the figure of merit (nested samplers, MCMC) get + 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 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. @@ -262,6 +331,16 @@ def call(self, parameters): log_likelihood = self._xp.where(self._xp.isnan(log_likelihood), self.resample_figure_of_merit, log_likelihood) log_likelihood = self._xp.where(self._xp.isinf(log_likelihood), self.resample_figure_of_merit, log_likelihood) + # 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 + # resample sentinels (-inf, -1e99, -1e30) map to themselves. + log_likelihood = self._xp.where( + self._xp.abs(log_likelihood) > self.log_likelihood_ceiling, + self.resample_figure_of_merit, + log_likelihood, + ) + # Determine final figure of merit if self.fom_is_log_likelihood: figure_of_merit = log_likelihood @@ -532,6 +611,9 @@ def __getstate__(self): def __setstate__(self, state): self.__dict__.update(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()) self._call = self.call if getattr(self, "use_jax_vmap", False): self._call = self._vmap diff --git a/autofit/non_linear/search/nest/nss/search.py b/autofit/non_linear/search/nest/nss/search.py index 505d03194..8e39aa069 100644 --- a/autofit/non_linear/search/nest/nss/search.py +++ b/autofit/non_linear/search/nest/nss/search.py @@ -9,7 +9,7 @@ import numpy as np from autofit.mapper.prior_model.abstract import AbstractPriorModel -from autofit.non_linear.fitness import Fitness +from autofit.non_linear.fitness import Fitness, get_log_likelihood_ceiling from autofit.non_linear.paths.null import NullPaths from autofit.non_linear.search.nest import abstract_nest from .samples import NSSamples @@ -39,6 +39,61 @@ logger = logging.getLogger(__name__) +#: The figure of merit ``af.NSS`` substitutes for a log likelihood it refuses to sample from. Not +#: ``-inf``: blackjax's nested sampler arithmetic (log weights, shell evidence) has to stay finite, +#: so an unreachably low finite value is used instead. +NSS_INVALID_LOG_LIKELIHOOD = -1e30 + + +def nss_log_likelihood_from(model, analysis, log_likelihood_ceiling=None): + """ + Build the JAX log-likelihood closure ``af.NSS`` samples through. + + ``af.NSS`` does not call `Fitness.call` while sampling -- it hands blackjax an inline JAX + closure -- so it does not inherit that method's guards and has to repeat them here. Keeping the + closure in one module-level factory means the guards exist once and can be tested directly, + rather than being restated by a test that only resembles the sampled path. + + 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. + + Parameters + ---------- + model + The model whose parameter vector is mapped to an instance. + analysis + 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. + + Returns + ------- + The closure blackjax samples through. + """ + import jax.numpy as jnp + + if log_likelihood_ceiling is None: + log_likelihood_ceiling = get_log_likelihood_ceiling() + + def log_likelihood(params): + instance = model.instance_from_vector(vector=params, xp=jnp) + raw = analysis.log_likelihood_function(instance=instance) + raw = jnp.where(jnp.isfinite(raw), raw, NSS_INVALID_LOG_LIKELIHOOD) + return jnp.where( + jnp.abs(raw) > log_likelihood_ceiling, + NSS_INVALID_LOG_LIKELIHOOD, + raw, + ) + + return log_likelihood + _CHECKPOINT_FILENAME = "nss_checkpoint.pkl" @@ -341,10 +396,7 @@ def _fit(self, model: AbstractPriorModel, analysis): ndim = model.prior_count - def log_likelihood(params): - instance = model.instance_from_vector(vector=params, xp=jnp) - raw = analysis.log_likelihood_function(instance=instance) - return jnp.where(jnp.isfinite(raw), raw, -1e30) + log_likelihood = nss_log_likelihood_from(model=model, analysis=analysis) def prior_logprob(params): log_priors = model.log_prior_list_from_vector(vector=params, xp=jnp) diff --git a/test_autofit/config/general.yaml b/test_autofit/config/general.yaml index ba764c8a9..2d77aa866 100644 --- a/test_autofit/config/general.yaml +++ b/test_autofit/config/general.yaml @@ -28,4 +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. parallel_profile: false diff --git a/test_autofit/non_linear/constant_analysis.py b/test_autofit/non_linear/constant_analysis.py new file mode 100644 index 000000000..97d52f91c --- /dev/null +++ b/test_autofit/non_linear/constant_analysis.py @@ -0,0 +1,18 @@ +import autofit as af + + +class ConstantAnalysis(af.Analysis): + """ + An `Analysis` whose log likelihood is a fixed number, independent of the instance. + + The magnitude guard in `Fitness.call` is a pure function of the log likelihood, so a real fit + would only add noise to the tests: what is under test is which values survive the guard, and + this makes that value the input. + """ + + def __init__(self, log_likelihood, use_jax: bool = False): + super().__init__(use_jax=use_jax) + self.log_likelihood = log_likelihood + + def log_likelihood_function(self, instance): + return self.log_likelihood 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 new file mode 100644 index 000000000..bae0a371c --- /dev/null +++ b/test_autofit/non_linear/search/nest/nss/test_log_likelihood_ceiling.py @@ -0,0 +1,99 @@ +""" +The log-likelihood guards on the closure ``af.NSS`` samples through. + +``af.NSS`` does not route sampling through `Fitness.call` — it hands blackjax an inline JAX +closure — so the guards there are a second implementation and need their own test. The closure is +built by `nss_log_likelihood_from`, and these tests call that factory rather than restating its +body, so a change to the sampled path cannot pass a test that only resembles it. + +The factory is JAX-only, so the file skips whole when JAX is absent (library policy: unit tests are +the numpy always-green layer). +""" + +import numpy as np +import pytest + +import autofit as af +from autofit.non_linear.search.nest.nss.search import ( + NSS_INVALID_LOG_LIKELIHOOD, + nss_log_likelihood_from, +) +from test_autofit.non_linear.constant_analysis import ConstantAnalysis + +jnp = pytest.importorskip("jax.numpy") + + +PARAMETERS = [1.0, 1.0, 1.0] + +#: 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 + +UNDER_CEILING = 1.0e19 + + +def _log_likelihood_from(log_likelihood, **kwargs): + return nss_log_likelihood_from( + model=af.Model(af.ex.Gaussian), + analysis=ConstantAnalysis(log_likelihood=log_likelihood), + **kwargs, + ) + + +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) + + 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) + + assert float(log_likelihood(jnp.array(PARAMETERS))) == pytest.approx( + UNDER_CEILING, rel=1.0e-5 + ) + + +@pytest.mark.parametrize("log_likelihood", [np.nan, np.inf, -np.inf]) +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) + + assert float(closure(jnp.array(PARAMETERS))) == NSS_INVALID_LOG_LIKELIHOOD + + +def test_nss_closure_sentinel_maps_to_itself(): + """ + `NSS_INVALID_LOG_LIKELIHOOD` is itself above the ceiling in magnitude, so the guard has to be + idempotent against the value it substitutes. + """ + closure = _log_likelihood_from( + NSS_INVALID_LOG_LIKELIHOOD, log_likelihood_ceiling=1.0e20 + ) + + assert float(closure(jnp.array(PARAMETERS))) == NSS_INVALID_LOG_LIKELIHOOD + + +def test_nss_closure_with_the_ceiling_disabled_passes_any_finite_value(): + closure = _log_likelihood_from(OVER_CEILING, log_likelihood_ceiling=float("inf")) + + assert float(closure(jnp.array(PARAMETERS))) == pytest.approx( + OVER_CEILING, rel=1.0e-5 + ) + + +def test_nss_closure_defaults_to_the_configured_ceiling(): + """ + With no explicit ceiling the closure reads the config, so `af.NSS` picks the guard up without + the search having to thread it. + """ + closure = _log_likelihood_from(OVER_CEILING) + + 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 fb9f4f901..2af34df64 100644 --- a/test_autofit/non_linear/test_fitness_assertions.py +++ b/test_autofit/non_linear/test_fitness_assertions.py @@ -1,7 +1,10 @@ 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 def test_fitness_returns_resample_fom_on_assertion_failure(): @@ -30,3 +33,134 @@ def test_fitness_returns_resample_fom_on_assertion_failure(): # centre_0 = 20 > centre_1 = 10 → assertion satisfied, real FOM returned satisfying = [20.0, 1.0, 1.0, 10.0, 1.0, 1.0] assert fitness.call(satisfying) != fitness.resample_figure_of_merit + + +def _ceiling_fitness(log_likelihood, **kwargs): + """ + A `Fitness` whose analysis returns `log_likelihood` for any instance. + """ + return Fitness( + model=af.Model(af.ex.Gaussian), + analysis=ConstantAnalysis(log_likelihood=log_likelihood), + **kwargs, + ) + + +PARAMETERS = [1.0, 1.0, 1.0] + + +def test_fitness_ceiling_defaults_to_the_configured_value(): + """ + 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. + """ + fitness = _ceiling_fitness(log_likelihood=1.0) + + assert fitness.log_likelihood_ceiling == 1.0e20 + assert type(fitness.log_likelihood_ceiling) is float + + +@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. + """ + fitness = _ceiling_fitness(log_likelihood=log_likelihood) + + assert fitness.call(PARAMETERS) == fitness.resample_figure_of_merit + + +@pytest.mark.parametrize("log_likelihood", [1.0e19, -1.0e19, 30701.3, 0.0]) +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) + + assert fitness.call(PARAMETERS) == log_likelihood + + +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") + + assert fitness.call(PARAMETERS) == 1.0e266 + + +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. + """ + assert _ceiling_fitness(log_likelihood=np.nan).call( + PARAMETERS + ) == _ceiling_fitness(log_likelihood=1.0).resample_figure_of_merit + assert _ceiling_fitness(log_likelihood=np.inf).call( + PARAMETERS + ) == _ceiling_fitness(log_likelihood=1.0).resample_figure_of_merit + + +def test_fitness_ceiling_is_idempotent_against_a_finite_resample_sentinel(): + """ + Searches that cannot use `-inf` pass a large negative sentinel (dynesty/nautilus use `-1e99`) + 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) + + assert fitness.call(PARAMETERS) == -1.0e99 + + +class _StubConf: + """ + Stands in for `autonerves.conf`, so the config-reading half of the guard can be tested without + pushing a config directory. + """ + + def __init__(self, value=None, present=True): + test = {"log_likelihood_ceiling": value} if present else {} + self.instance = {"general": {"test": test}} + + +@pytest.mark.parametrize( + "value, expected", + [ + # PyYAML parses a bare `1e20` as a *string* (it requires a decimal point or a signed + # exponent to resolve a float), so the reader must coerce rather than trust. + ("1e20", 1.0e20), + (1.0e20, 1.0e20), + (30701.0, 30701.0), + # Disabled, in each of the ways a config can express it. + (None, float("inf")), + (float("inf"), float("inf")), + ("not-a-number", float("inf")), + # A non-positive ceiling would reject every model; disable rather than wedge the fit. + (0.0, float("inf")), + (-1.0, float("inf")), + ], +) +def test_get_log_likelihood_ceiling_reads_the_config(monkeypatch, value, expected): + monkeypatch.setattr(fitness_module, "conf", _StubConf(value=value)) + + assert fitness_module.get_log_likelihood_ceiling() == expected + + +def test_get_log_likelihood_ceiling_falls_back_when_the_key_is_absent(monkeypatch): + """ + A workspace whose `general.yaml` pre-dates the key must still get the guard, not lose it. + """ + monkeypatch.setattr(fitness_module, "conf", _StubConf(present=False)) + + 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 new file mode 100644 index 000000000..e789fcb3e --- /dev/null +++ b/test_autofit/non_linear/test_fitness_ceiling_jax.py @@ -0,0 +1,92 @@ +""" +The log-likelihood magnitude guard on the JAX paths. + +The guard lives inside `Fitness.call`, so `_jit` and `_vmap` inherit it — but only if the ceiling +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. + +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 numpy as np +import pytest + +import autofit as af +from autofit.non_linear.fitness import Fitness +from test_autofit.non_linear.constant_analysis import ConstantAnalysis + +jax = pytest.importorskip("jax") +jnp = pytest.importorskip("jax.numpy") + + +#: Above the 1e20 ceiling but comfortably inside float32 range, so the test cannot pass for the +#: wrong reason (a value that overflows to `inf` would be caught by the isinf guard instead). +OVER_CEILING = 1.0e30 + +#: Below the ceiling, and representable in float32. +UNDER_CEILING = 1.0e19 + +PARAMETERS = [1.0, 1.0, 1.0] + + +def _jax_fitness(log_likelihood, **kwargs): + return Fitness( + model=af.Model(af.ex.Gaussian), + analysis=ConstantAnalysis(log_likelihood=log_likelihood, use_jax=True), + **kwargs, + ) + + +def test_jit_path_rejects_a_log_likelihood_above_the_ceiling(): + fitness = _jax_fitness(log_likelihood=OVER_CEILING, use_jax_jit=True) + + assert fitness._call is fitness._jit + assert float(fitness._call(jnp.array(PARAMETERS))) == fitness.resample_figure_of_merit + + +def test_jit_path_passes_a_log_likelihood_below_the_ceiling(): + fitness = _jax_fitness(log_likelihood=UNDER_CEILING, use_jax_jit=True) + + figure_of_merit = float(fitness._call(jnp.array(PARAMETERS))) + + assert np.isfinite(figure_of_merit) + assert figure_of_merit == pytest.approx(UNDER_CEILING, rel=1.0e-5) + + +def test_vmap_path_rejects_a_log_likelihood_above_the_ceiling(): + """ + `vmap` is the stricter check: every parameter is a tracer, so a ceiling that was not a static + Python float would fail here even where jit-on-concrete passed. + """ + fitness = _jax_fitness(log_likelihood=OVER_CEILING, use_jax_vmap=True) + + assert fitness._call is fitness._vmap + + figures_of_merit = np.asarray(fitness._call(jnp.array([PARAMETERS, PARAMETERS]))) + + assert figures_of_merit.shape == (2,) + assert np.all(figures_of_merit == fitness.resample_figure_of_merit) + + +def test_vmap_path_passes_a_log_likelihood_below_the_ceiling(): + fitness = _jax_fitness(log_likelihood=UNDER_CEILING, use_jax_vmap=True) + + figures_of_merit = np.asarray(fitness._call(jnp.array([PARAMETERS, PARAMETERS]))) + + assert np.all(np.isfinite(figures_of_merit)) + assert figures_of_merit == pytest.approx(UNDER_CEILING, rel=1.0e-5) + + +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. + """ + fitness = _jax_fitness(log_likelihood=OVER_CEILING, use_jax_jit=True) + fitness.log_likelihood_ceiling = float("inf") + + figure_of_merit = float(fitness._call(jnp.array(PARAMETERS))) + + assert figure_of_merit == pytest.approx(OVER_CEILING, rel=1.0e-5)