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
106 changes: 102 additions & 4 deletions autofit/non_linear/search/mle/multi_start_gradient/search.py
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,45 @@ def _is_final_boundary(self, converged: bool, total_steps: int) -> bool:
"""
return bool(converged) or total_steps >= self.n_steps

@staticmethod
def _nan_lane_counts(foms, grad_finite):
"""
Split one step's non-finite lanes into the two failure modes, and return
the alive mask the caller needs anyway.

Two distinct things go wrong per lane, and conflating them hides the
second:

- **value-NaN** — the likelihood is *undefined* at this point. This is
the lane death ``resurrect`` already triggers on.
- **gradient-NaN** — the likelihood is defined but *not differentiable*.
Nothing detects this today: ``optax.apply_if_finite`` zeroes the
update, so the lane silently freezes in place while still counting as
alive. A frozen lane looks exactly like a converged one in the
figure-of-merit trace.

The two counts are **disjoint by construction**: a lane that is
non-finite in both is one value-NaN, not one of each. A dead lane's
gradient is almost always non-finite too, so counting them independently
would double-report the ordinary case and drown the interesting one.

Returns ``(alive, n_value_nan, n_grad_nan)``. ``alive`` is returned
rather than recomputed by the caller so the finiteness test on ``foms``
happens once per step.

Pure NumPy and free of search state so it can be tested directly;
``_fit`` itself needs jax + optax + a JAX-traceable ``Analysis`` and
cannot be driven from the NumPy-only library suite (same reasoning as
``_is_final_boundary`` above).
"""
alive = np.isfinite(np.asarray(foms))
grad_finite = np.asarray(grad_finite).astype(bool)

n_value_nan = int(np.count_nonzero(~alive))
n_grad_nan = int(np.count_nonzero(alive & ~grad_finite))

return alive, n_value_nan, n_grad_nan

@staticmethod
def _stop_reason_on_resume(stop_reason):
"""
Expand Down Expand Up @@ -503,7 +542,26 @@ def _fit(
# numerically identical to the vmap; `batch_size` never changes
# results, it only bounds memory and compile.
_value_and_grad = jax.value_and_grad(fitness.call)
_vmapped = jax.jit(jax.vmap(_value_and_grad))

# Per-start gradient finiteness is reduced *inside* the jitted call, as a
# third output, rather than by a separate op on its result. The reduction
# itself is trivially cheap either way; what costs is dispatch. Fused,
# XLA folds the ``isfinite``/``all`` into the backward pass and the step
# returns one extra ``(n_starts,)`` bool alongside the foms it already
# syncs on — no extra kernel launch, no extra device->host round-trip.
# Reducing eagerly outside the jit instead measured ~+3% per step against
# a ~1.5% noise floor (worse than pulling the whole ``(n_starts, ndim)``
# gradient to host, which is what it was meant to avoid); fused it is
# +0.05%, below noise. See
# ``autolens_profiling/scripts/misc/searches/multi_start_nan_accounting_overhead.py``.
#
# ``_value_and_grad`` is deliberately left as a 2-tuple: the single-point
# initial-draw path below jits it directly and unpacks two values.
def _value_and_grad_finite(vector):
fom, grad = _value_and_grad(vector)
return fom, grad, jnp.all(jnp.isfinite(grad))

_vmapped = jax.jit(jax.vmap(_value_and_grad_finite))

if self.batch_size is None:
self._warn_if_unbatched_exceeds_memory(model=model, analysis=analysis)
Expand All @@ -514,21 +572,25 @@ def _fit(
def batched_value_and_grad(params):
foms_chunks = []
grads_chunks = []
grad_finite_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 = _vmapped(chunk)
foms, grads, grad_finite = _vmapped(chunk)
if pad:
foms = foms[:-pad]
grads = grads[:-pad]
grad_finite = grad_finite[:-pad]
foms_chunks.append(foms)
grads_chunks.append(grads)
grad_finite_chunks.append(grad_finite)
return (
jnp.concatenate(foms_chunks),
jnp.concatenate(grads_chunks),
jnp.concatenate(grad_finite_chunks),
)

# The optax rule (resolved from optax / optax.contrib), guarded by
Expand All @@ -547,6 +609,14 @@ def batched_value_and_grad(params):
fom_history = list(search_internal["fom_history"])
total_steps = int(search_internal["total_steps"])
n_resurrections = int(search_internal.get("n_resurrections", 0))
# ``.get`` with a default: a ``search_internal`` written before the
# NaN accounting existed has neither key, and a resumed run must not
# KeyError on it. The restored totals are lifetime counts, so a
# resumed run continues accumulating rather than restarting at zero.
n_value_nan_lane_steps = int(
search_internal.get("n_value_nan_lane_steps", 0)
)
n_grad_nan_lane_steps = int(search_internal.get("n_grad_nan_lane_steps", 0))
stop_reason = search_internal.get("stop_reason", None)

self.logger.info(
Expand All @@ -573,6 +643,8 @@ def batched_value_and_grad(params):
fom_history = []
total_steps = 0
n_resurrections = 0
n_value_nan_lane_steps = 0
n_grad_nan_lane_steps = 0
stop_reason = None

self.logger.info(
Expand Down Expand Up @@ -622,9 +694,22 @@ def batched_value_and_grad(params):
self.logger.info(self._compile_message(batched=True))
awaiting_compile = False

foms, grads = batched_value_and_grad(params)
foms, grads, grad_finite = batched_value_and_grad(params)

# Measurement only — this accounting never gates a redraw. A
# gradient-NaN lane is *not* resurrected here: doing so would
# change search behaviour and shift every existing benchmark,
# so the policy question waits on what these counts show. The
# counters are accumulated unconditionally, outside the
# ``self.resurrect`` guard below, because with ``resurrect``
# off ``n_resurrections`` stays zero and this is then the only
# record that lanes died at all.
alive, n_value_nan, n_grad_nan = self._nan_lane_counts(
foms=foms, grad_finite=grad_finite
)
n_value_nan_lane_steps += n_value_nan
n_grad_nan_lane_steps += n_grad_nan

alive = np.isfinite(np.asarray(foms))
foms_np = np.where(alive, np.asarray(foms), np.inf)
best_index = int(np.argmin(foms_np))
if foms_np[best_index] < best_fom:
Expand Down Expand Up @@ -705,6 +790,8 @@ def batched_value_and_grad(params):
"fom_history": np.asarray(fom_history),
"total_steps": total_steps,
"n_resurrections": n_resurrections,
"n_value_nan_lane_steps": n_value_nan_lane_steps,
"n_grad_nan_lane_steps": n_grad_nan_lane_steps,
"stop_reason": stop_reason,
}
self.paths.save_search_internal(obj=search_internal)
Expand Down Expand Up @@ -942,6 +1029,17 @@ def samples_via_internal_from(
"max_consecutive_nan": self.max_consecutive_nan,
"resurrect": self.resurrect,
"n_resurrections": int(search_internal.get("n_resurrections", 0)),
# Per-step non-finite accounting, split by failure mode. Value-NaN
# is an undefined likelihood; gradient-NaN is a defined but
# non-differentiable one, counted only for lanes still alive by
# value so the two are disjoint. ``.get`` for the same
# legacy-``search_internal`` reason as ``n_resurrections``.
"n_value_nan_lane_steps": int(
search_internal.get("n_value_nan_lane_steps", 0)
),
"n_grad_nan_lane_steps": int(
search_internal.get("n_grad_nan_lane_steps", 0)
),
# Auto-convergence outcome: whether the run stopped on the plateau
# check ("converged") or exhausted the ``n_steps`` ceiling
# ("max_steps"), the settings that produced it, and the global-best
Expand Down
36 changes: 36 additions & 0 deletions autofit/text/text_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,42 @@ def search_summary_from_samples(samples) -> [str]:
if hasattr(samples, "total_accepted_samples"):
line.append(f"Total Accepted Samples = {samples.total_accepted_samples}\n")
line.append(f"Acceptance Ratio = {samples.acceptance_ratio}\n")

# Per-step non-finite accounting from the gradient searches
# (``MultiStartGradient``). Guarded on the key rather than the search type,
# following the duck-typed MCMC block above: this function is on every
# search's summary path (``paths/abstract.py`` -> ``search_summary_to_file``),
# so a search whose ``samples_info`` lacks these keys — Nautilus, which is
# jit-only and has no gradient to be non-finite — must emit nothing at all.
#
# Rates, not just counts: raw totals are not comparable across runs, since
# they scale with the lane-step budget. 797 on a 16x3000 run and 10 on an
# 8x300 run differ 80x raw but only ~2x per lane-step.
#
# Named as the neutral facts they are. These are counts of undefined and
# non-differentiable likelihood evaluations; they are deliberately NOT
# presented as a smoothness or sampler-difficulty metric, because the
# correlation with (for example) HMC divergence rates is unvalidated.
samples_info = getattr(samples, "samples_info", None) or {}

if "n_value_nan_lane_steps" in samples_info:
n_value_nan = int(samples_info.get("n_value_nan_lane_steps", 0))
n_grad_nan = int(samples_info.get("n_grad_nan_lane_steps", 0))

line.append(f"Resurrections = {int(samples_info.get('n_resurrections', 0))}\n")
line.append(f"Value-NaN Lane-Steps = {n_value_nan}\n")
line.append(f"Gradient-NaN Lane-Steps = {n_grad_nan}\n")

# ``n_starts * total_steps`` is the number of lane-steps actually taken.
# A search that died before its first step has a zero denominator, so
# the rates are omitted rather than reported as a division error.
lane_steps = int(samples_info.get("n_starts", 0)) * int(
samples_info.get("total_steps", 0)
)
if lane_steps > 0:
line.append(f"Value-NaN Lane-Step Rate = {n_value_nan / lane_steps}\n")
line.append(f"Gradient-NaN Lane-Step Rate = {n_grad_nan / lane_steps}\n")

if samples.time is not None:
line.append(f"Time To Run = {dt.timedelta(seconds=float(samples.time))}\n")
line.append(
Expand Down
98 changes: 98 additions & 0 deletions test_autofit/non_linear/search/mle/test_multi_start_gradient.py
Original file line number Diff line number Diff line change
Expand Up @@ -383,6 +383,104 @@ def test__samples_info__stop_reason_max_steps_and_legacy_search_internal():
assert legacy.samples_info["fom_history"] is None


@pytest.mark.parametrize(
"foms, grad_finite, n_value_nan, n_grad_nan",
[
# Nothing wrong: every lane finite in value and gradient.
([1.0, 2.0, 3.0], [True, True, True], 0, 0),
# Value-NaN only -- the lane death resurrect already triggers on.
([1.0, np.nan, 3.0], [True, True, True], 1, 0),
([np.inf, -np.inf, 3.0], [True, True, True], 2, 0),
# Gradient-NaN only: likelihood defined, but not differentiable. This
# is the frozen-zombie lane that nothing detected before.
([1.0, 2.0, 3.0], [True, False, True], 0, 1),
# Both failure modes on *different* lanes: counted once each.
([1.0, np.nan, 3.0], [True, True, False], 1, 1),
# Both on the SAME lane: one value-NaN, NOT one of each. A dead lane's
# gradient is non-finite too, so double-counting here would inflate the
# gradient counter on every ordinary death and bury the real signal.
([1.0, np.nan, 3.0], [True, False, True], 1, 0),
([np.nan, np.nan], [False, False], 2, 0),
],
)
def test__nan_lane_counts__splits_value_and_gradient_failures(
foms, grad_finite, n_value_nan, n_grad_nan
):
alive, value_nan, grad_nan = af.MultiStartAdam._nan_lane_counts(
foms=np.asarray(foms), grad_finite=np.asarray(grad_finite)
)

assert value_nan == n_value_nan
assert grad_nan == n_grad_nan

# The alive mask is returned so the caller does not re-test finiteness.
assert list(alive) == list(np.isfinite(np.asarray(foms)))

# The two counts partition the lanes they describe: neither can exceed the
# lane count, and together they never over-count it.
assert value_nan + grad_nan <= len(foms)


def test__nan_lane_counts__accepts_jax_style_array_outputs():
"""
``grad_finite`` arrives from a jitted call as a device array of bools; the
helper must not assume a NumPy bool dtype (a 0/1 integer array is the
common surprise).
"""
alive, value_nan, grad_nan = af.MultiStartAdam._nan_lane_counts(
foms=np.asarray([1.0, 2.0, np.nan]),
grad_finite=np.asarray([1, 0, 1]),
)

assert value_nan == 1
assert grad_nan == 1
assert list(alive) == [True, True, False]


def test__samples_info__nan_lane_step_counters():
model = af.Model(example.Gaussian)

best_params = np.asarray(model.vector_from_unit_vector([0.5] * model.prior_count))
per_start_params = np.stack([best_params])

search = af.MultiStartAdam(n_starts=1, n_steps=300)

samples = search.samples_via_internal_from(
model=model,
search_internal={
"params": per_start_params,
"best_params": best_params,
"best_fom": -2.0,
"fom_history": np.asarray([-2.0]),
"total_steps": 300,
"n_resurrections": 7,
"n_value_nan_lane_steps": 7,
"n_grad_nan_lane_steps": 3,
"stop_reason": "max_steps",
},
)

assert samples.samples_info["n_value_nan_lane_steps"] == 7
assert samples.samples_info["n_grad_nan_lane_steps"] == 3

# A search_internal written before the NaN accounting existed has neither
# key. Resuming or re-reading one must degrade to zero, not KeyError.
legacy = search.samples_via_internal_from(
model=model,
search_internal={
"params": per_start_params,
"best_params": best_params,
"best_fom": -2.0,
"fom_history": np.asarray([-2.0]),
"total_steps": 300,
"n_resurrections": 0,
},
)

assert legacy.samples_info["n_value_nan_lane_steps"] == 0
assert legacy.samples_info["n_grad_nan_lane_steps"] == 0


def test__variable_length_zero_weight_nan_rows_are_robust():
"""The multi-start searches write zero-weight, NaN-log-likelihood diagnostic
rows for the non-best starts, and auto-convergence makes runs variable-length.
Expand Down
Loading
Loading