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 a352a4d42..c24a20d02 100644 --- a/autofit/non_linear/search/mle/multi_start_gradient/search.py +++ b/autofit/non_linear/search/mle/multi_start_gradient/search.py @@ -8,6 +8,7 @@ from autofit.mapper.prior_model.abstract import AbstractPriorModel +from autofit.non_linear.search.abstract_search import ITERATIONS_NEVER from autofit.non_linear.search.mle.abstract_mle import AbstractMLE from autofit.non_linear.analysis import Analysis from autofit.non_linear.fitness import Fitness @@ -311,13 +312,15 @@ def __init__( "... sampling complete", which on a long fit leaves a user unable to tell a live search from a hung one. - Neither of the framework's usual progress channels reaches this - search, which is why it needs its own: ``iterations_per_full_update`` + The framework's usual progress channels need help to reach this + search, which is why it has its own: ``iterations_per_full_update`` defaults to the never-sentinel, so the whole run is a single chunk whose lone ``perform_update`` is (correctly) suppressed as duplicated - work; and ``Fitness``'s quick-update counter is Python state mutated - inside ``fitness.call``, which is traced under ``jax.jit(jax.vmap(…))`` - here — it runs once at trace time and never again. The samplers dodge + work; and ``Fitness``'s own quick-update counter is Python state + mutated inside ``fitness.call``, which is traced under + ``jax.jit(jax.vmap(…))`` here — it would run once at trace time and + never again, so the step loop feeds the quick-update cadence itself + (see ``iterations_per_quick_update`` below). The samplers dodge the problem entirely by delegating to their own library's progress bar (emcee ``progress=True``, dynesty ``print_progress``); a search that owns its step loop has to report for itself. @@ -328,6 +331,28 @@ def __init__( than a progress bar: ``n_steps`` is a ceiling that auto-convergence routinely stops short of, so a bar's ETA would mislead, and lines survive SLURM/HPC log capture where bars do not. + iterations_per_quick_update + How many **gradient steps** pass between on-the-fly quick updates + of the maximum likelihood model (``analysis.perform_quick_update`` + on the current global-best point: the fast max-likelihood + visualization, e.g. a ``fit.png``, plus the live display paths + below). The unit is deliberately NOT the per-evaluation counting + ``Fitness`` does for the searches that count inside + ``Fitness.call_wrap`` — there a batch of ``n_starts`` evaluations + advances the counter by ``n_starts``, so a cadence of 50 with 48 + starts would fire roughly every second step. Here one gradient + step (which evaluates all ``n_starts`` lanes at once) advances the + counter by exactly one, driven from the host-side step loop via + ``_manage_quick_update_step`` because the traced + ``fitness.call`` cannot count (see ``iterations_per_log`` above). + Terminal steps skip the quick update — the framework performs the + full final update unconditionally when ``_fit`` returns. + live_visual_update + If ``True``, each quick update also refreshes a live view of the + fit (a matplotlib window in script mode, an in-place refreshed + cell in a notebook), through the same LiveDisplay / + BackgroundQuickUpdate machinery every other search uses. Requires + a finite ``iterations_per_quick_update``. """ super().__init__( @@ -429,6 +454,81 @@ def _is_final_boundary(self, converged: bool, total_steps: int) -> bool: """ return bool(converged) or total_steps >= self.n_steps + @property + def quick_update_message(self) -> str: + """ + The base-class message calls the cadence unit "iterations", which for + the searches that count inside ``Fitness.call_wrap`` means likelihood + evaluations — counted per batch, so ``n_starts`` at a time. This search + drives the cadence from its own host-side step loop instead (see + ``_manage_quick_update_step``), where the unit is **gradient steps**, + each of which evaluates all ``n_starts`` lanes at once. Saying so keeps + the startup line honest: before PyAutoFit#1552 this line announced a + cadence these searches then silently ignored, and a unit the search + does not count in is only a smaller version of the same false claim. + """ + iterations = self.iterations_per_quick_update + + if not np.isfinite(iterations) or iterations >= ITERATIONS_NEVER: + return super().quick_update_message + + return ( + "On-the-fly updates of the maximum likelihood model every " + f"{int(iterations)} gradient steps (each step evaluates all " + f"{self.n_starts} starts; progress log lines follow the separate " + "`iterations_per_log` cadence)." + ) + + def _manage_quick_update_step(self, fitness: Fitness, best_params, best_fom): + """ + Feed one gradient step into ``Fitness``'s quick-update machinery. + + ``fitness.call`` is traced under ``jax.jit(jax.vmap(...))`` here, so + the usual counting in ``Fitness.call_wrap`` can never run — the + Python-side counter would tick once at trace time and never again, + which is why these searches ignored ``iterations_per_quick_update`` + entirely before PyAutoFit#1552. The step loop is plain host Python + (the same seam ``iterations_per_log`` uses), so the cadence is driven + from it instead: one call per step, passing the current global-best + point as a single scalar evaluation, which makes + ``Fitness.quick_update_count`` count **gradient steps** — each of + which evaluates all ``n_starts`` lanes — rather than the + per-evaluation batch counting the ``call_wrap`` searches get. The two + countings never mix: this search's evaluations bypass ``call_wrap`` + by construction, so this is the sole feeder of the counter. The fire + path itself (``analysis.perform_quick_update``, the results text, + LiveDisplay / BackgroundQuickUpdate) runs unmodified. + + Skipped while the global best is not yet finite: there is no model + worth visualizing before the first finite evaluation, and firing would + hand ``instance_from_vector`` a ``None``. In practice + ``_broad_starts`` filters the initial draws to finite objectives, so + the guard only bites on a run whose every lane dies immediately. + + Parameters + ---------- + fitness + The ``Fitness`` built by ``_fit``, carrying the quick-update + cadence and display machinery. + best_params + The global-best parameter vector, in PHYSICAL units (the loop + maintains that invariant for ``samples_via_internal_from``). + best_fom + The global-best figure of merit (``-2 * log_posterior``). + """ + if fitness.iterations_per_quick_update is None: + return + + if not np.isfinite(best_fom): + return + + log_likelihood = fitness.log_likelihood_from( + figure_of_merit=best_fom, parameters=best_params + ) + fitness.manage_quick_update( + parameters=best_params, log_likelihood=float(log_likelihood) + ) + @staticmethod def _nan_lane_counts(foms, grad_finite): """ @@ -813,6 +913,23 @@ def _fit( "backend." ) + # ``fitness.call`` is differentiated inside ``jax.jit(jax.vmap(...))`` + # below, so the per-evaluation quick-update counting that fires from + # ``Fitness.call_wrap`` can never run here — the step loop drives the + # cadence itself via ``_manage_quick_update_step`` (one count per + # gradient step). The kwargs are still forwarded so ``Fitness`` owns + # the LiveDisplay / BackgroundQuickUpdate setup through the exact path + # every other search uses. The never-sentinel maps to ``None`` so a + # disabled cadence is disabled *inside* ``Fitness`` too: no + # visualization warm-up at construction, and + # ``_manage_quick_update_step`` short-circuits to zero per-step work. + iterations_per_quick_update = ( + None + if not np.isfinite(self.iterations_per_quick_update) + or self.iterations_per_quick_update >= ITERATIONS_NEVER + else self.iterations_per_quick_update + ) + fitness = Fitness( model=model, analysis=analysis, @@ -820,6 +937,9 @@ def _fit( fom_is_log_likelihood=False, resample_figure_of_merit=-np.inf, convert_to_chi_squared=True, + iterations_per_quick_update=iterations_per_quick_update, + background_quick_update=self.quick_update_background, + live_visual_update=self.live_visual_update, ) # -2 * log_posterior, to MINIMIZE. value_and_grad over every start. @@ -1432,6 +1552,21 @@ def batched_value_and_grad(params): ) previous_logged_fom = best_fom + # On-the-fly quick updates, at ``iterations_per_quick_update`` + # cadence in GRADIENT STEPS (see ``_manage_quick_update_step``). + # Skipped at a terminal step for the same reason + # ``perform_update`` is skipped at a terminal boundary below: + # ``start_resume_fit`` performs the final update unconditionally + # the moment ``_fit`` returns, so one here is duplicated work. + if not self._is_final_boundary( + converged=converged, total_steps=total_steps + ): + self._manage_quick_update_step( + fitness=fitness, + best_params=best_params, + best_fom=best_fom, + ) + if converged: break @@ -1540,6 +1675,16 @@ def batched_value_and_grad(params): self.logger.info(f"{self.optax_method} MultiStartGradient sampling complete.") + # The step loop above is the sole feeder of the quick-update counter + # (the traced ``fitness.call`` bypasses ``call_wrap``), but the final + # update's likelihood profiling calls ``fitness.call_wrap`` directly + # after ``_fit`` returns — and those evaluations would keep advancing + # the counter and could fire a quick update the unconditional final + # update supersedes. Disabling the cadence here closes that path; the + # display machinery is shut down separately by ``start_resume_fit`` + # via ``shutdown_quick_update``. + fitness.iterations_per_quick_update = None + return search_internal, fitness def _resolve_optax_rule(self, optax): 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 00532ca6b..7caaa9b87 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 @@ -19,7 +19,12 @@ # plumbing (config knobs, dict round-trip, and the internal-results -> Samples # mapping) is pure NumPy and is tested here. The end-to-end JAX/optax fit that # recovers a truth basin is validated in autofit_workspace_test, keeping JAX out -# of the library unit suite. +# of the library unit suite — with one deliberate exception: the quick-update +# cadence tests at the bottom of this file drive the real step loop (guarded by +# `pytest.importorskip`), because the defect they pin (PyAutoFit#1552: the +# cadence announced in the startup log silently never fired) lived precisely in +# the gap between the constructed knobs and the running loop, which no +# source-level or plumbing check can see. pytestmark = pytest.mark.filterwarnings("ignore::FutureWarning") @@ -1425,3 +1430,146 @@ def test__a_logit_on_the_ell_comps_pair_is_refused_before_the_first_step(): ) assert "(0, 1)" in str(exc_info.value) + + +# -------------------------------------------------------------------------- +# Quick-update wiring (PyAutoFit#1552). These drive the REAL step loop — the +# file-header exception — because the defect lived between the constructed +# knobs and the running loop: `iterations_per_quick_update` was accepted, +# stored and announced in the startup log, and then never fired, since the +# counter in `Fitness.call_wrap` sits inside the jit/vmap trace. +# -------------------------------------------------------------------------- + + +def _quick_update_fit(n_steps, iterations_per_quick_update=None, name=None): + """Run a real (tiny) MultiStartAdam fit on a JAX-traceable quadratic and + return how many times `analysis.perform_quick_update` fired. + + The count lives in a closure list rather than on the analysis instance so + the assertion cannot be defeated by the framework copying the analysis + between construction and the step loop. + """ + pytest.importorskip("jax") + pytest.importorskip("optax") + + calls = [] + + class QuickUpdateCountingAnalysis(af.Analysis): + def log_likelihood_function(self, instance): + xp = self._xp + values = xp.asarray([instance.one, instance.two]) + return -0.5 * xp.sum(values**2) + + def perform_quick_update(self, paths, instance): + calls.append(instance) + + model = af.Model(af.m.MockClassx2) + model.one = af.UniformPrior(lower_limit=-5.0, upper_limit=5.0) + model.two = af.UniformPrior(lower_limit=-5.0, upper_limit=5.0) + + search = af.MultiStartAdam( + name=name, + n_starts=4, + n_steps=n_steps, + iterations_per_quick_update=iterations_per_quick_update, + ) + + search.fit(model=model, analysis=QuickUpdateCountingAnalysis(use_jax=True)) + + return calls + + +def test__quick_update__fires_once_per_cadence_boundary_in_gradient_steps(): + """The Witness of the fix: a finite cadence fires `perform_quick_update` + once per cadence boundary of the step loop, counted in GRADIENT STEPS. + + n_steps=7 at a cadence of 3 fires at steps 3 and 6 (step 7 is terminal — + covered by the framework's unconditional final update). The same run under + the per-evaluation batch counting `Fitness` does for the `call_wrap` + searches would advance the counter by `n_starts=4 >= 3` every step and + fire at every non-terminal step: asserting exactly 2 pins the unit as + well as the wiring. + """ + calls = _quick_update_fit( + n_steps=7, iterations_per_quick_update=3, name="quick_update_cadence" + ) + + assert len(calls) == 2 + + +def test__quick_update__terminal_boundary_is_skipped(): + """A cadence boundary that lands on the final step must NOT fire: + `start_resume_fit` performs the full final update unconditionally the + moment `_fit` returns, so a quick update there is duplicated work (the + same doctrine as `_is_final_boundary` skipping `perform_update`).""" + calls = _quick_update_fit( + n_steps=6, iterations_per_quick_update=3, name="quick_update_terminal" + ) + + assert len(calls) == 1 + + +def test__quick_update__default_never_sentinel_stays_silent(): + """The packaged default is the `ITERATIONS_NEVER` sentinel: no quick + update fires, and (because `_fit` maps the sentinel to `None` before + building its `Fitness`) none of the quick-update machinery — warm-up + included — is set up for a run that never uses it.""" + calls = _quick_update_fit(n_steps=4, name="quick_update_disabled") + + assert len(calls) == 0 + + +def test__quick_update_message__states_the_gradient_step_unit(): + """The startup line was the false claim of PyAutoFit#1552 — and once the + cadence is real, announcing it in a unit the search does not count in + would be a smaller version of the same lie. The override states the unit; + the disabled branch defers to the base-class message.""" + search = af.MultiStartAdam(n_starts=8, iterations_per_quick_update=50) + + assert "every 50 gradient steps" in search.quick_update_message + assert "8 starts" in search.quick_update_message + + disabled = af.MultiStartAdam() + + assert "disabled" in disabled.quick_update_message + + +def test__manage_quick_update_step__guards_the_disabled_and_prestart_states(): + """The per-step feeder must cost nothing when the cadence is off, and must + not hand `instance_from_vector` a `None` before the first finite + evaluation (a run whose every lane dies immediately).""" + + class RecordingFitness: + def __init__(self, iterations_per_quick_update): + self.iterations_per_quick_update = iterations_per_quick_update + self.fed = [] + + def log_likelihood_from(self, figure_of_merit, parameters): + return -0.5 * figure_of_merit + + def manage_quick_update(self, parameters, log_likelihood): + self.fed.append((parameters, log_likelihood)) + + search = af.MultiStartAdam() + params = np.array([0.1, 0.2]) + + disabled = RecordingFitness(iterations_per_quick_update=None) + search._manage_quick_update_step( + fitness=disabled, best_params=params, best_fom=1.0 + ) + assert disabled.fed == [] + + prestart = RecordingFitness(iterations_per_quick_update=3) + search._manage_quick_update_step( + fitness=prestart, best_params=params, best_fom=np.inf + ) + assert prestart.fed == [] + + live = RecordingFitness(iterations_per_quick_update=3) + search._manage_quick_update_step( + fitness=live, best_params=params, best_fom=4.0 + ) + assert len(live.fed) == 1 + fed_params, fed_log_likelihood = live.fed[0] + assert fed_params is params + assert fed_log_likelihood == -2.0 diff --git a/test_autofit/non_linear/search/mle/test_multi_start_quick_update_termination.py b/test_autofit/non_linear/search/mle/test_multi_start_quick_update_termination.py index f39e3ab0b..753399544 100644 --- a/test_autofit/non_linear/search/mle/test_multi_start_quick_update_termination.py +++ b/test_autofit/non_linear/search/mle/test_multi_start_quick_update_termination.py @@ -76,13 +76,12 @@ def test__quick_update_mid_search_does_not_end_the_search(): assert int(search_internal["total_steps"]) == 60 assert search_internal["stop_reason"] == "max_steps" - # Today the cadence is INERT for this family: the search is an ``EXEMPT`` - # entry in ``test_quick_update_wiring.py`` (the traced ``fitness.call`` - # cannot count Python-side), so no quick update fires at all — asserted, - # so this test is sensitive to the knob's state rather than vacuously - # green. The change that wires real quick updates into the step loop MUST - # flip this to assert the updates FIRED (> 0) while keeping the two - # ceiling asserts above unchanged — that is the moment "a quick update - # mid-search does not end the search" is exercised for real, and a silent - # no-op (the PyAutoFit#1434 failure class) becomes a loud failure here. - assert analysis.quick_update_count == 0 + # The cadence is LIVE for this family since the multi-start step loop + # wires ``iterations_per_quick_update`` (PyAutoFit#1552): quick updates + # fire at the cadence boundaries, and the two ceiling asserts above prove + # firing mid-search does not end the search — the real exercise of "a + # quick update mid-search does not end the search", where a silent no-op + # (the PyAutoFit#1434 failure class) or a boundary-triggered stop both + # fail loudly. This flipped the inertness tripwire the test originally + # carried (``== 0``), exactly as that tripwire's comment demanded. + assert analysis.quick_update_count > 0 diff --git a/test_autofit/non_linear/search/test_quick_update_message.py b/test_autofit/non_linear/search/test_quick_update_message.py index d5a857477..112c46508 100644 --- a/test_autofit/non_linear/search/test_quick_update_message.py +++ b/test_autofit/non_linear/search/test_quick_update_message.py @@ -22,7 +22,7 @@ def test__real_cadence_renders_as_a_plain_integer(): # The knob is stored as a float (so ``search.json`` keeps a readable # ``1e99`` rather than a 99-digit integer), so the message has to cast -- # otherwise a user configuring 250000 is told "every 250000.0 iterations". - search = af.MultiStartAdam(n_steps=3000, iterations_per_quick_update=250000) + search = af.Emcee(iterations_per_quick_update=250000) assert isinstance(search.iterations_per_quick_update, float) @@ -32,6 +32,18 @@ def test__real_cadence_renders_as_a_plain_integer(): assert "250000.0" not in message assert "disabled" not in message + # The multi-start gradient searches drive the cadence from their own step + # loop, so their override reports the unit they actually count in -- + # gradient steps, not per-evaluation iterations (PyAutoFit#1552) -- and + # must make the same integer cast. + search = af.MultiStartAdam(n_steps=3000, iterations_per_quick_update=250000) + + message = search.quick_update_message + + assert "every 250000 gradient steps" in message + assert "250000.0" not in message + assert "disabled" not in message + def test__default_sentinel_says_disabled_and_names_the_config_key(): # The packaged default is 1e99 — updates never fire. Reporting that as @@ -65,6 +77,10 @@ def test__any_never_sized_cadence_reads_as_disabled(never): def test__a_cadence_of_one_still_reads_as_a_number(): # Guards the boundary from the other side: the disabled branch must not # swallow small real cadences. - search = af.MultiStartAdam(n_steps=300, iterations_per_quick_update=1) + search = af.Emcee(iterations_per_quick_update=1) assert "every 1 iterations" in search.quick_update_message + + search = af.MultiStartAdam(n_steps=300, iterations_per_quick_update=1) + + assert "every 1 gradient steps" in search.quick_update_message diff --git a/test_autofit/non_linear/search/test_quick_update_wiring.py b/test_autofit/non_linear/search/test_quick_update_wiring.py index f77617eb1..58204d8e4 100644 --- a/test_autofit/non_linear/search/test_quick_update_wiring.py +++ b/test_autofit/non_linear/search/test_quick_update_wiring.py @@ -31,12 +31,12 @@ "search's own outer loop instead: `iterations_per_quick_update` is " "consumed directly in `_fit` via `_fire_quick_update`." ), - "mle/multi_start_gradient/search.py": ( - "MultiStartGradient differentiates `fitness.call` inside its own " - "jit/vmap step loop, so the Python-side counter in `call_wrap` would run " - "once at trace time rather than per step. Its progress reporting is " - "handled separately -- see PyAutoFit#1433." - ), + # mle/multi_start_gradient/search.py was exempt here from PyAutoFit#1433 + # (its `fitness.call` is differentiated inside jit/vmap, so the counter in + # `call_wrap` cannot run) until PyAutoFit#1552 wired the cadence through + # the host-side step loop instead: the search now forwards the kwarg to its + # `Fitness` and feeds the counter one gradient step at a time via + # `_manage_quick_update_step`. }