Repository navigation
Description
Overview
Expectation propagation (EP) must never drive a per-factor Nautilus search through a Python multiprocessing pool. RAL job 342351_0 (the slope_hierarchy_scale EP arm, submitted --use_cpu) hung for 27 h on a 10-core allocation with 16 s of CPU and zero samples: two forked likelihood workers segfaulted in _ctypes seconds after the fork, Pool._maintain_pool silently replaced them, and because multiprocessing never re-issues a dead worker's in-flight task the Pool.map inside nautilus.Sampler.add_samples could never return. Nothing reached stderr. Human ruling (2026-09-09): EP is not combined with Python multiprocessing at all — per-factor searches run serially (pool=None), and parallelism comes from a vectorised JAX likelihood.
Two defects, both in PyAutoFit, one PR (the prompt's witness needs both):
- EP silently forks.
AbstractSearch.optimise(the EP factor-optimiser entry) calls the search's ordinaryfit, so a search built withnumber_of_cores>1and a non-JAX analysis takesNautilus.fit_multiprocessingand forks a pool per factor step. - A dead pool worker hangs every multi-core Nautilus fit, not just EP. fix(nautilus): serial bound training + no per-task Fitness pickling (#1547) #1548 made bound training serial but left likelihood evaluation (
_LikelihoodWorkerPool.map) unguarded: a vanished worker is replaced, its task is lost, andmapblocks to the wall clock.
Plan
- Make the EP factor-optimiser path refuse a multiprocessing search loudly:
AbstractSearch.optimiseraises a clearSearchExceptionwhennumber_of_cores > 1, naming the ruling and the two supported alternatives (number_of_cores=1, or ause_jax=Trueanalysis for vectorised parallelism). No pool is ever forked under EP. - Log, at EP factor-step time, which likelihood path the factor search takes (serial vs JAX-vectorised), so a run's log shows where its parallelism comes from.
- Give
_LikelihoodWorkerPool.mapa dead-worker watchdog: dispatch withmap_async, poll with a short timeout, and on each poll compare the pool's live worker PIDs against the set captured at construction. A PID that has vanished means a worker died and its task was lost, so terminate the pool and raise a diagnosableSearchExceptionwithin seconds instead of blocking forever. - Regression tests: EP with a multi-core search raises (and forks nothing); EP with
number_of_cores=1runs unchanged; a real fork pool whose worker isSIGKILLed mid-map raises within seconds; the healthy-pool tests from Nautilus 1-core fits deadlock under JAX: fork Pool(1) bypasses nautilus's serial-pool guard (release-integrate RED) #1442/fix(nautilus): serial bound training + no per-task Fitness pickling (#1547) #1548 still pass. - Update the Nautilus
number_of_coresdocstring andautofit/graphical/README.mdwith the EP-never-forks rule. - File the phase-2 follow-up separately: the
slope_hierarchy_scalescripts/ep.pyuse_jax = not use_cpuconflation (JAX-on-CPU is unreachable through--use_cpu) is that project's script, not PyAutoFit's, and gets its own Mind prompt.
Detailed implementation plan
Affected Repositories
- PyAutoFit (primary, only)
Work Classification
Library
Branch Survey
| Repository | Current Branch | Dirty? |
|---|---|---|
| ./PyAutoFit | main (e331e33) |
clean |
Remote heads: main, claude/slowest-ci-tests-s81dza, experiment/jax-vmap-jit-ordering — none touch EP or the Nautilus pool.
Suggested branch: feature/ep-no-multiprocessing-pool
Worktree root: ~/Code/PyAutoLabs-wt/ep-no-multiprocessing-pool/ (created by /start_library; a web session works on the clone directly)
Implementation Steps
Step 1 — EP refuses a multiprocessing search (autofit/non_linear/search/abstract_search.py, AbstractSearch.optimise)
- At the top of
optimise, after the factor-type check, add:if self.number_of_cores > 1: raise exc.SearchException(...)with a message that states the 2026-09-09 ruling (EP never runs a factor search through a Python multiprocessing pool: a forked worker that dies is silently replaced and its task never re-issued, soPool.maphangs to the wall clock — RAL 342351_0), and the two fixes: build the factor search withnumber_of_cores=1, and get parallelism fromAnalysis(use_jax=True)(Nautilus then takesfit_x1_cpuwithvectorized=True, no pool).- This is deliberately a refusal, not a silent downgrade:
number_of_coresis user intent, and the ruling wants the intent corrected at the call site. The check lives in the EP entry point so it covers every search type (Nautilus, dynesty, emcee, zeus, LBFGS), not just Nautilus.
- Log one
logger.infoper factor step naming the path:"EP factor search runs serially (number_of_cores=1); parallelism from JAX vectorisation: <analysis._use_jax>". ParallelEPOptimiser(graphical/expectation_propagation/optimiser.py:718) is EP's own explicit opt-in pool across factors (fork_context().Pool(n_cores-1)), not the per-factor path that hung. Leave it as-is in this PR; add a docstring note that it is subject to the same dead-worker hang and that the ruling's recommended configuration isEPOptimiser+ JAX likelihood. (Deprecation is a separate decision.)
Step 2 — dead-worker watchdog (autofit/non_linear/search/nest/nautilus/search.py, _LikelihoodWorkerPool)
- In
__init__, captureself._worker_pids = {p.pid for p in pool._pool}and accept apoll_interval: float = 1.0(module constant, monkeypatchable in tests). - Replace
mapwith:result = self._pool.map_async(likelihood_worker, iterable) while True: try: return result.get(timeout=self._poll_interval) except multiprocessing.TimeoutError: self._check_workers_alive()
_check_workers_alive():live = {p.pid for p in self._pool._pool if p.exitcode is None};dead = self._worker_pids - live. Ifdeadis non-empty:self._pool.terminate()and raiseexc.SearchExceptionnaming the dead PIDs and theirexitcodes (a negative exitcode is the signal number —-11reads as SIGSEGV), explaining thatmultiprocessing.Poolreplaced the worker but never re-issued its task, and pointing atnumber_of_cores=1/ JAX as the fix. Using the original PID set rather than the worker count is what makes a_repopulate_poolreplacement detectable (the count is restored; the PID is not).- Keep
__exit__semantics;terminate()on the error path is idempotent.
Step 3 — tests
test_autofit/graphical/test_ep_no_multiprocessing.py(new):test__ep_refuses_multi_core_search: build the two-factor Gaussian graph fromtest_autofit/graphical/gaussian/conftest.py,optimiser = af.DynestyStatic(maxcall=5, number_of_cores=2); monkeypatchautofit.non_linear.parallel.context.fork_context(and thefork_contextnames imported intodynesty/search/abstract.pyandnautilus/search.py) to raiseAssertionError("must not fork"); assertpytest.raises(af.exc.SearchException, match="multiprocessing")fromfactor.optimise(...)/search.optimise(factor_approx).test__ep_single_core_search_unchanged: same graph withnumber_of_cores=1runs to a result (existing behaviour).
test_autofit/non_linear/search/nest/test_nautilus.py(extend):test__likelihood_pool_raises_when_worker_dies: realforkPool(2)built withinitialize_worker(likelihood)where the likelihood sleeps ~0.2 s per call; startwrapper.mapon a 40-item iterable in a thread,os.kill(pool._pool[0].pid, SIGKILL)after the first results arrive, assertSearchExceptionis raised in under ~5 s and its message names the dead PID and a negative exitcode. Set_LikelihoodWorkerPoolpoll interval to 0.1 s via monkeypatch. Skip ifforkis unavailable.- Existing
test__likelihood_pool_does_not_pickle_fitness,test__multi_core_passes_serial_sampler_pool,test__single_core_builds_no_poolmust still pass (theStubPoolin the second gains a_pool = []attribute).
- Run:
python -m pytest test_autofit/non_linear/search/nest/test_nautilus.py test_autofit/graphical -qserially, then the fulltest_autofit/. Baseline on clean main (e331e33, 2026-09-11):test_autofit/graphical279 passed serially; under-n auto17 of them fail on untouched main (a parallel-runner artefact, not a defect), so the EP suite is judged serially.
Step 4 — docs
Nautilus.__init__docstring,number_of_cores: add "Not used by EP factor searches, which refuse it; seeAbstractSearch.optimise."autofit/graphical/README.md: one paragraph under the optimisation section stating the rule and pointing at the JAX path.
Key Files
autofit/non_linear/search/abstract_search.py—AbstractSearch.optimise: the EP → search seam; the refusal lives here.autofit/non_linear/search/nest/nautilus/search.py—_LikelihoodWorkerPool(watchdog) andNautilus._fit(path selection:force_x1_cpu or analysis._use_jax→fit_x1_cpu, elsefit_multiprocessing).autofit/graphical/expectation_propagation/optimiser.py—factor_step(the frame atep.py:91in the py-spy dump) andParallelEPOptimiser.autofit/graphical/declarative/abstract.py—AbstractDeclarativeFactor.optimise→EPOptimiser.run.test_autofit/non_linear/search/nest/test_nautilus.py— the Nautilus 1-core fits deadlock under JAX: fork Pool(1) bypasses nautilus's serial-pool guard (release-integrate RED) #1442 / fix(nautilus): serial bound training + no per-task Fitness pickling (#1547) #1548 pool tests to extend.test_autofit/graphical/gaussian/conftest.py— the small factor graph fixture for the EP tests.
Key trade-offs
- Refuse vs force-serial. Forcing
number_of_cores=1in place would mutate a search object the user reuses (the same search instance is re-entered per factor byoptimise) and would hide the intent mismatch; a loud refusal is what the ruling asks for and is one line to fix at the call site. The witness accepts either. - PID-set watchdog vs stack inspection. The prompt notes a replacement worker is distinguishable only by a
_maintain_poolframe in its stack; comparing live PIDs against the construction-time set gives the same signal without py-spy, in pure stdlib, at a 1 s poll. - Cost. Under a non-JAX likelihood the EP factor search is now single-core by construction; that is the ruling's accepted price, and the JAX path is where parallelism lives.
Prior art
- PyAutoFit#1439 (fork-context pin,
pool=<int>→Poolobject), fix: single-core Nautilus fits build no pool (release-integrate corrective, #1442) #1443 (pool=Noneat one core, XLA deadlock), fix(nautilus): train neural bounds serially so a dead pool worker cannot hang the fit #1547/fix(nautilus): serial bound training + no per-task Fitness pickling (#1547) #1548 (serial bound training, no per-task Fitness pickling). PyAutoMind/complete/2026/08/nautilus-serial-bound-training.md.
Original Prompt
Click to expand starting prompt
EP must never drive Nautilus through a Python multiprocessing pool
Type: bug
Target: PyAutoFit
Repos:
- PyAutoFit
Difficulty: large
Autonomy: supervised
Priority: high
Status: formalised
Consequence: judge
Witness: an EP fit requesting number_of_cores>1 either runs serially or refuses loudly (never silently forks a pool), demonstrated by the slope_hierarchy_scale EP arm getting past its first factor_step; plus a regression test that kills a pool worker mid-map and asserts the search raises a diagnosable error within seconds instead of blocking forever.
Review-minutes: 25
Unattended: ready
EP must never drive Nautilus through a Python multiprocessing pool
Witness: an EP fit requesting number_of_cores>1 either runs serially or refuses loudly (never silently forks a pool), demonstrated by the slope_hierarchy_scale EP arm getting past its first factor_step; plus a regression test that kills a pool worker mid-map and asserts the search raises a diagnosable error within seconds instead of blocking forever.
Ruling (human, 2026-09-09): expectation propagation should not be combined with Python multiprocessing at all. EP's per-factor Nautilus searches should run with pool=None / number_of_cores=1, and parallelism should come from a vectorised JAX likelihood, which bypasses Pool.map entirely.
Evidence that forced this. RAL job 342351_0 (slope_hierarchy_scale EP arm) hung for 27 hours consuming 16 seconds of CPU across a 10-core allocation, and was cancelled having produced zero samples. py-spy showed the parent blocked in multiprocessing/pool.py:367 map -> :768 get -> :765 wait, reached via _LikelihoodWorkerPool.map (autofit/non_linear/search/nest/nautilus/search.py:61) <- nautilus/sampler.py:869 evaluate_likelihood <- nautilus/sampler.py:1119 add_samples <- the EP optimiser's factor_step <- ep.py:91. Two of the ten forked workers (PIDs 924667/924668) had segfaulted inside _ctypes.cpython-312 within seconds of the fork ('segfault at 116cd5b08 ... error 4 in _ctypes.cpython-312-x86_64-linux-gnu.so'). Pool._maintain_pool forked replacements and restored the count to ten, but multiprocessing never re-issues a dead worker's in-flight task, so the map() could never return. Nothing reached stderr, because a signal death bypasses Python's exception machinery: every log looked healthy.
Root cause of the path being taken at all: the run was submitted --use_cpu, and scripts/ep.py:58 reads 'use_jax = not use_cpu'. That flag conflates 'run on the CPU partition' with 'disable JAX', so choosing CPU silently disabled the vectorised likelihood and dropped the fit onto the multiprocessing path. JAX-on-CPU, which needs no pool, is unreachable through that flag.
Scope, separable into phased PRs:
- Primary: EP never constructs a process pool. Force pool=None on the EP factor-optimiser path, or refuse number_of_cores>1 with a clear error rather than forking silently. Note the cost to weigh: with a non-JAX likelihood this makes each factor's search single-core, so the serial guard only pays off alongside the JAX path.
- Confirm EP drives a vectorised JAX likelihood end to end (the machinery exists: use_jax is threaded through make_factor_graph), so parallelism comes from vectorisation rather than processes.
- Residual, wider than EP: the dead-worker deadlock affects every multi-core Nautilus fit, not just EP, including per-lens fits and any user running number_of_cores>1. A vanished worker should fail loudly within seconds instead of hanging to the wall clock. Worker count is not a usable health check, because _repopulate_pool refills it; a replacement is distinguishable only by a _maintain_pool frame in its stack. PyAutoFit#1548 is present in the running mirror and does not cover this: it made neural-bound training serial and swapped in likelihood_worker, leaving ordinary likelihood evaluation unguarded. Prior art: PyAutoFit#1439, fix: single-core Nautilus fits build no pool (release-integrate corrective, #1442) #1443, fix(nautilus): serial bound training + no per-task Fitness pickling (#1547) #1548.
Raw py-spy dumps for all eleven processes and the dmesg segfault lines were captured while the job was still live.
Activity
Merge pull request #1610 from PyAutoLabs/feature/ep-no-multiprocessin…
Jammy2211 commentedon Sep 11, 2026
Shipped
915acd5f, labelledpending-release)Summary
AbstractSearch.optimise(the EP factor-optimiser entry, so every search type) refusesnumber_of_cores > 1with aSearchExceptionnaming the search, the value and the two fixes (number_of_cores=1;Analysis(use_jax=True)). A refusal, not a silent downgrade. One log line per factor step says where parallelism comes from._LikelihoodWorkerPool.mapdispatches viamap_asyncand polls; on each poll it checks the exit code of every workerProcesscaptured at construction, so a workermultiprocessing.Poolsilently replaced raises a diagnosableSearchException(PID + signal) within seconds instead of hanging every multi-core Nautilus fit.SIGKILLed worker raises in < 5 s with-9in the message; healthy map returns in order. CI green on nojax / 3.12 / 3.13 / docs.Follow-ups filed in PyAutoMind
draft/bug/graphical_ep/ep_use_cpu_flag_disables_jax.md— theslope_hierarchy_scalescript derivesuse_jax = not use_cpu.draft/bug/autofit/ep_test_suite_is_not_xdist_safe.md—test_autofit/graphicalshares one output directory under-n auto.draft/bug/autofit/dynesty_single_core_path_still_builds_a.md— Dynesty still enters aPool(1)at one core.ParallelEPOptimiserremoval — being filed now as its own refactor.Session: web (issue, PR and merge via the GitHub MCP surface; implementation delegated to a subagent).
Generated by Claude Code