diff --git a/autofit/non_linear/search/nest/nautilus/search.py b/autofit/non_linear/search/nest/nautilus/search.py index 3ae499e8f..9d65f12b5 100644 --- a/autofit/non_linear/search/nest/nautilus/search.py +++ b/autofit/non_linear/search/nest/nautilus/search.py @@ -25,6 +25,53 @@ logger = logging.getLogger(__name__) + +class _LikelihoodWorkerPool: + """ + A `multiprocessing.Pool` wrapper handed to nautilus as its likelihood pool + (`pool_l`), whose workers already hold the fitness function in a global set + by `nautilus.pool.initialize_worker` at fork time. + + Nautilus calls `pool.map(self.likelihood, args)` (`nautilus/sampler.py`), + which for a plain pool object makes `multiprocessing` pickle the bound + `Fitness.call_wrap` — and therefore the whole analysis, dataset, PSF + convolver, sparse operator and adapt images — into every task chunk, for + every likelihood call. This class ignores the function it is mapped with + and dispatches `likelihood_worker` instead, which reads the worker-global + likelihood, exactly as nautilus does for a `pool=` argument (#1547). + """ + + def __init__(self, pool): + self._pool = pool + + @property + def size(self): + """ + The number of worker processes, read by `nautilus.pool.NautilusPool.size`. + """ + return getattr(self._pool, "_processes", None) + + def map(self, func, iterable): + # `func` is deliberately ignored: nautilus's likelihood pool is only ever + # mapped with the likelihood, and dispatching the worker-global instead + # avoids pickling the `Fitness` (and its analysis and dataset) into every + # task chunk (#1547). + from nautilus.pool import likelihood_worker + + return self._pool.map(likelihood_worker, iterable) + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + if exc_type is None: + self._pool.close() + else: + self._pool.terminate() + self._pool.join() + return False + + class Nautilus(abstract_nest.AbstractNest): __identifier_fields__ = ( "n_live", @@ -338,10 +385,42 @@ def fit_multiprocessing(self, fitness, model, analysis): # forces every likelihood call into a forked worker — which deadlocks # in XLA compilation when the likelihood touches JAX, since a forked # child of a JAX-initialized parent cannot compile. + # + # The pool is passed as the tuple `(pool, None)` rather than as a bare + # `pool`, because nautilus otherwise uses the one pool for likelihood + # evaluations *and* for its own sampler calculations — in particular + # neural bound training (`nautilus/neural.py`, + # `NeuralNetworkEmulator.train` -> `pool.map`). A worker that dies + # mid-fit (e.g. a per-job OOM kill on a cluster) is silently replaced + # by `multiprocessing.Pool`, but the task it was running is never + # re-issued, so `map` blocks forever and the fit hangs — observed on + # RAL 2026-08-29 (#1547). `(pool, None)` keeps likelihoods parallel + # (`pool_l`) and makes bound training serial in the parent (`pool_s`), + # which is negligible: 4 small MLPs fit on at most a few hundred + # points. + # + # The pool is also built with nautilus's own `initialize_worker`, and is + # handed over wrapped in `_LikelihoodWorkerPool`, so that the likelihood + # is dispatched as `likelihood_worker`. Before a pool object was passed + # in place of `pool=` (e6279c53f, #1439), nautilus did this itself; + # with a pool object it instead maps the bound `Fitness.call_wrap`, so + # `multiprocessing` pickles the entire analysis (dataset, PSF convolver, + # sparse operator, adapt images) into every task chunk and each worker + # unpickles a fresh copy for every likelihood call. Worker memory then + # grows by a few MB per call (8-core RAL runs reached the 96 GB cgroup + # limit) while the parent starves the pool serialising it (#1547). if self.number_of_cores <= 1: pool_context = nullcontext(None) else: - pool_context = fork_context().Pool(self.number_of_cores) + from nautilus.pool import initialize_worker + + pool_context = _LikelihoodWorkerPool( + fork_context().Pool( + self.number_of_cores, + initializer=initialize_worker, + initargs=(fitness.call_wrap,), + ) + ) with pool_context as pool: search_internal = self.sampler_cls( @@ -349,7 +428,7 @@ def fit_multiprocessing(self, fitness, model, analysis): likelihood=fitness.call_wrap, n_dim=model.prior_count, filepath=self.checkpoint_file, - pool=pool, + pool=(pool, None) if pool is not None else None, n_live=self.n_live, n_update=self.n_update, enlarge_per_dim=self.enlarge_per_dim, diff --git a/test_autofit/non_linear/search/nest/test_nautilus.py b/test_autofit/non_linear/search/nest/test_nautilus.py index 87e621157..dd70cccae 100644 --- a/test_autofit/non_linear/search/nest/test_nautilus.py +++ b/test_autofit/non_linear/search/nest/test_nautilus.py @@ -97,3 +97,162 @@ def no_fork_context(): ) search.fit(model=model, analysis=analysis) + + +@requires_nautilus +def test__multi_core_passes_serial_sampler_pool(monkeypatch): + """ + number_of_cores > 1 must hand nautilus the tuple `(pool, None)`: the fork + pool for likelihood evaluations (`pool_l`) and no pool for the sampler's + own calculations (`pool_s`). + + The pool itself is handed over wrapped in `_LikelihoodWorkerPool`, whose + `map` dispatches nautilus's `likelihood_worker` so the `Fitness` is not + pickled into every task chunk (#1547). + + Nautilus otherwise trains its neural bounds on the same pool via + `pool.map`; a worker that dies mid-fit is replaced by + `multiprocessing.Pool` but its task is never re-issued, so `map` blocks + forever and the fit hangs (#1547). + """ + from autofit.non_linear.search.nest.nautilus import search as nautilus_search + + class StopFit(Exception): + pass + + captured = {} + + class StubPool: + _processes = 2 + + def close(self): + captured["closed"] = True + + def terminate(self): + captured["terminated"] = True + + def join(self): + captured["joined"] = True + + class StubSampler: + def __init__(self, **kwargs): + captured.update(kwargs) + raise StopFit + + class StubContext: + def Pool(self, number_of_cores, initializer=None, initargs=()): + captured["number_of_cores"] = number_of_cores + captured["initializer"] = initializer + captured["initargs"] = initargs + return StubPool() + + monkeypatch.setattr(nautilus_search, "fork_context", lambda: StubContext()) + monkeypatch.setattr( + af.Nautilus, "sampler_cls", property(lambda self: StubSampler) + ) + monkeypatch.setenv("PYAUTO_TEST_MODE", "1") + + model = af.Model(af.ex.Gaussian) + analysis = af.ex.Analysis( + data=np.full(100, 5.0), + noise_map=np.full(100, 1.0), + ) + + search = af.Nautilus( + name="nautilus_multi_core", + unique_tag="multi_core_serial_sampler_pool_test", + n_live=10, + number_of_cores=2, + ) + + with pytest.raises(StopFit): + search.fit(model=model, analysis=analysis) + + from nautilus.pool import initialize_worker + + assert captured["number_of_cores"] == 2 + assert captured["initializer"] is initialize_worker + assert len(captured["initargs"]) == 1 + + pool = captured["pool"] + + assert isinstance(pool, tuple) + assert pool[1] is None + assert isinstance(pool[0], nautilus_search._LikelihoodWorkerPool) + assert pool[0].size == 2 + + captured.clear() + + search = af.Nautilus( + name="nautilus_single_core_pool_kwarg", + unique_tag="single_core_serial_sampler_pool_test", + n_live=10, + number_of_cores=1, + ) + + with pytest.raises(StopFit): + search.fit(model=model, analysis=analysis) + + assert captured["pool"] is None + + +@requires_nautilus +def test__likelihood_pool_does_not_pickle_fitness(): + """ + `_LikelihoodWorkerPool.map` must ignore the function nautilus maps with and + dispatch `nautilus.pool.likelihood_worker`, which reads the likelihood from + the worker-global set by `initialize_worker` at fork time. + + If the mapped function were dispatched instead, `multiprocessing` would + pickle the bound `Fitness.call_wrap` — and with it the analysis, dataset, + PSF convolver and sparse operator — into every task chunk, for every + likelihood call (#1547). + """ + import multiprocessing + + from nautilus.pool import initialize_worker + + from autofit.non_linear.search.nest.nautilus.search import _LikelihoodWorkerPool + + if "fork" not in multiprocessing.get_all_start_methods(): + pytest.skip("requires the fork start method") + + likelihood = _UnpicklableLikelihood() + + context = multiprocessing.get_context("fork") + pool = context.Pool( + 2, + initializer=initialize_worker, + initargs=(likelihood,), + ) + + try: + with _LikelihoodWorkerPool(pool) as wrapper: + assert wrapper.size == 2 + + result = wrapper.map( + _must_not_be_dispatched, + [(1, 2), (3, 4)], + ) + + assert list(result) == [3, 7] + finally: + pool.terminate() + pool.join() + + +class _UnpicklableLikelihood: + """ + A stand-in for the `Fitness`: it is inherited by the forked workers, but + raises if anything tries to pickle it into a task. + """ + + def __getstate__(self): + raise AssertionError("Fitness must not be pickled") + + def __call__(self, args): + return sum(args) + + +def _must_not_be_dispatched(*args): + raise AssertionError("the mapped function must be ignored")