diff --git a/autofit/graphical/declarative/collection.py b/autofit/graphical/declarative/collection.py index 644e66d08..582efc2a0 100644 --- a/autofit/graphical/declarative/collection.py +++ b/autofit/graphical/declarative/collection.py @@ -1,5 +1,6 @@ -from typing import List, Union, Optional +from typing import Dict, List, Union, Optional +from autofit.graphical.declarative.factor.analysis import AnalysisFactor from autofit.graphical.declarative.factor.hierarchical import HierarchicalFactor from autofit.tools.namer import namer @@ -141,6 +142,90 @@ def check_backend_agreement(self): f"(graph.optimise) allows mixed factors." ) + def modify_before_fit(self, paths: AbstractPaths, model): + """ + Forward ``modify_before_fit`` to every factor's analysis before a whole-graph fit, + so each factor resolves its own compute setup (e.g. a PyAutoGalaxy / PyAutoLens + ``setup=``) exactly as it would fitted alone. + + Each analysis factor gets its own sub-paths (``analyses/analysis_``, as + ``_for_each_analysis`` names them) and its own model: the ``i``-th child of the + fitted ``model`` (which may carry replacement priors, e.g. in a grid-search + cell), else the factor's ``prior_model``. ``AnalysisFactor.modify_before_fit`` + rebinds both of the factor's analysis references to the object returned. + Hierarchical factors carry no analysis and are skipped. The factors must then + agree on their resolved setup (``check_setup_agreement``). + + Returns + ------- + This graph, its factors now holding their modified analyses. + """ + factors = self.model_factors + for i, factor in enumerate(factors): + if not isinstance(factor, (AnalysisFactor, FactorGraphModel)): + continue + child_paths = paths.for_sub_analysis(analysis_name=f"analyses/analysis_{i}") + factor.modify_before_fit(child_paths, self._factor_model(model, i, factor)) + + self.check_setup_agreement() + return self + + def _factor_model(self, model, index: int, factor): + """ + The model of factor ``index`` within the fitted graph ``model``, or the factor's + own ``prior_model`` when ``model`` does not have one child per factor. + """ + try: + if model is not None and len(model) == len(self.model_factors): + return model[index] + except (TypeError, KeyError, IndexError, AttributeError): + pass + return factor.prior_model + + def setup_ids(self) -> Dict[str, str]: + """ + The resolved compute setup of each factor that has one, as {factor name: + setup_id} (``analysis.setup.setup_id``, duck-typed: factors whose analysis has + no ``setup`` are left out). + """ + from autofit.non_linear.parallel.pool import setup_id_of + + ids = {} + for factor in self._flat_factors(): + setup_id = setup_id_of(factor) + if setup_id is not None: + ids[factor.name] = setup_id + return ids + + def check_setup_agreement(self): + """ + Raise ``SearchException`` when the factors resolved different compute setups. + + A whole-graph fit evaluates every factor in one process, so every factor that + has a setup must have resolved the same one (factors without a setup are + ignored). Called at the end of ``modify_before_fit`` and by the runtime gates + beside ``check_backend_agreement``. + """ + ids = self.setup_ids() + if len(set(ids.values())) <= 1: + return + + from autofit import exc + + by_setup = {} + for name, setup_id in ids.items(): + by_setup.setdefault(setup_id, []).append(name) + listing = "; ".join( + f"{setup_id}: {', '.join(names)}" for setup_id, names in by_setup.items() + ) + raise exc.SearchException( + f"The FactorGraphModel {self.name} is fitted as one analysis, but its " + f"factors resolved different compute setups ({listing}). Whole-graph " + f"fitting evaluates every factor in one process, so every factor must use " + f"the same setup: build every factor's analysis with the same setup= (or " + f"none, so each resolves the default)." + ) + @property def gradient_mode(self) -> str: """ diff --git a/autofit/graphical/declarative/factor/analysis.py b/autofit/graphical/declarative/factor/analysis.py index 061895932..34e0fcef2 100644 --- a/autofit/graphical/declarative/factor/analysis.py +++ b/autofit/graphical/declarative/factor/analysis.py @@ -86,6 +86,29 @@ def __init__( name=name, ) + def modify_before_fit(self, paths: AbstractPaths, model: AbstractPriorModel): + """ + Forward ``modify_before_fit`` to the wrapped analysis and rebind this factor to + the analysis it returns (``rebind_analysis``), so the factor evaluates the + modified analysis (e.g. one whose compute setup is resolved). + + Returns + ------- + This factor. + """ + self.rebind_analysis(self.analysis.modify_before_fit(paths=paths, model=model)) + return self + + def rebind_analysis(self, analysis: Analysis): + """ + Point both of this factor's analysis references at ``analysis``: the factor's own + ``analysis`` and the ``FactorCallable`` the graph evaluates. + """ + self.analysis = analysis + factor = self.__dict__.get("_factor") + if isinstance(factor, FactorCallable): + factor.analysis = analysis + @property def is_jax(self) -> bool: """ diff --git a/autofit/graphical/expectation_propagation/search_factor_optimiser.py b/autofit/graphical/expectation_propagation/search_factor_optimiser.py index a1ad7ad36..ffe71d949 100644 --- a/autofit/graphical/expectation_propagation/search_factor_optimiser.py +++ b/autofit/graphical/expectation_propagation/search_factor_optimiser.py @@ -140,11 +140,16 @@ def optimise( search._visualize_fit = visualize_ep_factor_searches search._visualize_before_fit = visualize_ep_factor_searches or number == 0 + # Marks the fit as an EP factor search, so a `number_of_cores="auto"` request + # resolves to 1 (`autofit.non_linear.parallel.pool.resolve_number_of_cores`). + search._ep_factor_search = True + try: result = search.fit(model=model, analysis=analysis) finally: search._visualize_fit = True search._visualize_before_fit = True + search._ep_factor_search = False # Record the sampler's log-evidence of this tilted-distribution fit on # the projected mean field — the per-factor Ẑₐ that README §5 documents diff --git a/autofit/non_linear/grid/grid_search/__init__.py b/autofit/non_linear/grid/grid_search/__init__.py index 0083ab909..233238fbd 100644 --- a/autofit/non_linear/grid/grid_search/__init__.py +++ b/autofit/non_linear/grid/grid_search/__init__.py @@ -51,9 +51,13 @@ def __init__( self.logger.info("Creating grid search") - self.number_of_cores = number_of_cores or 1 + # "auto" is the detected cores: each job is a whole fit, so there is no one + # analysis to cap the count by. + from autofit.non_linear.parallel.resources import resolve_job_cores - self.logger.info(f"Using {number_of_cores} core(s)") + self.number_of_cores = resolve_job_cores(number_of_cores, where="GridSearch") + + self.logger.info(f"Using {self.number_of_cores} core(s)") self._result_output_interval = result_output_interval diff --git a/autofit/non_linear/grid/sensitivity/__init__.py b/autofit/non_linear/grid/sensitivity/__init__.py index 554c810f7..4f8822d9d 100644 --- a/autofit/non_linear/grid/sensitivity/__init__.py +++ b/autofit/non_linear/grid/sensitivity/__init__.py @@ -84,7 +84,8 @@ def __init__( mapping. This is useful for removing regions of the sensitivity grid that are expected to have no sensitivity, for example because they have no signal. number_of_cores - How many cores does this computer have? + The number of jobs run in parallel: a whole number >= 1, or "auto" for every core this process may + use (`SLURM_CPUS_PER_TASK`, then the CPU affinity, then `os.cpu_count()`). limit_scale Scales the priors for each perturbation model. A scale of 1 means priors have limits the same size as the grid square. @@ -130,7 +131,11 @@ def __init__( """ ) - self.number_of_cores = number_of_cores + # "auto" is the detected cores: each job is a whole fit, so there is no one + # analysis to cap the count by. + from autofit.non_linear.parallel.resources import resolve_job_cores + + self.number_of_cores = resolve_job_cores(number_of_cores, where="Sensitivity") self.limit_scale = limit_scale diff --git a/autofit/non_linear/parallel/__init__.py b/autofit/non_linear/parallel/__init__.py index b8ed99830..27c7c5ee8 100644 --- a/autofit/non_linear/parallel/__init__.py +++ b/autofit/non_linear/parallel/__init__.py @@ -5,8 +5,18 @@ from .sneaky import SneakyJob from .sneaky import SneakyPool from .pool import ( + ParallelResolution, PoolFactory, check_factor_search_cores, effective_number_of_cores, jax_backend_initialized, + resolve_number_of_cores, + setup_id_of, +) +from .resources import ( + available_memory_gb, + detected_cores, + is_auto, + resolve_job_cores, + validate_number_of_cores, ) diff --git a/autofit/non_linear/parallel/pool.py b/autofit/non_linear/parallel/pool.py index 410fd9afc..78e0023f6 100644 --- a/autofit/non_linear/parallel/pool.py +++ b/autofit/non_linear/parallel/pool.py @@ -21,14 +21,35 @@ ``effective_number_of_cores`` is the rule; ``PoolFactory`` applies it to a search's fit and builds the pools the searches use, with the same pool classes, start method and arguments as before (``fork_context``), so pool semantics are unchanged wherever forking is allowed. + +**``number_of_cores="auto"``.** ``resolve_number_of_cores`` turns a search's request into +the worker count of one fit, after ``Analysis.modify_before_fit`` has resolved the +analysis's compute setup: an int request is honoured (the fork rule aside); ``"auto"`` is +the detected cores (``SLURM_CPUS_PER_TASK`` -> CPU affinity -> ``os.cpu_count()``), 1 for a +JAX analysis or an expectation-propagation factor search, and is capped by +``min(cores // cpus_per_eval, available memory // peak_rss_gb)`` only when the analysis +declares ``resources_per_eval()``. There is deliberately no parallel-efficiency cap: the one +measured curve (imaging, rectangular pixelization, numba) has cores x efficiency rising at +every step up to 32 cores, so throughput favours every core. The result +(``ParallelResolution``) drives the fit's one ``Parallel: ...`` banner line, +``search.summary`` and ``files/parallel.json``; ``search.json`` keeps the request. """ import logging +import math import sys -from typing import Optional +from dataclasses import dataclass, asdict +from typing import Optional, Union from autofit import exc from .context import fork_context +from .resources import ( + AUTO, + available_memory_gb, + detected_cores, + is_auto, + validate_number_of_cores, +) logger = logging.getLogger(__name__) @@ -108,7 +129,12 @@ def check_factor_search_cores(search): """ number_of_cores = getattr(search, "number_of_cores", 1) - if number_of_cores > 1: + # "auto" asks PyAutoFit to choose, and a factor search resolves it to 1 + # (`resolve_number_of_cores`), so only an explicit count above 1 is refused. + if is_auto(number_of_cores): + return + + if (number_of_cores or 1) > 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 " @@ -127,9 +153,287 @@ def check_factor_search_cores(search): f"with vectorized=True and no pool at all." ) +JAX_REASON = "JAX analyses run single-process" +EP_REASON = "expectation-propagation factor searches run single-process" + + +@dataclass +class ParallelResolution: + """ + The worker count of one fit and why (``resolve_number_of_cores``). + + Attributes + ---------- + requested + The search's ``number_of_cores``: an int or ``"auto"``. + number_of_cores + The resolved worker count. + reason + Why: ``"requested"`` (an int honoured), ``"detected_cores"`` (auto, uncapped), + ``"jax"``, ``"expectation_propagation"``, ``"cores_per_eval"`` or ``"memory"``. + detected_cores + The cores this process may use (``None`` when not probed). + available_memory_gb + The memory available when the memory cap was evaluated (``None`` otherwise). + setup_id + The analysis's resolved compute setup (``analysis.setup.setup_id``), or ``None``. + cpus_per_eval, peak_rss_gb + The analysis's ``resources_per_eval()`` (``None`` when it declares none). + """ + + requested: Union[int, str] + number_of_cores: int + reason: str + detected_cores: Optional[int] = None + available_memory_gb: Optional[float] = None + setup_id: Optional[str] = None + cpus_per_eval: Optional[float] = None + peak_rss_gb: Optional[float] = None + + @property + def reason_text(self) -> str: + """ + The reason as the banner and ``search.summary`` say it; empty for an honoured + int request. + """ + if self.reason == "detected_cores": + return "detected cores" + if self.reason == "jax": + return JAX_REASON + if self.reason == "expectation_propagation": + return EP_REASON + if self.reason == "cores_per_eval": + return ( + f"capped by cores: {self.detected_cores} cores / " + f"{_number(self.cpus_per_eval)} CPUs per evaluation" + ) + if self.reason == "memory": + return ( + f"capped by memory: {self.available_memory_gb:.1f} GB available / " + f"{_number(self.peak_rss_gb)} GB per evaluation" + ) + return "" + + @property + def banner(self) -> str: + """ + The one INFO line a fit logs once its compute setup is resolved, e.g. + ``Parallel: 64 workers (requested auto; detected cores) · setup numba_cpu_sparse_fp64``. + """ + workers = "worker" if self.number_of_cores == 1 else "workers" + detail = f"requested {self.requested}" + if self.reason_text: + detail += f"; {self.reason_text}" + line = f"Parallel: {self.number_of_cores} {workers} ({detail})" + if self.setup_id is not None: + line += f" · setup {self.setup_id}" + return line + + @property + def summary(self) -> str: + """ + The ``search.summary`` lines recording the requested and effective worker + counts, the reason and the compute setup. + """ + line = ( + f"Number of cores = {self.number_of_cores} " + f"(requested {self.requested})" + ) + if self.reason == "jax" and not is_auto(self.requested): + line += f": {JAX_FORK_REASON}" + elif self.reason_text: + line += f": {self.reason_text}" + line += "\n" + if self.setup_id is not None: + line += f"Setup = {self.setup_id}\n" + return line + + def to_dict(self) -> dict: + """ + The ``files/parallel.json`` record. + """ + record = asdict(self) + return { + key: record[key] + for key in ( + "requested", + "number_of_cores", + "reason", + "detected_cores", + "available_memory_gb", + "setup_id", + ) + } + + +def _number(value) -> str: + """ + ``value`` without a trailing ``.0`` when it is whole. + """ + try: + if float(value).is_integer(): + return str(int(value)) + except (TypeError, ValueError): + pass + return str(value) + + +def _unwrap_analysis(analysis): + """ + The analysis a wrapper (``ModelAnalysis``, ``AnalysisFactor``) forwards to; the + analysis itself when it wraps nothing. + """ + seen = set() + while analysis is not None and id(analysis) not in seen: + seen.add(id(analysis)) + inner = getattr(analysis, "__dict__", {}).get("analysis") + if inner is None or inner is analysis: + break + analysis = inner + return analysis + + +def setup_id_of(analysis) -> Optional[str]: + """ + The resolved compute setup of ``analysis`` (``analysis.setup.setup_id``, set by a + PyAutoGalaxy / PyAutoLens ``modify_before_fit``), duck-typed so PyAutoFit never + imports autoarray. A factor graph reports the setup its factors agree on + (``FactorGraphModel.setup_ids``). ``None`` when there is none. + """ + analysis = _unwrap_analysis(analysis) + if analysis is None: + return None + + setup_ids = getattr(type(analysis), "setup_ids", None) + if callable(setup_ids): + ids = set(analysis.setup_ids().values()) + return ids.pop() if len(ids) == 1 else None + + setup = getattr(analysis, "__dict__", {}).get("setup") + if setup is None: + try: + setup = getattr(analysis, "setup", None) + except Exception: + setup = None + setup_id = getattr(setup, "setup_id", None) + return None if setup_id is None else str(setup_id) + + +def resources_per_eval_of(analysis): + """ + ``(cpus_per_eval, peak_rss_gb)`` from the analysis's optional ``resources_per_eval()`` + hook (a dict or an object with those attributes), each ``None`` when not declared. + """ + analysis = _unwrap_analysis(analysis) + hook = getattr(analysis, "resources_per_eval", None) + if not callable(hook): + return None, None + + resources = hook() + if resources is None: + return None, None + + def read(name): + if isinstance(resources, dict): + value = resources.get(name) + else: + value = getattr(resources, name, None) + try: + value = float(value) if value is not None else None + except (TypeError, ValueError): + return None + return value if value is not None and value > 0 else None + + return read("cpus_per_eval"), read("peak_rss_gb") + + +def resolve_number_of_cores( + requested, + analysis=None, + is_jax: Optional[bool] = None, + where: str = "search", + ep_factor_search: bool = False, +) -> ParallelResolution: + """ + The worker count of one fit: the request, resolved after + ``Analysis.modify_before_fit``. + + - An int request is honoured, except a JAX analysis runs one process (the fork + rule; ``effective_number_of_cores`` logs its INFO line where the pools are built). + - ``"auto"`` is 1 for a JAX analysis or an expectation-propagation factor search, + otherwise the detected cores, capped by + ``min(cores // cpus_per_eval, floor(available_gb / peak_rss_gb))`` (never below + 1) only when the analysis declares ``resources_per_eval()``. + + Logs nothing; the fit logs ``ParallelResolution.banner``. + + Parameters + ---------- + requested + The search's ``number_of_cores`` (validated here). + analysis + The analysis being fitted, after ``modify_before_fit`` (or ``None``). + is_jax + Whether the analysis is JAX; defaults to ``analysis.is_jax``. + where + What is asking, for the validation error. + ep_factor_search + Whether the search is an expectation-propagation factor search. + """ + requested = validate_number_of_cores(requested, where=where) + if is_jax is None: + is_jax = bool(getattr(analysis, "is_jax", False)) + setup_id = setup_id_of(analysis) + + def resolution(n, reason, **kwargs): + return ParallelResolution( + requested=requested, + number_of_cores=n, + reason=reason, + setup_id=setup_id, + **kwargs, + ) + + if requested != AUTO: + if is_jax and requested > 1: + return resolution(1, "jax") + return resolution(requested, "requested") + + if is_jax: + return resolution(1, "jax") + if ep_factor_search: + return resolution(1, "expectation_propagation") + + cores = detected_cores() + cpus_per_eval, peak_rss_gb = resources_per_eval_of(analysis) + + n, reason = cores, "detected_cores" + available = None + + if cpus_per_eval is not None: + by_cores = max(1, int(cores // cpus_per_eval)) + if by_cores < n: + n, reason = by_cores, "cores_per_eval" + + if peak_rss_gb is not None: + available = available_memory_gb() + if available is not None: + by_memory = max(1, int(math.floor(available / peak_rss_gb))) + if by_memory < n: + n, reason = by_memory, "memory" + + return resolution( + n, + reason, + detected_cores=cores, + available_memory_gb=None if available is None else round(available, 3), + cpus_per_eval=cpus_per_eval, + peak_rss_gb=peak_rss_gb, + ) + class PoolFactory: - def __init__(self, search, analysis=None): + def __init__(self, search, analysis=None, resolution=None): """ The pools one fit of ``search`` may use, with the JAX fork rule applied once. @@ -146,16 +450,35 @@ def __init__(self, search, analysis=None): analysis The analysis being fitted, whose ``is_jax`` drives the fork rule. ``None`` (no fit context) applies no JAX rule. + resolution + The fit's ``ParallelResolution``, when ``NonLinearSearch`` already resolved + it after ``modify_before_fit``; otherwise it is resolved here + (``resolve_number_of_cores``). """ self.search = search - self.requested = getattr(search, "number_of_cores", 1) or 1 self.is_jax = bool(getattr(analysis, "is_jax", False)) - self.number_of_cores = effective_number_of_cores( - requested=self.requested, - is_jax=self.is_jax, - where=type(search).__name__, - ) + if resolution is None: + resolution = resolve_number_of_cores( + requested=getattr(search, "number_of_cores", 1), + analysis=analysis, + is_jax=self.is_jax, + where=type(search).__name__, + ep_factor_search=bool(getattr(search, "_ep_factor_search", False)), + ) + self.resolution = resolution + self.requested = resolution.requested + + # The JAX fork rule's one INFO line for an explicit count above 1 (an "auto" + # request is explained by the fit's `Parallel:` banner instead). + if not is_auto(self.requested): + effective_number_of_cores( + requested=self.requested, + is_jax=self.is_jax, + where=type(search).__name__, + ) + + self.number_of_cores = resolution.number_of_cores self._created = [] @@ -191,15 +514,10 @@ def prepare_for_fork(self, fitness=None): @property def summary(self) -> str: """ - The ``search.summary`` line recording the requested and effective worker counts. + The ``search.summary`` lines recording the requested and effective worker + counts, the reason and the compute setup (``ParallelResolution.summary``). """ - line = ( - f"Number of cores = {self.number_of_cores} " - f"(requested {self.requested})" - ) - if self.number_of_cores < self.requested: - line += f": {JAX_FORK_REASON}" - return line + "\n" + return self.resolution.summary def __call__(self, n_cores: Optional[int] = None, **pool_kwargs): """ diff --git a/autofit/non_linear/parallel/resources.py b/autofit/non_linear/parallel/resources.py new file mode 100644 index 000000000..388a54371 --- /dev/null +++ b/autofit/non_linear/parallel/resources.py @@ -0,0 +1,201 @@ +""" +The machine probes and the ``number_of_cores`` validation behind ``number_of_cores="auto"``. + +- ``validate_number_of_cores`` is the one check every search, ``SettingsSearch``, the grid + search and sensitivity mapping apply to a requested count: an int >= 1, ``None`` (1) or + ``"auto"`` (any case). +- ``detected_cores`` is the cores this process may use (``SLURM_CPUS_PER_TASK``, then the + CPU affinity, then ``os.cpu_count()``; ``autonerves.environment.detect_cores``). +- ``available_memory_gb`` is the memory a fit may still allocate: ``MemAvailable`` from + ``/proc/meminfo``, lowered to the cgroup v2 headroom (``memory.max - memory.current``) + when the process runs under a memory limit, falling back to the total RAM. Every file it + reads may be missing (macOS, Windows, cgroup v1), in which case it falls back quietly. +""" +import logging +import numbers +import os +from typing import Optional, Union + +logger = logging.getLogger(__name__) + +AUTO = "auto" + +_GB = 1024 ** 3 + + +def validate_number_of_cores(value, where: str = "number_of_cores") -> Union[int, str]: + """ + The validated ``number_of_cores`` request: an int >= 1, or ``"auto"``. + + Parameters + ---------- + value + The request: an int >= 1, ``None`` (meaning 1) or ``"auto"`` (case-insensitive). + where + What is being configured, as it should read in the error. + + Returns + ------- + ``value`` as an int, or the string ``"auto"``. + + Raises + ------ + ValueError + For anything else (0, negative counts, floats, bools, other strings). + """ + if value is None: + return 1 + + if isinstance(value, str): + if value.strip().lower() == AUTO: + return AUTO + elif isinstance(value, numbers.Integral) and not isinstance(value, bool): + if int(value) >= 1: + return int(value) + + raise ValueError( + f"{where}: number_of_cores={value!r} is not valid. Use a whole number of " + f"cores >= 1 (e.g. number_of_cores=4), or number_of_cores=\"auto\" to use " + f"every core this process may use (the count is resolved when the fit starts)." + ) + + +def is_auto(value) -> bool: + """ + Whether ``value`` is the ``"auto"`` request (any case). + """ + return isinstance(value, str) and value.strip().lower() == AUTO + + +def detected_cores() -> int: + """ + The number of CPU cores this process may use (``autonerves.environment.detect_cores``: + ``SLURM_CPUS_PER_TASK``, then the CPU affinity, then ``os.cpu_count()``; at least 1). + """ + from autonerves.environment import detect_cores + + return detect_cores() + + +def resolve_job_cores(value, where: str) -> int: + """ + A validated job-pool worker count for the grid search and sensitivity mapping, with + ``"auto"`` resolved to the detected cores (their jobs are whole fits, so no analysis + is known to cap the count by). + """ + value = validate_number_of_cores(value, where=where) + if value == AUTO: + return detected_cores() + return value + + +def _read_meminfo(meminfo_path: str) -> dict: + """ + ``/proc/meminfo`` as {field: bytes}; empty when the file is missing or unreadable. + """ + values = {} + try: + with open(meminfo_path) as f: + for line in f: + key, _, rest = line.partition(":") + parts = rest.split() + if not parts: + continue + try: + number = float(parts[0]) + except ValueError: + continue + unit = parts[1].lower() if len(parts) > 1 else "" + values[key.strip()] = number * 1024 if unit == "kb" else number + except OSError: + return {} + return values + + +def _read_int_file(path: str) -> Optional[int]: + """ + An integer file such as cgroup ``memory.max``; ``None`` when missing, unreadable or + ``max`` (no limit). + """ + try: + with open(path) as f: + text = f.read().strip() + except OSError: + return None + if not text or text == "max": + return None + try: + return int(text) + except ValueError: + return None + + +def _cgroup_headroom_bytes(cgroup_root: str, proc_cgroup_path: str) -> Optional[int]: + """ + The memory this process's cgroup v2 may still allocate (``memory.max`` minus + ``memory.current``), or ``None`` when there is no cgroup v2 memory limit. + + The process's own cgroup (the ``0::`` line of ``/proc/self/cgroup``, e.g. a + Slurm job step) is tried first, then the cgroup root (a container's namespace root). + """ + candidates = [] + try: + with open(proc_cgroup_path) as f: + for line in f: + if line.startswith("0::"): + relative = line[3:].strip().lstrip("/") + if relative: + candidates.append(os.path.join(cgroup_root, relative)) + except OSError: + pass + candidates.append(cgroup_root) + + for directory in candidates: + limit = _read_int_file(os.path.join(directory, "memory.max")) + if limit is None: + continue + current = _read_int_file(os.path.join(directory, "memory.current")) or 0 + return max(0, limit - current) + + return None + + +def available_memory_gb( + meminfo_path: str = "/proc/meminfo", + cgroup_root: str = "/sys/fs/cgroup", + proc_cgroup_path: str = "/proc/self/cgroup", +) -> Optional[float]: + """ + The memory, in GB (GiB), this process may still allocate. + + ``MemAvailable`` from ``/proc/meminfo`` (the kernel's estimate of memory available + without swapping), lowered to the cgroup v2 headroom when the process runs under a + lower memory limit (a Slurm job, a container). When ``MemAvailable`` is unknown the + total RAM is used (``MemTotal``, then ``autonerves.environment.detect_ram_gb``). + ``None`` when nothing can be read. + + Parameters + ---------- + meminfo_path, cgroup_root, proc_cgroup_path + The files read, overridable for tests. + """ + meminfo = _read_meminfo(meminfo_path) + + available = meminfo.get("MemAvailable") + if available is None: + available = meminfo.get("MemTotal") + + cgroup = _cgroup_headroom_bytes(cgroup_root, proc_cgroup_path) + if cgroup is not None and (available is None or cgroup < available): + available = cgroup + + if available is not None: + return available / _GB + + try: + from autonerves.environment import detect_ram_gb + + return detect_ram_gb() + except Exception: + logger.debug("Could not read the total RAM", exc_info=True) + return None diff --git a/autofit/non_linear/search/abstract_search.py b/autofit/non_linear/search/abstract_search.py index caa60da6c..29467bdb9 100644 --- a/autofit/non_linear/search/abstract_search.py +++ b/autofit/non_linear/search/abstract_search.py @@ -27,7 +27,10 @@ from autofit.non_linear.search.runtime import ( # noqa: F401 SearchRuntimeSettings, configure_handler, + fit_pools, log_fit_start, + number_of_cores_request, + resolve_fit_parallel, quick_update_message, warn_deprecated_jax_knob, warn_if_threads_unpinned, @@ -95,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: int = 1, + number_of_cores: Union[int, str] = 1, silence: bool = False, session: Optional[sa.orm.Session] = None, paths: Optional[AbstractPaths] = None, @@ -165,8 +168,7 @@ def __init__( warn_unknown_kwargs(self, kwargs, known=self._known_kwargs) - self.number_of_cores = number_of_cores - warn_if_threads_unpinned(number_of_cores) + self.number_of_cores = number_of_cores_request(self, number_of_cores) self.optimisation_counter = Counter() @@ -300,9 +302,8 @@ def _fit_and_output(self, model, analysis, info=None): """The body of ``fit``, inside its status record (``status_recorded``).""" self.check_model(model=model) - # Per-fit: set by `start_resume_fit` when the fit's pools are resolved, and read - # by `search.summary`; cleared so a reused search never reports a stale count. - self._parallel_summary = None + # Per-fit (`resolve_fit_parallel`); cleared so a reuse never reports a stale count. + self._parallel_summary = self._parallel_resolution = None log_fit_start(self, analysis) log_process_state() @@ -316,6 +317,7 @@ def _fit_and_output(self, model, analysis, info=None): model.freeze() analysis = analysis.modify_before_fit(paths=self.paths, model=model) model.unfreeze() + resolve_fit_parallel(self, analysis) if not skip_fit_output(): self.pre_fit_output(analysis=analysis, model=model, info=info) @@ -419,10 +421,8 @@ def start_resume_fit(self, analysis: Analysis, model: AbstractPriorModel) -> Res preflight.check_runtime_gates(self, analysis, model) - # The fit's pools, with the one JAX fork rule applied once (one INFO line when it - # downgrades) and the effective worker count recorded for `search.summary`. - self._fit_pools = PoolFactory(self, analysis) - self._parallel_summary = self._fit_pools.summary + # The fit's pools, on the count resolved after `modify_before_fit`. + self._fit_pools = fit_pools(self, analysis) model.freeze() try: diff --git a/autofit/non_linear/search/nest/nss/search.py b/autofit/non_linear/search/nest/nss/search.py index 40a3140c3..d66e84205 100644 --- a/autofit/non_linear/search/nest/nss/search.py +++ b/autofit/non_linear/search/nest/nss/search.py @@ -324,7 +324,7 @@ def __init__( self.termination = termination self.checkpoint_interval = checkpoint_interval - if number_of_cores is not None and number_of_cores > 1: + if isinstance(self.number_of_cores, int) and self.number_of_cores > 1: logger.warning( "af.NSS received number_of_cores=%d. NSS is JAX-native and " "runs on whatever device JAX is configured for; the value is " diff --git a/autofit/non_linear/search/preflight.py b/autofit/non_linear/search/preflight.py index 46dd0f051..528a4d65b 100644 --- a/autofit/non_linear/search/preflight.py +++ b/autofit/non_linear/search/preflight.py @@ -328,7 +328,8 @@ def check_runtime_gates(search, analysis, model): The fail-fast gates ``NonLinearSearch.start_resume_fit`` runs after the test-mode bypass return and before any backend state exists: - - whole-graph backend agreement (``FactorGraphModel.check_backend_agreement``), + - whole-graph backend and compute-setup agreement + (``FactorGraphModel.check_backend_agreement`` / ``check_setup_agreement``), through the analysis wrappers that forward their wrapped analysis's likelihood (``ModelAnalysis``, ``AnalysisFactor``), so a wrapped graph is still checked as one whole graph; @@ -349,6 +350,7 @@ def check_runtime_gates(search, analysis, model): inner = inner.__dict__.get("analysis") if isinstance(inner, FactorGraphModel): inner.check_backend_agreement() + inner.check_setup_agreement() cap.check_jax_required(search, analysis) diff --git a/autofit/non_linear/search/runtime.py b/autofit/non_linear/search/runtime.py index 6b0a54bd2..926c8dff8 100644 --- a/autofit/non_linear/search/runtime.py +++ b/autofit/non_linear/search/runtime.py @@ -94,13 +94,16 @@ def apply(self, search): ) -def warn_if_threads_unpinned(number_of_cores: int): +def warn_if_threads_unpinned(number_of_cores): """ Warn when a search uses multiprocessing (``number_of_cores > 1``) while the numerical libraries' thread-count environment variables are not pinned to 1. Disabled by ``general.yaml -> parallel -> warn_environment_variables``. + + Only an int count is checked: an ``"auto"`` request is checked once the fit + resolves it (``resolve_fit_parallel``). """ - if number_of_cores <= 1 or all( + if not isinstance(number_of_cores, int) or number_of_cores <= 1 or all( os.environ.get(key) == "1" for key in _THREAD_VARIABLES ): return @@ -241,8 +244,12 @@ def decorated(self, *args, **kwargs): def log_fit_start(search, analysis): """ - Log, once at the start of a fit, the device (JAX) or core count it runs on and the + Log, once at the start of a fit, the JAX device a JAX analysis runs on and the quick-update cadence (``NonLinearSearch.quick_update_message``). + + The worker count is not logged here: it is only known once ``modify_before_fit`` + has resolved the analysis's compute setup, and the fit's one ``Parallel:`` banner + line reports it (``resolve_fit_parallel``). """ if analysis.is_jax: try: @@ -257,12 +264,79 @@ def log_fit_start(search, analysis): except Exception: logger.info("Starting non-linear search with JAX.") else: - logger.info( - f"Starting non-linear search with {search.number_of_cores} cores." - ) + logger.info("Starting non-linear search.") logger.info(search.quick_update_message) +def resolve_fit_parallel(search, analysis): + """ + Resolve a fit's worker count once ``modify_before_fit`` has resolved the analysis's + compute setup (``autofit.non_linear.parallel.pool.resolve_number_of_cores``: + ``"auto"`` becomes the detected cores, 1 for a JAX analysis or an + expectation-propagation factor search, capped by memory when the analysis declares + ``resources_per_eval()``), log the fit's one ``Parallel:`` banner line and record + the resolution for the pools, ``search.summary`` and ``files/parallel.json``. + + ``search.number_of_cores`` keeps the request, so ``search.json`` records it; an + ``"auto"`` request gets its thread warning here, for the resolved count. Writes + ``files/parallel.json`` unless the fit is already complete (a completed fit keeps + the record of the run that produced it). + """ + from autofit.non_linear.parallel.pool import resolve_number_of_cores + from autofit.non_linear.parallel.resources import is_auto + + resolution = resolve_number_of_cores( + requested=getattr(search, "number_of_cores", 1), + analysis=analysis, + where=type(search).__name__, + ep_factor_search=bool(getattr(search, "_ep_factor_search", False)), + ) + search._parallel_resolution = resolution + search._parallel_summary = resolution.summary + + getattr(search, "logger", logger).info(resolution.banner) + + if is_auto(resolution.requested): + warn_if_threads_unpinned(resolution.number_of_cores) + + paths = getattr(search, "paths", None) + if paths is not None and not paths.is_complete: + paths.save_json("parallel", resolution.to_dict()) + + return resolution + + +def fit_pools(search, analysis): + """ + The fit's ``PoolFactory``, built on the resolution ``resolve_fit_parallel`` made + after ``modify_before_fit`` (or resolved here when there is none), with the one JAX + fork rule applied once; records the resolution for ``search.summary``. + """ + from autofit.non_linear.parallel import PoolFactory + + pools = PoolFactory( + search, analysis, resolution=search.__dict__.get("_parallel_resolution") + ) + search._parallel_resolution = pools.resolution + search._parallel_summary = pools.summary + return pools + + +def number_of_cores_request(search, number_of_cores): + """ + The validated ``number_of_cores`` request a search stores (and ``search.json`` + records): an int >= 1 or ``"auto"`` (``validate_number_of_cores``; ``None`` is 1). + An int count gets its thread warning now; ``"auto"`` gets it once a fit resolves it. + """ + from autofit.non_linear.parallel.resources import validate_number_of_cores + + number_of_cores = validate_number_of_cores( + number_of_cores, where=type(search).__name__ + ) + warn_if_threads_unpinned(number_of_cores) + return number_of_cores + + def quick_update_message(iterations: float) -> str: """ One line, logged at the start of every search, telling the user the real diff --git a/autofit/non_linear/settings.py b/autofit/non_linear/settings.py index 44127d570..a158da06c 100644 --- a/autofit/non_linear/settings.py +++ b/autofit/non_linear/settings.py @@ -1,7 +1,7 @@ from __future__ import annotations import inspect -from typing import Optional, List, TYPE_CHECKING +from typing import Optional, List, Union, TYPE_CHECKING if TYPE_CHECKING: from autofit.database.sqlalchemy_ import sa @@ -13,7 +13,7 @@ def __init__( self, path_prefix: str, unique_tag: Optional[str] = None, - number_of_cores: Optional[int] = 1, + number_of_cores: Optional[Union[int, str]] = 1, session: Optional[sa.orm.Session] = None, info: Optional[dict] = None, use_jax_vmap: Optional[bool] = None, @@ -34,6 +34,9 @@ def __init__( number_of_cores The number of CPU cores used to parallelize the model-fit. This is used internally in a non-linear search 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. 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. @@ -58,7 +61,11 @@ def __init__( self.path_prefix = path_prefix self.unique_tag = unique_tag - self.number_of_cores = number_of_cores + from autofit.non_linear.parallel.resources import validate_number_of_cores + + self.number_of_cores = validate_number_of_cores( + number_of_cores, where="SettingsSearch" + ) self.session = session self.use_jax_vmap = use_jax_vmap diff --git a/test_autofit/graphical/test_factor_graph_setup.py b/test_autofit/graphical/test_factor_graph_setup.py new file mode 100644 index 000000000..3a027017c --- /dev/null +++ b/test_autofit/graphical/test_factor_graph_setup.py @@ -0,0 +1,183 @@ +""" +Factor graphs forward `modify_before_fit` to each factor's analysis and check that the +factors resolved the same compute setup (likelihood-lifecycle phase 5D). + +Dummy analyses carry a duck-typed `setup` with a `setup_id`; nothing imports autoarray. +""" +import logging + +import numpy as np +import pytest + +import autofit as af +import autofit.graphical as g +from autofit import exc +from autofit.graphical.declarative.factor.analysis import FactorCallable +from autofit.non_linear.parallel import pool as pool_module +from autofit.non_linear.parallel import setup_id_of + +pytestmark = pytest.mark.filterwarnings("ignore::FutureWarning") + + +class _Setup: + def __init__(self, setup_id): + self.setup_id = setup_id + + +class _Analysis(af.Analysis): + """ + Records each `modify_before_fit` call and returns a *new* analysis carrying the + resolved setup, so the test can see both references are rebound. + """ + + def __init__(self, setup_id=None, calls=None): + super().__init__() + self.setup_id = setup_id + self.calls = calls if calls is not None else [] + self.modified = False + + def log_likelihood_function(self, instance): + return 1.0 if self.modified else 0.0 + + def modify_before_fit(self, paths, model): + self.calls.append((paths, model)) + new = _Analysis(setup_id=self.setup_id, calls=self.calls) + new.modified = True + if self.setup_id is not None: + new.setup = _Setup(self.setup_id) + return new + + +def _factor(analysis, name): + return g.AnalysisFactor( + af.Model(af.ex.Gaussian), analysis=analysis, name=name + ) + + +def test_forwarding_calls_each_factor_once_with_its_model_and_sub_paths(): + calls_a, calls_b = [], [] + factor_a = _factor(_Analysis("numba_cpu_sparse_fp64", calls_a), "a") + factor_b = _factor(_Analysis("numba_cpu_sparse_fp64", calls_b), "b") + graph = g.FactorGraphModel(factor_a, factor_b) + + paths = af.DirectoryPaths(name="graph_setup") + model = graph.global_prior_model + + assert graph.modify_before_fit(paths=paths, model=model) is graph + + assert len(calls_a) == 1 and len(calls_b) == 1 + child_paths_a, model_a = calls_a[0] + child_paths_b, model_b = calls_b[0] + assert "analyses/analysis_0" in str(child_paths_a.output_path) + assert "analyses/analysis_1" in str(child_paths_b.output_path) + assert model_a.prior_count == factor_a.prior_model.prior_count + assert model_a is model[0] + assert model_b is model[1] + + for factor in (factor_a, factor_b): + assert factor.analysis.modified + assert factor._factor.analysis is factor.analysis + assert isinstance(factor._factor, FactorCallable) + + assert graph.setup_ids() == { + "a": "numba_cpu_sparse_fp64", + "b": "numba_cpu_sparse_fp64", + } + assert setup_id_of(graph) == "numba_cpu_sparse_fp64" + + +def test_rebound_analysis_is_what_the_graph_evaluates(): + factor = _factor(_Analysis(), "a") + graph = g.FactorGraphModel(factor) + instance = graph.global_prior_model.instance_from_prior_medians() + + assert graph.log_likelihood_function(instance) == 0.0 + graph.modify_before_fit(paths=af.DirectoryPaths(name="graph_eval"), model=None) + assert graph.log_likelihood_function(instance) == 1.0 + + +def test_disagreeing_setups_raise(): + graph = g.FactorGraphModel( + _factor(_Analysis("numba_cpu_sparse_fp64"), "a"), + _factor(_Analysis("numpy_cpu_fp64"), "b"), + ) + + with pytest.raises(exc.SearchException, match="different compute setups"): + graph.modify_before_fit(paths=af.DirectoryPaths(name="graph_bad"), model=None) + + +def test_factors_without_a_setup_are_ignored(): + graph = g.FactorGraphModel( + _factor(_Analysis("numba_cpu_sparse_fp64"), "a"), + _factor(_Analysis(None), "b"), + ) + graph.modify_before_fit(paths=af.DirectoryPaths(name="graph_mixed"), model=None) + + assert graph.setup_ids() == {"a": "numba_cpu_sparse_fp64"} + graph.check_setup_agreement() + + +def test_no_setups_agree_trivially(): + graph = g.FactorGraphModel(_factor(_Analysis(), "a"), _factor(_Analysis(), "b")) + graph.check_setup_agreement() + assert setup_id_of(graph) is None + + +def test_hierarchical_factor_is_skipped(): + calls = [] + hierarchical = g.HierarchicalFactor( + af.GaussianPrior, + mean=af.GaussianPrior(mean=50, sigma=10), + sigma=af.GaussianPrior(mean=10, sigma=5), + ) + model = af.Model(af.ex.Gaussian) + hierarchical.add_drawn_variable(model.centre) + factor = g.AnalysisFactor(model, analysis=_Analysis("x", calls), name="a") + + graph = g.FactorGraphModel(factor, hierarchical) + graph.modify_before_fit(paths=af.DirectoryPaths(name="graph_hier"), model=None) + + assert len(calls) == 1 + assert graph.setup_ids() == {"a": "x"} + + +def test_runtime_gates_check_setup_agreement(): + from autofit.non_linear.search import preflight + + graph = g.FactorGraphModel( + _factor(_Analysis(), "a"), + _factor(_Analysis(), "b"), + ) + graph.model_factors[0].analysis.setup = _Setup("one") + graph.model_factors[1].analysis.setup = _Setup("two") + + with pytest.raises(exc.SearchException, match="different compute setups"): + preflight.check_runtime_gates(af.Emcee(), graph, graph.global_prior_model) + + +def test_whole_graph_fit_banner_reports_the_agreed_setup(monkeypatch, caplog, tmp_path): + monkeypatch.setenv("PYAUTO_TEST_MODE", "2") + monkeypatch.setattr(pool_module, "detected_cores", lambda: 8) + + class _FitAnalysis(_Analysis): + def log_likelihood_function(self, instance): + return -1.0 + + def modify_before_fit(self, paths, model): + self.setup = _Setup("numba_cpu_sparse_fp64") + return self + + graph = g.FactorGraphModel( + _factor(_FitAnalysis(), "a"), _factor(_FitAnalysis(), "b") + ) + search = af.Emcee( + name="graph_fit", path_prefix=str(tmp_path), number_of_cores="auto" + ) + + with caplog.at_level(logging.INFO): + search.fit(model=graph.global_prior_model, analysis=graph) + + banners = [r.getMessage() for r in caplog.records if r.getMessage().startswith("Parallel:")] + assert banners == [ + "Parallel: 8 workers (requested auto; detected cores) · setup numba_cpu_sparse_fp64" + ] diff --git a/test_autofit/non_linear/search/test_conformance_backend.py b/test_autofit/non_linear/search/test_conformance_backend.py index 096b58c95..9ef202c2c 100644 --- a/test_autofit/non_linear/search/test_conformance_backend.py +++ b/test_autofit/non_linear/search/test_conformance_backend.py @@ -89,6 +89,7 @@ "search.summary", "files/model.json", "files/search.json", + "files/parallel.json", "files/samples.csv", "files/samples_info.json", "files/samples_summary.json", diff --git a/test_autofit/non_linear/test_number_of_cores_auto.py b/test_autofit/non_linear/test_number_of_cores_auto.py new file mode 100644 index 000000000..1ab7ba2a0 --- /dev/null +++ b/test_autofit/non_linear/test_number_of_cores_auto.py @@ -0,0 +1,383 @@ +""" +`number_of_cores="auto"` (likelihood-lifecycle phase 5D): validation, resolution after +`modify_before_fit` (`autofit.non_linear.parallel.pool.resolve_number_of_cores`), the +available-memory probe, the one `Parallel:` banner line, `search.summary` and +`files/parallel.json`. + +The core and memory probes are always monkeypatched: no test depends on the machine's +core count or forks a worker. +""" +import json +import logging +import warnings +import zipfile + +import numpy as np +import pytest + +import autofit as af +from autofit.non_linear.parallel import pool as pool_module +from autofit.non_linear.parallel import resources +from autofit.non_linear.parallel import ( + PoolFactory, + check_factor_search_cores, + resolve_number_of_cores, + validate_number_of_cores, +) + +pytestmark = pytest.mark.filterwarnings("ignore::FutureWarning") + + +@pytest.fixture(autouse=True) +def fake_machine(monkeypatch): + """ + A fake 64-core machine with 120 GB available, and no forking allowed. + """ + monkeypatch.setattr(pool_module, "detected_cores", lambda: 64) + monkeypatch.setattr(resources, "detected_cores", lambda: 64) + monkeypatch.setattr(pool_module, "available_memory_gb", lambda: 120.0) + + def no_fork(*args, **kwargs): + raise AssertionError("must not fork") + + monkeypatch.setattr(pool_module, "fork_context", no_fork) + + +class _Setup: + def __init__(self, setup_id): + self.setup_id = setup_id + + +class _Analysis: + def __init__(self, is_jax=False, setup_id=None, resources_per_eval=None): + self.is_jax = is_jax + if setup_id is not None: + self.setup = _Setup(setup_id) + if resources_per_eval is not None: + self.resources_per_eval = lambda: resources_per_eval + + +# ---------------------------------------------------------------- validation + + +@pytest.mark.parametrize( + "value, expected", + [(1, 1), (8, 8), (np.int64(3), 3), (None, 1), ("auto", "auto"), ("AUTO", "auto"), + (" Auto ", "auto")], +) +def test_validate_accepts(value, expected): + assert validate_number_of_cores(value) == expected + + +@pytest.mark.parametrize("value", [0, -2, 2.0, 1.5, True, "all", "", [2]]) +def test_validate_rejects_with_a_clear_error(value): + with pytest.raises(ValueError, match="number_of_cores="): + validate_number_of_cores(value, where="Emcee") + + +def test_searches_and_settings_accept_auto_and_reject_garbage(): + assert af.Emcee(number_of_cores="auto").number_of_cores == "auto" + assert af.DynestyStatic(number_of_cores="Auto").number_of_cores == "auto" + assert af.DynestyDynamic(number_of_cores="auto").number_of_cores == "auto" + assert af.Nautilus(number_of_cores="auto").number_of_cores == "auto" + assert af.Zeus(number_of_cores="auto").number_of_cores == "auto" + assert af.Emcee(number_of_cores=None).number_of_cores == 1 + assert af.SettingsSearch(path_prefix="x", number_of_cores="AUTO").number_of_cores == "auto" + + with pytest.raises(ValueError, match="Emcee"): + af.Emcee(number_of_cores=0) + with pytest.raises(ValueError, match="SettingsSearch"): + af.SettingsSearch(path_prefix="x", number_of_cores="many") + + +def test_settings_search_passes_auto_through_to_a_search(): + settings = af.SettingsSearch(path_prefix="x", number_of_cores="auto") + search = af.Emcee(**settings.search_dict_for(af.Emcee)) + assert search.number_of_cores == "auto" + + +def test_auto_defers_the_thread_warning(monkeypatch): + for key in ("OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS", "OMP_NUM_THREADS", + "VECLIB_MAXIMUM_THREADS", "NUMEXPR_NUM_THREADS"): + monkeypatch.setenv(key, "4") + + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + af.Emcee(number_of_cores="auto") + + assert not [w for w in caught if issubclass(w.category, af.exc.SearchWarning)] + + +def test_grid_search_and_sensitivity_resolve_auto_to_detected_cores(): + grid = af.SearchGridSearch(search=af.m.MockSearch(), number_of_cores="auto") + assert grid.number_of_cores == 64 + assert resources.resolve_job_cores(None, where="x") == 1 + with pytest.raises(ValueError): + resources.resolve_job_cores(0, where="x") + + +# ---------------------------------------------------------------- resolution + + +def test_int_request_is_honoured(): + resolution = resolve_number_of_cores(4, _Analysis()) + assert (resolution.number_of_cores, resolution.reason) == (4, "requested") + assert resolution.banner == "Parallel: 4 workers (requested 4)" + + +def test_auto_resolves_to_detected_cores(): + resolution = resolve_number_of_cores("auto", _Analysis(setup_id="numba_cpu_sparse_fp64")) + assert resolution.number_of_cores == 64 + assert resolution.reason == "detected_cores" + assert resolution.detected_cores == 64 + assert resolution.available_memory_gb is None + assert resolution.banner == ( + "Parallel: 64 workers (requested auto; detected cores) · setup numba_cpu_sparse_fp64" + ) + + +def test_auto_under_jax_is_one(): + resolution = resolve_number_of_cores("auto", _Analysis(is_jax=True)) + assert resolution.number_of_cores == 1 + assert resolution.banner == ( + "Parallel: 1 worker (requested auto; JAX analyses run single-process)" + ) + + +def test_int_request_under_jax_is_one(): + resolution = resolve_number_of_cores(4, _Analysis(is_jax=True)) + assert (resolution.number_of_cores, resolution.reason) == (1, "jax") + + +def test_auto_ep_factor_search_is_one(): + resolution = resolve_number_of_cores("auto", _Analysis(), ep_factor_search=True) + assert (resolution.number_of_cores, resolution.reason) == (1, "expectation_propagation") + + +def test_ep_check_accepts_auto_and_refuses_an_explicit_count(): + check_factor_search_cores(af.Emcee(number_of_cores="auto")) + check_factor_search_cores(af.Emcee(number_of_cores=1)) + with pytest.raises(af.exc.SearchException): + check_factor_search_cores(af.Emcee(number_of_cores=2)) + + +def test_no_resources_hook_means_no_cap(): + resolution = resolve_number_of_cores("auto", _Analysis()) + assert resolution.number_of_cores == 64 + + +def test_memory_cap(monkeypatch): + analysis = _Analysis(resources_per_eval={"cpus_per_eval": 1, "peak_rss_gb": 2.5}) + resolution = resolve_number_of_cores("auto", analysis) + assert resolution.number_of_cores == 48 + assert resolution.reason == "memory" + assert resolution.available_memory_gb == 120.0 + assert resolution.banner == ( + "Parallel: 48 workers (requested auto; capped by memory: 120.0 GB available " + "/ 2.5 GB per evaluation)" + ) + + +def test_cores_per_eval_cap(): + analysis = _Analysis(resources_per_eval={"cpus_per_eval": 4, "peak_rss_gb": 0.5}) + resolution = resolve_number_of_cores("auto", analysis) + assert (resolution.number_of_cores, resolution.reason) == (16, "cores_per_eval") + + +def test_memory_cap_never_below_one(monkeypatch): + monkeypatch.setattr(pool_module, "available_memory_gb", lambda: 1.0) + analysis = _Analysis(resources_per_eval={"peak_rss_gb": 50.0}) + assert resolve_number_of_cores("auto", analysis).number_of_cores == 1 + + +def test_unknown_memory_means_no_memory_cap(monkeypatch): + monkeypatch.setattr(pool_module, "available_memory_gb", lambda: None) + analysis = _Analysis(resources_per_eval={"peak_rss_gb": 50.0}) + assert resolve_number_of_cores("auto", analysis).number_of_cores == 64 + + +def test_resources_hook_returning_none_means_no_cap(): + analysis = _Analysis() + analysis.resources_per_eval = lambda: None + assert resolve_number_of_cores("auto", analysis).number_of_cores == 64 + + +def test_int_request_is_not_capped_by_memory(): + analysis = _Analysis(resources_per_eval={"peak_rss_gb": 50.0}) + assert resolve_number_of_cores(8, analysis).number_of_cores == 8 + + +def test_pool_factory_uses_the_resolved_count(): + search = af.Emcee(number_of_cores="auto") + factory = PoolFactory(search, _Analysis()) + assert factory.requested == "auto" + assert factory.number_of_cores == 64 + assert "Number of cores = 64 (requested auto): detected cores" in factory.summary + + +def test_pool_factory_under_jax_auto_builds_no_pool(): + factory = PoolFactory(af.Emcee(number_of_cores="auto"), _Analysis(is_jax=True)) + assert factory.number_of_cores == 1 + assert factory() is None + assert factory.sneaky(fitness=None) is None + + +def test_pool_factory_ep_flag_resolves_to_one(): + search = af.Emcee(number_of_cores="auto") + search._ep_factor_search = True + assert PoolFactory(search, _Analysis()).number_of_cores == 1 + + +def test_summary_records_the_setup(): + resolution = resolve_number_of_cores(2, _Analysis(setup_id="numpy_cpu_fp64")) + assert resolution.summary == ( + "Number of cores = 2 (requested 2)\nSetup = numpy_cpu_fp64\n" + ) + assert resolution.to_dict() == { + "requested": 2, + "number_of_cores": 2, + "reason": "requested", + "detected_cores": None, + "available_memory_gb": None, + "setup_id": "numpy_cpu_fp64", + } + + +# ---------------------------------------------------------------- memory probe + + +def _write(path, text): + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text) + + +def test_available_memory_reads_memavailable(tmp_path): + meminfo = tmp_path / "meminfo" + _write(meminfo, "MemTotal: 16777216 kB\nMemAvailable: 8388608 kB\n") + assert resources.available_memory_gb( + meminfo_path=str(meminfo), + cgroup_root=str(tmp_path / "nocgroup"), + proc_cgroup_path=str(tmp_path / "nocgroupfile"), + ) == pytest.approx(8.0) + + +def test_available_memory_falls_back_to_total(tmp_path): + meminfo = tmp_path / "meminfo" + _write(meminfo, "MemTotal: 16777216 kB\n") + assert resources.available_memory_gb( + meminfo_path=str(meminfo), + cgroup_root=str(tmp_path / "nocgroup"), + proc_cgroup_path=str(tmp_path / "nocgroupfile"), + ) == pytest.approx(16.0) + + +def test_available_memory_respects_a_lower_cgroup_limit(tmp_path): + meminfo = tmp_path / "meminfo" + _write(meminfo, "MemTotal: 16777216 kB\nMemAvailable: 8388608 kB\n") + root = tmp_path / "cgroup" + _write(root / "job" / "memory.max", str(4 * 1024 ** 3)) + _write(root / "job" / "memory.current", str(1 * 1024 ** 3)) + proc = tmp_path / "proc_cgroup" + _write(proc, "0::/job\n") + + assert resources.available_memory_gb( + meminfo_path=str(meminfo), cgroup_root=str(root), proc_cgroup_path=str(proc) + ) == pytest.approx(3.0) + + +def test_available_memory_ignores_an_unlimited_cgroup(tmp_path): + meminfo = tmp_path / "meminfo" + _write(meminfo, "MemAvailable: 8388608 kB\n") + root = tmp_path / "cgroup" + _write(root / "memory.max", "max\n") + + assert resources.available_memory_gb( + meminfo_path=str(meminfo), + cgroup_root=str(root), + proc_cgroup_path=str(tmp_path / "missing"), + ) == pytest.approx(8.0) + + +def test_available_memory_with_nothing_readable_uses_nerves(tmp_path, monkeypatch): + import autonerves.environment + + monkeypatch.setattr(autonerves.environment, "detect_ram_gb", lambda: 32.0) + assert resources.available_memory_gb( + meminfo_path=str(tmp_path / "missing"), + cgroup_root=str(tmp_path / "missing_root"), + proc_cgroup_path=str(tmp_path / "missing_proc"), + ) == 32.0 + + +# ---------------------------------------------------------------- a fit + + +class _SetupAnalysis(af.ex.Analysis): + def modify_before_fit(self, paths, model): + self.setup = _Setup("numba_cpu_sparse_fp64") + return self + + +def _banner_records(caplog): + return [r for r in caplog.records if r.getMessage().startswith("Parallel:")] + + +def test_fit_logs_one_banner_after_modify_before_fit_and_writes_parallel_json( + monkeypatch, caplog, tmp_path +): + monkeypatch.setenv("PYAUTO_TEST_MODE", "2") + + analysis = _SetupAnalysis(data=np.ones(10), noise_map=np.ones(10)) + search = af.Emcee( + name="auto_cores", path_prefix=str(tmp_path), number_of_cores="auto" + ) + + with caplog.at_level(logging.INFO): + search.fit(model=af.Model(af.ex.Gaussian), analysis=analysis) + + banners = _banner_records(caplog) + assert [r.getMessage() for r in banners] == [ + "Parallel: 64 workers (requested auto; detected cores) · setup numba_cpu_sparse_fp64" + ] + assert not [r for r in caplog.records if "cores." in r.getMessage() + and r.getMessage().startswith("Starting non-linear search")] + + assert search.number_of_cores == "auto" + + with zipfile.ZipFile(search.paths._zip_path) as archive: + names = archive.namelist() + record = json.loads(archive.read("files/parallel.json")) + search_json = json.loads(archive.read("files/search.json")) + + # Test mode 2 writes no `search.summary`; its run-time lines come from here. + from autofit.non_linear.search.capabilities import run_summary_from + + summary = run_summary_from(search) + assert "Number of cores = 64 (requested auto): detected cores" in summary + assert "Setup = numba_cpu_sparse_fp64" in summary + + assert record == { + "requested": "auto", + "number_of_cores": 64, + "reason": "detected_cores", + "detected_cores": 64, + "available_memory_gb": None, + "setup_id": "numba_cpu_sparse_fp64", + } + + assert search_json["arguments"]["number_of_cores"] == "auto" + + +def test_fit_banner_for_jax_auto(monkeypatch, caplog, tmp_path): + pytest.importorskip("jax") + monkeypatch.setenv("PYAUTO_TEST_MODE", "2") + + analysis = af.ex.Analysis(data=np.ones(10), noise_map=np.ones(10), use_jax=True) + search = af.Emcee(name="auto_jax", path_prefix=str(tmp_path), number_of_cores="auto") + + with caplog.at_level(logging.INFO): + search.fit(model=af.Model(af.ex.Gaussian), analysis=analysis) + + assert [r.getMessage() for r in _banner_records(caplog)] == [ + "Parallel: 1 worker (requested auto; JAX analyses run single-process)" + ]