From 7a05d66f59c601ee9648255b02edd05911324f38 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Fri, 14 Aug 2026 18:29:29 -0400 Subject: [PATCH] feat: split value-NaN and gradient-NaN step counters in MultiStartGradient The fit loop detected a dead lane only via the VALUE (`alive = np.isfinite(foms)`). A lane whose likelihood is finite but whose gradient is non-finite was counted alive, had its update zeroed by `apply_if_finite`, and silently froze in place -- a differentiability failure that looked exactly like convergence in the figure-of-merit trace. Count both failure modes per step, disjointly (gradient-NaN only for lanes still alive by value), persist them into `search_internal` and `samples_info`, and surface them in `search.summary` with rates normalised by lane-steps. Gradient finiteness is reduced INSIDE the jitted call, as a third output. Reducing eagerly outside the jit measured ~+3%/step against a ~1.5% noise floor -- worse than pulling the whole gradient to host, which it was meant to avoid -- because an un-jitted reduction costs a kernel dispatch plus a host round-trip. Fused it is +0.05%, below noise. Measurement only: `resurrect` still triggers on value-NaN alone, so existing benchmark numbers stay comparable. The resurrection policy is decided after the counters show how often frozen lanes actually occur. The counting helper is pure NumPy and separately testable, keeping JAX out of the library unit suite. `search_summary_from_samples` is on every search's summary path, so the new block is guarded on the key: Nautilus and friends, which have no gradient to be non-finite, emit exactly what they did before. Refs #1472 Co-Authored-By: Claude Opus 5 --- .../search/mle/multi_start_gradient/search.py | 106 ++++++++++++++++- autofit/text/text_util.py | 36 ++++++ .../search/mle/test_multi_start_gradient.py | 98 +++++++++++++++ test_autofit/text/test_text_util.py | 112 ++++++++++++++++++ 4 files changed, 348 insertions(+), 4 deletions(-) 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 aa0837439..fcbd89df4 100644 --- a/autofit/non_linear/search/mle/multi_start_gradient/search.py +++ b/autofit/non_linear/search/mle/multi_start_gradient/search.py @@ -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): """ @@ -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) @@ -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 @@ -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( @@ -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( @@ -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: @@ -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) @@ -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 diff --git a/autofit/text/text_util.py b/autofit/text/text_util.py index 9d8720faf..7813c701b 100644 --- a/autofit/text/text_util.py +++ b/autofit/text/text_util.py @@ -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( diff --git a/test_autofit/non_linear/search/mle/test_multi_start_gradient.py b/test_autofit/non_linear/search/mle/test_multi_start_gradient.py index cb3803cc7..4458c71ac 100644 --- a/test_autofit/non_linear/search/mle/test_multi_start_gradient.py +++ b/test_autofit/non_linear/search/mle/test_multi_start_gradient.py @@ -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. diff --git a/test_autofit/text/test_text_util.py b/test_autofit/text/test_text_util.py index a659174be..5729a21d3 100644 --- a/test_autofit/text/test_text_util.py +++ b/test_autofit/text/test_text_util.py @@ -101,3 +101,115 @@ def test__search_summary_to_file(model): assert lines[4] == "Time Per Sample (seconds) = 0.1\n" assert lines[5] == "Log Likelihood Function Evaluation Time (seconds) = 1.0\n" results.close() + + +def _gradient_samples(model, samples_info): + parameters = [[1.0, 2.0], [1.2, 2.2]] + log_likelihood_list = [1.0, 0.0] + + return af.m.MockSamples( + model=model, + sample_list=af.Sample.from_lists( + parameter_lists=parameters, + log_likelihood_list=log_likelihood_list, + log_prior_list=[0.0, 0.0], + weight_list=log_likelihood_list, + model=model, + ), + samples_info=samples_info, + ) + + +def test__search_summary__nan_lane_step_counters(model): + """ + The gradient searches report both non-finite failure modes, plus rates + normalised by lane-steps (``n_starts * total_steps``) -- raw counts are not + comparable between runs of different size. + """ + samples = _gradient_samples( + model=model, + samples_info={ + "total_samples": 10, + "time": None, + "n_starts": 8, + "total_steps": 100, + "n_resurrections": 40, + "n_value_nan_lane_steps": 40, + "n_grad_nan_lane_steps": 8, + }, + ) + + summary = "".join(text_util.search_summary_from_samples(samples=samples)) + + assert "Resurrections = 40\n" in summary + assert "Value-NaN Lane-Steps = 40\n" in summary + assert "Gradient-NaN Lane-Steps = 8\n" in summary + + # 40 / (8 * 100) and 8 / (8 * 100). + assert "Value-NaN Lane-Step Rate = 0.05\n" in summary + assert "Gradient-NaN Lane-Step Rate = 0.01\n" in summary + + +def test__search_summary__nan_counters_absent_for_other_searches(model): + """ + ``search_summary_from_samples`` is on EVERY search's summary path, so a + search without the counters -- Nautilus, which is jit-only and has no + gradient to be non-finite -- must be completely unaffected. + """ + parameters = [[1.0, 2.0], [1.2, 2.2]] + log_likelihood_list = [1.0, 0.0] + + # MockSamplesNest, not MockSamples: Nautilus produces a SamplesNest, and + # `total_accepted_samples` (the neighbouring duck-typed block) only exists + # there. The samples_info below is Nautilus's real key set -- see + # `NautilusSearch.samples_info_from`. + samples = af.m.MockSamplesNest( + model=model, + sample_list=af.Sample.from_lists( + parameter_lists=parameters, + log_likelihood_list=log_likelihood_list, + log_prior_list=[0.0, 0.0], + weight_list=log_likelihood_list, + model=model, + ), + samples_info={ + "total_samples": 10, + "total_accepted_samples": 2, + "time": None, + "number_live_points": 1, + "log_evidence": 1.0, + }, + ) + + summary = "".join(text_util.search_summary_from_samples(samples=samples)) + + assert "NaN" not in summary + assert "Resurrections" not in summary + assert "Lane-Step" not in summary + + # The MCMC block it sits beside is untouched. + assert "Total Accepted Samples = 2\n" in summary + + +def test__search_summary__nan_rates_omitted_when_no_lane_steps_taken(model): + """ + A search that died before its first step has a zero denominator. The counts + still report; the rates are omitted rather than raising ZeroDivisionError. + """ + samples = _gradient_samples( + model=model, + samples_info={ + "total_samples": 10, + "time": None, + "n_starts": 8, + "total_steps": 0, + "n_resurrections": 0, + "n_value_nan_lane_steps": 0, + "n_grad_nan_lane_steps": 0, + }, + ) + + summary = "".join(text_util.search_summary_from_samples(samples=samples)) + + assert "Value-NaN Lane-Steps = 0\n" in summary + assert "Rate" not in summary