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 3c8db9127..129014d98 100644 --- a/autofit/non_linear/search/mle/multi_start_gradient/search.py +++ b/autofit/non_linear/search/mle/multi_start_gradient/search.py @@ -83,7 +83,11 @@ def __init__( single-start, line-search or second-order optimizer on the kinked likelihoods this promotes from (see the Phase-3 GPU MAP-optimizer benchmark). The best-basin start is returned as the maximum-log-posterior - (MAP) point, with every start's final point retained as a diagnostic. + (MAP) point, with every start's final point retained as a diagnostic, + and each start's own best (position, figure-of-merit, step index) + preserved in ``search_internal`` (``lane_best_*``) for per-start basin + classification — a final point can leave its best basin late, die, or + pin to a bound after its best step. The method is JAX-native: it requires an ``Analysis`` whose ``log_likelihood_function`` is JAX-traceable (``use_jax=True``) and the @@ -360,6 +364,42 @@ def _nan_lane_counts(foms, grad_finite): return alive, n_value_nan, n_grad_nan + @staticmethod + def _lane_best_update( + lane_best_params, + lane_best_foms, + lane_best_steps, + foms_np, + gather_physical, + step, + ): + """ + Update the per-lane best records (in place) for one step. + + Diagnostics only — never gates a redraw or a step, the same rule as + :meth:`_nan_lane_counts`. ``foms_np`` is the alive-masked + figure-of-merit vector (dead lanes carry ``inf``), so a dead lane can + never improve on its record. The comparison is strict, so a tie keeps + the EARLIEST best step — a plateaued lane does not creep its step + index forward. + + ``gather_physical`` maps improved lane indices to their PHYSICAL + parameter rows and is called only when some lane improved — in + ``_fit`` it is the device->host copy (plus the scaler multiply), which + this laziness keeps off the no-improvement steps. + + 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 + ``_nan_lane_counts`` above). + """ + improved = foms_np < lane_best_foms + if improved.any(): + improved_idx = np.flatnonzero(improved) + lane_best_params[improved_idx] = gather_physical(improved_idx) + lane_best_foms[improved_idx] = foms_np[improved_idx] + lane_best_steps[improved_idx] = step + @staticmethod def _constrained_lane_count(alive, grad_finite, constraint_violation): """ @@ -850,6 +890,33 @@ def batched_value_and_grad(params): n_clipped_lane_steps = int(search_internal.get("n_clipped_lane_steps", 0)) stop_reason = search_internal.get("stop_reason", None) + # ``.get``: a ``search_internal`` written before per-lane best + # tracking existed has none of these keys, and a resumed run must + # not KeyError on it. The old run's per-lane history is + # unrecoverable, so tracking re-seeds (params from the restored + # finals — PHYSICAL, like everything in the file — with ``inf`` + # foms) rather than being back-filled, the same doctrine as + # ``alive_history`` above. + # ``np.array`` (copies), not ``np.asarray``: the update writes in + # place, and a zero-copy view would be READ-ONLY for a device + # array and would alias the loaded dict's own array for the + # legacy-fallback seed. + lane_best_params = np.array( + search_internal.get("lane_best_params", search_internal["params"]) + ) + lane_best_foms = np.array( + search_internal.get( + "lane_best_foms", np.full(len(lane_best_params), np.inf) + ), + dtype=float, + ) + lane_best_steps = np.array( + search_internal.get( + "lane_best_steps", np.zeros(len(lane_best_params), dtype=int) + ), + dtype=int, + ) + self.logger.info( "Resuming MultiStartGradient search (previous samples found)." ) @@ -897,6 +964,18 @@ def batched_value_and_grad(params): best_params = np.asarray(params[0]) + # Per-lane best tracking (position, figure-of-merit, step index). + # Diagnostics only — never gates a redraw or a step, the same rule + # as the NaN-lane counters. Seeded here while ``params`` is still + # PHYSICAL (the scaler divide happens below), so the array is in + # the same units as ``best_params`` from step zero; ``inf`` foms + # mark "no finite evaluation captured yet". ``np.array`` (a copy), + # not ``np.asarray``: a zero-copy view of a device array is + # READ-ONLY and the update writes in place. + lane_best_params = np.array(params) + lane_best_foms = np.full(self.n_starts, np.inf) + lane_best_steps = np.zeros(self.n_starts, dtype=int) + if has_scaler: params = params / scale_jnp @@ -999,6 +1078,23 @@ def batched_value_and_grad(params): if has_scaler: best_params = best_params * scale + # Per-lane best capture, PHYSICAL for the same reason as + # ``best_params`` just above. The step index is the + # pre-increment ``total_steps``, which is exactly this step's + # index into ``fom_history`` — including across resumes. + self._lane_best_update( + lane_best_params=lane_best_params, + lane_best_foms=lane_best_foms, + lane_best_steps=lane_best_steps, + foms_np=foms_np, + gather_physical=lambda idx: ( + np.asarray(params[idx]) * scale + if has_scaler + else np.asarray(params[idx]) + ), + step=total_steps, + ) + fom_history.append(best_fom) # The size of the living population at this step. Recorded as a @@ -1033,6 +1129,16 @@ def batched_value_and_grad(params): rng=resurrect_rng, scale=scale, ) + # A resurrected slot is a NEW start: its per-lane record + # resets rather than conflating two starts' basins in one + # slot (the record answers "which basin did this start + # find", not "what is the best this slot ever held" — the + # global ``best_*`` already keeps the latter). NaN params + # + ``inf`` fom mark "no finite eval since redraw" without + # paying a device->host copy of the fresh draws here. + lane_best_params[dead_idx] = np.nan + lane_best_foms[dead_idx] = np.inf + lane_best_steps[dead_idx] = total_steps updates, opt_state = step_update(grads, opt_state, params, foms) params = optax.apply_updates(params, updates) @@ -1141,6 +1247,11 @@ def batched_value_and_grad(params): "opt_state": opt_state, "best_params": best_params, "best_fom": best_fom, + # Per-lane bests, PHYSICAL like ``params``/``best_params`` + # above; ``lane_best_steps`` indexes into ``fom_history``. + "lane_best_params": lane_best_params, + "lane_best_foms": lane_best_foms, + "lane_best_steps": lane_best_steps, "fom_history": np.asarray(fom_history), "alive_history": np.asarray(alive_history), "total_steps": total_steps, 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 46af6de3d..e1ad58b0f 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 @@ -1006,3 +1006,161 @@ def test__batch_size_within_budget__degenerate_inputs( fixed, per_start, n_starts, budget, expected ): assert batch_size_within_budget(fixed, per_start, n_starts, budget) == expected + + +# --- Per-lane best preservation (PyAutoFit#1514) ------------------------------ +# +# Same contract as the _nan_lane_counts tests above: the update rule is pure +# NumPy and tested directly; the _fit loop that drives it (and its resume / +# resurrection seams) is JAX and is pinned by source-level wiring guards. + + +def test__lane_best_update__captures_improvements_and_leaves_the_rest(): + lane_best_params = np.full((3, 2), np.nan) + lane_best_foms = np.array([np.inf, 10.0, 5.0]) + lane_best_steps = np.array([0, 3, 4]) + + physical = np.array([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]]) + + af.MultiStartAdam._lane_best_update( + lane_best_params=lane_best_params, + lane_best_foms=lane_best_foms, + lane_best_steps=lane_best_steps, + # lane 0: first finite eval; lane 1: improves; lane 2: worsens. + foms_np=np.array([100.0, 7.0, 9.0]), + gather_physical=lambda idx: physical[idx], + step=8, + ) + + assert lane_best_foms.tolist() == [100.0, 7.0, 5.0] + assert lane_best_params[0].tolist() == [1.0, 2.0] + assert lane_best_params[1].tolist() == [3.0, 4.0] + # the unimproved lane's record is untouched, NaN params included. + assert np.isnan(lane_best_params[2]).all() + assert lane_best_steps.tolist() == [8, 8, 4] + + +def test__lane_best_update__dead_lanes_never_improve(): + # ``foms_np`` arrives alive-masked (dead lanes carry inf), so a dead lane + # can never beat any record — including an inf one (inf < inf is False). + lane_best_params = np.zeros((2, 1)) + lane_best_foms = np.array([3.0, np.inf]) + lane_best_steps = np.array([2, 0]) + + af.MultiStartAdam._lane_best_update( + lane_best_params=lane_best_params, + lane_best_foms=lane_best_foms, + lane_best_steps=lane_best_steps, + foms_np=np.array([np.inf, np.inf]), + gather_physical=lambda idx: pytest.fail("no lane improved"), + step=9, + ) + + assert lane_best_foms.tolist() == [3.0, np.inf] + assert lane_best_steps.tolist() == [2, 0] + + +def test__lane_best_update__ties_keep_the_earliest_step(): + # Strict comparison: a plateaued lane does not creep its best-step index + # forward, so "steps after best" stays an honest waste measure. + lane_best_params = np.array([[7.0]]) + lane_best_foms = np.array([5.0]) + lane_best_steps = np.array([4]) + + af.MultiStartAdam._lane_best_update( + lane_best_params=lane_best_params, + lane_best_foms=lane_best_foms, + lane_best_steps=lane_best_steps, + foms_np=np.array([5.0]), + gather_physical=lambda idx: pytest.fail("a tie is not an improvement"), + step=9, + ) + + assert lane_best_foms.tolist() == [5.0] + assert lane_best_steps.tolist() == [4] + assert lane_best_params.tolist() == [[7.0]] + + +def test__lane_best_update__gather_is_lazy_and_improved_only(): + # ``gather_physical`` is the device->host copy in ``_fit``; it must be + # called once, only when something improved, and only with the improved + # lane indices — not the full population. + calls = [] + + def gather(idx): + calls.append(np.asarray(idx).tolist()) + return np.zeros((len(idx), 1)) + + lane_best_params = np.ones((3, 1)) + lane_best_foms = np.array([1.0, 2.0, 3.0]) + lane_best_steps = np.array([0, 0, 0]) + + af.MultiStartAdam._lane_best_update( + lane_best_params=lane_best_params, + lane_best_foms=lane_best_foms, + lane_best_steps=lane_best_steps, + foms_np=np.array([5.0, 1.5, 5.0]), + gather_physical=gather, + step=1, + ) + + assert calls == [[1]] + assert lane_best_params.tolist() == [[1.0], [0.0], [1.0]] + + +def test__lane_best_update__is_monotone_across_repeated_calls(): + lane_best_params = np.full((2, 1), np.nan) + lane_best_foms = np.array([np.inf, np.inf]) + lane_best_steps = np.array([0, 0]) + + trajectory = [ + np.array([9.0, 4.0]), + np.array([7.0, 6.0]), # lane 1 worsens: record must hold at 4.0 + np.array([8.0, 3.0]), # lane 0 worsens: record must hold at 7.0 + ] + for step, foms in enumerate(trajectory): + af.MultiStartAdam._lane_best_update( + lane_best_params=lane_best_params, + lane_best_foms=lane_best_foms, + lane_best_steps=lane_best_steps, + foms_np=foms, + gather_physical=lambda idx: foms[idx][:, None], + step=step, + ) + + assert lane_best_foms.tolist() == [7.0, 3.0] + assert lane_best_steps.tolist() == [1, 2] + # every record is the min of that lane's own trajectory — the global best + # is then min over lanes by construction. + assert lane_best_foms.min() == min(min(f) for f in trajectory) + + +def test__fit_wires_the_per_lane_best_seams(): + """Wiring guard for the per-lane best records (PyAutoFit#1514), which are + otherwise tested in isolation and would keep passing if ``_fit`` stopped + maintaining them. + + Necessarily a source-level check — ``_fit`` cannot run from this suite. + """ + source = " ".join(inspect.getsource(af.MultiStartAdam._fit).split()) + + # the per-step capture, driven by the alive-masked foms at the + # pre-increment step index (= this step's fom_history index). + assert "self._lane_best_update(" in source + assert "foms_np=foms_np" in source + assert "step=total_steps" in source + + # all three records are persisted for the profiling reader / resume. + assert '"lane_best_params": lane_best_params' in source + assert '"lane_best_foms": lane_best_foms' in source + assert '"lane_best_steps": lane_best_steps' in source + + # resume restores defensively: a legacy search_internal re-seeds from the + # restored finals rather than KeyError-ing. + assert 'search_internal.get("lane_best_params", search_internal["params"])' in source + + # a resurrected slot is a NEW start: its record resets rather than + # conflating two starts' basins in one slot. + assert "lane_best_params[dead_idx] = np.nan" in source + assert "lane_best_foms[dead_idx] = np.inf" in source + assert "lane_best_steps[dead_idx] = total_steps" in source