Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions autofit/config/general.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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
88 changes: 85 additions & 3 deletions autofit/non_linear/fitness.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
62 changes: 57 additions & 5 deletions autofit/non_linear/search/nest/nss/search.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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"

Expand Down Expand Up @@ -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)
Expand Down
1 change: 1 addition & 0 deletions test_autofit/config/general.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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
18 changes: 18 additions & 0 deletions test_autofit/non_linear/constant_analysis.py
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
@@ -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
Loading
Loading