diff --git a/autoarray/__init__.py b/autoarray/__init__.py index ca5fd05b7..7ce921649 100644 --- a/autoarray/__init__.py +++ b/autoarray/__init__.py @@ -28,6 +28,7 @@ from .inversion.mesh import image_mesh from .inversion import regularization as reg from .settings import Settings +from .setup import Setup from .inversion.inversion.abstract import AbstractInversion from .preloads import AbstractPreloads from .preloads import PreloadsImaging diff --git a/autoarray/config/setup_rules.yaml b/autoarray/config/setup_rules.yaml new file mode 100644 index 000000000..1a5cc2113 --- /dev/null +++ b/autoarray/config/setup_rules.yaml @@ -0,0 +1,302 @@ +# Setup rule table: the Pulse-designated optimal compute setup per +# (likelihood, regime, hardware_class), read by aa.Setup.auto. +# Generated by: python -m autoarray.setup.generate_rules --pulse +# Source: PyAutoPulse decisions.yaml (kind: designation) +# Pulse commit: 94a101f4e2c1d011d192c5721aac194bea5467cd +# Generated on: 2026-11-23 +# Do not hand-edit: change the Pulse decisions and regenerate. +rules: +- likelihood: cluster/image_plane + regime: standard + hardware_class: cpu_many_core + optimal: jax_cpu_na_fp64 + secondary: [] + decision_id: cluster-image-plane-standard-cpu-many-core + rule: A cluster-scale point-source dataset fitted in the image plane on a many-core CPU node with no GPU uses jax_cpu_na_fp64. +- likelihood: cluster/image_plane + regime: standard + hardware_class: gpu_a100 + optimal: jax_gpu_na_fp64 + secondary: [] + decision_id: cluster-image-plane-standard-gpu-a100 + rule: A cluster-scale point-source dataset fitted in the image plane on an A100 node uses jax_gpu_na_fp64. +- likelihood: cluster/source_plane + regime: standard + hardware_class: cpu_many_core + optimal: jax_cpu_na_fp64 + secondary: [] + decision_id: cluster-source-plane-standard-cpu-many-core + rule: A cluster-scale point-source dataset fitted in the source plane on a many-core CPU node with no GPU uses jax_cpu_na_fp64. +- likelihood: cluster/source_plane + regime: standard + hardware_class: gpu_a100 + optimal: jax_gpu_na_fp64 + secondary: [] + decision_id: cluster-source-plane-standard-gpu-a100 + rule: A cluster-scale point-source dataset fitted in the source plane on an A100 node uses jax_gpu_na_fp64. +- likelihood: datacube/delaunay + regime: standard + hardware_class: cpu_many_core + optimal: numba_cpu_sparse_fp64_wtilde + secondary: + - jax_cpu_sparse_fp64_wtilde + decision_id: datacube-delaunay-standard-cpu-many-core + rule: A datacube (interferometer channels fitted together) with a Delaunay pixelized source on a many-core CPU node with no GPU uses numba_cpu_sparse_fp64_wtilde, one serial likelihood per core (workers capped by node memory over peak RSS), falling back to jax_cpu_sparse_fp64_wtilde. +- likelihood: group/delaunay + regime: standard + hardware_class: cpu_many_core + optimal: numba_cpu_sparse_fp64 + secondary: + - jax_cpu_sparse_fp64 + decision_id: group-delaunay-standard-cpu-many-core + rule: A group-scale imaging dataset with a Delaunay pixelized source on a many-core CPU node with no GPU uses numba_cpu_sparse_fp64, one serial likelihood per core (workers capped by node memory over peak RSS), falling back to jax_cpu_sparse_fp64. +- likelihood: group/delaunay + regime: standard + hardware_class: gpu_a100 + optimal: jax_gpu_dense_fp64 + secondary: + - jax_gpu_sparse_fp64 + decision_id: group-delaunay-standard-gpu-a100 + rule: A group-scale imaging dataset with a Delaunay pixelized source on an A100 node uses jax_gpu_dense_fp64, falling back to jax_gpu_sparse_fp64. +- likelihood: group/mge + regime: standard + hardware_class: cpu_many_core + optimal: jax_cpu_dense_fp64 + secondary: [] + decision_id: group-mge-standard-cpu-many-core + rule: A group-scale imaging dataset with a parametric (MGE) source on a many-core CPU node with no GPU uses jax_cpu_dense_fp64. +- likelihood: group/mge + regime: standard + hardware_class: gpu_a100 + optimal: jax_gpu_dense_fp64 + secondary: [] + decision_id: group-mge-standard-gpu-a100 + rule: A group-scale imaging dataset with a parametric (MGE) source on an A100 node uses jax_gpu_dense_fp64. +- likelihood: group/rectangular + regime: standard + hardware_class: cpu_many_core + optimal: numba_cpu_sparse_fp64 + secondary: + - jax_cpu_sparse_fp64 + decision_id: group-rectangular-standard-cpu-many-core + rule: A group-scale imaging dataset with a rectangular pixelized source on a many-core CPU node with no GPU uses numba_cpu_sparse_fp64, one serial likelihood per core (workers capped by node memory over peak RSS), falling back to jax_cpu_sparse_fp64. +- likelihood: group/rectangular + regime: standard + hardware_class: gpu_a100 + optimal: jax_gpu_dense_fp64 + secondary: + - jax_gpu_sparse_fp64 + decision_id: group-rectangular-standard-gpu-a100 + rule: A group-scale imaging dataset with a rectangular pixelized source on an A100 node uses jax_gpu_dense_fp64, falling back to jax_gpu_sparse_fp64. +- likelihood: imaging/delaunay + regime: standard + hardware_class: cpu_many_core + optimal: numba_cpu_sparse_fp64 + secondary: + - jax_cpu_sparse_fp64 + decision_id: imaging-delaunay-standard-cpu-many-core + rule: Any imaging dataset with a Delaunay pixelized source on a many-core CPU node with no GPU uses numba_cpu_sparse_fp64, one serial likelihood per core (workers capped by node memory over peak RSS). +- likelihood: imaging/delaunay + regime: standard + hardware_class: gpu_a100 + optimal: jax_gpu_dense_fp64 + secondary: + - jax_gpu_sparse_fp64 + decision_id: imaging-delaunay-standard-gpu-a100 + rule: Any imaging dataset with a Delaunay pixelized source on an A100 node uses jax_gpu_dense_fp64, falling back to jax_gpu_sparse_fp64. +- likelihood: imaging/delaunay_nn + regime: standard + hardware_class: cpu_many_core + optimal: numba_cpu_sparse_fp64 + secondary: + - jax_cpu_sparse_fp64 + decision_id: imaging-delaunay-nn-standard-cpu-many-core + rule: Any imaging dataset with a Delaunay natural-neighbour source on a many-core CPU node with no GPU uses numba_cpu_sparse_fp64, one serial likelihood per core. +- likelihood: imaging/delaunay_nn + regime: standard + hardware_class: gpu_a100 + optimal: jax_gpu_dense_fp64 + secondary: + - jax_gpu_sparse_fp64 + decision_id: imaging-delaunay-nn-standard-gpu-a100 + rule: Any imaging dataset with a Delaunay natural-neighbour source on an A100 node uses jax_gpu_dense_fp64. +- likelihood: imaging/mge + regime: standard + hardware_class: cpu_many_core + optimal: jax_cpu_dense_fp64 + secondary: [] + decision_id: imaging-mge-standard-cpu-many-core + rule: Any imaging dataset fitted with a parametric (MGE) source on a many-core CPU node with no GPU uses jax_cpu_dense_fp64. +- likelihood: imaging/mge + regime: standard + hardware_class: gpu_a100 + optimal: jax_gpu_dense_fp64 + secondary: [] + decision_id: imaging-mge-standard-gpu-a100 + rule: Any imaging dataset fitted with a parametric (MGE) source on an A100 node uses jax_gpu_dense_fp64. +- likelihood: imaging/rectangular + regime: standard + hardware_class: cpu_many_core + optimal: numba_cpu_sparse_fp64 + secondary: + - jax_cpu_sparse_fp64 + decision_id: imaging-rectangular-standard-cpu-many-core + rule: Any imaging dataset with a rectangular pixelized source on a many-core CPU node with no GPU uses numba_cpu_sparse_fp64, one serial likelihood per core (workers capped by node memory over peak RSS). +- likelihood: imaging/rectangular + regime: standard + hardware_class: gpu_a100 + optimal: jax_gpu_dense_fp64 + secondary: + - jax_gpu_sparse_fp64 + decision_id: imaging-rectangular-standard-gpu-a100 + rule: Any imaging dataset with a rectangular pixelized source on an A100 node uses jax_gpu_dense_fp64, falling back to jax_gpu_sparse_fp64. +- likelihood: interferometer/delaunay + regime: standard + hardware_class: cpu_many_core + optimal: numba_cpu_sparse_fp64_wtilde + secondary: + - jax_cpu_sparse_fp64_wtilde + decision_id: interferometer-delaunay-standard-cpu-many-core + rule: 'Any interferometer dataset with a Delaunay pixelized source on a many-core CPU node with no GPU uses numba_cpu_sparse_fp64_wtilde, one serial likelihood per core (workers capped by node memory over peak RSS), falling back to jax_cpu_sparse_fp64_wtilde. Untested: CPU streaming and the MGE DFT route.' +- likelihood: interferometer/delaunay + regime: standard + hardware_class: gpu_a100 + optimal: jax_gpu_sparse_fp64_wtilde + secondary: + - jax_gpu_dense_fp64_nufft + decision_id: interferometer-delaunay-standard-gpu-a100 + rule: 'Any interferometer dataset with a Delaunay pixelized source on an A100 node uses jax_gpu_sparse_fp64_wtilde, falling back to jax_gpu_dense_fp64_nufft. Untested: the GPU streaming route (measured up to jvla, 2.5e7 visibilities, on W~ sparse).' +- likelihood: interferometer/mge + regime: standard + hardware_class: cpu_many_core + optimal: jax_cpu_dense_fp64_nufft + secondary: [] + decision_id: interferometer-mge-standard-cpu-many-core + rule: 'Any interferometer dataset with a parametric (MGE) source on a many-core CPU node with no GPU uses jax_cpu_dense_fp64_nufft. Untested: CPU streaming and the MGE DFT route.' +- likelihood: interferometer/mge + regime: standard + hardware_class: gpu_a100 + optimal: jax_gpu_dense_fp64_nufft + secondary: [] + decision_id: interferometer-mge-standard-gpu-a100 + rule: 'Any interferometer dataset with a parametric (MGE) source on an A100 node uses jax_gpu_dense_fp64_nufft. Untested: the GPU streaming route (measured up to jvla, 2.5e7 visibilities, on W~ sparse).' +- likelihood: interferometer/rectangular + regime: standard + hardware_class: cpu_many_core + optimal: numba_cpu_sparse_fp64_wtilde + secondary: + - jax_cpu_sparse_fp64_wtilde + decision_id: interferometer-rectangular-standard-cpu-many-core + rule: 'Any interferometer dataset with a rectangular pixelized source on a many-core CPU node with no GPU uses numba_cpu_sparse_fp64_wtilde, one serial likelihood per core (workers capped by node memory over peak RSS), falling back to jax_cpu_sparse_fp64_wtilde. Untested: CPU streaming and the MGE DFT route.' +- likelihood: interferometer/rectangular + regime: standard + hardware_class: gpu_a100 + optimal: jax_gpu_sparse_fp64_wtilde + secondary: + - jax_gpu_dense_fp64_nufft + decision_id: interferometer-rectangular-standard-gpu-a100 + rule: 'Any interferometer dataset with a rectangular pixelized source on an A100 node uses jax_gpu_sparse_fp64_wtilde, falling back to jax_gpu_dense_fp64_nufft. Untested: the GPU streaming route (measured up to jvla, 2.5e7 visibilities, on W~ sparse).' +- likelihood: multi_dataset/delaunay + regime: standard + hardware_class: cpu_many_core + optimal: numba_cpu_sparse_fp64 + secondary: + - jax_cpu_sparse_fp64 + decision_id: multi-dataset-delaunay-standard-cpu-many-core + rule: A multi-dataset imaging fit (several datasets fitted together) with a Delaunay pixelized source on a many-core CPU node with no GPU uses numba_cpu_sparse_fp64, one serial likelihood per core (workers capped by node memory over peak RSS), falling back to jax_cpu_sparse_fp64. +- likelihood: multi_dataset/delaunay + regime: standard + hardware_class: gpu_a100 + optimal: jax_gpu_dense_fp64 + secondary: + - jax_gpu_sparse_fp64 + decision_id: multi-dataset-delaunay-standard-gpu-a100 + rule: A multi-dataset imaging fit (several datasets fitted together) with a Delaunay pixelized source on an A100 node uses jax_gpu_dense_fp64, falling back to jax_gpu_sparse_fp64. +- likelihood: multi_galaxy/delaunay + regime: standard + hardware_class: cpu_many_core + optimal: numba_cpu_sparse_fp64 + secondary: + - jax_cpu_sparse_fp64 + decision_id: multi-galaxy-delaunay-standard-cpu-many-core + rule: A multi-galaxy imaging dataset with a Delaunay pixelized source on a many-core CPU node with no GPU uses numba_cpu_sparse_fp64, one serial likelihood per core (workers capped by node memory over peak RSS), falling back to jax_cpu_sparse_fp64. +- likelihood: multi_galaxy/delaunay + regime: standard + hardware_class: gpu_a100 + optimal: jax_gpu_dense_fp64 + secondary: + - jax_gpu_sparse_fp64 + decision_id: multi-galaxy-delaunay-standard-gpu-a100 + rule: A multi-galaxy imaging dataset with a Delaunay pixelized source on an A100 node uses jax_gpu_dense_fp64, falling back to jax_gpu_sparse_fp64. +- likelihood: multi_galaxy/mge + regime: standard + hardware_class: cpu_many_core + optimal: jax_cpu_dense_fp64 + secondary: [] + decision_id: multi-galaxy-mge-standard-cpu-many-core + rule: A multi-galaxy imaging dataset with a parametric (MGE) source on a many-core CPU node with no GPU uses jax_cpu_dense_fp64. +- likelihood: multi_galaxy/mge + regime: standard + hardware_class: gpu_a100 + optimal: jax_gpu_dense_fp64 + secondary: [] + decision_id: multi-galaxy-mge-standard-gpu-a100 + rule: A multi-galaxy imaging dataset with a parametric (MGE) source on an A100 node uses jax_gpu_dense_fp64. +- likelihood: multi_galaxy/rectangular + regime: standard + hardware_class: cpu_many_core + optimal: numba_cpu_sparse_fp64 + secondary: + - jax_cpu_sparse_fp64 + decision_id: multi-galaxy-rectangular-standard-cpu-many-core + rule: A multi-galaxy imaging dataset with a rectangular pixelized source on a many-core CPU node with no GPU uses numba_cpu_sparse_fp64, one serial likelihood per core (workers capped by node memory over peak RSS), falling back to jax_cpu_sparse_fp64. +- likelihood: multi_galaxy/rectangular + regime: standard + hardware_class: gpu_a100 + optimal: jax_gpu_dense_fp64 + secondary: + - jax_gpu_sparse_fp64 + decision_id: multi-galaxy-rectangular-standard-gpu-a100 + rule: A multi-galaxy imaging dataset with a rectangular pixelized source on an A100 node uses jax_gpu_dense_fp64, falling back to jax_gpu_sparse_fp64. +- likelihood: point_source_image/image_plane + regime: standard + hardware_class: cpu_many_core + optimal: jax_cpu_na_fp64 + secondary: [] + decision_id: point-source-image-image-plane-standard-cpu-many-core + rule: A galaxy-scale point-source dataset fitted in the image plane on a many-core CPU node with no GPU uses jax_cpu_na_fp64. +- likelihood: point_source_image/image_plane + regime: standard + hardware_class: gpu_a100 + optimal: jax_gpu_na_fp64 + secondary: [] + decision_id: point-source-image-image-plane-standard-gpu-a100 + rule: A galaxy-scale point-source dataset fitted in the image plane on an A100 node uses jax_gpu_na_fp64. +- likelihood: point_source_source/source_plane + regime: standard + hardware_class: cpu_many_core + optimal: jax_cpu_na_fp64 + secondary: [] + decision_id: point-source-source-source-plane-standard-cpu-many-core + rule: A galaxy-scale point-source dataset fitted in the source plane on a many-core CPU node with no GPU uses jax_cpu_na_fp64. +- likelihood: point_source_source/source_plane + regime: standard + hardware_class: gpu_a100 + optimal: jax_gpu_na_fp64 + secondary: [] + decision_id: point-source-source-source-plane-standard-gpu-a100 + rule: A galaxy-scale point-source dataset fitted in the source plane on an A100 node uses jax_gpu_na_fp64. +- likelihood: weak/isothermal + regime: standard + hardware_class: cpu_many_core + optimal: jax_cpu_dense_fp64 + secondary: [] + decision_id: weak-isothermal-standard-cpu-many-core + rule: A weak-lensing shear dataset with an isothermal lens on a many-core CPU node with no GPU uses jax_cpu_dense_fp64. +- likelihood: weak/isothermal + regime: standard + hardware_class: gpu_a100 + optimal: jax_gpu_dense_fp64 + secondary: [] + decision_id: weak-isothermal-standard-gpu-a100 + rule: A weak-lensing shear dataset with an isothermal lens on an A100 node uses jax_gpu_dense_fp64. diff --git a/autoarray/setup/__init__.py b/autoarray/setup/__init__.py new file mode 100644 index 000000000..df405aa91 --- /dev/null +++ b/autoarray/setup/__init__.py @@ -0,0 +1 @@ +from .setup import Setup diff --git a/autoarray/setup/generate_rules.py b/autoarray/setup/generate_rules.py new file mode 100644 index 000000000..5fad5778b --- /dev/null +++ b/autoarray/setup/generate_rules.py @@ -0,0 +1,182 @@ +""" +Generate the setup rule table ``autoarray/config/setup_rules.yaml`` from the +designation decisions of a PyAutoPulse checkout. + +Usage:: + + python -m autoarray.setup.generate_rules --pulse + python -m autoarray.setup.generate_rules --pulse --check + +The first form rewrites the table. ``--check`` writes nothing and exits non-zero when +the committed table differs from a regeneration (the header's Pulse commit and date +lines are ignored). +""" + +import argparse +import datetime +import subprocess +import sys +from pathlib import Path +from typing import List, Optional + +import yaml + +from autoarray.setup.setup import RULES_PATH + +ROW_KEYS = ( + "likelihood", + "regime", + "hardware_class", + "optimal", + "secondary", + "decision_id", + "rule", +) + +COMMIT_PREFIX = "# Pulse commit: " +DATE_PREFIX = "# Generated on: " + + +def rows_from_decisions(decisions_path) -> List[dict]: + """ + The rule rows of a PyAutoPulse ``decisions.yaml``: one per ``kind: designation`` + decision, sorted by ``(likelihood, regime, hardware_class)``. + + Parameters + ---------- + decisions_path + Path to the PyAutoPulse ``decisions.yaml``. + """ + with open(decisions_path) as f: + decisions = yaml.safe_load(f)["decisions"] + rows = [ + { + "likelihood": d["likelihood"], + "regime": d["regime"], + "hardware_class": d["hardware_class"], + "optimal": d["optimal"], + "secondary": list(d.get("secondary") or []), + "decision_id": d["id"], + "rule": d["rule"], + } + for d in decisions + if d.get("kind") == "designation" + ] + return sorted( + rows, key=lambda r: (r["likelihood"], r["regime"], r["hardware_class"]) + ) + + +def pulse_commit(pulse) -> str: + """The ``HEAD`` commit of the PyAutoPulse checkout, or ``"unknown"``.""" + try: + result = subprocess.run( + ["git", "-C", str(pulse), "rev-parse", "HEAD"], + capture_output=True, + text=True, + check=True, + ) + return result.stdout.strip() + except (OSError, subprocess.SubprocessError): + return "unknown" + + +def render(rows: List[dict], commit: str, date: Optional[str] = None) -> str: + """ + The text of the rule table: a provenance header and the ``rules:`` list. + + Parameters + ---------- + rows + The rule rows, as from :func:`rows_from_decisions`. + commit + The PyAutoPulse commit the rows were read from. + date + The generation date (ISO format); defaults to today. + """ + date = date or datetime.date.today().isoformat() + header = "\n".join( + [ + "# Setup rule table: the Pulse-designated optimal compute setup per", + "# (likelihood, regime, hardware_class), read by aa.Setup.auto.", + "# Generated by: python -m autoarray.setup.generate_rules --pulse ", + "# Source: PyAutoPulse decisions.yaml (kind: designation)", + f"{COMMIT_PREFIX}{commit}", + f"{DATE_PREFIX}{date}", + "# Do not hand-edit: change the Pulse decisions and regenerate.", + ] + ) + ordered = [{key: row[key] for key in ROW_KEYS} for row in rows] + body = yaml.safe_dump( + {"rules": ordered}, sort_keys=False, width=1000, default_flow_style=False + ) + return f"{header}\n{body}" + + +def _strip_volatile(text: str) -> str: + return "\n".join( + line + for line in text.splitlines() + if not line.startswith((COMMIT_PREFIX, DATE_PREFIX)) + ) + + +def generate(pulse, output=RULES_PATH) -> str: + """ + Regenerate the rule table from a PyAutoPulse checkout and write it to ``output``. + + Returns the written text. + """ + pulse = Path(pulse) + text = render(rows_from_decisions(pulse / "decisions.yaml"), pulse_commit(pulse)) + Path(output).write_text(text) + return text + + +def check(pulse, output=RULES_PATH) -> bool: + """ + Whether the table at ``output`` matches a regeneration from ``pulse``, ignoring the + header's Pulse commit and date lines. + """ + pulse = Path(pulse) + expected = render(rows_from_decisions(pulse / "decisions.yaml"), "", "") + try: + current = Path(output).read_text() + except OSError: + return False + return _strip_volatile(current) == _strip_volatile(expected) + + +def main(argv=None) -> int: + parser = argparse.ArgumentParser( + description="Generate autoarray/config/setup_rules.yaml from PyAutoPulse." + ) + parser.add_argument( + "--pulse", required=True, help="Path to a PyAutoPulse checkout." + ) + parser.add_argument( + "--output", default=str(RULES_PATH), help="The rule table to write or check." + ) + parser.add_argument( + "--check", + action="store_true", + help="Exit non-zero if the table differs from a regeneration; write nothing.", + ) + args = parser.parse_args(argv) + if args.check: + if check(args.pulse, args.output): + print(f"{args.output} matches {args.pulse}/decisions.yaml.") + return 0 + print( + f"{args.output} is out of date with {args.pulse}/decisions.yaml; " + "regenerate it.", + file=sys.stderr, + ) + return 1 + generate(args.pulse, args.output) + print(f"Wrote {args.output}.") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/autoarray/setup/setup.py b/autoarray/setup/setup.py new file mode 100644 index 000000000..18c883912 --- /dev/null +++ b/autoarray/setup/setup.py @@ -0,0 +1,303 @@ +""" +The compute setup of a likelihood: which backend, device, operator, precision and +(for interferometry) transformer evaluate it, and where that choice came from. + +:class:`Setup` is the setup tuple of the profiling campaigns, written as a setup_id +``___[_]`` (for example +``numba_cpu_sparse_fp64``, ``jax_gpu_dense_fp64`` or ``jax_gpu_sparse_fp64_wtilde``), +plus its provenance. + +:meth:`Setup.auto` chooses a setup from the rule table ``autoarray/config/setup_rules.yaml``, +which is generated from the PyAutoPulse designation decisions by +:mod:`autoarray.setup.generate_rules`. Detecting the hardware and parsing the +``PYAUTO_SETUP`` environment variable belong to :mod:`autonerves.environment`; this +module only chooses. +""" + +import functools +import os +from dataclasses import dataclass +from pathlib import Path +from typing import Dict, List, Optional, Tuple + +import yaml + +from autonerves.environment import ( + SETUP_BACKENDS, + SETUP_DEVICES, + SETUP_ENV_VAR, + SETUP_PRECISIONS, + Environment, + parse_setup_intent, +) + +RULES_PATH = Path(__file__).resolve().parent.parent / "config" / "setup_rules.yaml" + +HARDWARE_CLASS_CPU = "cpu_many_core" +HARDWARE_CLASS_GPU = "gpu_a100" + +# The fewest CPU cores a machine may have and still count as the ``cpu_many_core`` +# hardware class the Pulse designations were measured on. A CPU-only machine with +# fewer cores (a laptop) uses the ``cpu_many_core`` rule with ``extrapolated=True``. +MANY_CORE_MIN_CORES = 16 + +# The GPU name substring of the ``gpu_a100`` hardware class. Any other GPU uses the +# ``gpu_a100`` rule with ``extrapolated=True``. +GPU_A100_NAME = "A100" + +EXPLICIT_RULE_ID = f"explicit:{SETUP_ENV_VAR}" + + +def _validate_token(name: str, value: Optional[str], allowed=None, optional=False): + if value is None and optional: + return + if not isinstance(value, str): + raise ValueError(f"Setup {name} must be a string, got {value!r}.") + if allowed is not None: + if value not in allowed: + raise ValueError( + f"Setup {name}={value!r} is not valid; allowed: {allowed}." + ) + return + if not (value and value.isascii() and value.isalnum() and value == value.lower()): + raise ValueError( + f"Setup {name}={value!r} is not valid; it must be a non-empty lowercase " + "alphanumeric token (e.g. 'dense', 'sparse', 'na', 'wtilde', 'nufft')." + ) + + +@functools.lru_cache(maxsize=None) +def _load_rules(path: str = str(RULES_PATH)) -> Tuple[dict, ...]: + """ + The rows of the setup rule table, loaded once and cached. + + Parameters + ---------- + path + The rule table to load; defaults to the table shipped with autoarray. + """ + with open(path) as f: + rules = yaml.safe_load(f)["rules"] + return tuple(rules) + + +def rules() -> List[dict]: + """ + A copy of the rows of the setup rule table ``autoarray/config/setup_rules.yaml``. + + Each row has the keys ``likelihood`` (``/``), ``regime``, + ``hardware_class``, ``optimal`` (a setup_id), ``secondary`` (a list of setup_ids), + ``decision_id`` (the PyAutoPulse decision id) and ``rule`` (one sentence). + """ + return [dict(row) for row in _load_rules()] + + +def _rule_index() -> Dict[Tuple[str, str, str], dict]: + return { + (row["likelihood"], row["regime"], row["hardware_class"]): row + for row in _load_rules() + } + + +@dataclass(frozen=True) +class Setup: + """ + A compute setup for evaluating a likelihood, plus where it came from. + + The first five fields are the setup tuple, written as the setup_id + ``___[_]`` (see + :attr:`setup_id`). The remaining fields record how the setup was chosen and do + not take part in the setup_id. + + Parameters + ---------- + backend + The array backend: ``"jax"``, ``"numba"`` or ``"numpy"``. + device + ``"cpu"`` or ``"gpu"``. + operator + How the linear algebra is formed, a lowercase alphanumeric token, for + example ``"dense"``, ``"sparse"`` or ``"na"`` (no operator, e.g. point + sources). + precision + ``"fp64"``, ``"fp32"`` or ``"mp"`` (mixed precision). + transformer + The interferometer route, a lowercase alphanumeric token (``"wtilde"``, + ``"nufft"``, ...), or ``None`` when there is none. + rule_id + What chose this setup: ``None`` for a setup written by hand, + ``"explicit:PYAUTO_SETUP"`` when it came from the environment variable, or + the Pulse decision id of the rule :meth:`auto` used. + regime + The dataset regime of the rule, e.g. ``"standard"``. + hardware_class + The hardware class of the rule, ``"cpu_many_core"`` or ``"gpu_a100"``. + decision_id + The PyAutoPulse decision id of the rule, if any. + extrapolated + Whether the rule was measured on different hardware from this machine (a + non-A100 GPU, a CPU with fewer than ``MANY_CORE_MIN_CORES`` cores, or a + hardware class the likelihood has no designation for). + """ + + backend: str + device: str + operator: str + precision: str + transformer: Optional[str] = None + rule_id: Optional[str] = None + regime: str = "standard" + hardware_class: Optional[str] = None + decision_id: Optional[str] = None + extrapolated: bool = False + + def __post_init__(self): + _validate_token("backend", self.backend, allowed=SETUP_BACKENDS) + _validate_token("device", self.device, allowed=SETUP_DEVICES) + _validate_token("operator", self.operator) + _validate_token("precision", self.precision, allowed=SETUP_PRECISIONS) + _validate_token("transformer", self.transformer, optional=True) + + @property + def setup_id(self) -> str: + """ + The setup_id ``___[_]``. + """ + parts = [self.backend, self.device, self.operator, self.precision] + if self.transformer is not None: + parts.append(self.transformer) + return "_".join(parts) + + @classmethod + def from_setup_id(cls, setup_id: str, **provenance) -> "Setup": + """ + The setup a setup_id names, e.g. ``Setup.from_setup_id("numba_cpu_sparse_fp64")``. + + The grammar is that of :func:`autonerves.environment.parse_setup_intent`; + case and surrounding whitespace are ignored. + + Parameters + ---------- + setup_id + ``___[_]``. + provenance + Optional ``rule_id``, ``regime``, ``hardware_class``, ``decision_id`` + and ``extrapolated`` values for the returned setup. + + Raises + ------ + ValueError + If ``setup_id`` is not a setup_id (``"auto"``, ``"cpu"`` and ``"gpu"`` + are device intents, not setup_ids). + """ + if not isinstance(setup_id, str): + raise ValueError(f"A setup_id must be a string, got {setup_id!r}.") + text = setup_id.strip().lower() + if text in ("", "auto") + SETUP_DEVICES: + raise ValueError( + f"{setup_id!r} is a device intent, not a setup_id " + "'___[_]'." + ) + parse_setup_intent(text) + backend, device, operator, precision, *rest = text.split("_") + return cls( + backend=backend, + device=device, + operator=operator, + precision=precision, + transformer=rest[0] if rest else None, + **provenance, + ) + + @classmethod + def auto( + cls, + dataset_type: str, + variant: str, + regime: str = "standard", + environment: Optional[Environment] = None, + ) -> "Setup": + """ + The Pulse-designated optimal setup for a likelihood on this machine. + + In order: + + 1. If ``PYAUTO_SETUP`` is a full setup_id, that setup is returned with + ``rule_id="explicit:PYAUTO_SETUP"``. An explicit ``Setup(...)`` passed by + the caller also always wins, by not calling this method. + 2. The hardware class is ``gpu_a100`` when ``PYAUTO_SETUP=gpu``, or when it + is ``auto``/unset and the environment has a GPU; otherwise + ``cpu_many_core``. The setup is marked ``extrapolated`` when the machine + differs from the class the rule was measured on: a GPU whose name does + not contain ``"A100"`` (or no GPU at all) for ``gpu_a100``, or fewer than + ``MANY_CORE_MIN_CORES`` cores for ``cpu_many_core``. + 3. The rule ``(f"{dataset_type}/{variant}", regime, hardware_class)`` is + looked up in the rule table. When the likelihood has no rule for that + hardware class, its rule for the other class is used, with + ``extrapolated=True``. + + Parameters + ---------- + dataset_type + The dataset type, e.g. ``"imaging"`` or ``"interferometer"``. + variant + The likelihood variant, e.g. ``"rectangular"``, ``"delaunay"`` or ``"mge"``. + regime + The dataset regime; only ``"standard"`` is designated so far. + environment + The hardware to choose for; defaults to ``Environment.detect()``. + + Raises + ------ + ValueError + If ``PYAUTO_SETUP`` is invalid, or the likelihood and regime have no + rule; the message lists the known likelihoods. + """ + value = os.environ.get(SETUP_ENV_VAR) + intent = parse_setup_intent(value) + if ( + value is not None + and value.strip().lower() not in ("", "auto") + SETUP_DEVICES + ): + return cls.from_setup_id(value, rule_id=EXPLICIT_RULE_ID) + + environment = environment or Environment.detect() + + if intent == "auto": + intent = "gpu" if environment.gpu else "cpu" + + if intent == "gpu": + hardware_class = HARDWARE_CLASS_GPU + extrapolated = not ( + environment.gpu and GPU_A100_NAME in (environment.gpu_name or "") + ) + else: + hardware_class = HARDWARE_CLASS_CPU + extrapolated = environment.cores < MANY_CORE_MIN_CORES + + likelihood = f"{dataset_type}/{variant}" + index = _rule_index() + row = index.get((likelihood, regime, hardware_class)) + if row is None: + other = ( + HARDWARE_CLASS_CPU + if hardware_class == HARDWARE_CLASS_GPU + else HARDWARE_CLASS_GPU + ) + row = index.get((likelihood, regime, other)) + extrapolated = True + if row is None: + known = sorted({key[0] for key in index if key[1] == regime}) + raise ValueError( + f"No setup rule for likelihood {likelihood!r} in regime {regime!r}. " + f"Known likelihoods: {known}." + ) + + return cls.from_setup_id( + row["optimal"], + rule_id=row["decision_id"], + regime=row["regime"], + hardware_class=row["hardware_class"], + decision_id=row["decision_id"], + extrapolated=extrapolated, + ) diff --git a/test_autoarray/setup/__init__.py b/test_autoarray/setup/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/test_autoarray/setup/test_setup.py b/test_autoarray/setup/test_setup.py new file mode 100644 index 000000000..08ea0418e --- /dev/null +++ b/test_autoarray/setup/test_setup.py @@ -0,0 +1,350 @@ +import os +from pathlib import Path + +import pytest + +import autoarray as aa +from autoarray.setup import generate_rules +from autoarray.setup import setup as setup_py +from autonerves.environment import Environment + + +def _environment(gpu=False, gpu_name=None, cores=64): + return Environment( + gpu=gpu, + gpu_name=gpu_name, + gpu_memory_gb=None, + cores=cores, + ram_gb=None, + numba=True, + nufftax=True, + site="local", + ) + + +A100 = _environment(gpu=True, gpu_name="NVIDIA A100-SXM4-80GB") +MANY_CORE = _environment(cores=64) + +RULES = setup_py.rules() + + +def _all_setup_ids(): + ids = set() + for row in RULES: + ids.add(row["optimal"]) + ids.update(row["secondary"]) + return sorted(ids) + + +@pytest.fixture(autouse=True) +def unset_pyauto_setup(monkeypatch): + monkeypatch.delenv("PYAUTO_SETUP", raising=False) + + +def test__setup__tokens_and_setup_id(): + setup = aa.Setup("jax", "gpu", "sparse", "fp64", transformer="wtilde") + + assert setup.setup_id == "jax_gpu_sparse_fp64_wtilde" + assert setup.rule_id is None + assert setup.regime == "standard" + assert setup.extrapolated is False + + assert ( + aa.Setup("numba", "cpu", "sparse", "fp64").setup_id == "numba_cpu_sparse_fp64" + ) + + +@pytest.mark.parametrize( + "kwargs", + [ + dict(backend="torch", device="cpu", operator="dense", precision="fp64"), + dict(backend="jax", device="tpu", operator="dense", precision="fp64"), + dict(backend="jax", device="cpu", operator="dense", precision="fp16"), + dict(backend="jax", device="cpu", operator="Dense", precision="fp64"), + dict(backend="jax", device="cpu", operator="den_se", precision="fp64"), + dict(backend="jax", device="cpu", operator="", precision="fp64"), + dict( + backend="jax", + device="cpu", + operator="dense", + precision="fp64", + transformer="nu-fft", + ), + ], +) +def test__setup__invalid_tokens_raise(kwargs): + with pytest.raises(ValueError): + aa.Setup(**kwargs) + + +@pytest.mark.parametrize( + "value", + [ + "auto", + "cpu", + "gpu", + "", + "jax_cpu", + "torch_cpu_dense_fp64", + "jax_cpu_dense_fp64_a_b", + ], +) +def test__from_setup_id__invalid_raises(value): + with pytest.raises(ValueError): + aa.Setup.from_setup_id(value) + + +def test__from_setup_id__case_and_whitespace(): + setup = aa.Setup.from_setup_id(" JAX_GPU_Dense_FP64_NUFFT ") + + assert setup.setup_id == "jax_gpu_dense_fp64_nufft" + assert setup.transformer == "nufft" + + +@pytest.mark.parametrize("setup_id", _all_setup_ids()) +def test__from_setup_id__round_trips_every_table_id(setup_id): + assert aa.Setup.from_setup_id(setup_id).setup_id == setup_id + + +def test__rule_table__schema(): + assert len(RULES) == 39 + + keys = [(r["likelihood"], r["regime"], r["hardware_class"]) for r in RULES] + assert len(set(keys)) == len(keys) + assert keys == sorted(keys) + + for row in RULES: + assert set(row) == set(generate_rules.ROW_KEYS) + assert row["decision_id"] + assert row["rule"] + assert row["hardware_class"] in ("cpu_many_core", "gpu_a100") + assert "/" in row["likelihood"] + assert isinstance(row["secondary"], list) + + +@pytest.mark.parametrize( + "row", RULES, ids=[f"{r['likelihood']}-{r['hardware_class']}" for r in RULES] +) +def test__auto__every_rule_row(row): + dataset_type, variant = row["likelihood"].split("/") + environment = A100 if row["hardware_class"] == "gpu_a100" else MANY_CORE + + setup = aa.Setup.auto(dataset_type, variant, environment=environment) + + assert setup.setup_id == row["optimal"] + assert setup.rule_id == row["decision_id"] + assert setup.decision_id == row["decision_id"] + assert setup.hardware_class == row["hardware_class"] + assert setup.regime == "standard" + assert setup.extrapolated is False + + +def test__auto__examples(): + assert ( + aa.Setup.auto("imaging", "rectangular", environment=MANY_CORE).setup_id + == "numba_cpu_sparse_fp64" + ) + assert ( + aa.Setup.auto("imaging", "rectangular", environment=A100).setup_id + == "jax_gpu_dense_fp64" + ) + assert ( + aa.Setup.auto("interferometer", "delaunay", environment=A100).setup_id + == "jax_gpu_sparse_fp64_wtilde" + ) + assert ( + aa.Setup.auto("interferometer", "mge", environment=MANY_CORE).setup_id + == "jax_cpu_dense_fp64_nufft" + ) + + +def test__auto__extrapolated_non_a100_gpu(): + environment = _environment(gpu=True, gpu_name="NVIDIA GeForce RTX 2060") + + setup = aa.Setup.auto("imaging", "delaunay", environment=environment) + + assert setup.hardware_class == "gpu_a100" + assert setup.setup_id == "jax_gpu_dense_fp64" + assert setup.extrapolated is True + + +def test__auto__extrapolated_gpu_without_name(): + setup = aa.Setup.auto( + "imaging", "delaunay", environment=_environment(gpu=True, gpu_name=None) + ) + + assert setup.extrapolated is True + + +def test__auto__extrapolated_small_core_cpu(): + cores = setup_py.MANY_CORE_MIN_CORES - 1 + + setup = aa.Setup.auto("imaging", "mge", environment=_environment(cores=cores)) + + assert setup.hardware_class == "cpu_many_core" + assert setup.setup_id == "jax_cpu_dense_fp64" + assert setup.extrapolated is True + + setup = aa.Setup.auto( + "imaging", + "mge", + environment=_environment(cores=setup_py.MANY_CORE_MIN_CORES), + ) + assert setup.extrapolated is False + + +def test__auto__missing_hardware_class_uses_nearest_row_extrapolated(): + # datacube/delaunay is only designated on cpu_many_core. + setup = aa.Setup.auto("datacube", "delaunay", environment=A100) + + assert setup.hardware_class == "cpu_many_core" + assert setup.setup_id == "numba_cpu_sparse_fp64_wtilde" + assert setup.extrapolated is True + + +def test__auto__unknown_likelihood_raises_listing_known(): + with pytest.raises(ValueError, match="imaging/rectangular"): + aa.Setup.auto("imaging", "voronoi", environment=MANY_CORE) + + with pytest.raises(ValueError, match="Known likelihoods"): + aa.Setup.auto("imaging", "rectangular", regime="huge", environment=MANY_CORE) + + +def test__auto__pyauto_setup_full_id_wins(monkeypatch): + monkeypatch.setenv("PYAUTO_SETUP", "numpy_cpu_dense_fp64") + + setup = aa.Setup.auto("imaging", "rectangular", environment=A100) + + assert setup.setup_id == "numpy_cpu_dense_fp64" + assert setup.rule_id == "explicit:PYAUTO_SETUP" + assert setup.decision_id is None + assert setup.hardware_class is None + + +def test__auto__pyauto_setup_full_id_wins_for_unknown_likelihood(monkeypatch): + monkeypatch.setenv("PYAUTO_SETUP", "jax_gpu_sparse_fp64_wtilde") + + setup = aa.Setup.auto("anything", "else") + + assert setup.setup_id == "jax_gpu_sparse_fp64_wtilde" + + +def test__auto__pyauto_setup_cpu_forces_cpu_class(monkeypatch): + monkeypatch.setenv("PYAUTO_SETUP", "cpu") + + setup = aa.Setup.auto( + "imaging", + "rectangular", + environment=_environment(gpu=True, gpu_name="A100", cores=64), + ) + + assert setup.hardware_class == "cpu_many_core" + assert setup.setup_id == "numba_cpu_sparse_fp64" + assert setup.extrapolated is False + + +def test__auto__pyauto_setup_gpu_forces_gpu_class(monkeypatch): + monkeypatch.setenv("PYAUTO_SETUP", "GPU") + + setup = aa.Setup.auto("imaging", "rectangular", environment=MANY_CORE) + + assert setup.hardware_class == "gpu_a100" + assert setup.setup_id == "jax_gpu_dense_fp64" + assert setup.extrapolated is True + + +@pytest.mark.parametrize("value", ["auto", "", " Auto "]) +def test__auto__pyauto_setup_auto_detects(monkeypatch, value): + monkeypatch.setenv("PYAUTO_SETUP", value) + + assert ( + aa.Setup.auto("imaging", "mge", environment=A100).hardware_class == "gpu_a100" + ) + assert ( + aa.Setup.auto("imaging", "mge", environment=MANY_CORE).hardware_class + == "cpu_many_core" + ) + + +def test__auto__pyauto_setup_invalid_raises(monkeypatch): + monkeypatch.setenv("PYAUTO_SETUP", "tpu") + + with pytest.raises(ValueError, match="PYAUTO_SETUP"): + aa.Setup.auto("imaging", "mge", environment=MANY_CORE) + + +def test__auto__detects_environment_when_not_given(monkeypatch): + monkeypatch.setattr(Environment, "detect", classmethod(lambda cls: A100)) + + assert aa.Setup.auto("imaging", "mge").hardware_class == "gpu_a100" + + +def test__generate_rules__check_detects_drift(tmp_path): + decisions = tmp_path / "pulse" / "decisions.yaml" + decisions.parent.mkdir() + decisions.write_text( + "decisions:\n" + "- id: imaging-mge-standard-cpu-many-core\n" + " kind: designation\n" + " likelihood: imaging/mge\n" + " regime: standard\n" + " hardware_class: cpu_many_core\n" + " optimal: jax_cpu_dense_fp64\n" + " secondary: []\n" + " rule: An imaging MGE fit uses jax_cpu_dense_fp64.\n" + "- id: not-a-designation\n" + " title: something else\n" + ) + output = tmp_path / "setup_rules.yaml" + + assert ( + generate_rules.main(["--pulse", str(decisions.parent), "--output", str(output)]) + == 0 + ) + assert ( + generate_rules.main( + ["--pulse", str(decisions.parent), "--output", str(output), "--check"] + ) + == 0 + ) + + output.write_text( + output.read_text().replace("jax_cpu_dense_fp64", "numba_cpu_sparse_fp64") + ) + assert ( + generate_rules.main( + ["--pulse", str(decisions.parent), "--output", str(output), "--check"] + ) + == 1 + ) + + +def _pulse_checkout(): + env = os.environ.get("PYAUTO_PULSE") + if env and (Path(env) / "decisions.yaml").is_file(): + return Path(env) + here = Path(__file__).resolve() + for parent in here.parents: + for candidate in ( + parent / "organs" / "PyAutoPulse", + parent / "PyAutoPulse", + ): + if (candidate / "decisions.yaml").is_file(): + return candidate + return None + + +def test__rule_table__parity_with_pulse(tmp_path): + pulse = _pulse_checkout() + if pulse is None: + pytest.skip( + "No PyAutoPulse checkout (set PYAUTO_PULSE to run the parity test)." + ) + + output = tmp_path / "setup_rules.yaml" + generate_rules.generate(pulse, output) + + regenerated = list(setup_py._load_rules(str(output))) + + assert regenerated == RULES + assert generate_rules.check(pulse, setup_py.RULES_PATH)