From 4239e9cf29df14a64f78407bd518f44cdc9e686a Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Sat, 24 Oct 2026 16:31:27 +0100 Subject: [PATCH] fix: warm the likelihood up in the parent before forking workers (PyAutoArray#654) numba is imported lazily since autoarray 2026.8.20.1; when nothing in the parent ran numba, every forked Nautilus worker imported/initialised it at once and >=16 workers segfaulted. Fitness.prepare_for_fork runs the likelihood once on the NumPy path (and imports numba) before any likelihood pool forks: Nautilus, PoolFactory and SneakyPool. The watchdog gets a specific SIGSEGV message. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013C7Zd6ibK9J4V8CFEUzrJU --- autofit/non_linear/fitness.py | 48 +++++ autofit/non_linear/parallel/pool.py | 31 +++ autofit/non_linear/parallel/sneaky.py | 9 + autofit/non_linear/search/execution.py | 7 +- .../non_linear/search/nest/nautilus/search.py | 27 +++ .../non_linear/search/nest/test_nautilus.py | 122 ++++++++++++ .../non_linear/test_prepare_for_fork.py | 185 ++++++++++++++++++ 7 files changed, 428 insertions(+), 1 deletion(-) create mode 100644 test_autofit/non_linear/test_prepare_for_fork.py diff --git a/autofit/non_linear/fitness.py b/autofit/non_linear/fitness.py index f7631ee1a..7321e8c90 100644 --- a/autofit/non_linear/fitness.py +++ b/autofit/non_linear/fitness.py @@ -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)" @@ -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 diff --git a/autofit/non_linear/parallel/pool.py b/autofit/non_linear/parallel/pool.py index 9a6b295f0..410fd9afc 100644 --- a/autofit/non_linear/parallel/pool.py +++ b/autofit/non_linear/parallel/pool.py @@ -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: """ @@ -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) diff --git a/autofit/non_linear/parallel/sneaky.py b/autofit/non_linear/parallel/sneaky.py index d29bf88ca..48cd8907c 100644 --- a/autofit/non_linear/parallel/sneaky.py +++ b/autofit/non_linear/parallel/sneaky.py @@ -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( diff --git a/autofit/non_linear/search/execution.py b/autofit/non_linear/search/execution.py index 6f9698d67..07b8c6cfe 100644 --- a/autofit/non_linear/search/execution.py +++ b/autofit/non_linear/search/execution.py @@ -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(), ) diff --git a/autofit/non_linear/search/nest/nautilus/search.py b/autofit/non_linear/search/nest/nautilus/search.py index 87219158f..00152e2c2 100644 --- a/autofit/non_linear/search/nest/nautilus/search.py +++ b/autofit/non_linear/search/nest/nautilus/search.py @@ -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 " @@ -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, diff --git a/test_autofit/non_linear/search/nest/test_nautilus.py b/test_autofit/non_linear/search/nest/test_nautilus.py index 5d5954d18..b3ee0ef1a 100644 --- a/test_autofit/non_linear/search/nest/test_nautilus.py +++ b/test_autofit/non_linear/search/nest/test_nautilus.py @@ -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) --- diff --git a/test_autofit/non_linear/test_prepare_for_fork.py b/test_autofit/non_linear/test_prepare_for_fork.py new file mode 100644 index 000000000..3a0d7b8d0 --- /dev/null +++ b/test_autofit/non_linear/test_prepare_for_fork.py @@ -0,0 +1,185 @@ +""" +`Fitness.prepare_for_fork`: the one likelihood call a search makes in the parent before it forks +likelihood workers, so lazily initialised native libraries (numba's import and first LLVM compile +since PyAutoArray made numba lazy) are initialised once rather than in every forked worker at once, +which segfaulted >= 16-worker Nautilus fits on RAL (PyAutoArray#654). +""" +import logging +import pickle + +import numpy as np +import pytest + +import autofit as af +from autofit.non_linear.fitness import Fitness +from autofit.non_linear.parallel import PoolFactory +from autofit.non_linear.parallel import pool as pool_module +from autofit.non_linear.parallel import sneaky as sneaky_module + +pytestmark = pytest.mark.filterwarnings("ignore::FutureWarning") + + +class CountingAnalysis(af.ex.Analysis): + def __init__(self, *args, raises=False, **kwargs): + super().__init__(*args, **kwargs) + self.calls = 0 + self.raises = raises + + def log_likelihood_function(self, instance, **kwargs): + self.calls += 1 + if self.raises: + raise ValueError("broken likelihood") + return super().log_likelihood_function(instance=instance, **kwargs) + + +def _fitness(use_jax=False, raises=False, **kwargs): + analysis = CountingAnalysis( + data=np.ones(20), noise_map=np.ones(20) * 0.1, use_jax=use_jax, raises=raises + ) + return Fitness(model=af.Model(af.ex.Gaussian), analysis=analysis, **kwargs) + + +def test__numpy__calls_the_likelihood_exactly_once_and_records_nothing(): + fitness = _fitness(store_history=True, iterations_per_quick_update=1) + + fitness.prepare_for_fork() + fitness.prepare_for_fork() + + assert fitness.analysis.calls == 1 + + # The warm-up bypasses `call_wrap`: no history and no quick-update progress. + assert fitness.parameters_history_list == [] + assert fitness.log_likelihood_history_list == [] + assert fitness.quick_update_count == 0 + + +def test__flag_survives_pickling_so_a_worker_never_repeats_it(): + fitness = _fitness() + fitness.prepare_for_fork() + + restored = pickle.loads(pickle.dumps(fitness)) + restored.prepare_for_fork() + + assert restored.analysis.calls == 1 + + # A fitness pickled before the flag existed simply warms up once. + del fitness.__dict__["_prepared_for_fork"] + legacy = pickle.loads(pickle.dumps(fitness)) + legacy.prepare_for_fork() + + assert legacy.analysis.calls == 2 + + +def test__a_raising_likelihood_only_warns(caplog): + fitness = _fitness(raises=True) + + with caplog.at_level(logging.WARNING): + fitness.prepare_for_fork() + + assert fitness.analysis.calls == 1 + assert "warm-up before forking workers failed" in caplog.text + assert "broken likelihood" in caplog.text + + +def test__jax_analysis_is_a_no_op(): + pytest.importorskip("jax") + + fitness = _fitness(use_jax=True) + calls_after_init = fitness.analysis.calls + + fitness.prepare_for_fork() + + assert fitness.analysis.calls == calls_after_init + + +class _Analysis: + def __init__(self, is_jax): + self.is_jax = is_jax + + +class _RecordingFitness: + def __init__(self, events): + self.events = events + + def prepare_for_fork(self): + self.events.append("prepare") + + +def test__pool_factory_call_prepares_the_fitness_before_forking(monkeypatch): + events = [] + + class StubContext: + def Pool(self, processes, **kwargs): + events.append("pool") + return object() + + monkeypatch.setattr(pool_module, "fork_context", lambda: StubContext()) + + factory = PoolFactory(af.Emcee(number_of_cores=2), _Analysis(is_jax=False)) + factory.fitness = _RecordingFitness(events) + + factory() + + assert events == ["prepare", "pool"] + + # One core forks nothing, so nothing is warmed up. + events.clear() + factory = PoolFactory(af.Emcee(number_of_cores=1), _Analysis(is_jax=False)) + factory.fitness = _RecordingFitness(events) + + assert factory() is None + factory.prepare_for_fork() + assert events == [] + + +def test__sneaky_pool_prepares_the_fitness_before_starting_processes(monkeypatch): + events = [] + + class StubProcess: + def __init__(self, *args, **kwargs): + pass + + def start(self): + events.append("start") + + monkeypatch.setattr(sneaky_module, "SneakyProcess", StubProcess) + + sneaky_module.SneakyPool( + processes=2, fitness=_RecordingFitness(events), paths=None + ) + + assert events == ["prepare", "start", "start"] + + +def test__fit_hands_the_fitness_to_the_pool_factory(monkeypatch): + """ + Searches that fork via `ctx.pool()` (Zeus, Dynesty) rely on the fit's `PoolFactory` + knowing the fitness, so its `__call__` can warm it up. + """ + captured = {} + + class StopFit(Exception): + pass + + def run(self, ctx): + captured["ctx"] = ctx + raise StopFit + + monkeypatch.setattr(af.Emcee, "run", run) + monkeypatch.setenv("PYAUTO_TEST_MODE", "1") + + search = af.Emcee( + name="prepare_for_fork_pool_factory", + unique_tag="prepare_for_fork_pool_factory_test", + number_of_cores=2, + ) + + with pytest.raises(StopFit): + search.fit( + model=af.Model(af.ex.Gaussian), + analysis=af.ex.Analysis(data=np.ones(20), noise_map=np.ones(20)), + ) + + ctx = captured["ctx"] + + assert ctx.pool.fitness is ctx.fitness