diff --git a/autofit/non_linear/search/mcmc/blackjax/chains.py b/autofit/non_linear/search/mcmc/blackjax/chains.py index 284e965d0..e709a8ac1 100644 --- a/autofit/non_linear/search/mcmc/blackjax/chains.py +++ b/autofit/non_linear/search/mcmc/blackjax/chains.py @@ -205,7 +205,7 @@ def stack_initial_positions(parameter_lists) -> np.ndarray: """ Stack the per-chain starting vectors generated by an initializer (a length-``num_chains`` list of length-``n_dim`` lists/vectors) into a single ``(num_chains, n_dim)`` array, the shape - ``BlackJAXNUTS._fit`` vmaps warmup and sampling over. + ``BlackJAXNUTS.run`` vmaps warmup and sampling over. """ return np.asarray(parameter_lists, dtype=float) diff --git a/autofit/non_linear/search/mcmc/blackjax/nuts/search.py b/autofit/non_linear/search/mcmc/blackjax/nuts/search.py index d9e8bfd03..ed4a7c1fa 100644 --- a/autofit/non_linear/search/mcmc/blackjax/nuts/search.py +++ b/autofit/non_linear/search/mcmc/blackjax/nuts/search.py @@ -60,7 +60,7 @@ class BlackJAXNUTS(NonLinearSearch): invalid_value = -float("inf") # The chain dict is plain NumPy, pickled (atomically) after every chunk and kept # after completion: the samples cannot be rebuilt without it. Not a resume state: - # every ``_fit`` starts afresh (``resumable = False``). + # every fit starts afresh (``resumable = False``). checkpointer = PickleCheckpointer() __identifier_fields__ = ( @@ -305,37 +305,31 @@ def apply_test_mode(self): self.num_samples = 20 self.num_chains = min(self.num_chains, 2) - def _fit(self, model: AbstractPriorModel, analysis): + def run(self, ctx): """ - Fit a model using BlackJAX NUTS. The autofit ``Analysis`` must be - constructed with ``use_jax=True`` so the log-likelihood is - JAX-traceable and differentiable. - - Returns - ------- - (search_internal, fitness): tuple - ``search_internal`` is the dict pickled under - ``search_internal/``; ``fitness`` is the autofit Fitness wrapper. + Run BlackJAX NUTS (the ``run(ctx)`` hook; see ``docs/design/run_ctx.md``) and + return the chain dict archived under ``search_internal/``. The autofit + ``Analysis`` must be constructed with ``use_jax=True`` so the log-likelihood is + JAX-traceable and differentiable (the bridge's REQUIRED gate refuses a numpy + analysis before this runs). + + Parameters + ---------- + ctx + The fit's ``FitContext``. """ import jax import jax.numpy as jnp import blackjax - # JAX is mandatory (jax_use='required'): NUTS needs gradients of the - # log-density. `fit` already ran this gate; repeated for direct callers. - cap.check_jax_required(self, analysis) - - fitness = self.make_fitness(analysis=analysis, model=model) + model = ctx.model + fitness = ctx.fitness # Initial position(s): borrow the standard initializer machinery so # users can substitute their own (InitializerBall by default for # MCMC; InitializerParamStartPoints.from_result(...) to warm-start). # One starting point per chain. - unit_lists, parameter_lists, _ = self.start_points( - model=model, - fitness=fitness, - n=self.num_chains, - ) + parameter_lists, _ = ctx.start_points(self.num_chains) n_dim = model.prior_count @@ -463,7 +457,7 @@ def run_chunk(rng_key, initial_state, n_steps): while iterations_remaining > 0: # ``run_chunk`` scans ``chunk_n`` steps and the key split below sizes # itself from it, so this must be an ``int`` (PyAutoFit#1422). - chunk_n = self._steps_until_full_update(iterations_remaining) + chunk_n = ctx.schedule.next_budget(total_done, self.num_samples) rng_key, sample_key = jax.random.split(rng_key) states, infos = run_chunk(sample_key, state, chunk_n) @@ -513,15 +507,9 @@ def run_chunk(rng_key, initial_state, n_steps): self.output_search_internal(search_internal=search_internal) 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 # ------------------------------------------------------------------ # Persistence + samples @@ -533,7 +521,7 @@ def backend_filename(self): @property def backend(self) -> dict: - """The search-internal dict archived by ``_fit`` (``search_internal.pickle``).""" + """The search-internal dict archived by ``run`` (``search_internal.pickle``).""" if not self.checkpointer.exists(self.paths): raise FileNotFoundError( f"{PICKLE_FILENAME} does not exist at {self.paths.search_internal_path}" diff --git a/autofit/non_linear/search/mcmc/blackjax/smc/samples.py b/autofit/non_linear/search/mcmc/blackjax/smc/samples.py index 057de15e7..d0e6f3da1 100644 --- a/autofit/non_linear/search/mcmc/blackjax/smc/samples.py +++ b/autofit/non_linear/search/mcmc/blackjax/smc/samples.py @@ -70,7 +70,7 @@ def log_evidence(self) -> Optional[float]: """ The log evidence `log Z = log integral(prior(x) L(x) dx)`, accumulated for free from the SMC tempering bridge as the sum of every step's `log_likelihood_increment` (plus the whitening Jacobian `log|det L|` - when the run was warm-started; see `SMC._fit`). + when the run was warm-started; see `SMC.run`). This is the true evidence on the same scale a nested sampler reports, and is directly comparable to a `Nautilus` or `Dynesty` `log_evidence` for the same model and data. diff --git a/autofit/non_linear/search/mcmc/blackjax/smc/search.py b/autofit/non_linear/search/mcmc/blackjax/smc/search.py index 249f8175b..83d16b7df 100644 --- a/autofit/non_linear/search/mcmc/blackjax/smc/search.py +++ b/autofit/non_linear/search/mcmc/blackjax/smc/search.py @@ -76,7 +76,7 @@ class SMC(NonLinearSearch): invalid_value = -1.0e99 # The chain dict is plain NumPy, pickled (atomically) after every chunk and kept # after completion: the samples cannot be rebuilt without it. Not a resume state: - # every ``_fit`` starts afresh (``resumable = False``). + # every fit starts afresh (``resumable = False``). checkpointer = PickleCheckpointer() __identifier_fields__ = ( @@ -382,25 +382,25 @@ def is_warm_start(self) -> bool: """ return self._inverse_mass_matrix_spec is not None - def _fit(self, model: AbstractPriorModel, analysis): + def run(self, ctx): """ - Fit a model using BlackJAX adaptive tempered SMC. The autofit ``Analysis`` must be constructed with - ``use_jax=True`` so the log-likelihood is JAX-traceable and differentiable. - - Returns - ------- - (search_internal, fitness): tuple - ``search_internal`` is the dict pickled under ``search_internal/``; ``fitness`` is the autofit - Fitness wrapper. + Run BlackJAX adaptive tempered SMC (the ``run(ctx)`` hook; see + ``docs/design/run_ctx.md``) and return the particle dict archived under + ``search_internal/``. The autofit ``Analysis`` must be constructed with + ``use_jax=True`` so the log-likelihood is JAX-traceable and differentiable (the + bridge's REQUIRED gate refuses a numpy analysis before this runs). + + Parameters + ---------- + ctx + The fit's ``FitContext``. """ import jax import jax.numpy as jnp import blackjax import blackjax.smc.resampling as resampling - # JAX is mandatory (jax_use='required'): MALA/HMC need gradients of the log-density. `fit` already ran - # this gate; repeated for direct callers. - cap.check_jax_required(self, analysis) + model = ctx.model n_dim = model.prior_count @@ -410,8 +410,9 @@ def _fit(self, model: AbstractPriorModel, analysis): # # The resample sentinel is the library-standard `-1e99` rather than `-inf`: blackjax's ESS root solver # multiplies the log-likelihood by a candidate `delta` that can be exactly 0.0, and `0 * -inf` is NaN. - # A large finite negative value gives the same zero weight without that hazard. - fitness = self.make_fitness(analysis=analysis, model=model) + # A large finite negative value gives the same zero weight without that hazard. Both are the search's + # declared `objective_target` / `invalid_value`, so the bridge's `Fitness` (`ctx.fitness`) carries them. + fitness = ctx.fitness # ---- Whitening --------------------------------------------------- # @@ -446,11 +447,7 @@ def _fit(self, model: AbstractPriorModel, analysis): "Pass initializer=result.start_point_from() alongside inverse_mass_matrix=result." ) - _, parameter_lists, _ = self.start_points( - model=model, - fitness=fitness, - n=n_start_points, - ) + parameter_lists, _ = ctx.start_points(n_start_points) start_points = stack_initial_positions(parameter_lists) @@ -658,13 +655,7 @@ def smc_loglikelihood_fn(z): self.output_search_internal(search_internal=search_internal) if float(state.tempering_param) < 1.0 and n_smc_steps < self.max_smc_steps: - self.perform_update( - model=model, - analysis=analysis, - search_internal=search_internal, - fitness=fitness, - during_analysis=True, - ) + ctx.update(search_internal) if search_internal is None: raise RuntimeError( @@ -678,7 +669,7 @@ def smc_loglikelihood_fn(z): "particles are not posterior samples." ) - return search_internal, fitness + return search_internal def effective_step_size(self, n_dim: int) -> float: """ @@ -716,7 +707,7 @@ def backend_filename(self): @property def backend(self) -> dict: - """The search-internal dict archived by ``_fit`` (``search_internal.pickle``).""" + """The search-internal dict archived by ``run`` (``search_internal.pickle``).""" if not self.checkpointer.exists(self.paths): raise FileNotFoundError( f"{PICKLE_FILENAME} does not exist at {self.paths.search_internal_path}" diff --git a/autofit/non_linear/search/mcmc/emcee/search.py b/autofit/non_linear/search/mcmc/emcee/search.py index 6c658c1f6..ea4f9444d 100644 --- a/autofit/non_linear/search/mcmc/emcee/search.py +++ b/autofit/non_linear/search/mcmc/emcee/search.py @@ -42,7 +42,7 @@ class Emcee(NonLinearSearch): honours_gradient_mode = False posterior_kind = cap.PosteriorKind.CHAIN produces_evidence = False - # Resumable: ``_fit`` reopens the HDF backend, loads the last sample and iteration + # Resumable: ``run`` reopens the HDF backend, loads the last sample and iteration # count and samples only the remaining steps. The search-extensibility report's # section 3.1 table listed Emcee as not resumable; that was corrected here (A1 # review) against the published meaning "resumes from its own checkpoint". diff --git a/autofit/non_linear/search/nest/dynesty/search/abstract.py b/autofit/non_linear/search/nest/dynesty/search/abstract.py index e5f948113..d5fbd3f1d 100644 --- a/autofit/non_linear/search/nest/dynesty/search/abstract.py +++ b/autofit/non_linear/search/nest/dynesty/search/abstract.py @@ -25,18 +25,17 @@ logger = logging.getLogger(__name__) -def _fork_pool_cls(): +def _fork_pool_cls(pools): """ - dynesty's `Pool` pinned to the "fork" start method via - `autofit.non_linear.parallel.fork_context` — upstream hardcodes the default - multiprocessing context, which Python 3.14 changed to "forkserver" on Linux - (see that helper's docstring). `__enter__` mirrors `dynesty.pool.Pool.__enter__` - exactly apart from the context. + dynesty's `Pool` whose worker pool comes from the fit's `PoolFactory` (`pools`, the + `ctx.pool` of the fit), so it is a "fork" pool (`autofit.non_linear.parallel.fork_context`; + upstream hardcodes the default multiprocessing context, which Python 3.14 changed to + "forkserver" on Linux), the JAX fork rule applies and the context shuts it down on + every exit. `__enter__` mirrors `dynesty.pool.Pool.__enter__` exactly apart from where + the pool comes from. """ from dynesty import pool as dynesty_pool - from autofit.non_linear.parallel import fork_context - class ForkPool(dynesty_pool.Pool): def __enter__(self): initargs = ( @@ -47,8 +46,10 @@ def __enter__(self): self.ptform_args or (), self.ptform_kwargs or {}, ) - self.pool = fork_context().Pool( - self.njobs, dynesty_pool.initializer, initargs + self.pool = pools( + self.njobs, + initializer=dynesty_pool.initializer, + initargs=initargs, ) dynesty_pool.initializer(*initargs) return self @@ -58,7 +59,7 @@ def __enter__(self): class _SingleCoreRun(Exception): """ - Control flow inside ``AbstractDynesty._fit``: run dynesty without a pool. + Control flow inside ``AbstractDynesty.run``: run dynesty without a pool. Raised when the fit is single-core by construction (``number_of_cores <= 1``, ``force_x1_cpu`` or a JAX analysis) and when the multiprocessing pool cannot be @@ -272,48 +273,34 @@ def run_kwargs(self) -> Dict: """Run kwargs specific to each subclass, excluding maxcall.""" raise NotImplementedError() - def _fit( - self, - model: AbstractPriorModel, - analysis, - ): + def run(self, ctx): """ - Fit a model using the search 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 dynesty (the ``run(ctx)`` hook; see ``docs/design/run_ctx.md``) and return the + sampler. - A multiprocessing pool is built only when `number_of_cores > 1`. At `number_of_cores=1` the search runs - fully serially with no pool, because a `Pool(1)` forces every likelihood call through a forked worker, - which deadlocks in XLA compilation when the likelihood touches JAX and hangs forever if that worker dies - (the same fix Nautilus received in #1442 / #1443; see #1630). Consequently, a run started with - `number_of_cores=1` cannot be resumed with more cores (`check_pool` raises a `SearchException`), exactly - as on the existing `force_x1_cpu` path. + A multiprocessing pool is built only when the fit's effective core count is above 1. At + `number_of_cores=1` the search runs fully serially with no pool, because a `Pool(1)` forces every + likelihood call through a forked worker, which deadlocks in XLA compilation when the likelihood touches + JAX and hangs forever if that worker dies (the same fix Nautilus received in #1442 / #1443; see #1630). + Consequently, a run started with `number_of_cores=1` cannot be resumed with more cores (`check_pool` + raises a `SearchException`), exactly as on the existing `force_x1_cpu` path. However, certain operating systems (e.g. Windows) do not support Python multiprocessing particularly well. If creating the pool raises a `RuntimeError`, a Dynesty object without a pool is created and used instead. Only the pool's creation falls back: a `RuntimeError` raised while Dynesty runs (including JAX's `XlaRuntimeError`) propagates rather than silently restarting the run single-core (`_SingleCoreRun`). + dynesty resumes from its own native checkpoint (``savestate.save``). + 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 dynesty maximizes. - - Returns - ------- - A result object comprising the Samples object that includes the maximum log likelihood instance and full - set of accepted samples of the fit. + ctx + The fit's ``FitContext``. """ + model = ctx.model + fitness = ctx.fitness - fitness = self.make_fitness( - analysis=analysis, - model=model, - **self.execution_settings(analysis).fitness_overrides, - ) - - if self.paths.supports_checkpointing: + if ctx.paths.supports_checkpointing: checkpoint_exists = Path(self.checkpoint_file).exists() else: checkpoint_exists = False @@ -329,16 +316,17 @@ def _fit( # The fit's effective core count: the JAX fork rule makes it 1 for a JAX # analysis (`autofit.non_linear.parallel.pool`). - number_of_cores = self._pools(analysis).number_of_cores + number_of_cores = ctx.pool.number_of_cores + is_jax = ctx.pool.is_jax finished = False while not finished: try: - if number_of_cores <= 1 or self.force_x1_cpu or analysis.is_jax: + if number_of_cores <= 1 or self.force_x1_cpu or is_jax: raise _SingleCoreRun() - Pool = _fork_pool_cls() + Pool = _fork_pool_cls(ctx.pool) with ExitStack() as stack: # Only a failure to *create* the pool falls back to a single-core @@ -370,7 +358,7 @@ def _fit( except _SingleCoreRun as e: if not checkpoint_exists: - if analysis.is_jax: + if is_jax: self.logger.info( "Running Dynesty with JAX-jitted likelihood (single CPU, no pool)." ) @@ -404,15 +392,9 @@ def _fit( checkpoint_exists = True if not finished: - 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): search_internal = search_internal or self.search_internal diff --git a/test_autofit/non_linear/search/nest/test_dynesty.py b/test_autofit/non_linear/search/nest/test_dynesty.py index 6eaaa2a8b..273931f8c 100644 --- a/test_autofit/non_linear/search/nest/test_dynesty.py +++ b/test_autofit/non_linear/search/nest/test_dynesty.py @@ -101,10 +101,13 @@ def no_fork_context(*args, **kwargs): raise AssertionError("fork_context must not be used when number_of_cores == 1") parallel = importlib.import_module("autofit.non_linear.parallel") + parallel_pool = importlib.import_module("autofit.non_linear.parallel.pool") - # `_fork_pool_cls` imports `fork_context` from the package at call time, so - # patching the package attribute is what intercepts the pool build. + # dynesty's `ForkPool` takes its workers from the fit's `PoolFactory`, which + # builds them through `parallel.pool.fork_context`; the package attribute is + # patched too so no other route can build one. monkeypatch.setattr(parallel, "fork_context", no_fork_context) + monkeypatch.setattr(parallel_pool, "fork_context", no_fork_context) monkeypatch.setenv("PYAUTO_TEST_MODE", "1") diff --git a/test_autofit/non_linear/search/nest/test_dynesty_single_core_sentinel.py b/test_autofit/non_linear/search/nest/test_dynesty_single_core_sentinel.py index 9cec9945d..b3fde8adf 100644 --- a/test_autofit/non_linear/search/nest/test_dynesty_single_core_sentinel.py +++ b/test_autofit/non_linear/search/nest/test_dynesty_single_core_sentinel.py @@ -2,7 +2,7 @@ Dynesty's single-core control flow (search-extensibility A3b; survey 01 §8, survey 02 §3.7). -``AbstractDynesty._fit`` used ``raise RuntimeError`` inside a ``try`` to select its +``AbstractDynesty._fit`` (now ``run``) used ``raise RuntimeError`` inside a ``try`` to select its single-core path, so its ``except RuntimeError`` also swallowed any ``RuntimeError`` raised while a pooled run executed (a genuine dynesty error, or JAX's ``XlaRuntimeError``, which subclasses it) and silently restarted the run single-core. @@ -63,7 +63,7 @@ def search_internal_from(model, fitness, checkpoint_exists, pool, queue_size): pools.append(pool) return object() - monkeypatch.setattr(dynesty_abstract, "_fork_pool_cls", lambda: pool_cls) + monkeypatch.setattr(dynesty_abstract, "_fork_pool_cls", lambda pools: pool_cls) monkeypatch.setattr(search, "search_internal_from", search_internal_from) monkeypatch.setattr(search, "run_search_internal", run_search_internal) return search, pools @@ -111,7 +111,7 @@ def test_single_core_is_selected_without_a_runtime_error(monkeypatch): def run_search_internal(search_internal): return True - def pool_must_not_be_built(): + def pool_must_not_be_built(pools): raise AssertionError("a single-core fit built a pool") search = af.DynestyStatic(number_of_cores=1) diff --git a/test_autofit/non_linear/search/test_fit_context.py b/test_autofit/non_linear/search/test_fit_context.py index 87add83eb..55693341f 100644 --- a/test_autofit/non_linear/search/test_fit_context.py +++ b/test_autofit/non_linear/search/test_fit_context.py @@ -38,7 +38,18 @@ def _analysis(): @pytest.mark.parametrize( "search_cls", - [af.Drawer, af.Nautilus, af.Emcee, af.Zeus, af.BFGS, af.LBFGS], + [ + af.Drawer, + af.Nautilus, + af.Emcee, + af.Zeus, + af.BFGS, + af.LBFGS, + af.DynestyStatic, + af.DynestyDynamic, + af.BlackJAXNUTS, + af.SMC, + ], ) def test_proofs_are_on_the_bridge(search_cls): assert search_cls.run is not NonLinearSearch.run diff --git a/test_autofit/non_linear/test_fork_context.py b/test_autofit/non_linear/test_fork_context.py index d5acf06e9..85caa1e55 100644 --- a/test_autofit/non_linear/test_fork_context.py +++ b/test_autofit/non_linear/test_fork_context.py @@ -6,7 +6,7 @@ import autofit as af from autofit.non_linear.fitness import Fitness -from autofit.non_linear.parallel import fork_context +from autofit.non_linear.parallel import PoolFactory, fork_context from autofit.non_linear.parallel.process import Process from autofit.non_linear.search.nest.dynesty.search.abstract import ( _fork_pool_cls, @@ -147,16 +147,22 @@ def test_factor_graph_instance_shape_in_pool_worker(factor_graph_and_fitness): ) in_process_likelihood = fitness(in_process_vector) - ForkPool = _fork_pool_cls() - - with ForkPool( - njobs=2, - loglike=fitness, - prior_transform=prior_transform, - logl_args=(global_prior_model, fitness), - ptform_args=(global_prior_model,), - ) as pool: - worker_vector = list(pool.map(pool.prior_transform, [unit_vector]))[0] - worker_likelihood = list(pool.map(pool.loglike, [worker_vector]))[0] + # dynesty's pool takes its workers from the fit's `PoolFactory` (`ctx.pool`). + pools = PoolFactory(af.DynestyStatic(number_of_cores=2)) + ForkPool = _fork_pool_cls(pools) + + try: + with ForkPool( + njobs=2, + loglike=fitness, + prior_transform=prior_transform, + logl_args=(global_prior_model, fitness), + ptform_args=(global_prior_model,), + ) as pool: + assert pools._created == [pool.pool] + worker_vector = list(pool.map(pool.prior_transform, [unit_vector]))[0] + worker_likelihood = list(pool.map(pool.loglike, [worker_vector]))[0] + finally: + pools.close(failed=False) assert worker_likelihood == pytest.approx(in_process_likelihood, rel=1e-10)