Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion autofit/non_linear/search/mcmc/blackjax/chains.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
50 changes: 19 additions & 31 deletions autofit/non_linear/search/mcmc/blackjax/nuts/search.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__ = (
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand All @@ -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}"
Expand Down
2 changes: 1 addition & 1 deletion autofit/non_linear/search/mcmc/blackjax/smc/samples.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
49 changes: 20 additions & 29 deletions autofit/non_linear/search/mcmc/blackjax/smc/search.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__ = (
Expand Down Expand Up @@ -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

Expand All @@ -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 ---------------------------------------------------
#
Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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(
Expand All @@ -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:
"""
Expand Down Expand Up @@ -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}"
Expand Down
2 changes: 1 addition & 1 deletion autofit/non_linear/search/mcmc/emcee/search.py
Original file line number Diff line number Diff line change
Expand Up @@ -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".
Expand Down
88 changes: 35 additions & 53 deletions autofit/non_linear/search/nest/dynesty/search/abstract.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 = (
Expand All @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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)."
)
Expand Down Expand Up @@ -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
Expand Down
Loading
Loading