diff --git a/autofit/interpolator/covariance.py b/autofit/interpolator/covariance.py index e398c8d46..a512b2849 100644 --- a/autofit/interpolator/covariance.py +++ b/autofit/interpolator/covariance.py @@ -187,7 +187,9 @@ def _relationships_for_path( """ analysis = self._analysis_for_path(path) model = self.model(path_relationship_map=path_relationship_map or {}) - search = DynestyStatic() + # A small internal fit, run on one core: the `number_of_cores="auto"` default + # would fork a pool of every core for it. + search = DynestyStatic(number_of_cores=1) result = search.fit(model=model, analysis=analysis) return result.instance diff --git a/autofit/non_linear/grid/grid_search/__init__.py b/autofit/non_linear/grid/grid_search/__init__.py index 233238fbd..78c23fc48 100644 --- a/autofit/non_linear/grid/grid_search/__init__.py +++ b/autofit/non_linear/grid/grid_search/__init__.py @@ -27,7 +27,7 @@ def __init__( self, search, number_of_steps: int = 4, - number_of_cores: int = 1, + number_of_cores: Union[int, str] = 1, result_output_interval: int = 100, ): """ @@ -41,6 +41,11 @@ def __init__( The number of steps to go in each direction search The class of the search that is run at each step + number_of_cores + The number of processes the grid's jobs (one fit each) run across: a whole number >= 1 (default 1, + the jobs run in turn and each job's search resolves its own `number_of_cores`), or `"auto"`, the + detected cores. A JAX analysis runs its jobs serially (the JAX fork rule); when the jobs run in + parallel each job's search runs with one core. result_output_interval The interval between saving a GridSearchResult object via paths """ diff --git a/autofit/non_linear/search/_template/search.py b/autofit/non_linear/search/_template/search.py index 3e9e8d36f..b2c7ac427 100644 --- a/autofit/non_linear/search/_template/search.py +++ b/autofit/non_linear/search/_template/search.py @@ -47,7 +47,7 @@ from __future__ import annotations -from typing import Optional +from typing import Optional, Union import numpy as np @@ -96,7 +96,7 @@ def __init__( initializer: Optional[AbstractInitializer] = None, iterations_per_quick_update: int = None, iterations_per_full_update: int = None, - number_of_cores: int = 1, + number_of_cores: Union[int, str] = "auto", silence: bool = False, session=None, **kwargs, diff --git a/autofit/non_linear/search/abstract_search.py b/autofit/non_linear/search/abstract_search.py index 57f8d25f3..41d8fbd23 100644 --- a/autofit/non_linear/search/abstract_search.py +++ b/autofit/non_linear/search/abstract_search.py @@ -98,7 +98,7 @@ def __init__( iterations_per_quick_update: Optional[int] = None, iterations_per_full_update: int = None, live_visual_update: Optional[bool] = None, - number_of_cores: Union[int, str] = 1, + number_of_cores: Union[int, str] = "auto", silence: bool = False, session: Optional[sa.orm.Session] = None, paths: Optional[AbstractPaths] = None, diff --git a/autofit/non_linear/search/mcmc/abstract_mcmc.py b/autofit/non_linear/search/mcmc/abstract_mcmc.py index fe0491bf7..2d65df422 100644 --- a/autofit/non_linear/search/mcmc/abstract_mcmc.py +++ b/autofit/non_linear/search/mcmc/abstract_mcmc.py @@ -1,6 +1,6 @@ from __future__ import annotations -from typing import Optional, TYPE_CHECKING +from typing import Optional, TYPE_CHECKING, Union from autofit.non_linear.search.abstract_search import NonLinearSearch from autofit.non_linear.initializer import Initializer @@ -40,7 +40,7 @@ def __init__( auto_correlation_settings=AutoCorrelationsSettings(), iterations_per_full_update: Optional[int] = None, iterations_per_quick_update: int = None, - number_of_cores: int = 1, + number_of_cores: Union[int, str] = "auto", silence: bool = False, session: Optional[sa.orm.Session] = None, **kwargs diff --git a/autofit/non_linear/search/mcmc/blackjax/nuts/search.py b/autofit/non_linear/search/mcmc/blackjax/nuts/search.py index ed4a7c1fa..202062b1a 100644 --- a/autofit/non_linear/search/mcmc/blackjax/nuts/search.py +++ b/autofit/non_linear/search/mcmc/blackjax/nuts/search.py @@ -3,7 +3,7 @@ import logging import os from pathlib import Path -from typing import Optional, TYPE_CHECKING +from typing import Optional, TYPE_CHECKING, Union import numpy as np @@ -88,7 +88,7 @@ def __init__( auto_correlation_settings: Optional[AutoCorrelationsSettings] = None, iterations_per_quick_update: Optional[int] = None, iterations_per_full_update: Optional[int] = None, - number_of_cores: int = 1, + number_of_cores: Union[int, str] = "auto", silence: bool = False, session: Optional[sa.orm.Session] = None, **kwargs, diff --git a/autofit/non_linear/search/mcmc/blackjax/smc/search.py b/autofit/non_linear/search/mcmc/blackjax/smc/search.py index 83d16b7df..729f5e6c4 100644 --- a/autofit/non_linear/search/mcmc/blackjax/smc/search.py +++ b/autofit/non_linear/search/mcmc/blackjax/smc/search.py @@ -5,7 +5,7 @@ import os import warnings from pathlib import Path -from typing import List, Optional, Tuple, TYPE_CHECKING +from typing import List, Optional, Tuple, TYPE_CHECKING, Union import numpy as np @@ -108,7 +108,7 @@ def __init__( *legacy_positional, iterations_per_quick_update: Optional[int] = None, iterations_per_full_update: Optional[int] = None, - number_of_cores: int = 1, + number_of_cores: Union[int, str] = "auto", silence: bool = False, session: Optional[sa.orm.Session] = None, **kwargs, diff --git a/autofit/non_linear/search/mcmc/emcee/search.py b/autofit/non_linear/search/mcmc/emcee/search.py index 41e802ae1..ab4118e33 100644 --- a/autofit/non_linear/search/mcmc/emcee/search.py +++ b/autofit/non_linear/search/mcmc/emcee/search.py @@ -3,7 +3,7 @@ import logging import os from pathlib import Path -from typing import Dict, Optional, TYPE_CHECKING +from typing import Dict, Optional, TYPE_CHECKING, Union import numpy as np @@ -75,7 +75,7 @@ def __init__( auto_correlation_settings: Optional[AutoCorrelationsSettings] = None, iterations_per_quick_update: int = None, iterations_per_full_update: int = None, - number_of_cores: int = 1, + number_of_cores: Union[int, str] = "auto", silence: bool = False, session: Optional[sa.orm.Session] = None, **kwargs, @@ -110,7 +110,9 @@ def __init__( auto_correlation_settings Customizes and performs auto correlation calculations performed during and after the search. number_of_cores - The number of cores sampling is performed using a Python multiprocessing Pool instance. + The number of cores sampling is performed using a Python multiprocessing Pool instance: a whole + number >= 1, or `"auto"` (the default), every core this process may use, resolved when the fit starts + (1 for a JAX analysis). silence If True, the default print output of the non-linear search is silenced. session diff --git a/autofit/non_linear/search/mcmc/zeus/search.py b/autofit/non_linear/search/mcmc/zeus/search.py index d3b7a39bb..6dd322e5f 100644 --- a/autofit/non_linear/search/mcmc/zeus/search.py +++ b/autofit/non_linear/search/mcmc/zeus/search.py @@ -1,7 +1,7 @@ from __future__ import annotations import logging -from typing import Dict, Optional, TYPE_CHECKING +from typing import Dict, Optional, TYPE_CHECKING, Union import numpy as np import os @@ -81,7 +81,7 @@ def __init__( auto_correlation_settings: Optional[AutoCorrelationsSettings] = None, iterations_per_quick_update: int = None, iterations_per_full_update: int = None, - number_of_cores: int = 1, + number_of_cores: Union[int, str] = "auto", silence: bool = False, session: Optional[sa.orm.Session] = None, **kwargs @@ -116,7 +116,9 @@ def __init__( auto_correlation_settings Customizes and performs auto correlation calculations performed during and after the search. number_of_cores - The number of cores Zeus sampling is performed using a Python multiprocessing Pool instance. + The number of cores Zeus sampling is performed using a Python multiprocessing Pool instance: a whole + number >= 1, or `"auto"` (the default), every core this process may use, resolved when the fit starts + (1 for a JAX analysis). silence If True, the default print output of the non-linear search is silenced. session @@ -210,7 +212,6 @@ def run(self, ctx): nwalkers=self.nwalkers, ndim=model.prior_count, logprob_fn=ctx.fitness.call_wrap, - pool=ctx.pool(), ) search_internal.ncall_total = 0 @@ -225,6 +226,11 @@ def run(self, ctx): total_iterations = 0 iterations_remaining = self.nsteps + # The pool (``None`` on one core) is attached only while zeus samples: a + # multiprocessing pool cannot be pickled, and the sampler is saved (resume state, + # quick updates, the final archive) between and after the sampling calls. + pool = ctx.pool() if iterations_remaining > 0 else None + while iterations_remaining > 0: # zeus casts internally (``self.nsteps = int(iterations)``), so a # float never crashes it — but ``total_iterations`` below is @@ -233,13 +239,19 @@ def run(self, ctx): # (PyAutoFit#1422). iterations = ctx.schedule.next_budget(total_iterations, self.nsteps) - for sample in search_internal.sample( - start=state, - log_prob0=log_posterior_list, - iterations=iterations, - progress=True, - ): - pass + search_internal.pool = pool + + try: + for sample in search_internal.sample( + start=state, + log_prob0=log_posterior_list, + iterations=iterations, + progress=True, + ): + pass + finally: + search_internal.pool = None + search_internal.distribute = map search_internal.ncall_total += search_internal.ncall diff --git a/autofit/non_linear/search/nest/abstract_nest.py b/autofit/non_linear/search/nest/abstract_nest.py index da70c427a..dedeedec7 100644 --- a/autofit/non_linear/search/nest/abstract_nest.py +++ b/autofit/non_linear/search/nest/abstract_nest.py @@ -1,7 +1,7 @@ from __future__ import annotations from abc import ABC -from typing import Optional, TYPE_CHECKING +from typing import Optional, TYPE_CHECKING, Union from autofit.non_linear.search.abstract_search import NonLinearSearch from autofit.non_linear.initializer import AbstractInitializer @@ -38,7 +38,7 @@ def __init__( unique_tag: Optional[str] = None, iterations_per_quick_update: Optional[int] = None, iterations_per_full_update: Optional[int] = None, - number_of_cores: int = 1, + number_of_cores: Union[int, str] = "auto", silence: bool = False, session: Optional[sa.orm.Session] = None, initializer: Optional[AbstractInitializer] = None, diff --git a/autofit/non_linear/search/nest/dynesty/search/abstract.py b/autofit/non_linear/search/nest/dynesty/search/abstract.py index bdba0c09d..7ef4ecf4e 100644 --- a/autofit/non_linear/search/nest/dynesty/search/abstract.py +++ b/autofit/non_linear/search/nest/dynesty/search/abstract.py @@ -130,7 +130,7 @@ def __init__( maxcall: Optional[int] = None, iterations_per_quick_update: int = None, iterations_per_full_update: int = None, - number_of_cores: int = 1, + number_of_cores: Union[int, str] = "auto", silence: bool = False, force_x1_cpu: bool = False, use_jax_jit: Optional[bool] = None, @@ -163,8 +163,9 @@ def __init__( iterations_per_full_update The number of iterations performed between every Dynesty back-up. number_of_cores - The number of cores sampling is performed using a Python multiprocessing Pool instance. A value of 1 - builds no pool and runs serially. + The number of cores sampling is performed using a Python multiprocessing Pool instance: a whole + number >= 1, or `"auto"` (the default), every core this process may use, resolved when the fit starts + (1 for a JAX analysis). A resolved value of 1 builds no pool and runs serially. silence If True, the default print output of the non-linear search is silenced. force_x1_cpu diff --git a/autofit/non_linear/search/nest/dynesty/search/dynamic.py b/autofit/non_linear/search/nest/dynesty/search/dynamic.py index 24a1c39a1..17c70f261 100644 --- a/autofit/non_linear/search/nest/dynesty/search/dynamic.py +++ b/autofit/non_linear/search/nest/dynesty/search/dynamic.py @@ -1,7 +1,7 @@ from __future__ import annotations import sys -from typing import Dict, Optional +from typing import Dict, Optional, Union from autofit.mapper.prior_model.abstract import AbstractPriorModel @@ -50,7 +50,7 @@ def __init__( n_effective: Optional[int] = None, iterations_per_quick_update: int = None, iterations_per_full_update: int = None, - number_of_cores: int = 1, + number_of_cores: Union[int, str] = "auto", silence: bool = False, **kwargs ): @@ -85,7 +85,9 @@ def __init__( iterations_per_full_update 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. + The number of cores sampling is performed using a Python multiprocessing Pool instance: a whole + number >= 1, or `"auto"` (the default), every core this process may use, resolved when the fit starts + (1 for a JAX analysis). """ super().__init__( diff --git a/autofit/non_linear/search/nest/dynesty/search/static.py b/autofit/non_linear/search/nest/dynesty/search/static.py index 79201c728..5ec9d30d2 100644 --- a/autofit/non_linear/search/nest/dynesty/search/static.py +++ b/autofit/non_linear/search/nest/dynesty/search/static.py @@ -52,7 +52,7 @@ def __init__( logl_max: float = float("inf"), iterations_per_quick_update: int = None, iterations_per_full_update: int = None, - number_of_cores: int = 1, + number_of_cores: Union[int, str] = "auto", silence: bool = False, session: Optional[sa.orm.Session] = None, **kwargs, @@ -86,7 +86,9 @@ def __init__( iterations_per_full_update 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. + The number of cores sampling is performed using a Python multiprocessing Pool instance: a whole + number >= 1, or `"auto"` (the default), every core this process may use, resolved when the fit starts + (1 for a JAX analysis). session An SQLalchemy session instance so the results of the model-fit are written to an SQLite database. """ diff --git a/autofit/non_linear/search/nest/nautilus/search.py b/autofit/non_linear/search/nest/nautilus/search.py index 16a9176d9..c7335763a 100644 --- a/autofit/non_linear/search/nest/nautilus/search.py +++ b/autofit/non_linear/search/nest/nautilus/search.py @@ -9,7 +9,7 @@ from contextlib import contextmanager, nullcontext from pathlib import Path from time import monotonic -from typing import Dict, Optional, Tuple, TYPE_CHECKING +from typing import Dict, Optional, Tuple, TYPE_CHECKING, Union from autofit import exc @@ -342,7 +342,7 @@ def __init__( verbose: bool = True, iterations_per_quick_update: Optional[int] = None, iterations_per_full_update: int = None, - number_of_cores: int = 1, + number_of_cores: Union[int, str] = "auto", silence: bool = False, force_x1_cpu: bool = False, session: Optional[sa.orm.Session] = None, @@ -399,7 +399,9 @@ def __init__( iterations_per_full_update 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. + The number of cores sampling is performed using a Python multiprocessing Pool instance: a whole + number >= 1, or `"auto"` (the default), every core this process may use, resolved when the fit starts + (1 for a JAX analysis). Not used by expectation-propagation factor searches, which refuse `number_of_cores > 1` outright (`AbstractSearch.optimise`, human diff --git a/autofit/non_linear/search/nest/nss/search.py b/autofit/non_linear/search/nest/nss/search.py index d66e84205..8f8746da3 100644 --- a/autofit/non_linear/search/nest/nss/search.py +++ b/autofit/non_linear/search/nest/nss/search.py @@ -4,7 +4,7 @@ import os import pickle from pathlib import Path -from typing import Optional, TYPE_CHECKING +from typing import Optional, TYPE_CHECKING, Union import numpy as np @@ -185,7 +185,7 @@ def __init__( checkpoint_interval: int = 100, iterations_per_quick_update: Optional[int] = None, iterations_per_full_update: Optional[int] = None, - number_of_cores: int = 1, + number_of_cores: Union[int, str] = "auto", seed: int = 42, silence: bool = False, session: Optional[sa.orm.Session] = None, diff --git a/autofit/non_linear/settings.py b/autofit/non_linear/settings.py index a158da06c..d9bfc9644 100644 --- a/autofit/non_linear/settings.py +++ b/autofit/non_linear/settings.py @@ -13,7 +13,7 @@ def __init__( self, path_prefix: str, unique_tag: Optional[str] = None, - number_of_cores: Optional[Union[int, str]] = 1, + number_of_cores: Optional[Union[int, str]] = "auto", session: Optional[sa.orm.Session] = None, info: Optional[dict] = None, use_jax_vmap: Optional[bool] = None, @@ -36,7 +36,7 @@ def __init__( for most model fits, but is done on a per-fit basis for grid based searches (e.g. sensitivity mapping). A whole number >= 1, or `"auto"` to use every core this process may use, resolved when the fit starts (after the analysis has resolved its compute setup; 1 for a JAX analysis, and capped by memory when the - analysis declares `resources_per_eval()`). The default is 1. + analysis declares `resources_per_eval()`). The default is `"auto"`. session The SQLite database session which is active means results are directly wrtten to the SQLite database at the end of a fit and loaded from the database at the start. diff --git a/test_autofit/non_linear/search/mcmc/test_emcee.py b/test_autofit/non_linear/search/mcmc/test_emcee.py index e74683a81..93c22f872 100644 --- a/test_autofit/non_linear/search/mcmc/test_emcee.py +++ b/test_autofit/non_linear/search/mcmc/test_emcee.py @@ -41,7 +41,7 @@ def test__explicit_params(): assert search.auto_correlation_settings.check_size == 100 assert search.auto_correlation_settings.required_length == 50 assert search.auto_correlation_settings.change_threshold == 0.01 - assert search.number_of_cores == 1 + assert search.number_of_cores == "auto" def test__log_posteriors_are_aligned_with_the_thinned_chain(monkeypatch): diff --git a/test_autofit/non_linear/search/mcmc/test_zeus.py b/test_autofit/non_linear/search/mcmc/test_zeus.py index 8b4dac8dd..f45ef4d69 100644 --- a/test_autofit/non_linear/search/mcmc/test_zeus.py +++ b/test_autofit/non_linear/search/mcmc/test_zeus.py @@ -46,7 +46,7 @@ def test__explicit_params(): assert search.auto_correlation_settings.check_size == 100 assert search.auto_correlation_settings.required_length == 50 assert search.auto_correlation_settings.change_threshold == 0.01 - assert search.number_of_cores == 1 + assert search.number_of_cores == "auto" requires_zeus = pytest.mark.skipif( diff --git a/test_autofit/non_linear/search/nest/test_dynesty.py b/test_autofit/non_linear/search/nest/test_dynesty.py index 2024f0520..0378f3a9c 100644 --- a/test_autofit/non_linear/search/nest/test_dynesty.py +++ b/test_autofit/non_linear/search/nest/test_dynesty.py @@ -42,7 +42,7 @@ def test__explicit_params(): assert search.nlive == 50 assert search.dlogz is None - assert search.number_of_cores == 1 + assert search.number_of_cores == "auto" search = af.DynestyDynamic( facc=0.4, @@ -61,7 +61,7 @@ def test__explicit_params(): assert search.facc == 0.2 assert search.dlogz_init == 0.01 - assert search.number_of_cores == 1 + assert search.number_of_cores == "auto" def test__dynamic_n_effective_passed_to_run_nested_only_when_set(): diff --git a/test_autofit/non_linear/search/nest/test_nautilus.py b/test_autofit/non_linear/search/nest/test_nautilus.py index 2b12f7d50..cfcfee8fa 100644 --- a/test_autofit/non_linear/search/nest/test_nautilus.py +++ b/test_autofit/non_linear/search/nest/test_nautilus.py @@ -187,7 +187,7 @@ def test__explicit_params(): assert search.n_shell == 1 assert search.n_eff == 500 assert search.discard_exploration is False - assert search.number_of_cores == 1 + assert search.number_of_cores == "auto" def test__identifier_fields(): diff --git a/test_autofit/non_linear/search/template_toy_search.py b/test_autofit/non_linear/search/template_toy_search.py index 03fc581c7..12aad8be3 100644 --- a/test_autofit/non_linear/search/template_toy_search.py +++ b/test_autofit/non_linear/search/template_toy_search.py @@ -7,7 +7,7 @@ from __future__ import annotations -from typing import Optional +from typing import Optional, Union import numpy as np @@ -56,7 +56,7 @@ def __init__( initializer: Optional[AbstractInitializer] = None, iterations_per_quick_update: int = None, iterations_per_full_update: int = None, - number_of_cores: int = 1, + number_of_cores: Union[int, str] = "auto", silence: bool = False, session=None, **kwargs, diff --git a/test_autofit/non_linear/test_dict.py b/test_autofit/non_linear/test_dict.py index fff0fbc9d..5504470dd 100644 --- a/test_autofit/non_linear/test_dict.py +++ b/test_autofit/non_linear/test_dict.py @@ -32,7 +32,7 @@ def make_dynesty_dict(): "maxiter": None, "name": "", "nlive": 50, - "number_of_cores": 1, + "number_of_cores": "auto", "path_prefix": None, "paths": { "arguments": {},