From bf8c302aab8298629f96cbb45f00f6b058da0477 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 16 Aug 2026 00:36:17 +0000 Subject: [PATCH 1/3] Add a search-agnostic Clipper enforcing prior support (#1476) The gradient searches step in physical parameter space against an objective that folds in the prior (`fom = -2 * (log_likelihood + sum(log_prior_list))`), with nothing constraining a step to the prior box. A `UniformPrior` is `-inf` outside its limits, so a lane that oversteps a hard prior edge reads as non-finite and is marked dead. It is worse than frozen: `log_prior = -inf` is *constant* outside the box, so its derivative is zero and the total gradient is the finite likelihood gradient. `optax.apply_if_finite` never fires, and the dead lane keeps stepping for the rest of the run at full cost with its output discarded. On the reference `imaging/mge` cell this was 60.25% of lane-steps and 14 of 16 lane deaths, while the likelihood never went non-finite once (autolens_profiling#128). Adds `AbstractClipper` / `ClipperNone` / `ClipperPriorBox` in a new `autofit/non_linear/clipper.py`, modelled on `initializer.py`, and wires them opt-in into `AbstractMultiStartGradient` (imperative `project` after `optax.apply_updates`) and `AbstractBFGS` (declarative bounds handed to scipy). `project` returns the clipped mask as well as the vector, so a caller can zero optimiser momentum along clipped directions -- projecting parameters while the accumulated state keeps pushing outward is what leaves lanes pinned. The default is `ClipperNone` and this change is bit-identical with it, verified by running both searches with and without the argument. Flipping the default moves where a search converges and would shift every stored multi-start benchmark, so it is deliberately left to a separate, re-baselined change. Three things the implementation is shaped around, each measured rather than assumed, and each a silent failure if got wrong: - The inset is keyed on **bound kind**, never on unguarded `upper - lower`. The obvious `lower + margin * (upper - lower)` is `-inf + inf` = NaN for a `GaussianPrior`, and clipping against NaN bounds turns the coordinate into NaN and the objective with it -- killing lanes on exactly the models this rescues, with a symptom indistinguishable from the bug being fixed. - `bounds_from_model` returns two arrays, which is the shape `project` broadcasts against, but *not* what scipy accepts: `minimize` reads a `(lower, upper)` tuple as a sequence of `(min, max)` pairs, silently mis-fitting two-parameter models and raising at any other dimensionality. The BFGS wiring builds an explicit `optimize.Bounds`. - `LogGaussianPrior` reports `(-inf, inf)` because its `TransformedMessage` is never given limits, yet its `log_prior_from_value` is `-inf` for `value <= 0`. Its real `(0, inf)` support is declared in the clipper, with an *absolute* epsilon: a relative margin is identically zero for a half-open bound and would clip onto exactly `0.0`. Also corrects the `AbstractMultiStartGradient` class docstring, which claimed the rule steps "on the unconstrained (unit-cube) parameterization" -- it does not; `_broad_starts` maps draws to physical parameters, and that sentence is what would tell the next reader this class of bug cannot occur. End-to-end on a Gaussian fit whose truth sits outside the prior box: lane deaths go 249 -> 0, with 252 clips, and the clipped run pins `centre` at the upper bound, which is the correct MAP answer under a prior excluding the truth. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01Kt89ELdo9fb8gEoU1bP2yH --- autofit/__init__.py | 3 + autofit/non_linear/clipper.py | 276 ++++++++++++++ autofit/non_linear/search/mle/abstract_mle.py | 10 +- autofit/non_linear/search/mle/bfgs/search.py | 72 +++- .../search/mle/multi_start_gradient/search.py | 53 ++- test_autofit/non_linear/test_clipper.py | 341 ++++++++++++++++++ 6 files changed, 751 insertions(+), 4 deletions(-) create mode 100644 autofit/non_linear/clipper.py create mode 100644 test_autofit/non_linear/test_clipper.py diff --git a/autofit/__init__.py b/autofit/__init__.py index 1d4b0b96c..557ae50ab 100644 --- a/autofit/__init__.py +++ b/autofit/__init__.py @@ -80,6 +80,9 @@ from .non_linear.analysis.analysis import Analysis from .non_linear.grid.grid_search import GridSearchResult from .non_linear.grid.sensitivity import Sensitivity +from .non_linear.clipper import AbstractClipper +from .non_linear.clipper import ClipperNone +from .non_linear.clipper import ClipperPriorBox from .non_linear.initializer import InitializerBall from .non_linear.initializer import InitializerPrior from .non_linear.initializer import InitializerParamBounds diff --git a/autofit/non_linear/clipper.py b/autofit/non_linear/clipper.py new file mode 100644 index 000000000..ddadca834 --- /dev/null +++ b/autofit/non_linear/clipper.py @@ -0,0 +1,276 @@ +""" +Search-local enforcement of prior support. + +The gradient searches step in **physical** parameter space against an objective +that folds in the prior:: + + fom = -2 * (log_likelihood + sum(log_prior_list)) + +A hard-edged prior (``UniformPrior``, ``TruncatedGaussianPrior``, ...) is +``-inf`` outside its box, so a step that leaves that box makes the objective +non-finite. Nothing in the step itself pulls the parameter back: because +``log_prior = -inf`` is *constant* outside the box its derivative is zero, so the +total gradient is the finite **likelihood** gradient and ``optax.apply_if_finite`` +never fires. The lane is marked dead but keeps stepping for the rest of the run, +paying full likelihood-and-gradient cost with its output discarded. On the +reference ``imaging/mge`` cell this accounted for 60.25% of lane-steps and 14 of +16 lane deaths, while the likelihood itself never went non-finite once (see +autolens_profiling#128). + +The samplers that are *not* exposed are instructive: the nested samplers already +work in unit-cube coordinates, and the MCMC samplers reject ``-inf`` proposals so +the walker simply stays put. **Rejection is the restoring mechanism the gradient +methods lack**, and a ``Clipper`` supplies it. + +Two consumers, one source of truth +---------------------------------- + +Unlike :mod:`autofit.non_linear.initializer`, which this module is otherwise +modelled on, a ``Clipper`` has two structurally different consumers: + +- ``MultiStartGradient`` enforces the constraint itself after every update, so it + wants an imperative :meth:`AbstractClipper.project`; +- ``LBFGS`` hands box bounds to scipy and lets *scipy* enforce them, so it wants a + declarative :meth:`AbstractClipper.bounds_from_model`. + +Both read one private ``_limits_from_model`` so the declarative and imperative +views can never drift apart. + +``project`` returns **which coordinates it clipped**, not just the new vector. +That mask is what lets a caller zero optimiser momentum along clipped directions: +projecting the parameters while the accumulated optimiser state keeps pushing +outward leaves lanes pinned to a bound. The ``Clipper`` cannot fix that itself +(it does not own ``opt_state``), so it exposes enough for the search to. + +A soft-wall strategy would belong here too, as a ``Clipper`` — **never** as a +change to the ``Prior`` classes, which would silently alter the objective for the +nested samplers, where the hard box currently works correctly. + +Bound kinds +----------- + +The inset applied to keep a projected value strictly inside its support is keyed +on **what kind of bound it is**, never on unguarded ``upper - lower`` arithmetic. +That distinction is load-bearing rather than fussy — see +:class:`ClipperPriorBox` for the three cases and why collapsing them breaks. +""" + +import logging +from abc import ABC, abstractmethod +from typing import Tuple + +import numpy as np + +from autofit.mapper.prior.log_gaussian import LogGaussianPrior + +logger = logging.getLogger(__name__) + + +class AbstractClipper(ABC): + """ + A strategy for keeping a search's parameter vector inside the support of the + model's priors. + + Subclasses are pluggable per-search, exactly like + :class:`~autofit.non_linear.initializer.AbstractInitializer`, and the default + is :class:`ClipperNone` so that behaviour is unchanged until a user opts in. + """ + + @abstractmethod + def bounds_from_model(self, model) -> Tuple[np.ndarray, np.ndarray]: + """ + The ``(lower, upper)`` box, in **physical** parameter order. + + Unbounded coordinates are ``-inf`` / ``+inf``. The two arrays are returned + separately because that is the shape :meth:`project` broadcasts against. + + Note that this is **not** the shape ``scipy.optimize.minimize`` accepts: + it reads a ``(lower, upper)`` tuple as a *sequence of ``(min, max)`` + pairs*, which for a two-parameter model silently produces a wrong fit + rather than an error. Callers handing these to scipy must build an + explicit ``scipy.optimize.Bounds`` — see + :meth:`~autofit.non_linear.search.mle.bfgs.search.AbstractBFGS._bounds_from`. + + Parameters + ---------- + model + The model whose priors define the support. + """ + + @abstractmethod + def project(self, vector, model, xp=np): + """ + Project ``vector`` onto the prior support. + + Parameters + ---------- + vector + A physical parameter vector, either a single ``(n_params,)`` vector or + a batched ``(n_starts, n_params)`` array of them. Broadcasting handles + both, so no ``vmap`` is required of the caller. + model + The model whose priors define the support. + xp + The array module, ``numpy`` or ``jax.numpy``. + + Returns + ------- + A ``(projected, clipped_mask)`` pair. ``clipped_mask`` is boolean, the same + shape as ``vector``, and ``True`` exactly where a coordinate was moved. + """ + + +class ClipperNone(AbstractClipper): + """ + The no-op clipper, and **the default**. + + Bounds are ``±inf`` and ``project`` is the identity, so a search configured + with this is bit-identical to one with no clipper concept at all. Searches + should test for it and skip the projection entirely rather than applying it as + a no-op, so that the compiled step is unchanged too. + """ + + def bounds_from_model(self, model) -> Tuple[np.ndarray, np.ndarray]: + n = model.prior_count + return np.full(n, -np.inf), np.full(n, np.inf) + + def project(self, vector, model, xp=np): + return vector, xp.zeros_like(vector, dtype=bool) + + +class ClipperPriorBox(AbstractClipper): + """ + Hard projection onto the prior support, inset to stay strictly inside it. + + The inset is keyed on the **kind** of each bound. Collapsing these three cases + into one relative ``margin * (upper - lower)`` is the obvious implementation + and it is wrong in two separate ways, both silent: + + - **Two-sided finite** (``UniformPrior``, ``LogUniformPrior``, + ``TruncatedGaussianPrior``) — inset by ``margin`` *relative* to the box + width. This is deliberately **not** for prior support: those priors are + *inclusive* at the limit (``log_prior`` is finite exactly on the bound), so + clipping onto the bound would already be valid. It is to avoid parking a + lane exactly **on** a prior edge, where the model's own transforms are prone + to singularities (``arctan2`` / ``sqrt`` at exactly 0) — the same reason + ``MultiStartGradient`` draws its broad starts from the interior + ``(0.15, 0.85)`` of the unit cube rather than from ``(0, 1)``. + + - **Unbounded** (``GaussianPrior``) — no inset, and critically **no width + arithmetic at all**. ``lower + margin * (upper - lower)`` evaluates + ``-inf + inf``, which is ``NaN``; clipping against ``NaN`` bounds turns the + coordinate into ``NaN`` and the whole objective with it. That failure looks + exactly like the lane death this class exists to prevent, so the guarantee + that an unbounded coordinate passes through untouched holds only if the + width is never computed for it. + + - **Half-open and exclusive** (``LogGaussianPrior``, whose support is + ``(0, inf)``) — inset by an *absolute* ``strict_epsilon``. A relative margin + is identically zero here, there being no finite width, so it would clip + exactly onto ``0.0``, where the support is strict and ``log_prior`` is + ``-inf``. Only an absolute nudge lands strictly inside. + + Parameters + ---------- + margin + The relative inset applied to two-sided finite bounds, as a fraction of + the box width. + strict_epsilon + The absolute inset applied to half-open bounds whose support excludes the + limit itself. Deliberately small: the floor it produces is a very + low-density point, but it is *finite*, and the resulting steep prior + gradient is what pushes the lane back into the bulk rather than leaving it + dead. + """ + + def __init__(self, margin: float = 1.0e-6, strict_epsilon: float = 1.0e-12): + self.margin = float(margin) + self.strict_epsilon = float(strict_epsilon) + + def _limits_from_model(self, model): + """ + The raw ``(lower, upper, lower_strict, upper_strict)`` arrays for ``model``, + in physical parameter order. + + Limits are read off ``prior.lower_limit`` / ``prior.upper_limit``, which + resolves for **every** prior type without a type switch: ``Prior.__getattr__`` + delegates to the prior's message, and ``AbstractMessage`` defaults both to + ``±inf``. ``UniformPrior`` and ``LogUniformPrior`` shadow them with their + own attributes, ``TruncatedGaussianPrior`` picks up real limits from + ``TruncatedNormalMessage``, and ``GaussianPrior`` correctly falls through + to ``±inf``. + + ``LogGaussianPrior`` is the one prior that read gets *wrong*, and silently. + Its message is a ``TransformedMessage``, which defaults its limits to + ``±inf`` and is never passed any — yet + ``LogGaussianPrior.log_prior_from_value`` returns ``-inf`` for + ``value <= 0``. Left uncorrected, the clipper would report that coordinate + as unbounded and fail to protect precisely the mechanism it exists to fix, + so its ``(0, inf)`` support is declared here. Declaring it on the prior + itself is the cleaner fix, but it would change a class the EP machinery and + the nested samplers also read, so it is deliberately kept local. + + The ``strict`` flags mark bounds the support *excludes* (``value > limit`` + rather than ``value >= limit``); only those need the absolute inset. + """ + lower, upper, lower_strict, upper_strict = [], [], [], [] + + for prior in model.priors_ordered_by_id: + low = float(prior.lower_limit) + high = float(prior.upper_limit) + low_strict = False + high_strict = False + + if isinstance(prior, LogGaussianPrior): + low = 0.0 + low_strict = True + + lower.append(low) + upper.append(high) + lower_strict.append(low_strict) + upper_strict.append(high_strict) + + return ( + np.array(lower, dtype=float), + np.array(upper, dtype=float), + np.array(lower_strict, dtype=bool), + np.array(upper_strict, dtype=bool), + ) + + def bounds_from_model(self, model) -> Tuple[np.ndarray, np.ndarray]: + lower, upper, lower_strict, upper_strict = self._limits_from_model(model) + + two_sided = np.isfinite(lower) & np.isfinite(upper) + + # The width is evaluated ONLY where both bounds are finite. `np.where` + # alone would not be enough -- it evaluates both branches, so `inf - -inf` + # would still be computed and still be NaN. The finite substitution has to + # happen before the subtraction, not after it. + safe_lower = np.where(two_sided, lower, 0.0) + safe_upper = np.where(two_sided, upper, 0.0) + relative = self.margin * (safe_upper - safe_lower) + + lower_inset = lower + np.where(two_sided, relative, 0.0) + upper_inset = upper - np.where(two_sided, relative, 0.0) + + # Half-open bounds get an absolute nudge, since `relative` is identically + # zero for them. + lower_inset = lower_inset + np.where( + lower_strict & ~two_sided, self.strict_epsilon, 0.0 + ) + upper_inset = upper_inset - np.where( + upper_strict & ~two_sided, self.strict_epsilon, 0.0 + ) + + return lower_inset, upper_inset + + def project(self, vector, model, xp=np): + lower, upper = self.bounds_from_model(model) + + dtype = getattr(vector, "dtype", None) + lower = xp.asarray(lower, dtype=dtype) + upper = xp.asarray(upper, dtype=dtype) + + projected = xp.clip(vector, lower, upper) + + return projected, projected != vector diff --git a/autofit/non_linear/search/mle/abstract_mle.py b/autofit/non_linear/search/mle/abstract_mle.py index 90956c947..3cc23c779 100644 --- a/autofit/non_linear/search/mle/abstract_mle.py +++ b/autofit/non_linear/search/mle/abstract_mle.py @@ -2,6 +2,7 @@ from autonerves import conf from autofit.non_linear.search.abstract_search import NonLinearSearch +from autofit.non_linear.clipper import ClipperNone from autofit.non_linear.initializer import InitializerBall from autofit.non_linear.plot import ( subplot_parameters, @@ -12,7 +13,14 @@ class AbstractMLE(NonLinearSearch, ABC): - def __init__(self, initializer=None, **kwargs): + def __init__(self, initializer=None, clipper=None, **kwargs): + # ``clipper`` is resolved here, at the same tier and by the same + # ``or `` pattern as ``initializer``, so every MLE search + # inherits it. The default is the no-op ``ClipperNone``: enforcing prior + # support changes where a search converges, which would shift every stored + # multi-start benchmark, so it is opt-in until that re-baseline is done. + self.clipper = clipper or ClipperNone() + super().__init__( initializer=initializer or InitializerBall(lower_limit=0.49, upper_limit=0.51), diff --git a/autofit/non_linear/search/mle/bfgs/search.py b/autofit/non_linear/search/mle/bfgs/search.py index afdfe4167..97eb8a3a8 100644 --- a/autofit/non_linear/search/mle/bfgs/search.py +++ b/autofit/non_linear/search/mle/bfgs/search.py @@ -1,11 +1,13 @@ from typing import Optional +from autofit import exc from autofit.database.sqlalchemy_ import sa from autofit.mapper.prior_model.abstract import AbstractPriorModel from autofit.non_linear.search.mle.abstract_mle import AbstractMLE from autofit.non_linear.analysis import Analysis from autofit.non_linear.fitness import Fitness +from autofit.non_linear.clipper import AbstractClipper, ClipperNone from autofit.non_linear.initializer import AbstractInitializer from autofit.non_linear.samples.sample import Sample from autofit.non_linear.samples.samples import Samples @@ -33,6 +35,7 @@ def __init__( maxiter: int = 15000, maxls: int = 20, initializer: Optional[AbstractInitializer] = None, + clipper: Optional[AbstractClipper] = None, iterations_per_full_update: int = None, iterations_per_quick_update: int = None, silence: bool = False, @@ -52,6 +55,15 @@ def __init__( Maximum number of iterations. maxfun Maximum number of function evaluations. + clipper + Enforcement of prior support (see :mod:`autofit.non_linear.clipper`). + Unlike the multi-start gradient searches, which project the parameters + themselves after every update, this search declares the box to scipy + and lets scipy enforce it — ``L-BFGS-B`` supports box bounds natively. + + Default ``ClipperNone``, under which no ``bounds=`` is passed at all + and behaviour is unchanged. Only bound-supporting methods accept a + real clipper; see ``_bounds_from``. """ super().__init__( @@ -59,6 +71,7 @@ def __init__( path_prefix=path_prefix, unique_tag=unique_tag, initializer=initializer, + clipper=clipper, iterations_per_quick_update=iterations_per_quick_update, iterations_per_full_update=iterations_per_full_update, silence=silence, @@ -79,6 +92,49 @@ def __init__( self.logger.debug(f"Creating {self.method} Search") + # The scipy methods that accept box bounds. Plain ``BFGS`` is deliberately + # absent: scipy does not reject bounds it cannot use, it *ignores* them behind + # a ``UserWarning`` and returns the unconstrained optimum. A user who asked for + # prior-support enforcement and received an unbounded fit plus a log line is + # exactly the silent-wrong-answer this class is meant to prevent, so + # ``_bounds_from`` raises instead. + _BOUND_SUPPORTING_METHODS = ("L-BFGS-B", "TNC", "SLSQP") + + def _bounds_from(self, model): + """ + The ``scipy.optimize.Bounds`` for ``model``, or ``None`` when no clipper is + configured (in which case no ``bounds=`` is passed at all and behaviour is + unchanged). + + The conversion is not incidental. ``AbstractClipper.bounds_from_model`` + returns ``(lower, upper)`` as two arrays, which is the shape ``project`` + broadcasts against — but ``optimize.minimize`` reads a ``(lower, upper)`` + tuple as a *sequence of ``(min, max)`` pairs*. For a two-parameter model + that is a valid-looking pair sequence, so scipy pins each parameter to a + constant and returns a wrong fit with no error and no warning; at every + other dimensionality it raises. Building an explicit ``Bounds`` is what + makes the intent unambiguous. + """ + # Imported lazily, as everywhere else in autofit -- no module in the + # package pulls scipy in at import time. + from scipy import optimize + + if isinstance(self.clipper, ClipperNone): + return None + + if self.method not in self._BOUND_SUPPORTING_METHODS: + raise exc.SearchException( + f"A {type(self.clipper).__name__} was passed to a search using " + f"method '{self.method}', which does not support box bounds. " + f"SciPy would silently ignore the bounds and return an " + f"unconstrained fit. Use one of " + f"{', '.join(self._BOUND_SUPPORTING_METHODS)} (e.g. af.LBFGS) or " + f"leave the clipper as the default ClipperNone." + ) + + lower, upper = self.clipper.bounds_from_model(model) + return optimize.Bounds(lower, upper) + @property def options(self): return { @@ -115,7 +171,9 @@ def _fit( A result object comprising the Samples object that inclues the maximum log likelihood instance and full chains used by the fit. """ - from scipy import optimize + # Resolved once, before any stepping: an unsupported method should fail + # immediately rather than after the first chunk of iterations. + bounds = self._bounds_from(model=model) fitness = Fitness( model=model, @@ -180,6 +238,16 @@ def _fit( options = dict(self.options) options["maxiter"] = iterations + # ``bounds`` is ``None`` under the default ``ClipperNone``, and + # ``minimize(bounds=None)`` is the same call as omitting it, so the + # default path is unchanged. + # + # Only the JAX branch is actually *exposed* to the prior-support + # problem: ``UniformPrior.log_prior_from_value`` returns ``0.0`` + # unconditionally on the NumPy path, with no bound test, so there + # is no hard wall to fall off there. Bounds are still passed on + # both branches — they are correct on both, and having them + # diverge by branch would be a trap of its own. if analysis._use_jax: search_internal = optimize.minimize( @@ -188,6 +256,7 @@ def _fit( method=self.method, options=options, tol=self.tol, + bounds=bounds, ) else: @@ -197,6 +266,7 @@ def _fit( method=self.method, options=options, tol=self.tol, + bounds=bounds, ) total_iterations += search_internal.nit diff --git a/autofit/non_linear/search/mle/multi_start_gradient/search.py b/autofit/non_linear/search/mle/multi_start_gradient/search.py index 5a445134e..dcb332ec3 100644 --- a/autofit/non_linear/search/mle/multi_start_gradient/search.py +++ b/autofit/non_linear/search/mle/multi_start_gradient/search.py @@ -9,6 +9,7 @@ from autofit.non_linear.search.mle.abstract_mle import AbstractMLE from autofit.non_linear.analysis import Analysis from autofit.non_linear.fitness import Fitness +from autofit.non_linear.clipper import AbstractClipper, ClipperNone from autofit.non_linear.initializer import AbstractInitializer from autofit.non_linear.samples.sample import Sample from autofit.non_linear.samples.samples import Samples @@ -44,6 +45,7 @@ def __init__( convergence: Optional[MultiStartGradientConvergence] = None, iterations_per_log: int = 10, initializer: Optional[AbstractInitializer] = None, + clipper: Optional[AbstractClipper] = None, iterations_per_full_update: int = None, iterations_per_quick_update: int = None, silence: bool = False, @@ -55,8 +57,11 @@ def __init__( This search runs ``n_starts`` independent optimizations from broad, randomly drawn starting points, all in parallel via ``jax.vmap``, using a - fixed self-normalised optax update rule (Adam / ADABelief / Lion) on the - unconstrained (unit-cube) parameterization. A wide population of starts is + fixed self-normalised optax update rule (Adam / ADABelief / Lion). Starts + are *drawn* in the unit cube but are immediately mapped to **physical** + parameters (see ``_broad_starts``), and the rule steps in that physical + space — nothing constrains a step to the prior box, which is why a + ``clipper`` is available below. A wide population of starts is what lets the method escape the many wrong basins that trap every single-start, line-search or second-order optimizer on the kinked likelihoods this promotes from (see the Phase-3 GPU MAP-optimizer @@ -111,6 +116,21 @@ def __init__( The unit-cube bounds broad starts are drawn uniformly from. The interior default ``(0.15, 0.85)`` avoids the prior edges where many transforms (e.g. ``arctan2`` / ``sqrt`` at exactly 0) are singular. + clipper + Enforcement of prior support, applied to the parameters after every + update (see :mod:`autofit.non_linear.clipper`). Because the rule steps + in physical space against an objective that folds in the prior, a step + that leaves a hard-edged prior box makes the figure of merit ``-inf``; + the gradient there is the *finite* likelihood gradient, since + ``log_prior = -inf`` is constant outside the box and contributes + nothing, so ``apply_if_finite`` never fires and the lane keeps stepping + at full cost with its output discarded, for the rest of the run. + ``ClipperPriorBox`` projects such a lane back inside instead. + + Default ``ClipperNone`` — a no-op, so behaviour is unchanged. Turning + enforcement on moves where the search converges and would shift every + stored multi-start benchmark, so the default flip is deliberately a + separate, re-baselined change. resurrect Restart-on-death. When ``True``, any start whose objective goes non-finite is redrawn each step (fresh params from the start band + @@ -165,6 +185,7 @@ def __init__( path_prefix=path_prefix, unique_tag=unique_tag, initializer=initializer, + clipper=clipper, iterations_per_quick_update=iterations_per_quick_update, iterations_per_full_update=iterations_per_full_update, silence=silence, @@ -612,6 +633,11 @@ def _fit( # ``fitness.call``, which is untouched. has_constraint = bool(model.constrained_model_tuples()) + # Same short-circuit shape as ``has_constraint``: the default clipper is a + # no-op, and testing for it here keeps the projection out of the step loop + # entirely rather than applying an identity every step. + has_clipper = not isinstance(self.clipper, ClipperNone) + def _value_and_grad_finite(vector): fom, grad = _value_and_grad(vector) violation = ( @@ -684,6 +710,7 @@ def batched_value_and_grad(params): n_constrained_lane_steps = int( search_internal.get("n_constrained_lane_steps", 0) ) + n_clipped_lane_steps = int(search_internal.get("n_clipped_lane_steps", 0)) stop_reason = search_internal.get("stop_reason", None) self.logger.info( @@ -713,6 +740,7 @@ def batched_value_and_grad(params): n_value_nan_lane_steps = 0 n_grad_nan_lane_steps = 0 n_constrained_lane_steps = 0 + n_clipped_lane_steps = 0 stop_reason = None self.logger.info( @@ -816,6 +844,26 @@ def batched_value_and_grad(params): updates, opt_state = step_update(grads, opt_state, params, foms) params = optax.apply_updates(params, updates) + # Prior-support enforcement, applied to the updated parameters + # before they are evaluated again. Skipped entirely rather than + # applied as a no-op under the default ``ClipperNone``, so that + # the default path is bit-identical and its compiled step is + # unchanged — the same short-circuit ``has_constraint`` makes for + # the declared-constraint measure above. + # + # ``project`` broadcasts the ``(n_params,)`` bounds against the + # ``(n_starts, n_params)`` batch, so no vmap is needed here. + if has_clipper: + params, clipped_mask = self.clipper.project( + vector=params, model=model, xp=jnp + ) + # Per-LANE, not per-coordinate: a lane clipped in three + # parameters at once is one clipped lane-step, matching how + # the NaN and constrained counters above are read. + n_clipped_lane_steps += int( + np.count_nonzero(np.asarray(jnp.any(clipped_mask, axis=-1))) + ) + total_steps += 1 if not self.resurrect and self.convergence.check_if_converged( @@ -868,6 +916,7 @@ def batched_value_and_grad(params): "n_value_nan_lane_steps": n_value_nan_lane_steps, "n_grad_nan_lane_steps": n_grad_nan_lane_steps, "n_constrained_lane_steps": n_constrained_lane_steps, + "n_clipped_lane_steps": n_clipped_lane_steps, "stop_reason": stop_reason, } self.paths.save_search_internal(obj=search_internal) diff --git a/test_autofit/non_linear/test_clipper.py b/test_autofit/non_linear/test_clipper.py new file mode 100644 index 000000000..45b3a1672 --- /dev/null +++ b/test_autofit/non_linear/test_clipper.py @@ -0,0 +1,341 @@ +import numpy as np +import pytest + +import autofit as af +from autofit import exc +from autofit.non_linear.clipper import ClipperNone, ClipperPriorBox + + +class Widget: + def __init__(self, alpha=None, beta=None, gamma=None): + self.alpha = alpha + self.beta = beta + self.gamma = gamma + + +def _model(**priors): + model = af.Model(Widget) + for name, prior in priors.items(): + setattr(model, name, prior) + return model + + +class TestBoundsExtraction: + def test__uniform_prior__finite_both_sides(self): + model = _model( + alpha=af.UniformPrior(lower_limit=0.0, upper_limit=2.0), + beta=af.UniformPrior(lower_limit=-1.0, upper_limit=1.0), + gamma=af.UniformPrior(lower_limit=10.0, upper_limit=20.0), + ) + + lower, upper = ClipperPriorBox(margin=0.0).bounds_from_model(model=model) + + assert lower == pytest.approx(np.array([0.0, -1.0, 10.0])) + assert upper == pytest.approx(np.array([2.0, 1.0, 20.0])) + + def test__truncated_gaussian_prior__reads_message_limits(self): + model = _model( + alpha=af.TruncatedGaussianPrior( + mean=0.0, sigma=1.0, lower_limit=-1.0, upper_limit=1.0 + ) + ) + + lower, upper = ClipperPriorBox(margin=0.0).bounds_from_model(model=model) + + assert lower[0] == pytest.approx(-1.0) + assert upper[0] == pytest.approx(1.0) + + def test__log_uniform_prior__finite_both_sides(self): + model = _model(alpha=af.LogUniformPrior(lower_limit=1.0e-6, upper_limit=1.0)) + + lower, upper = ClipperPriorBox(margin=0.0).bounds_from_model(model=model) + + assert lower[0] == pytest.approx(1.0e-6) + assert upper[0] == pytest.approx(1.0) + + def test__gaussian_prior__passes_through_as_infinite(self): + """ + A GaussianPrior has unbounded support and must be reported as such -- and, + critically, must not acquire a NaN bound from any inset arithmetic. See + ``test__gaussian_coordinate_is_never_nan`` for the projection-level guard. + """ + model = _model(alpha=af.GaussianPrior(mean=0.0, sigma=1.0)) + + lower, upper = ClipperPriorBox().bounds_from_model(model=model) + + assert lower[0] == -np.inf + assert upper[0] == np.inf + assert not np.isnan(lower).any() + assert not np.isnan(upper).any() + + def test__log_gaussian_prior__lower_bound_is_declared_by_the_clipper(self): + """ + LogGaussianPrior reports (-inf, inf) because its TransformedMessage is never + given limits, yet ``log_prior_from_value`` is -inf for value <= 0. The + clipper declares the real (0, inf) support, strictly, so the projected value + lands *above* zero rather than on it. + """ + prior = af.LogGaussianPrior(mean=0.0, sigma=1.0) + + assert prior.lower_limit == -np.inf + + model = _model(alpha=prior) + lower, upper = ClipperPriorBox(strict_epsilon=1.0e-12).bounds_from_model( + model=model + ) + + assert lower[0] > 0.0 + assert lower[0] == pytest.approx(1.0e-12) + assert upper[0] == np.inf + + def test__mixed_model__every_prior_type_at_once(self): + model = af.Model(Widget) + model.alpha = af.UniformPrior(lower_limit=0.0, upper_limit=2.0) + model.beta = af.GaussianPrior(mean=0.0, sigma=1.0) + model.gamma = af.LogGaussianPrior(mean=0.0, sigma=1.0) + + lower, upper = ClipperPriorBox().bounds_from_model(model=model) + + assert not np.isnan(lower).any() + assert not np.isnan(upper).any() + assert len(lower) == model.prior_count + + +class TestOrdering: + def test__bound_at_index_i_belongs_to_the_parameter_at_index_i(self): + """ + The ordering is load-bearing and silent if wrong: a mismatch would clip the + wrong parameter with no error. + + Asserting ``priors_ordered_by_id`` against ``prior_tuples_ordered_by_id`` + would be vacuous -- the former is derived from the latter. The real check is + against ``instance_from_vector``, which is what actually consumes the vector, + so the priors are given disjoint boxes and each attribute must land inside + its own. + """ + model = af.Model(Widget) + # Assigned out of alphabetical order so prior id order and attribute order + # cannot coincide by accident. + model.gamma = af.UniformPrior(lower_limit=30.0, upper_limit=31.0) + model.alpha = af.UniformPrior(lower_limit=10.0, upper_limit=11.0) + model.beta = af.UniformPrior(lower_limit=20.0, upper_limit=21.0) + + lower, upper = ClipperPriorBox(margin=0.0).bounds_from_model(model=model) + + midpoints = (lower + upper) / 2.0 + instance = model.instance_from_vector(vector=list(midpoints)) + + for value, low, high in [ + (instance.alpha, 10.0, 11.0), + (instance.beta, 20.0, 21.0), + (instance.gamma, 30.0, 31.0), + ]: + assert low <= value <= high + + +class TestProject: + def test__overshoot_is_projected_back_inside_and_masked(self): + """ + The boxes are placed near zero deliberately. At float32 an overshoot of + ``2.0000001`` against an upper bound of ``2.0`` is not representable and the + assertion would pass vacuously; near zero the overshoot survives the dtype. + """ + model = _model( + alpha=af.UniformPrior(lower_limit=0.0, upper_limit=1.0), + beta=af.UniformPrior(lower_limit=0.0, upper_limit=1.0), + gamma=af.UniformPrior(lower_limit=0.0, upper_limit=1.0), + ) + + clipper = ClipperPriorBox(margin=0.0) + + projected, mask = clipper.project( + vector=np.array([1.5, 0.5, -0.5]), model=model + ) + + assert projected == pytest.approx(np.array([1.0, 0.5, 0.0])) + assert list(mask) == [True, False, True] + + def test__in_bounds_vector_is_untouched_and_mask_is_all_false(self): + model = _model( + alpha=af.UniformPrior(lower_limit=0.0, upper_limit=1.0), + beta=af.UniformPrior(lower_limit=0.0, upper_limit=1.0), + ) + + vector = np.array([0.25, 0.75]) + projected, mask = ClipperPriorBox(margin=0.0).project( + vector=vector, model=model + ) + + assert projected == pytest.approx(vector) + assert not mask.any() + + def test__gaussian_coordinate_is_never_nan(self): + """ + Regression guard. + + The obvious inset, ``lower + margin * (upper - lower)``, is ``-inf + inf`` for + an unbounded prior, i.e. NaN -- and clipping against a NaN bound turns the + coordinate into NaN, taking the whole objective with it. That failure looks + exactly like the lane death the clipper exists to prevent, and it would fire + on any model carrying a GaussianPrior. This test fails against that + implementation and passes against the bound-kind one. + """ + model = af.Model(Widget) + model.alpha = af.UniformPrior(lower_limit=0.0, upper_limit=2.0) + model.beta = af.GaussianPrior(mean=0.0, sigma=1.0) + + projected, mask = ClipperPriorBox().project( + vector=np.array([2.5, 900.0]), model=model + ) + + assert not np.isnan(projected).any() + assert projected[1] == 900.0 + assert list(mask) == [True, False] + + def test__log_gaussian_is_projected_to_finite_log_prior(self): + """ + Regression guard. + + A relative margin is identically zero for a half-open bound, so it would clip + onto exactly 0.0 -- where LogGaussianPrior's support is strict and + ``log_prior`` is -inf. The projected value must therefore be strictly + positive, and the resulting log prior finite. + """ + prior = af.LogGaussianPrior(mean=0.0, sigma=1.0) + model = _model(alpha=prior) + + for value in [0.0, -3.0]: + projected, mask = ClipperPriorBox().project( + vector=np.array([value]), model=model + ) + + assert projected[0] > 0.0 + assert mask[0] + assert np.isfinite(prior.log_prior_from_value(value=projected[0], xp=np)) + + def test__batched_vector_clips_per_lane(self): + model = _model( + alpha=af.UniformPrior(lower_limit=0.0, upper_limit=1.0), + beta=af.UniformPrior(lower_limit=0.0, upper_limit=1.0), + ) + + params = np.array([[1.5, 0.5], [0.25, 0.75], [-0.5, 2.0]]) + + projected, mask = ClipperPriorBox(margin=0.0).project( + vector=params, model=model + ) + + assert projected.shape == params.shape + assert projected == pytest.approx( + np.array([[1.0, 0.5], [0.25, 0.75], [0.0, 1.0]]) + ) + assert list(mask.any(axis=-1)) == [True, False, True] + + def test__margin_insets_inside_a_two_sided_box(self): + model = _model(alpha=af.UniformPrior(lower_limit=0.0, upper_limit=2.0)) + + projected, _ = ClipperPriorBox(margin=1.0e-6).project( + vector=np.array([5.0]), model=model + ) + + assert projected[0] < 2.0 + assert projected[0] == pytest.approx(2.0 - 2.0e-6) + + +class TestClipperNone: + def test__project_is_the_identity_and_mask_is_all_false(self): + model = _model( + alpha=af.UniformPrior(lower_limit=0.0, upper_limit=1.0), + beta=af.UniformPrior(lower_limit=0.0, upper_limit=1.0), + ) + + vector = np.array([5.0, -5.0]) + projected, mask = ClipperNone().project(vector=vector, model=model) + + assert projected is vector + assert not mask.any() + + def test__bounds_are_infinite(self): + model = _model( + alpha=af.UniformPrior(lower_limit=0.0, upper_limit=1.0), + beta=af.UniformPrior(lower_limit=0.0, upper_limit=1.0), + ) + + lower, upper = ClipperNone().bounds_from_model(model=model) + + assert list(lower) == [-np.inf, -np.inf] + assert list(upper) == [np.inf, np.inf] + + +class TestSearchWiring: + def test__default_clipper_is_clipper_none(self): + assert isinstance(af.LBFGS().clipper, ClipperNone) + assert isinstance(af.MultiStartAdam().clipper, ClipperNone) + + def test__clipper_round_trips_through_the_constructor(self): + clipper = ClipperPriorBox(margin=1.0e-4) + + assert af.MultiStartAdam(clipper=clipper).clipper is clipper + assert af.LBFGS(clipper=clipper).clipper is clipper + + def test__lbfgs_builds_a_scipy_bounds_object(self): + """ + Not merely "bounds are passed": ``bounds_from_model`` returns two arrays, and + ``optimize.minimize`` reads a ``(lower, upper)`` tuple as a *sequence of + (min, max) pairs*. Handing the tuple straight through silently mis-fits a + two-parameter model and raises at any other dimensionality, so the search + must build an explicit ``Bounds``. + """ + from scipy import optimize + + model = _model( + alpha=af.UniformPrior(lower_limit=0.0, upper_limit=1.0), + beta=af.UniformPrior(lower_limit=0.0, upper_limit=1.0), + ) + + bounds = af.LBFGS(clipper=ClipperPriorBox(margin=0.0))._bounds_from(model=model) + + assert isinstance(bounds, optimize.Bounds) + assert bounds.lb == pytest.approx(np.array([0.0, 0.0])) + assert bounds.ub == pytest.approx(np.array([1.0, 1.0])) + + def test__lbfgs_bounds_actually_constrain_a_two_parameter_fit(self): + """ + Two parameters specifically: the dimensionality at which the wrong bounds + shape fails *silently* rather than raising. With the optimum outside the box + the correct answer is the corner; the tuple form would return ``[0, 1]``. + """ + from scipy import optimize + + model = _model( + alpha=af.UniformPrior(lower_limit=0.0, upper_limit=1.0), + beta=af.UniformPrior(lower_limit=0.0, upper_limit=1.0), + ) + bounds = af.LBFGS(clipper=ClipperPriorBox(margin=0.0))._bounds_from(model=model) + + result = optimize.minimize( + fun=lambda x: float(np.sum((x - 5.0) ** 2)), + x0=np.array([0.5, 0.5]), + method="L-BFGS-B", + bounds=bounds, + ) + + assert result.x == pytest.approx(np.array([1.0, 1.0])) + + def test__no_clipper_means_no_bounds_are_passed(self): + model = _model(alpha=af.UniformPrior(lower_limit=0.0, upper_limit=1.0)) + + assert af.LBFGS()._bounds_from(model=model) is None + + def test__non_bound_supporting_method_raises_rather_than_being_ignored(self): + """ + SciPy does not reject bounds that ``BFGS`` cannot use -- it warns and returns + the unconstrained optimum. Silently handing back an unbounded fit to a user + who asked for prior-support enforcement is the failure mode being prevented. + """ + model = _model(alpha=af.UniformPrior(lower_limit=0.0, upper_limit=1.0)) + + search = af.BFGS(clipper=ClipperPriorBox()) + + with pytest.raises(exc.SearchException): + search._bounds_from(model=model) From 4ef04e1e62ef7c98b8ec708bbc5dd45f43fe3ee2 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 16 Aug 2026 02:18:43 +0000 Subject: [PATCH 2/3] Fix an undefined `optimize` in LBFGS `_fit`, and cover it The earlier commit's insertion of the `bounds` resolution replaced `_fit`'s local `from scipy import optimize`, and a module-level import added at the same time masked it. Removing that module-level import (no other module in autofit pulls scipy in at import time) left `optimize` undefined, so any real `LBFGS.fit()` raised `NameError`. The whole 1790-test suite passed against that, because nothing in the library suite ever executes an LBFGS fit -- it was only caught by a randomised end-to-end stress run. So this restores the local import and adds the cheap smoke test that closes the gap: a real `search.fit()` on the NumPy path, with and without a clipper, asserting the clipped run respects the prior box. That test fails with exactly this `NameError` if the import is removed again. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01Kt89ELdo9fb8gEoU1bP2yH --- autofit/non_linear/search/mle/bfgs/search.py | 2 + test_autofit/non_linear/test_clipper.py | 44 ++++++++++++++++++++ 2 files changed, 46 insertions(+) diff --git a/autofit/non_linear/search/mle/bfgs/search.py b/autofit/non_linear/search/mle/bfgs/search.py index 97eb8a3a8..13568d1f8 100644 --- a/autofit/non_linear/search/mle/bfgs/search.py +++ b/autofit/non_linear/search/mle/bfgs/search.py @@ -171,6 +171,8 @@ def _fit( A result object comprising the Samples object that inclues the maximum log likelihood instance and full chains used by the fit. """ + from scipy import optimize + # Resolved once, before any stepping: an unsupported method should fail # immediately rather than after the first chunk of iterations. bounds = self._bounds_from(model=model) diff --git a/test_autofit/non_linear/test_clipper.py b/test_autofit/non_linear/test_clipper.py index 45b3a1672..8404fb7f3 100644 --- a/test_autofit/non_linear/test_clipper.py +++ b/test_autofit/non_linear/test_clipper.py @@ -327,6 +327,50 @@ def test__no_clipper_means_no_bounds_are_passed(self): assert af.LBFGS()._bounds_from(model=model) is None + def test__lbfgs_fit_runs_end_to_end_with_and_without_a_clipper(self): + """ + A real `search.fit()`, not just `_bounds_from` in isolation. + + The whole library suite passed while `_fit` had an undefined `optimize`, + because nothing in it ever executed an LBFGS fit -- the bug only surfaced + in a manual end-to-end run. This is the cheap smoke test that closes that + gap: it fits a 1D Gaussian on the NumPy path and asserts the clipped run + respects the box. + """ + from autofit import example + + xvalues = np.arange(60) + truth = example.Gaussian(centre=30.0, normalization=25.0, sigma=8.0) + data = np.asarray(truth.model_data_from(xvalues=xvalues)) + noise_map = np.full(60, 1.0) + + def analysis(): + instance = example.Analysis(data=data, noise_map=noise_map) + instance._use_jax = False + return instance + + def model(): + built = af.Model(example.Gaussian) + # The truth (centre=30) is deliberately outside this box, so an + # enforced bound visibly changes the answer. + built.centre = af.UniformPrior(lower_limit=5.0, upper_limit=20.0) + built.normalization = af.UniformPrior(lower_limit=10.0, upper_limit=40.0) + built.sigma = af.UniformPrior(lower_limit=1.0, upper_limit=20.0) + return built + + unbounded = af.LBFGS(maxiter=15).fit(model=model(), analysis=analysis()) + clipped = af.LBFGS(maxiter=15, clipper=ClipperPriorBox()).fit( + model=model(), analysis=analysis() + ) + + unbounded_centre = unbounded.samples.max_log_likelihood(as_instance=False)[0] + clipped_centre = clipped.samples.max_log_likelihood(as_instance=False)[0] + + assert clipped_centre <= 20.0 + assert not np.isnan(clipped_centre) + # The unconstrained fit is free to chase the truth past the prior edge. + assert unbounded_centre > 20.0 + def test__non_bound_supporting_method_raises_rather_than_being_ignored(self): """ SciPy does not reject bounds that ``BFGS`` cannot use -- it warns and returns From 7cb84f7a08a9fa94d6b70c61b45892f70f563987 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 16 Aug 2026 02:41:23 +0000 Subject: [PATCH 3/3] Document the Clipper classes in the searches API page `ClipperNone` and `ClipperPriorBox` are exported from `autofit` but were absent from `docs/api/searches.rst`, where their `Initializer*` siblings are listed. Adds them to the same autosummary block. This is the first time the clipper docstrings are processed by Sphinx, and the docs job fails on a warning-count regression against `docs/sphinx_warning_baseline.txt`, so it is pushed as its own commit to keep that signal attributable. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01Kt89ELdo9fb8gEoU1bP2yH --- docs/api/searches.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/api/searches.rst b/docs/api/searches.rst index bb35a77a6..fde9b66e9 100644 --- a/docs/api/searches.rst +++ b/docs/api/searches.rst @@ -71,6 +71,8 @@ Tools Result InitializerBall InitializerPrior + ClipperNone + ClipperPriorBox AutoCorrelationsSettings **PyAutoFit** can perform a parallelized grid-search of non-linear searches, where a subset of parameters in the