From b309d158c3b797af6082c84f28a2527fc5ff9838 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 11 Sep 2026 01:55:17 +0000 Subject: [PATCH] fix(ep): never drive a factor search through a multiprocessing pool; fail fast on a dead Nautilus worker EP factor searches refuse number_of_cores>1 with a clear SearchException (ruling 2026-09-09; RAL 342351_0 hung 27 h after two forked likelihood workers segfaulted and Pool.map never returned). Parallelism for EP comes from a JAX-vectorised likelihood, never a process pool. _LikelihoodWorkerPool.map now dispatches via map_async and polls; on each poll it compares the pool's live worker PIDs against the construction-time set, so a worker that multiprocessing silently replaced (its in-flight task never re-issued) raises a diagnosable SearchException within seconds instead of hanging every multi-core Nautilus fit to the wall clock. Closes #1608 Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01FU8EkdahFWmrL6pewkHZR3 --- autofit/graphical/README.md | 10 ++ .../expectation_propagation/optimiser.py | 21 +++- autofit/non_linear/search/abstract_search.py | 51 ++++++++ .../non_linear/search/nest/nautilus/search.py | 92 +++++++++++++- .../graphical/test_ep_no_multiprocessing.py | 102 +++++++++++++++ .../non_linear/search/nest/test_nautilus.py | 117 ++++++++++++++++++ 6 files changed, 391 insertions(+), 2 deletions(-) create mode 100644 test_autofit/graphical/test_ep_no_multiprocessing.py diff --git a/autofit/graphical/README.md b/autofit/graphical/README.md index f5ddd44fc..6700396bb 100644 --- a/autofit/graphical/README.md +++ b/autofit/graphical/README.md @@ -122,6 +122,16 @@ tilted distribution is then *fitted* by the factor's optimiser: and the update is the closed-form natural-parameter sum — no sampler. `EPOptimiser.from_meanfield` auto-selects this path. +**No process pool inside a factor search.** The sampling path refuses a +factor optimiser built with `number_of_cores > 1` (`AbstractSearch.optimise` +raises `SearchException`; human ruling 2026-09-09). A forked likelihood worker +that dies is silently replaced by `multiprocessing.Pool`, but the task it was +running is never re-issued, so the `Pool.map` driving the fit blocks forever +and the EP run hangs to the wall clock rather than failing (RAL job 342351_0, +27 hours). Factor searches are therefore built with `number_of_cores=1`, and +parallelism comes from a vectorised JAX likelihood — `Analysis(use_jax=True)`, +which puts Nautilus on `fit_x1_cpu` with `vectorized=True` and no pool at all. + ### 3.3 Projection (moment matching) — `AbstractMessage.project` Find the family member closest to the tilted distribution in inclusive diff --git a/autofit/graphical/expectation_propagation/optimiser.py b/autofit/graphical/expectation_propagation/optimiser.py index c9c55a121..ced35100e 100644 --- a/autofit/graphical/expectation_propagation/optimiser.py +++ b/autofit/graphical/expectation_propagation/optimiser.py @@ -681,13 +681,32 @@ def __init__( Optimises all factors simultaneously on parallel processes, combines the results and repeats. + Notes + ----- + This is EP's own *explicit opt-in* process pool, parallelising **across** + factors — it is not the thing refused by `AbstractSearch.optimise`, which + refuses a multiprocessing pool **inside** a single factor search (human + ruling 2026-09-09). The two are distinct, but the failure mode is the + same: a worker that dies mid-`starmap` is replaced by + `multiprocessing.Pool` while the task it was running is never re-issued, + so the sweep blocks forever rather than failing. + + The ruling's recommended configuration is therefore the serial + `EPOptimiser` with a JAX-vectorised likelihood + (`Analysis(use_jax=True)`), which parallelises the likelihood itself + without forking anything. Reach for `ParallelEPOptimiser` only knowing + the above. + Parameters ---------- factor_graph A graph describing the relationships between multiple factors n_cores How many cores are available? The main process takes one core so the - multiprocessing pool has n_cores - 1 processes. Should be at least 3 + multiprocessing pool has n_cores - 1 processes. Should be at least 3. + This pool is EP's explicit opt-in parallelism across factors and is + subject to the dead-worker hang described above; it is unrelated to + (and does not licence) a `number_of_cores > 1` factor search. default_optimiser An optimiser that is used if no specific optimiser is provided for a factor factor_optimisers diff --git a/autofit/non_linear/search/abstract_search.py b/autofit/non_linear/search/abstract_search.py index afd7a7fc2..9abff5a0c 100644 --- a/autofit/non_linear/search/abstract_search.py +++ b/autofit/non_linear/search/abstract_search.py @@ -364,6 +364,42 @@ def optimise( f" AnalysisFactors, HierarchicalFactors and PriorFactors" ) + # A deliberate refusal, not a silent downgrade. `number_of_cores` is the + # user's stated intent, and the *same* search instance is re-entered once + # per factor per EP step — so quietly rewriting it to 1 here would mutate + # shared state the caller still owns and would hide the misconfiguration + # rather than fix it. Raising makes the operator change the search they + # built. + # + # The guard lives here, in `AbstractSearch.optimise`, rather than in any + # one search: `optimise` is the single door every factor optimisation + # passes through, so every search type (Nautilus, Dynesty, Emcee, the MLE + # searches) is covered by one check instead of N. + # + # `getattr` with a default of 1: a handful of search doubles subclass + # `NonLinearSearch` without running its `__init__` (e.g. the regression + # suite's `StaticSearch`), and they run nothing in parallel anyway. + number_of_cores = getattr(self, "number_of_cores", 1) + + if number_of_cores > 1: + raise exc.SearchException( + f"Expectation propagation never runs a factor search through a " + f"Python multiprocessing pool (human ruling 2026-09-09), but the " + f"factor optimiser {self.__class__.__name__} was built with " + f"number_of_cores={number_of_cores}.\n\n" + f"Why: a forked likelihood worker that dies (a segfault, an OOM " + f"kill) is silently replaced by `multiprocessing.Pool`, but the " + f"task it was running is never re-issued, so the `Pool.map` " + f"driving the fit blocks forever and the EP run hangs to the wall " + f"clock rather than failing. RAL job 342351_0 burned 27 hours " + f"exactly this way.\n\n" + f"Fix, either of:\n" + f" - build the factor search with number_of_cores=1;\n" + f" - get parallelism from a vectorised JAX likelihood instead, " + f"`Analysis(use_jax=True)` — Nautilus then takes `fit_x1_cpu` " + f"with vectorized=True and no pool at all." + ) + model = factor.prior_model.mapper_from_prior_arguments( { prior: prior.with_message(message) @@ -373,6 +409,21 @@ def optimise( analysis = factor.analysis + uses_jax = getattr(analysis, "_use_jax", False) + + self.logger.info( + f"EP factor step [{factor.name}]: running the factor search " + f"{self.__class__.__name__} serially (number_of_cores=1); " + + ( + "parallelism comes from the vectorised JAX likelihood " + "(analysis.use_jax=True)." + if uses_jax + else "the likelihood is not JAX-vectorised, so this factor step " + "is single-threaded (set `Analysis(use_jax=True)` for " + "parallelism)." + ) + ) + number = self.optimisation_counter[factor.name] self.optimisation_counter[factor.name] += 1 diff --git a/autofit/non_linear/search/nest/nautilus/search.py b/autofit/non_linear/search/nest/nautilus/search.py index 9d65f12b5..9b42fd183 100644 --- a/autofit/non_linear/search/nest/nautilus/search.py +++ b/autofit/non_linear/search/nest/nautilus/search.py @@ -1,5 +1,6 @@ from __future__ import annotations +import multiprocessing import numpy as np import logging import os @@ -9,6 +10,7 @@ from typing import Dict, Optional, Tuple, TYPE_CHECKING +from autofit import exc from autofit.mapper.prior_model.abstract import AbstractPriorModel from autofit.mapper.prior.vectorized import PriorVectorized from autofit.non_linear.fitness import Fitness @@ -26,6 +28,12 @@ logger = logging.getLogger(__name__) +# How often `_LikelihoodWorkerPool.map` wakes up to check that the pool's +# workers are the ones it was built with. Read at call time (not bound at +# import) so tests can monkeypatch the module attribute. +LIKELIHOOD_POOL_POLL_INTERVAL = 1.0 + + class _LikelihoodWorkerPool: """ A `multiprocessing.Pool` wrapper handed to nautilus as its likelihood pool @@ -39,10 +47,34 @@ class _LikelihoodWorkerPool: 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). + + It also carries a **dead-worker watchdog**. `multiprocessing.Pool` silently + replaces a worker that dies (`Pool._maintain_pool` -> `_repopulate_pool`) + but never re-issues the task that worker was running, so a plain + `Pool.map` blocks forever and the whole fit hangs to the wall clock — RAL + job 342351_0 burned 27 hours after two likelihood workers segfaulted + (#1608, and the same mechanism as #1547). `map` therefore dispatches via + `map_async` and polls; on every poll it checks the exit code of every + worker captured at construction. A replacement restores the worker + *count*, but the original worker stays dead, so the loss is detectable, + and the fit fails with a diagnosable `SearchException` (naming the PID and + the signal) in seconds instead of hanging. """ def __init__(self, pool): self._pool = pool + # The construction-time worker `Process` objects. Watching *these* is + # what makes a `_repopulate_pool` replacement detectable: the pool + # restores the number of workers, so counting them proves nothing, + # while an original worker that died stays dead. Holding the objects + # (not just their PIDs) matters because the pool's maintenance thread + # joins and drops a dead worker from `pool._pool` within ~0.1 s; the + # retained object still reports its cached `exitcode` after that. + # + # `getattr` rather than `pool._pool` directly, so a pool-like test + # double without a `_pool` attribute still works (the watchdog then + # simply has nothing to watch). + self._workers = list(getattr(pool, "_pool", [])) @property def size(self): @@ -58,7 +90,57 @@ def map(self, func, iterable): # task chunk (#1547). from nautilus.pool import likelihood_worker - return self._pool.map(likelihood_worker, iterable) + result = self._pool.map_async(likelihood_worker, iterable) + + while True: + try: + return result.get(timeout=LIKELIHOOD_POOL_POLL_INTERVAL) + except multiprocessing.TimeoutError: + # Not done yet — which is the normal case for a long chunk of + # likelihood evaluations, and also exactly what a hang looks + # like. Only the worker check can tell them apart. + self._check_workers_alive() + + def _check_workers_alive(self): + """ + Raise if any worker the pool was built with is gone. + + `multiprocessing.Pool` replaces a dead worker behind our back and drops + its in-flight task on the floor, so the `map_async` above would never + complete. Detect the replacement and fail loudly instead. + """ + dead = [worker for worker in self._workers if worker.exitcode is not None] + + if not dead: + return + + def _describe(worker): + code = worker.exitcode + if code < 0: + return f"pid {worker.pid} (exit code {code}, killed by signal {-code})" + return f"pid {worker.pid} (exit code {code})" + + detail = ", ".join(_describe(worker) for worker in dead) + + self._pool.terminate() + + 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 " + f"(-11 SIGSEGV, -9 SIGKILL — typically an out-of-memory kill on a " + f"cluster).\n\n" + f"`multiprocessing.Pool` has already replaced the worker, but it " + f"never re-issues the task that worker was running, so the " + f"`Pool.map` driving this fit would otherwise block forever and the " + f"fit would hang to the wall clock rather than fail (RAL job " + f"342351_0 hung 27 hours this way). Failing now instead.\n\n" + f"Fix, either of:\n" + f" - run the search with number_of_cores=1, which builds no pool " + f"at all;\n" + f" - get parallelism from a vectorised JAX likelihood instead, " + f"`Analysis(use_jax=True)` — Nautilus then takes `fit_x1_cpu` with " + f"vectorized=True and no pool." + ) def __enter__(self): return self @@ -150,6 +232,14 @@ def __init__( The number of iterations performed between update (e.g. output latest model to hard-disk, visualization). number_of_cores The number of cores sampling is performed using a Python multiprocessing Pool instance. + + Not used by expectation-propagation factor searches, which refuse + `number_of_cores > 1` outright (`AbstractSearch.optimise`, human + ruling 2026-09-09): a forked worker that dies is replaced by + `multiprocessing.Pool` while its in-flight task is never re-issued, + so the fit hangs instead of failing. EP parallelism comes from a + JAX-vectorised likelihood (`Analysis(use_jax=True)`), which takes + the pool-free `fit_x1_cpu` path. silence If True, the default print output of the non-linear search is silenced. force_x1_cpu diff --git a/test_autofit/graphical/test_ep_no_multiprocessing.py b/test_autofit/graphical/test_ep_no_multiprocessing.py new file mode 100644 index 000000000..c7c9f0d2f --- /dev/null +++ b/test_autofit/graphical/test_ep_no_multiprocessing.py @@ -0,0 +1,102 @@ +""" +Expectation propagation never drives a factor search through a Python +multiprocessing pool (human ruling 2026-09-09, #1608). + +RAL job 342351_0 hung 27 hours because the EP factor search was a Nautilus +built with `number_of_cores=10` over a non-JAX analysis: two forked likelihood +workers segfaulted, `multiprocessing.Pool` replaced them, and because the pool +never re-issues a dead worker's in-flight task the `Pool.map` inside the fit +blocked to the wall clock. + +`AbstractSearch.optimise` therefore refuses `number_of_cores > 1` outright, +rather than downgrading it silently. +""" + +import numpy as np +import pytest + +import autofit as af +import autofit.graphical as g +from autofit.graphical.utils import Status +from test_autofit.graphical.gaussian.model import Analysis, Gaussian, make_data + +pytestmark = pytest.mark.filterwarnings("ignore::FutureWarning") + + +@pytest.fixture(name="factor_model") +def make_factor_model(): + x = np.arange(100) + y = make_data(Gaussian(centre=50.0, normalization=25.0, sigma=10.0), x) + + prior_model = af.Model( + Gaussian, + centre=af.GaussianPrior(mean=50, sigma=20), + normalization=af.GaussianPrior(mean=25, sigma=10), + sigma=af.GaussianPrior(mean=10, sigma=10), + ) + + return g.AnalysisFactor(prior_model, analysis=Analysis(x=x, y=y)) + + +@pytest.fixture(name="no_forking") +def make_no_forking(monkeypatch): + """ + Make any attempt to fork a pool a hard failure, in every module that holds + `fork_context` as a module-level name (plus the package namespace, which the + dynesty search imports from inside its own method). + """ + + def no_fork_context(*args, **kwargs): + raise AssertionError("must not fork") + + module_paths = ( + "autofit.non_linear.parallel", + "autofit.non_linear.parallel.context", + "autofit.non_linear.search.abstract_search", + "autofit.non_linear.search.nest.dynesty.search.abstract", + "autofit.non_linear.search.nest.nautilus.search", + "autofit.non_linear.parallel.sneaky", + "autofit.non_linear.parallel.process", + ) + + import importlib + + for module_path in module_paths: + module = importlib.import_module(module_path) + if hasattr(module, "fork_context"): + monkeypatch.setattr(module, "fork_context", no_fork_context) + + +@pytest.mark.filterwarnings("ignore::RuntimeWarning") +def test__ep_refuses_multi_core_search(factor_model, no_forking): + search = af.DynestyStatic(maxcall=5, number_of_cores=2) + + factor_approx = factor_model.mean_field_approximation().factor_approximation( + factor_model + ) + + with pytest.raises(af.exc.SearchException, match="multiprocessing") as error: + search.optimise(factor_approx) + + message = str(error.value) + + assert "number_of_cores=2" in message + assert "number_of_cores=1" in message + assert "use_jax" in message + assert "DynestyStatic" in message + + +@pytest.mark.filterwarnings("ignore::RuntimeWarning") +def test__ep_single_core_search_unchanged(factor_model): + # No `no_forking` here: the guard is the only thing this change adds, and + # Dynesty's own single-core path still enters a `Pool(1)` of its own + # (`_fork_pool_cls`, with a serial RuntimeError fallback) — pre-existing + # behaviour this issue does not touch. + search = af.DynestyStatic(maxcall=5, number_of_cores=1) + + result, status = search.optimise( + factor_model.mean_field_approximation().factor_approximation(factor_model) + ) + + assert isinstance(result, g.MeanField) + assert isinstance(status, Status) diff --git a/test_autofit/non_linear/search/nest/test_nautilus.py b/test_autofit/non_linear/search/nest/test_nautilus.py index dd70cccae..58b85ce2b 100644 --- a/test_autofit/non_linear/search/nest/test_nautilus.py +++ b/test_autofit/non_linear/search/nest/test_nautilus.py @@ -124,6 +124,10 @@ class StopFit(Exception): class StubPool: _processes = 2 + # `_LikelihoodWorkerPool` reads the pool's worker list at construction + # to capture the workers its watchdog checks; an empty list simply + # gives it nothing to watch. + _pool = [] def close(self): captured["closed"] = True @@ -256,3 +260,116 @@ def __call__(self, args): def _must_not_be_dispatched(*args): raise AssertionError("the mapped function must be ignored") + + +def _sleepy_likelihood(args): + """ + A module-level (and therefore picklable) stand-in for the `Fitness`, slow + enough that a worker can be killed while the map is still in flight. + """ + import time + + time.sleep(0.2) + return args + + +def _ignored(*args): + raise AssertionError("the mapped function must be ignored") + + +@requires_nautilus +def test__likelihood_pool_raises_when_worker_dies(monkeypatch): + """ + A worker that dies mid-`map` must fail the fit, not hang it. + + `multiprocessing.Pool` replaces a dead worker (`_maintain_pool` -> + `_repopulate_pool`) but never re-issues the task it was running, so a plain + `Pool.map` blocks to the wall clock — RAL job 342351_0 hung 27 hours this + way (#1608). `_LikelihoodWorkerPool.map` polls the exit code of every + worker captured at construction, so the replacement is detectable (the + count is restored, the original worker stays dead) and raises within + seconds. + """ + import multiprocessing + import os + import signal + import threading + import time + + from nautilus.pool import initialize_worker + + from autofit.non_linear.search.nest.nautilus import search as nautilus_search + + if "fork" not in multiprocessing.get_all_start_methods(): + pytest.skip("requires the fork start method") + + monkeypatch.setattr(nautilus_search, "LIKELIHOOD_POOL_POLL_INTERVAL", 0.1) + + context = multiprocessing.get_context("fork") + pool = context.Pool( + 2, + initializer=initialize_worker, + initargs=(_sleepy_likelihood,), + ) + + try: + wrapper = nautilus_search._LikelihoodWorkerPool(pool) + + victim_pid = pool._pool[0].pid + + killer = threading.Timer(0.3, os.kill, args=(victim_pid, signal.SIGKILL)) + killer.start() + + start = time.time() + + try: + with pytest.raises(af.exc.SearchException) as error: + wrapper.map(_ignored, list(range(40))) + finally: + killer.cancel() + + elapsed = time.time() - start + + assert elapsed < 5.0 + + message = str(error.value) + + assert str(victim_pid) in message + assert "-9" in message + assert "multiprocessing.Pool" in message + finally: + pool.terminate() + pool.join() + + +@requires_nautilus +def test__likelihood_pool_healthy_map_completes(monkeypatch): + """ + The `map_async` + polling loop must be transparent when nothing dies: the + results come back complete and in order, across more tasks than workers. + """ + import multiprocessing + + from nautilus.pool import initialize_worker + + from autofit.non_linear.search.nest.nautilus import search as nautilus_search + + if "fork" not in multiprocessing.get_all_start_methods(): + pytest.skip("requires the fork start method") + + monkeypatch.setattr(nautilus_search, "LIKELIHOOD_POOL_POLL_INTERVAL", 0.1) + + context = multiprocessing.get_context("fork") + pool = context.Pool( + 2, + initializer=initialize_worker, + initargs=(_sleepy_likelihood,), + ) + + try: + wrapper = nautilus_search._LikelihoodWorkerPool(pool) + + assert list(wrapper.map(_ignored, list(range(40)))) == list(range(40)) + finally: + pool.terminate() + pool.join()