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
10 changes: 10 additions & 0 deletions autofit/graphical/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
21 changes: 20 additions & 1 deletion autofit/graphical/expectation_propagation/optimiser.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
51 changes: 51 additions & 0 deletions autofit/non_linear/search/abstract_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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
Expand Down
92 changes: 91 additions & 1 deletion autofit/non_linear/search/nest/nautilus/search.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations

import multiprocessing
import numpy as np
import logging
import os
Expand All @@ -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
Expand All @@ -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
Expand All @@ -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=<int>` 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):
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down
102 changes: 102 additions & 0 deletions test_autofit/graphical/test_ep_no_multiprocessing.py
Original file line number Diff line number Diff line change
@@ -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)
Loading
Loading