From 1f7808e69e1a9777239eaf67420d093d30ca7a86 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Sat, 29 Aug 2026 18:47:01 -0400 Subject: [PATCH 1/2] fix(nautilus): train neural bounds serially so a dead pool worker cannot hang the fit MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit nautilus was given the fork pool as `pool=pool`, so it used it for both likelihood calls and sampler calculations (neural bound training via `pool.map`). A worker that dies — e.g. a per-job OOM kill on a cluster — is replaced by multiprocessing.Pool but its task is never re-issued, so `map` blocks forever. Pass `pool=(pool, None)`: likelihoods stay parallel, bound training (4 small MLPs) runs in the parent. Closes #1547 Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_01M6Bmv35TPD1rGQ4bzrbZ15 --- .../non_linear/search/nest/nautilus/search.py | 15 +++- .../non_linear/search/nest/test_nautilus.py | 78 +++++++++++++++++++ 2 files changed, 92 insertions(+), 1 deletion(-) diff --git a/autofit/non_linear/search/nest/nautilus/search.py b/autofit/non_linear/search/nest/nautilus/search.py index 3ae499e8f..46cd18582 100644 --- a/autofit/non_linear/search/nest/nautilus/search.py +++ b/autofit/non_linear/search/nest/nautilus/search.py @@ -338,6 +338,19 @@ 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. if self.number_of_cores <= 1: pool_context = nullcontext(None) else: @@ -349,7 +362,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..351652c18 100644 --- a/test_autofit/non_linear/search/nest/test_nautilus.py +++ b/test_autofit/non_linear/search/nest/test_nautilus.py @@ -97,3 +97,81 @@ 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`). + + 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 StubSampler: + def __init__(self, **kwargs): + captured.update(kwargs) + raise StopFit + + sentinel = object() + + class StubPoolContext: + def __enter__(self): + return sentinel + + def __exit__(self, *args): + return False + + class StubContext: + def Pool(self, number_of_cores): + captured["number_of_cores"] = number_of_cores + return StubPoolContext() + + 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) + + assert captured["number_of_cores"] == 2 + assert captured["pool"] == (sentinel, None) + + 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 From 56fb8b63b83c057afa0ac99ecbb8eccac708f771 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Sat, 29 Aug 2026 21:50:40 -0400 Subject: [PATCH 2/2] fix(nautilus): dispatch likelihood_worker so the Fitness is not pickled per task With a Pool object, nautilus maps the bound Fitness.call_wrap directly, so multiprocessing pickles the whole analysis (dataset, PSF, sparse operator, adapt images) into every task chunk and each worker unpickles it per likelihood call: worker memory grows a few MB per call (8-core RAL runs hit 96 GB) and the parent starves the pool serialising it. Build the fork pool with nautilus's initialize_worker and hand nautilus a wrapper whose map dispatches likelihood_worker, as the int-pool path did before #1439. Refs #1547 Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_01M6Bmv35TPD1rGQ4bzrbZ15 --- .../non_linear/search/nest/nautilus/search.py | 68 +++++++++++- .../non_linear/search/nest/test_nautilus.py | 105 ++++++++++++++++-- 2 files changed, 160 insertions(+), 13 deletions(-) diff --git a/autofit/non_linear/search/nest/nautilus/search.py b/autofit/non_linear/search/nest/nautilus/search.py index 46cd18582..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", @@ -351,10 +398,29 @@ def fit_multiprocessing(self, fitness, model, analysis): # (`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( diff --git a/test_autofit/non_linear/search/nest/test_nautilus.py b/test_autofit/non_linear/search/nest/test_nautilus.py index 351652c18..dd70cccae 100644 --- a/test_autofit/non_linear/search/nest/test_nautilus.py +++ b/test_autofit/non_linear/search/nest/test_nautilus.py @@ -106,6 +106,10 @@ def test__multi_core_passes_serial_sampler_pool(monkeypatch): 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 @@ -118,24 +122,29 @@ class StopFit(Exception): 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 - sentinel = object() - - class StubPoolContext: - def __enter__(self): - return sentinel - - def __exit__(self, *args): - return False - class StubContext: - def Pool(self, number_of_cores): + def Pool(self, number_of_cores, initializer=None, initargs=()): captured["number_of_cores"] = number_of_cores - return StubPoolContext() + captured["initializer"] = initializer + captured["initargs"] = initargs + return StubPool() monkeypatch.setattr(nautilus_search, "fork_context", lambda: StubContext()) monkeypatch.setattr( @@ -159,8 +168,18 @@ def Pool(self, number_of_cores): with pytest.raises(StopFit): search.fit(model=model, analysis=analysis) + from nautilus.pool import initialize_worker + assert captured["number_of_cores"] == 2 - assert captured["pool"] == (sentinel, None) + 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() @@ -175,3 +194,65 @@ def Pool(self, number_of_cores): 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")