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
48 changes: 48 additions & 0 deletions autofit/non_linear/fitness.py
Original file line number Diff line number Diff line change
Expand Up @@ -305,6 +305,8 @@ def __init__(
self.parameters_history_list = []
self.log_likelihood_history_list = []

self._prepared_for_fork = False

if use_jax_vmap is not None:
_warn_deprecated_fitness_kwarg(
"use_jax_vmap", "pass `batched=` instead (the same meaning)"
Expand Down Expand Up @@ -396,6 +398,52 @@ def _warmup_visualization(self):
else:
logger.info("Visualization warm-up complete.")

def prepare_for_fork(self):
"""Run the likelihood once in this (the parent) process before a search forks workers.

Native libraries that initialise lazily must be initialised in the parent before it
forks, or every forked worker initialises them at the same time on its first likelihood
call -- and that can segfault. numba is the case that bites: since PyAutoArray made
`import numba` lazy (2026.8.20.1), a likelihood whose setup ran no numba in the parent
(e.g. an interferometer fit with NUFFT preprocessing and NumPy meshes) imports numba and
LLVM-compiles its first functions inside every worker at once, and with 16 or more
Nautilus workers they die by SIGSEGV in llvmlite (RAL, PyAutoArray#654). One call here
initialises them once, and also moves the numba compile out of N workers into a single
parent call that every forked worker inherits.

The call goes straight to `call`, bypassing `call_wrap`, so it is not recorded into
`store_history` or counted towards quick updates. It runs once per `Fitness` (a flag
that survives pickling, so a worker never repeats it), is a no-op for a JAX analysis
(which never forks likelihood workers), and a failure only logs a warning: the fit
itself will raise the real error if the likelihood is genuinely broken.
"""
if self._is_jax or getattr(self, "_prepared_for_fork", False):
return

self._prepared_for_fork = True

logger.info(
"Running the likelihood once before forking workers (initialises lazily "
"loaded native libraries, e.g. numba, in the parent)..."
)
try:
self.call(self.model.physical_values_from_prior_medians)
except Exception as e:
logger.warning(
f"Likelihood warm-up before forking workers failed (non-fatal): {e!r}. "
f"Forked workers will initialise native libraries themselves."
)
else:
logger.info("Likelihood warm-up before forking workers complete.")

# A likelihood that returns early (e.g. a resampled model) may never reach its
# numba code, so import numba here too: importing it in the parent is on its
# own enough to stop forked workers from initialising it all at once.
try:
import numba # noqa: F401
except ImportError:
pass

@property
def _xp(self):
return self.analysis._xp
Expand Down
31 changes: 31 additions & 0 deletions autofit/non_linear/parallel/pool.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,35 @@ def __init__(self, search, analysis=None):

self._created = []

# The fit's `Fitness`, set by `NonLinearSearch` once it exists, so that
# `__call__` can warm the likelihood up before forking (`prepare_for_fork`).
self.fitness = None

def prepare_for_fork(self, fitness=None):
"""
Run the likelihood once in the parent before any pool of this fit forks workers
(`Fitness.prepare_for_fork`), so lazily initialised native libraries (numba's
import and first LLVM compile) are initialised once here rather than in every
forked worker at once, which can segfault them.

A no-op on one core (no workers are forked), when no fitness is known, or for a
fitness without the hook (a test double, an external search's own callable).

Parameters
----------
fitness
The fitness the workers will call; defaults to the fit's own (`self.fitness`).
"""
if self.number_of_cores <= 1:
return

fitness = fitness if fitness is not None else self.fitness

prepare = getattr(fitness, "prepare_for_fork", None)

if prepare is not None:
prepare()

@property
def summary(self) -> str:
"""
Expand Down Expand Up @@ -194,6 +223,8 @@ def __call__(self, n_cores: Optional[int] = None, **pool_kwargs):
if n_cores <= 1:
return None

self.prepare_for_fork()

getattr(self.search, "logger", logger).info("...using pool")
pool = fork_context().Pool(processes=n_cores, **pool_kwargs)
self._created.append(pool)
Expand Down
9 changes: 9 additions & 0 deletions autofit/non_linear/parallel/sneaky.py
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,15 @@ def __init__(
initializer
initargs
"""
# Warm the likelihood up in the parent first, so lazily initialised native
# libraries (numba's import and first LLVM compile) are not initialised by
# every forked process at once (`Fitness.prepare_for_fork`). Every SneakyPool
# -- `PoolFactory.sneaky` and the initializer's -- passes through here.
prepare = getattr(fitness, "prepare_for_fork", None)

if processes > 1 and prepare is not None:
prepare()

logger.info(f"Creating pool with {processes} processes")
self._processes = [
SneakyProcess(
Expand Down
7 changes: 6 additions & 1 deletion autofit/non_linear/search/execution.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,12 +95,17 @@ def _run_bridge(self, model: AbstractPriorModel, analysis: Analysis):
**self.execution_settings(analysis).fitness_overrides,
)

pools = self._pools(analysis)
# Every `pools(...)` pool then warms this fitness up before it forks
# (`PoolFactory.prepare_for_fork`).
pools.fitness = fitness

ctx = FitContext(
search=self,
model=model,
analysis=analysis,
fitness=fitness,
pool=self._pools(analysis),
pool=pools,
test_mode_level=test_mode_level(),
)

Expand Down
27 changes: 27 additions & 0 deletions autofit/non_linear/search/nest/nautilus/search.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,26 @@ def _describe(worker):

self._pool.terminate()

if any(worker.exitcode == -11 for worker in dead):
raise exc.SearchException(
f"A Nautilus likelihood worker died mid-fit by a segmentation "
f"fault (SIGSEGV): {detail}.\n\n"
f"A forked worker that segfaults has typically crashed while "
f"initialising a native library after the fork (e.g. numba "
f"importing and compiling its first function, which since "
f"PyAutoArray 2026.8.20.1 happens lazily on first use): with many "
f"workers forked at once, each initialising it, they crash "
f"together. PyAutoFit runs the likelihood once in the parent "
f"before forking (`Fitness.prepare_for_fork`) to prevent exactly "
f"this, so if you see this message:\n"
f" - run the search with number_of_cores=1, which builds no pool "
f"at all, to see the underlying error;\n"
f" - check that the likelihood runs serially (e.g. call "
f"`analysis.log_likelihood_function` on an instance yourself);\n"
f" - report it, with this message, at "
f"https://github.com/PyAutoLabs/PyAutoFit/issues."
)

raise exc.SearchException(
f"A Nautilus likelihood worker died mid-fit: {detail}.\n\n"
f"A negative exit code is the signal that killed the worker "
Expand Down Expand Up @@ -689,6 +709,13 @@ def fit_multiprocessing(self, fitness, model, analysis=None, pools=None, update=
else:
from nautilus.pool import initialize_worker

# Initialise lazily loaded native libraries (numba) in the parent before
# forking, rather than in every worker at once (`Fitness.prepare_for_fork`).
prepare_for_fork = getattr(fitness, "prepare_for_fork", None)

if prepare_for_fork is not None:
prepare_for_fork()

pool_context = _LikelihoodWorkerPool(
fork_context().Pool(
pools.number_of_cores,
Expand Down
122 changes: 122 additions & 0 deletions test_autofit/non_linear/search/nest/test_nautilus.py
Original file line number Diff line number Diff line change
Expand Up @@ -429,6 +429,128 @@ def test__likelihood_pool_healthy_map_completes(monkeypatch):
pool.join()


@requires_nautilus
def test__multi_core_prepares_the_fitness_before_forking(monkeypatch):
"""
`fit_multiprocessing` runs the likelihood once in the parent (`Fitness.prepare_for_fork`)
before it creates the fork pool, so numba's lazy import / first compile is not done by every
worker at once (PyAutoArray#654: >= 16 workers segfaulted in llvmlite).
"""
from autofit.non_linear.fitness import Fitness
from autofit.non_linear.search.nest.nautilus import search as nautilus_search

class StopFit(Exception):
pass

events = []

class StubPool:
_processes = 2
_pool = []

def close(self):
pass

def terminate(self):
pass

def join(self):
pass

class StubSampler:
def __init__(self, **kwargs):
raise StopFit

class StubContext:
def Pool(self, number_of_cores, initializer=None, initargs=()):
events.append("pool")
return StubPool()

original = Fitness.prepare_for_fork

def recording_prepare_for_fork(self):
events.append("prepare")
original(self)

monkeypatch.setattr(Fitness, "prepare_for_fork", recording_prepare_for_fork)
monkeypatch.setattr(nautilus_search, "fork_context", lambda: StubContext())
monkeypatch.setattr(
af.Nautilus, "sampler_cls", property(lambda self: StubSampler)
)
monkeypatch.setenv("PYAUTO_TEST_MODE", "1")

search = af.Nautilus(
name="nautilus_prepare_for_fork",
unique_tag="nautilus_prepare_for_fork_test",
n_live=10,
number_of_cores=2,
)

with pytest.raises(StopFit):
search.fit(
model=af.Model(af.ex.Gaussian),
analysis=af.ex.Analysis(
data=np.full(100, 5.0), noise_map=np.full(100, 1.0)
),
)

assert events[:2] == ["prepare", "pool"]


class _FakeWorker:
def __init__(self, pid, exitcode):
self.pid = pid
self.exitcode = exitcode


class _FakePool:
"""A pool double exposing only what the dead-worker watchdog reads."""

def __init__(self, workers):
self._pool = workers
self._processes = len(workers)
self.terminated = False

def terminate(self):
self.terminated = True


def _watchdog_message(exitcode):
from autofit.non_linear.search.nest.nautilus import search as nautilus_search

pool = _FakePool([_FakeWorker(101, None), _FakeWorker(102, None)])
wrapper = nautilus_search._LikelihoodWorkerPool(pool)

pool._pool[1].exitcode = exitcode

with pytest.raises(af.exc.SearchException) as error:
wrapper._check_workers_alive()

assert pool.terminated

return str(error.value)


def test__likelihood_pool__sigsegv_names_native_library_initialisation():
message = _watchdog_message(exitcode=-11)

assert "pid 102" in message
assert "segmentation fault" in message
assert "numba" in message
assert "prepare_for_fork" in message
assert "number_of_cores=1" in message
assert "report it" in message


def test__likelihood_pool__other_deaths_keep_the_generic_message():
for exitcode in (-9, 1):
message = _watchdog_message(exitcode=exitcode)

assert "pid 102" in message
assert "multiprocessing.Pool" in message
assert "segmentation fault" not in message


# --- D >= 91: the live-point guard and the HDF5 checkpoint format (#1697) ---


Expand Down
Loading
Loading