diff --git a/autofit/non_linear/search/execution.py b/autofit/non_linear/search/execution.py index a74fc5170..75aab13e1 100644 --- a/autofit/non_linear/search/execution.py +++ b/autofit/non_linear/search/execution.py @@ -67,6 +67,9 @@ class SearchExecutionMixin: # Whether `ctx.start_points` makes the start-point plot. `Drawer` draws its whole # result through the initializer, so it has no starting point to plot. _plots_start_point = True + # Whether `ctx.start_points` lets the initializer return its test-mode samples under + # `PYAUTO_TEST_MODE=1` (`test_mode_samples`); `Zeus` draws real start points. + _start_points_in_test_mode = True def _run_bridge(self, model: AbstractPriorModel, analysis: Analysis): """ diff --git a/autofit/non_linear/search/fit_context.py b/autofit/non_linear/search/fit_context.py index e5f143d3c..bfbda1ec7 100644 --- a/autofit/non_linear/search/fit_context.py +++ b/autofit/non_linear/search/fit_context.py @@ -116,6 +116,7 @@ def start_points(self, n: int): fitness=self.fitness, n=n, plot=self._search._plots_start_point, + test_mode_samples=self._search._start_points_in_test_mode, ) return np.asarray(parameter_lists), np.asarray(figure_of_merit_list) diff --git a/autofit/non_linear/search/mcmc/emcee/search.py b/autofit/non_linear/search/mcmc/emcee/search.py index 2d3a6c367..6c658c1f6 100644 --- a/autofit/non_linear/search/mcmc/emcee/search.py +++ b/autofit/non_linear/search/mcmc/emcee/search.py @@ -24,7 +24,6 @@ from autofit.non_linear.test_mode import is_test_mode from autofit.non_linear.samples.adapter import ChainPosterior, RawSamples from autofit.non_linear.search import capabilities as cap -from autofit.non_linear.search.seed import backend_random_state if TYPE_CHECKING: from autofit.database.sqlalchemy_ import sa @@ -140,29 +139,24 @@ def __init__( self.logger.debug("Creating Emcee Search") - def _fit(self, model: AbstractPriorModel, analysis): + def run(self, ctx): """ - Fit a model using Emcee and the Analysis class which contains the data and returns the log likelihood from - instances of the model, which the `NonLinearSearch` seeks to maximize. + Run emcee (the ``run(ctx)`` hook; see ``docs/design/run_ctx.md``) and return the + ``emcee.EnsembleSampler``. + + emcee's HDF backend (``search_internal/search_internal.hdf``) is both the archive + and the resume state: a resumed run reopens it, continues from its last sample + and samples only the remaining steps. Likelihoods are spread over the fit's + ``SneakyPool`` (``ctx.pool.sneaky``), which is ``None`` on one core. Parameters ---------- - model : ModelMapper - The model which generates instances for different points in parameter space. - analysis : Analysis - Contains the data and the log likelihood function which fits an instance of the model to the data, returning - the log likelihood the `NonLinearSearch` maximizes. - - Returns - ------- - A result object comprising the Samples object that inclues the maximum log likelihood instance and full - chains used by the fit. + ctx + The fit's ``FitContext``. """ import emcee - fitness = self.make_fitness(analysis=analysis, model=model) - - pool = self.make_sneaky_pool(fitness) + model = ctx.model try: backend = emcee.backends.HDFBackend(filename=self.backend_filename) @@ -172,17 +166,18 @@ def _fit(self, model: AbstractPriorModel, analysis): search_internal = emcee.EnsembleSampler( nwalkers=self.nwalkers, ndim=model.prior_count, - log_prob_fn=fitness.call_wrap, + log_prob_fn=ctx.fitness.call_wrap, backend=backend, - pool=pool, + pool=ctx.pool.sneaky(ctx.fitness), ) - # Backend stream 1 of the search-level seed (`autofit.non_linear.search.seed`); - # emcee otherwise copies numpy's global state. A resumed run restores the state - # its HDF backend saved. - random_state = backend_random_state(self) - if random_state is not None: - search_internal._random = random_state + # Backend stream 1 of the search-level seed (`ctx.rng`, whose stream 0 the + # initializer already took); emcee otherwise copies numpy's global state. A + # resumed run restores the state its HDF backend saved. + if self.seed is not None: + search_internal._random = np.random.RandomState( + np.random.MT19937(ctx.rng.spawn(1)[0]) + ) try: state = search_internal.get_last_sample() @@ -200,32 +195,19 @@ def _fit(self, model: AbstractPriorModel, analysis): ) except AttributeError: - ( - unit_parameter_lists, - parameter_lists, - log_posterior_list, - ) = self.start_points( - model=model, - fitness=fitness, - n=search_internal.nwalkers, - ) - - state = np.zeros(shape=(search_internal.nwalkers, model.prior_count)) + state, _ = ctx.start_points(search_internal.nwalkers) self.logger.info( "Starting new Emcee non-linear search (no previous samples found)." ) - for index, parameters in enumerate(parameter_lists): - state[index, :] = np.asarray(parameters) - total_iterations = 0 iterations_remaining = self.nsteps while iterations_remaining > 0: # ``emcee``'s ``sample`` does ``range(iterations)`` internally and # never casts, so this must be an ``int`` (PyAutoFit#1422). - iterations = self._steps_until_full_update(iterations_remaining) + iterations = ctx.schedule.next_budget(total_iterations, self.nsteps) for sample in search_internal.sample( initial_state=state, @@ -252,15 +234,9 @@ def _fit(self, model: AbstractPriorModel, analysis): iterations_remaining = 0 if iterations_remaining > 0: - self.perform_update( - model=model, - analysis=analysis, - search_internal=search_internal, - fitness=fitness, - during_analysis=True, - ) + ctx.update(search_internal) - return search_internal, fitness + return search_internal def samples_info_from(self, search_internal=None, auto_correlations=None): search_internal = search_internal or self.backend diff --git a/autofit/non_linear/search/mcmc/zeus/search.py b/autofit/non_linear/search/mcmc/zeus/search.py index 97ac769ff..44c6988d2 100644 --- a/autofit/non_linear/search/mcmc/zeus/search.py +++ b/autofit/non_linear/search/mcmc/zeus/search.py @@ -45,6 +45,10 @@ class Zeus(NonLinearSearch): test_mode_budget = {"nwalkers": 20, "nsteps": 10} objective_target = cap.ObjectiveTarget(cap.ObjectiveQuantity.LOG_POSTERIOR, cap.CoordinateSpace.PHYSICAL) invalid_value = -float("inf") + # Zeus has always drawn its walkers' start points through the initializer under + # ``PYAUTO_TEST_MODE=1`` too (``test_mode_samples=False``), so ``ctx.start_points`` + # does not substitute the initializer's test-mode samples for it. + _start_points_in_test_mode = False __identifier_fields__ = ( "nwalkers", @@ -152,23 +156,20 @@ def __init__( self.logger.debug("Creating Zeus Search") - def _fit(self, model: AbstractPriorModel, analysis): + def run(self, ctx): """ - Fit a model using Zeus and the Analysis class which contains the data and returns the log likelihood from - instances of the model, which the `NonLinearSearch` seeks to maximize. + Run Zeus (the ``run(ctx)`` hook; see ``docs/design/run_ctx.md``) and return the + ``zeus.EnsembleSampler``. + + The sampler is archived (``search_internal.dill``) after every chunk of steps; a + rerun of an interrupted fit continues from the archived sampler's last sample. + Likelihoods are spread over the fit's pool (``ctx.pool()``, ``None`` on one + core). Parameters ---------- - model : ModelMapper - The model which generates instances for different points in parameter space. - analysis : Analysis - Contains the data and the log likelihood function which fits an instance of the model to the data, returning - the log likelihood the `NonLinearSearch` maximizes. - - Returns - ------- - A result object comprising the Samples object that inclues the maximum log likelihood instance and full - chains used by the fit. + ctx + The fit's ``FitContext``. """ try: @@ -183,12 +184,10 @@ def _fit(self, model: AbstractPriorModel, analysis): "----------------------" ) - pool = self.make_pool() - - fitness = self.make_fitness(analysis=analysis, model=model) + model = ctx.model try: - search_internal = self.paths.load_search_internal() + search_internal = ctx.paths.load_search_internal() state = search_internal.get_last_sample() log_posterior_list = search_internal.get_last_log_prob() @@ -210,32 +209,19 @@ def _fit(self, model: AbstractPriorModel, analysis): search_internal = zeus.EnsembleSampler( nwalkers=self.nwalkers, ndim=model.prior_count, - logprob_fn=fitness.call_wrap, - pool=pool, + logprob_fn=ctx.fitness.call_wrap, + pool=ctx.pool(), ) search_internal.ncall_total = 0 - ( - unit_parameter_lists, - parameter_lists, - log_posterior_list, - ) = self.start_points( - model=model, - fitness=fitness, - n=search_internal.nwalkers, - test_mode_samples=False, - ) - - state = np.zeros(shape=(search_internal.nwalkers, model.prior_count)) + state, log_posterior_list = ctx.start_points(search_internal.nwalkers) + log_posterior_list = log_posterior_list.tolist() self.logger.info( "Starting new Zeus non-linear search (no previous samples found)." ) - for index, parameters in enumerate(parameter_lists): - state[index, :] = np.asarray(parameters) - total_iterations = 0 iterations_remaining = self.nsteps @@ -245,7 +231,7 @@ def _fit(self, model: AbstractPriorModel, analysis): # incremented by this value, so an uncast float would drift the # bookkeeping away from the samples zeus actually drew # (PyAutoFit#1422). - iterations = self._steps_until_full_update(iterations_remaining) + iterations = ctx.schedule.next_budget(total_iterations, self.nsteps) for sample in search_internal.sample( start=state, @@ -257,7 +243,7 @@ def _fit(self, model: AbstractPriorModel, analysis): search_internal.ncall_total += search_internal.ncall - self.paths.save_search_internal( + ctx.paths.save_search_internal( obj=search_internal, ) @@ -282,15 +268,9 @@ def _fit(self, model: AbstractPriorModel, analysis): iterations_remaining = 0 if iterations_remaining > 0: - self.perform_update( - model=model, - analysis=analysis, - search_internal=search_internal, - fitness=fitness, - during_analysis=True, - ) + ctx.update(search_internal) - return search_internal, fitness + return search_internal def samples_info_from(self, search_internal=None, auto_correlations=None): search_internal = search_internal or self.paths.load_search_internal() diff --git a/autofit/non_linear/search/mle/bfgs/search.py b/autofit/non_linear/search/mle/bfgs/search.py index ba675ddfd..01a1395de 100644 --- a/autofit/non_linear/search/mle/bfgs/search.py +++ b/autofit/non_linear/search/mle/bfgs/search.py @@ -217,42 +217,40 @@ def options(self): "maxls": self.maxls, } - def _fit( - self, - model: AbstractPriorModel, - analysis: Analysis, - ): + def fitness_overrides(self, analysis: Analysis) -> dict: """ - Fit a model using the scipy L-BFGS method and the Analysis class which contains the data and returns the log - likelihood from instances of the model, which the `NonLinearSearch` seeks to maximize. + The ``Fitness`` stores its evaluation history when the start point is plotted: + the samples are then the whole optimisation path (``raw_samples_from``). + """ + return {"store_history": self.should_plot_start_point} + + def run(self, ctx): + """ + Run scipy's ``minimize`` (the ``run(ctx)`` hook; see ``docs/design/run_ctx.md``) + and return its ``OptimizeResult``. + + The optimisation runs in chunks of ``iterations_per_full_update`` iterations, each + restarted from the last chunk's optimum, with the result archived + (``search_internal.dill``) and the fit updated between chunks. A JAX analysis + gives scipy the exact gradient of the ``"value_and_grad"`` objective; a numpy + analysis lets scipy take finite differences of the scalar objective. Parameters ---------- - model - The model which generates instances for different points in parameter space. - analysis - Contains the data and the log likelihood function which fits an instance of the model to the data, - returning the log likelihood the `NonLinearSearch` maximizes. - - Returns - ------- - A result object comprising the Samples object that inclues the maximum log likelihood instance and full - chains used by the fit. + ctx + The fit's ``FitContext``. """ from scipy import optimize + model = ctx.model + fitness = ctx.fitness + # Resolved once, before any stepping: an unsupported method should fail # immediately rather than after the first chunk of iterations. bounds = self._bounds_from(model=model) - fitness = self.make_fitness( - analysis=analysis, - model=model, - store_history=self.should_plot_start_point, - ) - try: - search_internal_dict = self.paths.load_search_internal() + search_internal_dict = ctx.paths.load_search_internal() x0 = search_internal_dict["x0"] total_iterations = search_internal_dict["total_iterations"] @@ -263,17 +261,9 @@ def _fit( except (FileNotFoundError, TypeError): - ( - unit_parameter_lists, - parameter_lists, - log_posterior_list, - ) = self.start_points( - model=model, - fitness=fitness, - n=1, - ) + parameters, _ = ctx.start_points(1) - x0 = np.asarray(parameter_lists[0]) + x0 = parameters[0] total_iterations = 0 @@ -283,11 +273,10 @@ def _fit( while total_iterations < self.maxiter: - iterations_remaining = self.maxiter - total_iterations # SciPy tolerates an integral float ``maxiter``, but a fractional one # would quietly acquire ceiling semantics instead of being rejected # (PyAutoFit#1422). - iterations = self._steps_until_full_update(iterations_remaining) + iterations = ctx.schedule.next_budget(total_iterations, self.maxiter) if iterations > 0: options = dict(self.options) @@ -304,7 +293,7 @@ def _fit( # box makes the objective non-finite on either branch. Bounds are # passed on both — they are correct on both, and having them # diverge by branch would be a trap of its own. - if analysis.is_jax: + if fitness.analysis.is_jax: # The exact gradient from the "value_and_grad" objective, one jitted # call per step: no finite differences (which cost n_params + 1 @@ -341,26 +330,20 @@ def _fit( search_internal.parameters_history_list = fitness.parameters_history_list search_internal.log_likelihood_history_list = fitness.log_likelihood_history_list - self.paths.save_search_internal( + ctx.paths.save_search_internal( obj=search_internal, ) x0 = search_internal.x if search_internal.nit < iterations: - return search_internal, fitness - - self.perform_update( - model=model, - analysis=analysis, - during_analysis=True, - fitness=fitness, - search_internal=search_internal, - ) + return search_internal + + ctx.update(search_internal) self.logger.info(f"{self.method} sampling complete.") - return search_internal, fitness + return search_internal def raw_samples_from(self, model: AbstractPriorModel, search_internal): """ diff --git a/test_autofit/non_linear/search/test_fit_context.py b/test_autofit/non_linear/search/test_fit_context.py index fdc18ad0f..87add83eb 100644 --- a/test_autofit/non_linear/search/test_fit_context.py +++ b/test_autofit/non_linear/search/test_fit_context.py @@ -36,13 +36,60 @@ def _analysis(): ) -@pytest.mark.parametrize("search_cls", [af.Drawer, af.Nautilus]) +@pytest.mark.parametrize( + "search_cls", + [af.Drawer, af.Nautilus, af.Emcee, af.Zeus, af.BFGS, af.LBFGS], +) def test_proofs_are_on_the_bridge(search_cls): assert search_cls.run is not NonLinearSearch.run assert search_cls.raw_samples_from is not NonLinearSearch.raw_samples_from assert search_cls._fit is NonLinearSearch._fit +@pytest.mark.parametrize( + "search_cls, test_mode_samples", + [(af.Emcee, True), (af.Zeus, False), (af.LBFGS, True)], +) +def test_ctx_start_points_forwards_the_search_test_mode_samples_choice( + monkeypatch, search_cls, test_mode_samples +): + """ + ``ctx.start_points`` lets the initializer return its test-mode samples unless the + search opts out (``_start_points_in_test_mode``): Zeus always drew real start + points (``test_mode_samples=False`` in its former ``_fit``). + """ + from autofit.non_linear.search.fit_context import FitContext + + seen = {} + + def samples_from_model(total_points, model, fitness, paths, **kwargs): + seen.update(kwargs) + points = [[50.0, 1.0, 5.0]] * total_points + return points, points, [0.0] * total_points + + search = search_cls() + monkeypatch.setattr(search.initializer, "samples_from_model", samples_from_model) + + model = af.Model(af.ex.Gaussian) + analysis = _analysis() + fitness = search.make_fitness(analysis=analysis, model=model) + + ctx = FitContext( + search=search, + model=model, + analysis=analysis, + fitness=fitness, + pool=search._pools(analysis), + test_mode_level=1, + ) + monkeypatch.setattr(search, "plot_start_point", lambda **kwargs: None) + + parameters, _ = ctx.start_points(3) + + assert parameters.shape == (3, 3) + assert seen["test_mode_samples"] is test_mode_samples + + def test_drawer_fit_runs_through_run_ctx(monkeypatch): monkeypatch.setenv("PYAUTO_TEST_MODE", "1") diff --git a/test_autofit/non_linear/search/test_steps_until_full_update.py b/test_autofit/non_linear/search/test_steps_until_full_update.py index df57dde29..57d363ff2 100644 --- a/test_autofit/non_linear/search/test_steps_until_full_update.py +++ b/test_autofit/non_linear/search/test_steps_until_full_update.py @@ -114,12 +114,19 @@ def test__chunked_searches_take_their_chunk_size_from_the_helper(search_cls): its chunk inline — which is precisely the regression this helper exists to prevent, and precisely what shipped in PyAutoFit#1420. - These ``_fit`` bodies cannot be executed from this suite (jax/optax/emcee - plus a real ``Analysis``), so the call site is asserted at the source level. + These backend loops cannot be executed from this suite (jax/optax/emcee + plus a real ``Analysis``), so the call site is asserted at the source level: + a ``run(ctx)`` search takes its chunk from ``ctx.schedule.next_budget`` + (``UpdateSchedule``, which wraps the helper), a legacy one from the helper. """ - source = inspect.getsource(search_cls._fit) - - assert "self._steps_until_full_update(" in source + from autofit.non_linear.search.abstract_search import NonLinearSearch + + if search_cls.run is not NonLinearSearch.run: + source = inspect.getsource(search_cls.run) + assert "ctx.schedule.next_budget(" in source + else: + source = inspect.getsource(search_cls._fit) + assert "self._steps_until_full_update(" in source # the un-cast inline forms the crashes came from must not come back assert "self.iterations_per_full_update or self.n_steps" not in source assert "min(self.iterations_per_full_update" not in source