diff --git a/autofit/mapper/prior_model/abstract.py b/autofit/mapper/prior_model/abstract.py index 37a25ede3..3dec7e519 100644 --- a/autofit/mapper/prior_model/abstract.py +++ b/autofit/mapper/prior_model/abstract.py @@ -833,6 +833,82 @@ def instance_from_vector(self, vector, ignore_assertions: bool = False, xp=np): xp=xp ) + def constrained_model_tuples(self): + """ + Every component in this model whose class declares a model constraint. + + Returns + ------- + [(path, model)] + Path/model pairs, including this model itself when it declares one. + """ + from autofit.mapper.prior_model.prior_model import Model + + tuples = [ + (path, model) + for path, model in self.attribute_tuples_with_type( + Model, ignore_children=False + ) + if model.has_model_constraint + ] + if isinstance(self, Model) and self.has_model_constraint: + tuples = [(("",), self)] + tuples + return tuples + + def model_constraint_from_vector(self, vector, xp=np): + """ + The largest constraint violation any component reports for this vector. + + Zero means every declared constraint is satisfied. The value is traced, + so this composes with ``jit``, ``vmap`` and ``grad`` — which is the whole + point, since the exception-based path (:meth:`add_assertion`, + ``validate_ell_comps``) cannot run inside a trace at all. See + :mod:`autofit.mapper.prior_model.constraint`. + + Components are instantiated individually rather than by building the + whole model, so a model declaring no constraints costs nothing. + + Note that on the NumPy path a component's own ``__init__`` validation may + raise before its constraint is ever evaluated — that is the existing + concrete-scalar guard behaviour and is deliberately not suppressed here. + This method exists for the traced path, where those guards return early. + + Parameters + ---------- + vector + A physical parameter vector, as passed to + :meth:`instance_from_vector`. + xp + The array module, ``numpy`` or ``jax.numpy``. + + Returns + ------- + The maximum violation measure across all constrained components. + """ + from autofit.mapper.prior_model.constraint import violation_for_instance + + constrained = self.constrained_model_tuples() + if not constrained: + return xp.asarray(0.0) + + arguments = dict( + map( + lambda prior_tuple, physical_unit: (prior_tuple.prior, physical_unit), + self.prior_tuples_ordered_by_id, + vector, + ) + ) + + violation = xp.asarray(0.0) + for _, model in constrained: + instance = model.instance_for_arguments( + arguments, + ignore_assertions=True, + xp=xp, + ) + violation = xp.maximum(violation, violation_for_instance(instance, xp=xp)) + return violation + def has(self, cls: Union[Type, Tuple[Type, ...]]) -> bool: """ Parameters diff --git a/autofit/mapper/prior_model/constraint.py b/autofit/mapper/prior_model/constraint.py new file mode 100644 index 000000000..1898fc187 --- /dev/null +++ b/autofit/mapper/prior_model/constraint.py @@ -0,0 +1,69 @@ +""" +Class-declared model constraints, evaluated as traced values. + +This is the differentiable sibling of :meth:`AbstractPriorModel.add_assertion`. +Assertions are attached to a *model instance* by the user and signal failure by +raising :class:`FitException`; that works on the NumPy path, where +:class:`Fitness` catches the exception and returns the resample sentinel, but it +cannot work under JAX. A ``raise`` needs a concrete boolean, and inside a trace +the condition is a tracer — attempting it gives ``TracerBoolConversionError``. +That is why guards such as ``autogalaxy.profiles.validate.validate_ell_comps`` +return early for non-concrete scalars rather than raising: the escape hatch is +load-bearing, or every jitted likelihood would crash instead of sampling. + +A model constraint differs in exactly two ways: + +- it is declared **on the class**, so every model built from that class carries + it without the user remembering to attach anything; +- it is evaluated as a **traced non-negative violation measure** rather than + raising, so it survives ``jit``, ``vmap`` and ``grad``. + +Declaring one +------------- + +A class declares a constraint by defining ``__model_constraint__``, which takes +the array module and returns a non-negative violation measure — ``0`` when the +constraint is satisfied, growing with the severity of the violation: + +.. code-block:: python + + class EllProfile: + def __model_constraint__(self, xp=np): + magnitude = xp.sqrt( + self.ell_comps[0] ** 2 + self.ell_comps[1] ** 2 + ) + return xp.maximum(magnitude - 0.999, 0.0) + +A *measure* rather than a boolean deliberately: a bool is enough for the +diagnostic counters that consume this today, but a magnitude is what a penalty +term would need later, and it carries a usable gradient back into the valid +region. Returning a bool would work for counting and then have to be redesigned. +""" + +import numpy as np + +MODEL_CONSTRAINT = "__model_constraint__" + + +def declares_model_constraint(cls) -> bool: + """ + Whether ``cls`` declares a model constraint. + + Duck-typed rather than requiring a base class, so profile libraries do not + have to inherit from PyAutoFit to describe their own parameter validity. + """ + return callable(getattr(cls, MODEL_CONSTRAINT, None)) + + +def violation_for_instance(instance, xp=np): + """ + The non-negative violation measure ``instance`` reports for itself. + + Parameters + ---------- + instance + An instance of a class declaring ``__model_constraint__``. + xp + The array module, ``numpy`` or ``jax.numpy``. + """ + return getattr(instance, MODEL_CONSTRAINT)(xp=xp) diff --git a/autofit/mapper/prior_model/prior_model.py b/autofit/mapper/prior_model/prior_model.py index e8e355240..759187c85 100644 --- a/autofit/mapper/prior_model/prior_model.py +++ b/autofit/mapper/prior_model/prior_model.py @@ -15,6 +15,10 @@ from autofit.mapper.prior.deferred import DeferredInstance from autofit.mapper.prior.tuple_prior import TuplePrior from autofit.mapper.prior_model.abstract import AbstractPriorModel +from autofit.mapper.prior_model.constraint import ( + MODEL_CONSTRAINT, + declares_model_constraint, +) from autofit.mapper.prior_model.util import gather_namespaces from autofit.tools.namer import namer @@ -31,6 +35,17 @@ class Model(AbstractPriorModel): def name(self): return self.cls.__name__ + @property + def has_model_constraint(self) -> bool: + """ + Whether this component's class declares a model constraint. + + Resolved from ``cls`` rather than cached on the instance, so a model + rebuilt or deserialised without going through ``__init__`` still reports + correctly. + """ + return declares_model_constraint(self.cls) + def __str__(self): prior_string = ", ".join(map(str, self.prior_tuples)) return f"{self.name} {prior_string}" @@ -206,6 +221,17 @@ def __init__( if not hasattr(self, key): setattr(self, key, self._convert_value(value)) + # Surface a class-declared model constraint at composition time, so a + # malformed declaration fails where the model is built rather than deep + # inside a jitted likelihood. Nothing is stored on the instance: the + # `__setattr__` above routes underscore-containing names into tuple + # priors, so the authoritative lookup stays on `cls`. + if MODEL_CONSTRAINT in vars(cls) and not declares_model_constraint(cls): + raise AssertionError( + f"{cls.__name__}.{MODEL_CONSTRAINT} must be callable; got " + f"{vars(cls)[MODEL_CONSTRAINT]!r}" + ) + # try: # # noinspection PyTypeChecker # register_pytree_node( 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 fcbd89df4..5a445134e 100644 --- a/autofit/non_linear/search/mle/multi_start_gradient/search.py +++ b/autofit/non_linear/search/mle/multi_start_gradient/search.py @@ -254,6 +254,43 @@ def _nan_lane_counts(foms, grad_finite): return alive, n_value_nan, n_grad_nan + @staticmethod + def _constrained_lane_count(alive, grad_finite, constraint_violation): + """ + Count the lanes sitting outside a declared model constraint. + + This is the third failure mode, disjoint from the two above and invisible + to both. A lane can walk into a saturating region of the model — the + ``ell_comps`` magnitude clamp is the reference case — where the + likelihood is finite and the gradient is finite but carries **no + component along the saturated direction**. There is no restoring force, + so the lane can never leave, and because its figure of merit is finite + and flat it looks exactly like a converged one. + + Detecting this by inspecting the gradient does not work. The clamp kills + only the radial derivative; the angle stays differentiable, so in general + position both ``ell_comps`` components carry a large non-zero gradient + while their radial projection is zero only to floating-point residue. A + component-wise ``== 0`` test finds nothing. The detector therefore reads + the model's own declared constraint (see + :mod:`autofit.mapper.prior_model.constraint`), which states the valid + region exactly rather than inferring it from the gradient. + + Disjoint by construction, on the same "one lane, one bucket" rule as + :meth:`_nan_lane_counts`: a lane already counted as value-NaN or + gradient-NaN is not counted here as well. + + Measurement only — this never gates a redraw and never changes stepping, + exactly like the gradient-NaN count above. + + Pure NumPy and free of search state so it can be tested directly; ``_fit`` + needs jax + optax + a JAX-traceable ``Analysis`` and cannot be driven from + the NumPy-only library suite. + """ + violation = np.asarray(constraint_violation) + eligible = np.asarray(alive) & np.asarray(grad_finite).astype(bool) + return int(np.count_nonzero(eligible & (violation > 0.0))) + @staticmethod def _stop_reason_on_resume(stop_reason): """ @@ -334,6 +371,7 @@ def _progress_message( best_fom: float, previous_fom: Optional[float], n_alive: int, + n_constrained: int = 0, estim_lr=None, ) -> str: """ @@ -364,6 +402,11 @@ def _progress_message( n_alive Starts whose objective is currently finite, against ``n_starts`` — the population-health signal that a falling best-fom alone hides. + n_constrained + Starts currently outside a declared model constraint. Omitted when + zero, so the line is unchanged for models declaring no constraint. + These starts are counted in ``n_alive`` as well: they are finite and + differentiable, which is exactly why they are otherwise invisible. estim_lr Per-start self-estimated step scale, for the learning-rate-free rules that carry one (Prodigy's ``d``). ``None`` for the fixed-rate Adam @@ -384,6 +427,9 @@ def _progress_message( parts.append(f"alive {n_alive}/{self.n_starts}") + if n_constrained: + parts.append(f"constrained {n_constrained}/{self.n_starts}") + if estim_lr is not None: lr = np.asarray(estim_lr, dtype=float) parts.append( @@ -557,9 +603,23 @@ def _fit( # # ``_value_and_grad`` is deliberately left as a 2-tuple: the single-point # initial-draw path below jits it directly and unpacks two values. + # The declared model constraint rides the same fused call, for the same + # reason and at the same class of cost: it is a fixed handful of ops on + # the parameter vector (independent of likelihood cost) returning one + # more ``(n_starts,)`` array on a device->host sync that already happens. + # Nothing flows *up* through the likelihood — the constraint is a pure + # function of the vector, so it is evaluated beside + # ``fitness.call``, which is untouched. + has_constraint = bool(model.constrained_model_tuples()) + def _value_and_grad_finite(vector): fom, grad = _value_and_grad(vector) - return fom, grad, jnp.all(jnp.isfinite(grad)) + violation = ( + model.model_constraint_from_vector(vector, xp=jnp) + if has_constraint + else jnp.asarray(0.0) + ) + return fom, grad, jnp.all(jnp.isfinite(grad)), violation _vmapped = jax.jit(jax.vmap(_value_and_grad_finite)) @@ -573,24 +633,28 @@ def batched_value_and_grad(params): foms_chunks = [] grads_chunks = [] grad_finite_chunks = [] + violation_chunks = [] for lo, hi, pad in _chunk_slices(params.shape[0], batch_size): chunk = params[lo:hi] if pad: chunk = jnp.concatenate( [chunk, jnp.tile(chunk[-1:], (pad, 1))] ) - foms, grads, grad_finite = _vmapped(chunk) + foms, grads, grad_finite, violation = _vmapped(chunk) if pad: foms = foms[:-pad] grads = grads[:-pad] grad_finite = grad_finite[:-pad] + violation = violation[:-pad] foms_chunks.append(foms) grads_chunks.append(grads) grad_finite_chunks.append(grad_finite) + violation_chunks.append(violation) return ( jnp.concatenate(foms_chunks), jnp.concatenate(grads_chunks), jnp.concatenate(grad_finite_chunks), + jnp.concatenate(violation_chunks), ) # The optax rule (resolved from optax / optax.contrib), guarded by @@ -617,6 +681,9 @@ def batched_value_and_grad(params): search_internal.get("n_value_nan_lane_steps", 0) ) n_grad_nan_lane_steps = int(search_internal.get("n_grad_nan_lane_steps", 0)) + n_constrained_lane_steps = int( + search_internal.get("n_constrained_lane_steps", 0) + ) stop_reason = search_internal.get("stop_reason", None) self.logger.info( @@ -645,6 +712,7 @@ def batched_value_and_grad(params): n_resurrections = 0 n_value_nan_lane_steps = 0 n_grad_nan_lane_steps = 0 + n_constrained_lane_steps = 0 stop_reason = None self.logger.info( @@ -694,7 +762,7 @@ def batched_value_and_grad(params): self.logger.info(self._compile_message(batched=True)) awaiting_compile = False - foms, grads, grad_finite = batched_value_and_grad(params) + foms, grads, grad_finite, violation = batched_value_and_grad(params) # Measurement only — this accounting never gates a redraw. A # gradient-NaN lane is *not* resurrected here: doing so would @@ -709,6 +777,12 @@ def batched_value_and_grad(params): ) n_value_nan_lane_steps += n_value_nan n_grad_nan_lane_steps += n_grad_nan + n_constrained = self._constrained_lane_count( + alive=alive, + grad_finite=grad_finite, + constraint_violation=violation, + ) + n_constrained_lane_steps += n_constrained foms_np = np.where(alive, np.asarray(foms), np.inf) best_index = int(np.argmin(foms_np)) @@ -769,6 +843,7 @@ def batched_value_and_grad(params): best_fom=best_fom, previous_fom=previous_logged_fom, n_alive=int(alive.sum()), + n_constrained=n_constrained, estim_lr=estim_lr, ) ) @@ -792,6 +867,7 @@ def batched_value_and_grad(params): "n_resurrections": n_resurrections, "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, "stop_reason": stop_reason, } self.paths.save_search_internal(obj=search_internal) @@ -1037,6 +1113,9 @@ def samples_via_internal_from( "n_value_nan_lane_steps": int( search_internal.get("n_value_nan_lane_steps", 0) ), + "n_constrained_lane_steps": int( + search_internal.get("n_constrained_lane_steps", 0) + ), "n_grad_nan_lane_steps": int( search_internal.get("n_grad_nan_lane_steps", 0) ), diff --git a/test_autofit/mapper/model/test_model_constraint.py b/test_autofit/mapper/model/test_model_constraint.py new file mode 100644 index 000000000..cb62a0f4e --- /dev/null +++ b/test_autofit/mapper/model/test_model_constraint.py @@ -0,0 +1,171 @@ +import numpy as np +import pytest + +import autofit as af +from autofit.mapper.prior_model.constraint import ( + MODEL_CONSTRAINT, + declares_model_constraint, + violation_for_instance, +) +from autofit.non_linear.search.mle.multi_start_gradient.search import ( + AbstractMultiStartGradient, +) + + +class Unconstrained: + def __init__(self, centre=0.0, normalization=0.1): + self.centre = centre + self.normalization = normalization + + +class Saturating: + """Stands in for an elliptical profile: two components, a joint unit-disc + constraint that no per-parameter prior limit can express.""" + + def __init__(self, ell_comps_0=0.0, ell_comps_1=0.0): + self.ell_comps_0 = ell_comps_0 + self.ell_comps_1 = ell_comps_1 + + def __model_constraint__(self, xp=np): + magnitude = xp.sqrt(self.ell_comps_0**2 + self.ell_comps_1**2) + return xp.maximum(magnitude - 0.999, 0.0) + + +class TestDeclaration: + def test_duck_typed_detection(self): + assert declares_model_constraint(Saturating) + assert not declares_model_constraint(Unconstrained) + + def test_model_exposes_the_declaration(self): + assert af.Model(Saturating).has_model_constraint + assert not af.Model(Unconstrained).has_model_constraint + + def test_malformed_declaration_fails_at_composition(self): + class Malformed: + def __init__(self, centre=0.0): + self.centre = centre + + setattr(Malformed, MODEL_CONSTRAINT, "not callable") + + with pytest.raises(AssertionError): + af.Model(Malformed) + + def test_violation_for_instance(self): + assert violation_for_instance(Saturating(0.5, 0.0)) == 0.0 + assert violation_for_instance(Saturating(1.2, 0.0)) == pytest.approx(0.201) + + +def saturating_model(): + """Priors given explicitly: the fixture classes have no entry in the priors + config, so `make_prior` would otherwise hand back a `ConfigException`.""" + return af.Model( + Saturating, + ell_comps_0=af.UniformPrior(lower_limit=-4.0, upper_limit=4.0), + ell_comps_1=af.UniformPrior(lower_limit=-4.0, upper_limit=4.0), + ) + + +def unconstrained_model(): + return af.Model( + Unconstrained, + centre=af.UniformPrior(lower_limit=-1.0, upper_limit=1.0), + normalization=af.UniformPrior(lower_limit=0.0, upper_limit=1.0), + ) + + +class TestConstrainedModelTuples: + def test_finds_nested_components(self): + model = af.Collection( + a=saturating_model(), + b=unconstrained_model(), + c=af.Collection(d=saturating_model()), + ) + assert len(model.constrained_model_tuples()) == 2 + + def test_none_when_nothing_declares(self): + model = af.Collection(b=unconstrained_model()) + assert model.constrained_model_tuples() == [] + + +class TestConstraintFromVector: + def test_zero_inside_the_valid_region(self): + model = af.Collection(a=saturating_model()) + assert float(model.model_constraint_from_vector([0.5, 0.2])) == 0.0 + + def test_positive_outside(self): + model = af.Collection(a=saturating_model()) + assert float(model.model_constraint_from_vector([1.2, 0.0])) > 0.0 + + def test_catches_the_corner_region(self): + """Both components inside (-1, 1) yet magnitude above 1 — the case a + per-parameter prior-limit test provably cannot see.""" + model = af.Collection(a=saturating_model()) + assert float(model.model_constraint_from_vector([0.8, 0.8])) > 0.0 + + def test_zero_when_model_declares_nothing(self): + model = af.Collection(b=unconstrained_model()) + assert float(model.model_constraint_from_vector([0.5, 0.2])) == 0.0 + + def test_reduces_over_components_with_a_maximum(self): + model = af.Collection(a=saturating_model(), c=saturating_model()) + vector = [0.0] * model.prior_count + # set whichever pair belongs to `c`, without assuming prior ordering + index = model.prior_count - 2 + for path, sub in model.constrained_model_tuples(): + if path and path[-1] == "c": + index = min( + model.prior_tuples_ordered_by_id.index(t) + for t in sub.prior_tuples_ordered_by_id + ) + vector[index] = 3.0 + assert float(model.model_constraint_from_vector(vector)) == pytest.approx(2.001) + + +class TestConstrainedLaneCount: + """The predicate is pure NumPy and search-state-free, so it is driven + directly — `_fit` needs jax + optax and cannot run in this suite.""" + + def test_counts_only_violating_lanes(self): + assert ( + AbstractMultiStartGradient._constrained_lane_count( + alive=np.array([True, True, True]), + grad_finite=np.array([True, True, True]), + constraint_violation=np.array([0.0, 0.5, 0.0]), + ) + == 1 + ) + + def test_disjoint_from_value_nan(self): + """A dead lane is not also counted as constrained.""" + assert ( + AbstractMultiStartGradient._constrained_lane_count( + alive=np.array([False, True]), + grad_finite=np.array([True, True]), + constraint_violation=np.array([9.0, 0.0]), + ) + == 0 + ) + + def test_disjoint_from_gradient_nan(self): + assert ( + AbstractMultiStartGradient._constrained_lane_count( + alive=np.array([True, True]), + grad_finite=np.array([False, True]), + constraint_violation=np.array([9.0, 0.0]), + ) + == 0 + ) + + def test_buckets_sum_to_at_most_the_lane_count(self): + foms = np.array([np.nan, 1.0, 2.0, 3.0]) + grad_finite = np.array([False, False, True, True]) + violation = np.array([5.0, 5.0, 5.0, 0.0]) + + alive, n_value_nan, n_grad_nan = AbstractMultiStartGradient._nan_lane_counts( + foms=foms, grad_finite=grad_finite + ) + n_constrained = AbstractMultiStartGradient._constrained_lane_count( + alive=alive, grad_finite=grad_finite, constraint_violation=violation + ) + assert (n_value_nan, n_grad_nan, n_constrained) == (1, 1, 1) + assert n_value_nan + n_grad_nan + n_constrained <= len(foms)