diff --git a/AGENTS.md b/AGENTS.md index 5992b1f48..40ee685fa 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -76,7 +76,7 @@ nautilus; MLE: LBFGS/BFGS/drawer), `mapper/` (model + priors), factor-graph/message engine and the `declarative/` user layer. A new statistical capability in the inner layer must land **in the same PR** with its declarative expression *or* an explicit "not exposed" row in - the lowering-contract table (`autofit/graphical/README.md` §8), plus a + the lowering-contract table (`autofit/graphical/README.md` §7), plus a seam test where behaviour crosses the boundary (`test_autofit/graphical/test_declarative_deterministic.py` is the pattern). Capabilities that exist below but are silently absent above diff --git a/autofit/graphical/README.md b/autofit/graphical/README.md index 6700396bb..7c7f729dd 100644 --- a/autofit/graphical/README.md +++ b/autofit/graphical/README.md @@ -348,7 +348,7 @@ relation holds exactly inside each factor), while `factor_out` trades that exactness for modularity (the deterministic variable receives its own messages and `q(z)` factorises from its parents). The declarative surface for deterministic quantities is the explicit compound pattern -(e.g. `model.sigma * 2.355`), pinned by the seam tests (§8); the +(e.g. `model.sigma * 2.355`), pinned by the seam tests (§7); the `model.` sugar from #1153 was deliberately retired. 1. **Graph-level deterministic variables**: `Factor(..., factor_out=v)` @@ -364,19 +364,10 @@ surface for deterministic quantities is the explicit compound pattern 3. **Free shared variables**: share a prior across factors and encode the relation inside the likelihood. -## 7. Parallel EP — `ParallelEPOptimiser` - -All factor approximations for a sweep are built from the **same** -mean field, factor optimisations run in a process pool, and the updates -are applied sequentially afterwards. This is standard "parallel EP" -semantics: cavities within a sweep are stale relative to serial EP, so -serial and parallel runs converge along different trajectories (to the -same fixed points when EP converges). - -## 8. The lowering contract (declarative → graph) +## 7. The lowering contract (declarative → graph) `autofit.graphical` is two layers: the **inner layer** above (factor -graphs, messages, EP updates — this document's §1–§7) and the +graphs, messages, EP updates — this document's §1–§6) and the **declarative layer** (`declarative/`: `FactorGraphModel`, `AnalysisFactor`, `HierarchicalFactor`) that scientists actually use. This section is the seam contract: what every declarative concept @@ -402,7 +393,7 @@ declarative expression, or an explicit "not exposed" entry with the reason. Capabilities that exist below but are silently absent above (the `PriorFactor` exact-hooks row) are the seam's known failure mode. -## 9. Reading +## 8. Reading - T. Minka (2001), *Expectation Propagation for Approximate Bayesian Inference* — the algorithm of §3. diff --git a/autofit/graphical/expectation_propagation/optimiser.py b/autofit/graphical/expectation_propagation/optimiser.py index ced35100e..6ee1dfa14 100644 --- a/autofit/graphical/expectation_propagation/optimiser.py +++ b/autofit/graphical/expectation_propagation/optimiser.py @@ -1,5 +1,4 @@ import logging -import multiprocessing import os from abc import ABC, abstractmethod from pathlib import Path @@ -13,7 +12,6 @@ from autofit.graphical.mean_field import Status, MeanField, FactorApproximation from autofit.graphical.utils import StatusFlag, LogWarnings from autofit.mapper.identifier import Identifier -from autofit.non_linear.parallel import fork_context from autofit.non_linear.paths import DirectoryPaths from autofit.non_linear.paths.abstract import AbstractPaths from autofit.tools.util import IntervalCounter @@ -661,177 +659,3 @@ def _warn_sigma_collapse(self): """ for warning in check_sigma_collapse(self.diagnostics): logger.warning(warning) - - -class ParallelEPOptimiser(EPOptimiser): - def __init__( - self, - factor_graph: FactorGraph, - n_cores: int, - default_optimiser: Optional[AbstractFactorOptimiser] = None, - factor_optimisers: Optional[Dict[Factor, AbstractFactorOptimiser]] = None, - ep_history: Optional[EPHistory] = None, - factor_order: Optional[List[Factor]] = None, - paths: AbstractPaths = None, - updater: Optional[ApproxUpdater] = None, - ): - """ - Optimise a factor graph. - - 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. - 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 - Specific optimisers used to optimise each factor - ep_history - Optionally specify an alternate history - factor_order - The factors in the graph but placed in the order in which they should - be optimised - paths - Optionally define how data should be output - """ - - if n_cores < 3: - raise AssertionError( - "With less than three cores it is better to use EPOptimiser" - ) - - super().__init__( - factor_graph=factor_graph, - default_optimiser=default_optimiser, - factor_optimisers=factor_optimisers, - ep_history=ep_history, - factor_order=factor_order, - paths=paths, - updater=updater, - ) - self.pool = fork_context().Pool(n_cores - 1) - - def run( - self, - model_approx: EPMeanField, - max_steps: int = 100, - log_interval: int = 10, - visualise_interval: int = 100, - output_interval: int = 10, - max_consecutive_failures: int = 3, - ) -> EPMeanField: - """ - Run the optimisation on an approximation of the model. - - Parameters - ---------- - model_approx - A collection of messages describing priors on the model's variables. - max_steps - The maximum number of steps prior to termination. Termination may also - occur when difference in log evidence or KL Divergence drop below a given - threshold for two consecutive optimisations of a given factor. - log_interval - How steps should we wait before logging information? - visualise_interval - How steps should we wait before visualising information? - This includes plots of KL Divergence and Evidence. - output_interval - How steps should we wait before outputting information? - This includes the model.results file which describes the current mean values - of each message. - max_consecutive_failures - How many consecutive sweeps a single factor's optimiser may raise on - before the fit is aborted. See `EPOptimiser.run`. - - Returns - ------- - An updated approximation of the model - """ - should_log = IntervalCounter(log_interval) - should_visualise = IntervalCounter(visualise_interval) - should_output = IntervalCounter(output_interval) - - self._consecutive_failures = {} - self._factors_raised = set() - self._factors_skipped = set() - self._factors_updated = set() - self._variables_seen = {} - self._variables_changed = {} - self._factor_sweeps = {} - - for _ in range(max_steps): - _should_log = should_log() - _should_visualise = should_visualise() - _should_output = should_output() - - factor_approx_optimisers = [ - (model_approx.factor_approximation(factor), optimiser) - for factor, optimiser in self.factor_optimisers.items() - ] - - new_dist_statuses = self.pool.starmap(factor_step, factor_approx_optimisers) - - for (factor_approx, _), (new_model_dist, status) in zip( - factor_approx_optimisers, new_dist_statuses - ): - raised = status.flag is StatusFlag.EXCEPTION - model_approx, status = self.updater.update_model_approx( - new_model_dist, factor_approx, model_approx, status - ) - factor = factor_approx.factor - self.diagnostics.snapshot(factor, model_approx, status) - if self._check_consecutive_failures( - factor, status, max_consecutive_failures, raised=raised - ): - break - if status and _should_log: - self._log_factor(factor) - - if self.ep_history(factor, model_approx, status): - logger.info("Terminating optimisation") - break # callback controls convergence - - else: # If no break do next iteration - if self.visualiser and _should_visualise: - self.visualiser() - if self.output_path and _should_output: - self._output_results(model_approx) - self._output_diagnostics() - continue - break # stop iterations - - if self.visualiser: - self.visualiser() - if self.output_path: - self._output_results(model_approx) - self._output_diagnostics(final=True, model_approx=model_approx) - self._warn_sigma_collapse() - self._warn_stale_factors() - - return model_approx diff --git a/test_autofit/graphical/functionality/test_diagnostics.py b/test_autofit/graphical/functionality/test_diagnostics.py index 14c9b3f34..97ad36483 100644 --- a/test_autofit/graphical/functionality/test_diagnostics.py +++ b/test_autofit/graphical/functionality/test_diagnostics.py @@ -173,23 +173,17 @@ def test_no_collapse_on_healthy_run(): assert graph.check_sigma_collapse(opt.diagnostics) == [] -def test_parallel_end_of_run_guards(): +def test_end_of_run_guards_no_paths(): """ - F3: a real ParallelEPOptimiser run needs n_cores >= 3 and spins up a - multiprocessing.Pool. The only existing ParallelEPOptimiser test in - this repo, `_test_parallel_laplace` in - test_autofit/graphical/regression/test_linear_regression.py, is - prefixed with an underscore so pytest never collects it -- i.e. a - real parallel run is already established as impractical to exercise - routinely under this test suite (pool startup cost / environment - flakiness), so we don't add a second one here. - - Instead we verify directly the end-of-run diagnostics guards that - ParallelEPOptimiser.run shares with EPOptimiser.run (both call - self._output_diagnostics(...) and self._warn_sigma_collapse() after - the main loop): with paths=False, self.visualiser stays None and - self.output_path stays None, and both calls must be no-ops rather - than raising. + `EPOptimiser.run` calls `self._output_diagnostics(...)` and + `self._warn_sigma_collapse()` once the main loop has finished, both + of them unconditionally on the final pass. With `paths=False`, + `self.visualiser` and `self.output_path` both stay None, so those + end-of-run calls must guard on them and be no-ops rather than + raising. + + This exercises those guards directly, without running a full fit to + reach them. """ model_approx, x = make_model_approx() @@ -199,8 +193,8 @@ def test_parallel_end_of_run_guards(): assert opt.output_path is None # no snapshots taken yet -- factor_rows/variable_rows are empty, which - # is the same state ParallelEPOptimiser.run's guards must tolerate - # before touching self.output_path / self.visualiser. + # is the emptiest state these guards must tolerate before touching + # self.output_path / self.visualiser. opt._output_diagnostics() opt._output_diagnostics(final=True, model_approx=model_approx) opt._warn_sigma_collapse() diff --git a/test_autofit/graphical/regression/test_linear_regression.py b/test_autofit/graphical/regression/test_linear_regression.py index 0e0d48189..6d2174abe 100644 --- a/test_autofit/graphical/regression/test_linear_regression.py +++ b/test_autofit/graphical/regression/test_linear_regression.py @@ -7,7 +7,6 @@ EPOptimiser, Factor, ) -from autofit.graphical.expectation_propagation.optimiser import ParallelEPOptimiser from autofit.messages import FixedMessage, NormalMessage np.random.seed(1) @@ -129,25 +128,6 @@ def test_laplace( check_model_approx(mean_field, a_, b_, z_, x_, y_) -def _test_parallel_laplace( - model_approx, - a_, - b_, - x_, - y_, - z_, -): - laplace = LaplaceOptimiser() - opt = ParallelEPOptimiser( - model_approx.factor_graph, - n_cores=len(model_approx.factors) + 1, - default_optimiser=laplace, - ) - model_approx = opt.run(model_approx) - mean_field = model_approx.mean_field - check_model_approx(mean_field, a_, b_, z_, x_, y_) - - def _test_laplace_jac( model_jac_approx, a_, diff --git a/test_autofit/graphical/test_declarative_deterministic.py b/test_autofit/graphical/test_declarative_deterministic.py index 63eb4f397..20f24744d 100644 --- a/test_autofit/graphical/test_declarative_deterministic.py +++ b/test_autofit/graphical/test_declarative_deterministic.py @@ -1,6 +1,6 @@ """ Seam tests for the declarative → graph lowering contract -(`autofit/graphical/README.md` §8), focused on deterministic quantities +(`autofit/graphical/README.md` §7), focused on deterministic quantities expressed as compound priors. History: PR #1153 introduced this pattern with an illustration test that @@ -44,7 +44,7 @@ def test_compound_lowering_adds_no_variables(factor_graph_pieces): """ A compound prior lowers to *no* graph variable: only its component priors are variables, and they are shared with the source models - (README §8 — the relation is enforced exactly inside each factor). + (README §7 — the relation is enforced exactly inside each factor). """ model_1, model_2, deterministic_model, _, factor_graph = factor_graph_pieces