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
76 changes: 76 additions & 0 deletions autofit/mapper/prior_model/abstract.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
69 changes: 69 additions & 0 deletions autofit/mapper/prior_model/constraint.py
Original file line number Diff line number Diff line change
@@ -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)
26 changes: 26 additions & 0 deletions autofit/mapper/prior_model/prior_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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}"
Expand Down Expand Up @@ -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(
Expand Down
85 changes: 82 additions & 3 deletions autofit/non_linear/search/mle/multi_start_gradient/search.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
"""
Expand Down Expand Up @@ -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:
"""
Expand Down Expand Up @@ -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
Expand All @@ -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(
Expand Down Expand Up @@ -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))

Expand All @@ -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
Expand All @@ -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(
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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
Expand All @@ -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))
Expand Down Expand Up @@ -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,
)
)
Expand All @@ -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)
Expand Down Expand Up @@ -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)
),
Expand Down
Loading
Loading