From 32ee087e6138409ce4b13b93ae9a67ff88f3059e Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Mon, 23 Nov 2026 09:55:36 +0000 Subject: [PATCH] feat: environment probe, PYAUTO_SETUP at import, honour JAX_ENABLE_X64=False (#222) Co-Authored-By: Claude Opus 5.5 --- autonerves/environment.py | 270 ++++++++++++++++++++++++++ autonerves/jax_wrapper.py | 50 ++++- test_autonerves/test_environment.py | 281 ++++++++++++++++++++++++++++ test_autonerves/test_jax_wrapper.py | 120 +++++++++++- 4 files changed, 710 insertions(+), 11 deletions(-) create mode 100644 autonerves/environment.py create mode 100644 test_autonerves/test_environment.py diff --git a/autonerves/environment.py b/autonerves/environment.py new file mode 100644 index 0000000..865052c --- /dev/null +++ b/autonerves/environment.py @@ -0,0 +1,270 @@ +""" +The environment layer: what hardware and optional packages this process can use, +and what compute setup the user asked for through ``PYAUTO_SETUP``. + +This module only *detects* and *parses*; it never chooses a setup. Choosing (the +backend, device, operator and precision that ``setup="auto"`` resolves to) belongs to +``Setup.auto`` in PyAutoArray, which reads :class:`Environment` and +:func:`parse_setup_intent` from here. + +It imports nothing heavy at module level (no JAX, numba or nufftax), because +``autonerves.jax_wrapper`` calls :func:`parse_setup_intent` and +:func:`detect_cores` before JAX may be imported. +""" +import importlib.util +import os +import re +import socket +import subprocess +import sys +from dataclasses import dataclass +from typing import Optional + +SETUP_ENV_VAR = "PYAUTO_SETUP" + +SETUP_BACKENDS = ("jax", "numba", "numpy") +SETUP_DEVICES = ("cpu", "gpu") +SETUP_PRECISIONS = ("fp64", "fp32", "mp") + +_SETUP_ID = re.compile( + r"^(?Pjax|numba|numpy)" + r"_(?Pcpu|gpu)" + r"_(?P[a-z0-9]+)" + r"_(?Pfp64|fp32|mp)" + r"(?:_(?P[a-z0-9]+))?$" +) + +_ALLOWED_FORMS = ( + "unset, '' or 'auto'; 'cpu'; 'gpu'; or a setup_id " + "'___[_]' with backend in " + f"{SETUP_BACKENDS}, device in {SETUP_DEVICES}, precision in {SETUP_PRECISIONS} " + "and operator/transformer lowercase alphanumeric tokens " + "(e.g. 'numba_cpu_sparse_fp64', 'jax_gpu_dense_fp64', " + "'jax_gpu_sparse_fp64_wtilde')" +) + + +def parse_setup_intent(value: Optional[str]) -> str: + """ + The device intent of a ``PYAUTO_SETUP`` value: ``"auto"``, ``"cpu"`` or ``"gpu"``. + + Accepted forms (case-insensitive, surrounding whitespace ignored): + + - ``None`` (unset), ``""`` or ``"auto"`` -> ``"auto"``: nothing is pinned; JAX + picks the GPU when one is present. + - ``"cpu"`` / ``"gpu"`` -> that device. + - a setup_id ``___[_]``, the + vocabulary of the profiling campaigns (e.g. ``numba_cpu_sparse_fp64``, + ``jax_gpu_dense_fp64``, ``jax_gpu_sparse_fp64_wtilde``): ``backend`` is one of + ``jax``, ``numba``, ``numpy``; ``device`` is ``cpu`` or ``gpu``; ``precision`` + is ``fp64``, ``fp32`` or ``mp``; ``operator`` (``dense``, ``sparse``, ``na``, + ...) and the optional ``transformer`` (``wtilde``, ``nufft``, ...) are any + lowercase alphanumeric token. The device token decides the intent. + + Raises + ------ + ValueError + If ``value`` is none of these; the message names the allowed forms. + """ + if value is None: + return "auto" + text = value.strip().lower() + if text in ("", "auto"): + return "auto" + if text in SETUP_DEVICES: + return text + match = _SETUP_ID.match(text) + if match is None: + raise ValueError( + f"{SETUP_ENV_VAR}={value!r} is not a valid setup. Allowed: {_ALLOWED_FORMS}." + ) + return match.group("device") + + +def detect_cores() -> int: + """ + The number of CPU cores this process may use. + + In order: ``SLURM_CPUS_PER_TASK`` (the cores Slurm allocated to the task), then + ``len(os.sched_getaffinity(0))`` (the cores this process is pinned to, which + respects ``taskset`` and cgroup CPU sets), then ``os.cpu_count()``; at least 1. + """ + slurm = os.environ.get("SLURM_CPUS_PER_TASK") + if slurm: + try: + cores = int(slurm) + if cores > 0: + return cores + except ValueError: + pass + try: + return max(1, len(os.sched_getaffinity(0))) + except (AttributeError, OSError): + pass + return max(1, os.cpu_count() or 1) + + +def detect_ram_gb() -> Optional[float]: + """ + Total physical memory in GB, from ``MemTotal`` in ``/proc/meminfo``, falling back + to ``os.sysconf`` (pages x page size); ``None`` if neither is available. + """ + try: + with open("/proc/meminfo") as f: + for line in f: + if line.startswith("MemTotal:"): + return int(line.split()[1]) / 1024**2 + except (OSError, ValueError, IndexError): + pass + try: + return os.sysconf("SC_PHYS_PAGES") * os.sysconf("SC_PAGE_SIZE") / 1024**3 + except (AttributeError, ValueError, OSError): + return None + + +def _package_available(name: str) -> bool: + """Whether ``name`` is importable, checked with ``find_spec`` (never imported).""" + try: + return importlib.util.find_spec(name) is not None + except (ImportError, ValueError): + return False + + +def detect_gpu(timeout: float = 5.0): + """ + ``(gpu, gpu_name, gpu_memory_gb)`` for the first GPU this process can see. + + This never imports JAX itself, so it is safe before JAX initialises: + + - If ``jax`` is already in ``sys.modules``, ``jax.devices()`` is asked (JAX has + already chosen its platform, so this reflects what JAX will actually use, + including ``JAX_PLATFORMS=cpu``). The name is the device kind; memory comes + from ``memory_stats()["bytes_limit"]`` when the backend reports it. + - Otherwise one ``nvidia-smi --query-gpu=name,memory.total`` subprocess runs with + ``timeout`` seconds. A missing ``nvidia-smi``, a non-zero exit, a timeout or + empty output all mean ``gpu=False``. + """ + if "jax" in sys.modules: + try: + jax = sys.modules["jax"] + gpus = [d for d in jax.devices() if d.platform == "gpu"] + except Exception: + gpus = [] + if not gpus: + return False, None, None + device = gpus[0] + memory_gb = None + try: + stats = device.memory_stats() or {} + if "bytes_limit" in stats: + memory_gb = stats["bytes_limit"] / 1024**3 + except Exception: + pass + return True, getattr(device, "device_kind", None), memory_gb + + try: + result = subprocess.run( + [ + "nvidia-smi", + "--query-gpu=name,memory.total", + "--format=csv,noheader,nounits", + ], + capture_output=True, + text=True, + timeout=timeout, + ) + except (OSError, subprocess.SubprocessError): + return False, None, None + if result.returncode != 0 or not result.stdout.strip(): + return False, None, None + first = result.stdout.strip().splitlines()[0] + name, _, memory = first.rpartition(",") + if not name: + name, memory = memory, "" + try: + memory_gb = float(memory.strip()) / 1024 # nvidia-smi reports MiB + except ValueError: + memory_gb = None + return True, name.strip() or None, memory_gb + + +def detect_site() -> str: + """ + A hint naming the computing site. + + ``SLURM_CLUSTER_NAME`` (lowercased) when Slurm sets it; otherwise a class of the + hostname: the name of a site file shipped in ``autonerves/site/`` (the site layer + of :mod:`autonerves.site_config`) when the hostname starts with it, ``"colab"`` + on Google Colab, else ``"local"``. It is a hint only; nothing is loaded. + """ + cluster = os.environ.get("SLURM_CLUSTER_NAME") + if cluster: + return cluster.strip().lower() + try: + hostname = socket.gethostname().lower() + except OSError: + hostname = "" + from autonerves.site_config import PACKAGE_SITE_DIRECTORY + + for path in sorted(PACKAGE_SITE_DIRECTORY.glob("*.yaml")): + if hostname.startswith(path.stem.lower()): + return path.stem.lower() + if "COLAB_RELEASE_TAG" in os.environ or "COLAB_GPU" in os.environ: + return "colab" + return "local" + + +@dataclass(frozen=True) +class Environment: + """ + What this process can use, as detected by :meth:`Environment.detect`. + + Attributes + ---------- + gpu + Whether a GPU is visible. + gpu_name + The first GPU's name, or ``None``. + gpu_memory_gb + The first GPU's memory in GB, or ``None`` if unknown. + cores + CPU cores this process may use (see :func:`detect_cores`). + ram_gb + Total physical memory in GB, or ``None`` if unknown. + numba + Whether ``numba`` is installed (checked without importing it). + nufftax + Whether ``nufftax`` is installed (checked without importing it). + site + A site hint (see :func:`detect_site`). + """ + + gpu: bool + gpu_name: Optional[str] + gpu_memory_gb: Optional[float] + cores: int + ram_gb: Optional[float] + numba: bool + nufftax: bool + site: str + + @classmethod + def detect(cls) -> "Environment": + """ + Probe the current process. Reports only; chooses nothing. + + Never imports JAX: GPU facts come from ``jax.devices()`` only when JAX is + already imported, otherwise from a single ``nvidia-smi`` query with a short + timeout (see :func:`detect_gpu`). + """ + gpu, gpu_name, gpu_memory_gb = detect_gpu() + return cls( + gpu=gpu, + gpu_name=gpu_name, + gpu_memory_gb=gpu_memory_gb, + cores=detect_cores(), + ram_gb=detect_ram_gb(), + numba=_package_available("numba"), + nufftax=_package_available("nufftax"), + site=detect_site(), + ) diff --git a/autonerves/jax_wrapper.py b/autonerves/jax_wrapper.py index 05bc675..70619c6 100644 --- a/autonerves/jax_wrapper.py +++ b/autonerves/jax_wrapper.py @@ -5,6 +5,35 @@ import os +from autonerves.environment import SETUP_ENV_VAR, detect_cores, parse_setup_intent + +# PYAUTO_SETUP is read before anything can import JAX, because JAX_PLATFORMS and the +# thread variables only take effect if set before JAX (and the BLAS / numba thread +# pools) initialise. An explicit CPU intent ("cpu", or a setup_id whose device token +# is cpu, e.g. numba_cpu_sparse_fp64) pins JAX to the CPU and sizes the thread pools +# to the detected cores; "auto", unset and "gpu" set nothing. A value the user has +# already set is never overwritten. Invalid values raise ValueError naming the +# allowed forms (see autonerves.environment.parse_setup_intent). +_setup_intent = parse_setup_intent(os.environ.get(SETUP_ENV_VAR)) + +if _setup_intent == "cpu": + _cores = str(detect_cores()) + _applied = {} + for _key, _value in ( + ("JAX_PLATFORMS", "cpu"), + ("OMP_NUM_THREADS", _cores), + ("MKL_NUM_THREADS", _cores), + ("OPENBLAS_NUM_THREADS", _cores), + ("NUMBA_NUM_THREADS", _cores), + ): + if _key not in os.environ: + os.environ[_key] = _value + _applied[_key] = _value + logger.info( + f"{SETUP_ENV_VAR}={os.environ[SETUP_ENV_VAR]!r} requests CPU: set {_applied} " + "(variables already set were left unchanged)." + ) + if importlib.util.find_spec("jax") is None: logger.warning( """ @@ -87,25 +116,30 @@ jax_enable_x64 = os.environ.get("JAX_ENABLE_X64") +# Unset -> force x64 on (double precision is the default for the PyAuto stack). An +# explicit false value ("false", "0") is a deliberate fp32 request and is respected; +# any other explicit value (e.g. "true", "1") is left to JAX as given. if jax_enable_x64 is None: - jax_enable_x64 = False -elif isinstance(jax_enable_x64, str): - jax_enable_x64 = jax_enable_x64.lower() == "true" - -if not jax_enable_x64: os.environ["JAX_ENABLE_X64"] = "True" logger.info( - """" + """ JAX 64-bit precision has been automatically enabled for you (JAX_ENABLE_X64=True), as double precision is required for most scientific computing applications. - To enable 64 precision as default in JAX, set the environment variable - JAX_ENABLE_X64=true before running your script. + To run JAX in 32-bit precision instead, set the environment variable + JAX_ENABLE_X64=False before running your script. """ ) +elif jax_enable_x64.strip().lower() in ("false", "0"): + + logger.info( + f"JAX_ENABLE_X64={jax_enable_x64!r}: 32-bit (fp32) JAX precision was " + "requested and is respected; 64-bit precision is not enabled." + ) + if "JAX_COMPILATION_CACHE_DIR" not in os.environ: _cache_root = os.environ.get("XDG_CACHE_HOME") or os.path.join( diff --git a/test_autonerves/test_environment.py b/test_autonerves/test_environment.py new file mode 100644 index 0000000..2fdec54 --- /dev/null +++ b/test_autonerves/test_environment.py @@ -0,0 +1,281 @@ +"""Tests for autonerves.environment: the hardware probe and PYAUTO_SETUP parsing. + +Every detect branch runs with the environment monkeypatched; no test imports JAX or +needs a GPU. +""" +import builtins +import subprocess +import sys +import types + +import pytest + +from autonerves import environment +from autonerves.environment import Environment, parse_setup_intent + + +# --- parse_setup_intent ------------------------------------------------------- + + +@pytest.mark.parametrize("value", [None, "", " ", "auto", "AUTO", " Auto "]) +def test_parse_auto(value): + assert parse_setup_intent(value) == "auto" + + +@pytest.mark.parametrize("value, intent", [("cpu", "cpu"), ("gpu", "gpu"), ("CPU", "cpu")]) +def test_parse_device(value, intent): + assert parse_setup_intent(value) == intent + + +@pytest.mark.parametrize( + "value, intent", + [ + ("numba_cpu_sparse_fp64", "cpu"), + ("numba_cpu_sparse_fp64_wtilde", "cpu"), + ("jax_cpu_na_fp64", "cpu"), + ("numpy_cpu_dense_fp32", "cpu"), + ("jax_gpu_dense_fp64", "gpu"), + ("jax_gpu_sparse_fp64_wtilde", "gpu"), + ("jax_gpu_dense_mp_nufft", "gpu"), + ("JAX_GPU_DENSE_FP64", "gpu"), + ], +) +def test_parse_setup_id(value, intent): + assert parse_setup_intent(value) == intent + + +@pytest.mark.parametrize( + "value", + [ + "tpu", + "jax", + "jax_cpu", + "jax_cpu_dense", + "torch_cpu_dense_fp64", + "jax_tpu_dense_fp64", + "jax_cpu_dense_fp16", + "jax_cpu__fp64", + "jax_cpu_dense_fp64_wtilde_extra", + "jax-cpu-dense-fp64", + ], +) +def test_parse_invalid_raises(value): + with pytest.raises(ValueError, match="PYAUTO_SETUP") as info: + parse_setup_intent(value) + assert "setup_id" in str(info.value) + + +# --- cores -------------------------------------------------------------------- + + +def test_cores_from_slurm(monkeypatch): + monkeypatch.setenv("SLURM_CPUS_PER_TASK", "7") + monkeypatch.setattr(environment.os, "sched_getaffinity", lambda pid: {0, 1}, raising=False) + assert environment.detect_cores() == 7 + + +def test_cores_bad_slurm_falls_back_to_affinity(monkeypatch): + monkeypatch.setenv("SLURM_CPUS_PER_TASK", "lots") + monkeypatch.setattr(environment.os, "sched_getaffinity", lambda pid: {0, 1, 2}, raising=False) + assert environment.detect_cores() == 3 + + +def test_cores_from_affinity(monkeypatch): + monkeypatch.delenv("SLURM_CPUS_PER_TASK", raising=False) + monkeypatch.setattr(environment.os, "sched_getaffinity", lambda pid: {0, 1, 2}, raising=False) + monkeypatch.setattr(environment.os, "cpu_count", lambda: 64) + assert environment.detect_cores() == 3 + + +def test_cores_from_cpu_count(monkeypatch): + monkeypatch.delenv("SLURM_CPUS_PER_TASK", raising=False) + monkeypatch.delattr(environment.os, "sched_getaffinity", raising=False) + monkeypatch.setattr(environment.os, "cpu_count", lambda: 12) + assert environment.detect_cores() == 12 + + +def test_cores_at_least_one(monkeypatch): + monkeypatch.delenv("SLURM_CPUS_PER_TASK", raising=False) + monkeypatch.delattr(environment.os, "sched_getaffinity", raising=False) + monkeypatch.setattr(environment.os, "cpu_count", lambda: None) + assert environment.detect_cores() == 1 + + +# --- RAM ---------------------------------------------------------------------- + + +def test_ram_from_proc_meminfo(monkeypatch, tmp_path): + meminfo = tmp_path / "meminfo" + meminfo.write_text("MemTotal: 16777216 kB\nMemFree: 1 kB\n") + real_open = builtins.open + monkeypatch.setattr( + builtins, + "open", + lambda path, *a, **k: real_open(meminfo if path == "/proc/meminfo" else path, *a, **k), + ) + assert environment.detect_ram_gb() == pytest.approx(16.0) + + +def _no_proc(monkeypatch): + real_open = builtins.open + + def fake_open(path, *args, **kwargs): + if path == "/proc/meminfo": + raise FileNotFoundError(path) + return real_open(path, *args, **kwargs) + + monkeypatch.setattr(builtins, "open", fake_open) + + +def test_ram_sysconf_fallback(monkeypatch): + _no_proc(monkeypatch) + values = {"SC_PHYS_PAGES": 2 * 1024**2, "SC_PAGE_SIZE": 4096} + monkeypatch.setattr(environment.os, "sysconf", lambda name: values[name], raising=False) + assert environment.detect_ram_gb() == pytest.approx(8.0) + + +def test_ram_unknown(monkeypatch): + _no_proc(monkeypatch) + monkeypatch.delattr(environment.os, "sysconf", raising=False) + assert environment.detect_ram_gb() is None + + +# --- optional packages -------------------------------------------------------- + + +def test_optional_packages_absent(monkeypatch): + monkeypatch.setattr(environment.importlib.util, "find_spec", lambda name: None) + assert environment._package_available("numba") is False + assert environment._package_available("nufftax") is False + + +def test_optional_packages_present(monkeypatch): + monkeypatch.setattr(environment.importlib.util, "find_spec", lambda name: object()) + assert environment._package_available("numba") is True + + +# --- GPU ---------------------------------------------------------------------- + + +@pytest.fixture +def no_jax(monkeypatch): + monkeypatch.delitem(sys.modules, "jax", raising=False) + + +def _completed(stdout, returncode=0): + return subprocess.CompletedProcess(args=[], returncode=returncode, stdout=stdout, stderr="") + + +def test_gpu_nvidia_smi_absent(monkeypatch, no_jax): + def run(*args, **kwargs): + raise FileNotFoundError("nvidia-smi") + + monkeypatch.setattr(environment.subprocess, "run", run) + assert environment.detect_gpu() == (False, None, None) + + +def test_gpu_nvidia_smi_timeout(monkeypatch, no_jax): + def run(*args, **kwargs): + raise subprocess.TimeoutExpired("nvidia-smi", kwargs.get("timeout")) + + monkeypatch.setattr(environment.subprocess, "run", run) + assert environment.detect_gpu() == (False, None, None) + + +def test_gpu_nvidia_smi_failing(monkeypatch, no_jax): + monkeypatch.setattr(environment.subprocess, "run", lambda *a, **k: _completed("", 9)) + assert environment.detect_gpu() == (False, None, None) + + +def test_gpu_nvidia_smi_present(monkeypatch, no_jax): + calls = [] + + def run(cmd, **kwargs): + calls.append((cmd, kwargs)) + return _completed("NVIDIA A100-SXM4-40GB, 40960\nNVIDIA A100-SXM4-40GB, 40960\n") + + monkeypatch.setattr(environment.subprocess, "run", run) + assert environment.detect_gpu() == (True, "NVIDIA A100-SXM4-40GB", 40.0) + assert len(calls) == 1 + assert calls[0][1]["timeout"] > 0 + + +def test_gpu_via_already_imported_jax(monkeypatch): + class Device: + platform = "gpu" + device_kind = "NVIDIA A100" + + def memory_stats(self): + return {"bytes_limit": 8 * 1024**3} + + fake_jax = types.SimpleNamespace(devices=lambda: [Device()]) + monkeypatch.setitem(sys.modules, "jax", fake_jax) + + def run(*args, **kwargs): + raise AssertionError("nvidia-smi must not run when jax is imported") + + monkeypatch.setattr(environment.subprocess, "run", run) + assert environment.detect_gpu() == (True, "NVIDIA A100", 8.0) + + +def test_gpu_via_already_imported_jax_cpu_only(monkeypatch): + fake_jax = types.SimpleNamespace( + devices=lambda: [types.SimpleNamespace(platform="cpu")] + ) + monkeypatch.setitem(sys.modules, "jax", fake_jax) + assert environment.detect_gpu() == (False, None, None) + + +# --- site --------------------------------------------------------------------- + + +def test_site_from_slurm(monkeypatch): + monkeypatch.setenv("SLURM_CLUSTER_NAME", "RAL") + assert environment.detect_site() == "ral" + + +def test_site_from_hostname_matching_shipped_site(monkeypatch): + monkeypatch.delenv("SLURM_CLUSTER_NAME", raising=False) + monkeypatch.setattr(environment.socket, "gethostname", lambda: "ral-login01") + assert environment.detect_site() == "ral" + + +def test_site_colab(monkeypatch): + monkeypatch.delenv("SLURM_CLUSTER_NAME", raising=False) + monkeypatch.setattr(environment.socket, "gethostname", lambda: "abc123") + monkeypatch.setenv("COLAB_RELEASE_TAG", "release-1") + assert environment.detect_site() == "colab" + + +def test_site_local(monkeypatch): + for key in ("SLURM_CLUSTER_NAME", "COLAB_RELEASE_TAG", "COLAB_GPU"): + monkeypatch.delenv(key, raising=False) + monkeypatch.setattr(environment.socket, "gethostname", lambda: "my-laptop") + assert environment.detect_site() == "local" + + +# --- Environment.detect ------------------------------------------------------- + + +def test_detect_assembles_fields(monkeypatch, no_jax): + monkeypatch.setenv("SLURM_CPUS_PER_TASK", "4") + monkeypatch.setenv("SLURM_CLUSTER_NAME", "ral") + monkeypatch.setattr(environment.subprocess, "run", lambda *a, **k: _completed("", 1)) + monkeypatch.setattr( + environment.importlib.util, "find_spec", lambda name: object() if name == "numba" else None + ) + env = Environment.detect() + assert env.gpu is False and env.gpu_name is None and env.gpu_memory_gb is None + assert env.cores == 4 + assert env.numba is True + assert env.nufftax is False + assert env.site == "ral" + assert env.ram_gb is None or env.ram_gb > 0 + with pytest.raises(Exception): + env.cores = 8 # frozen + + +def test_detect_does_not_import_jax(monkeypatch, no_jax): + monkeypatch.setattr(environment.subprocess, "run", lambda *a, **k: _completed("", 1)) + Environment.detect() + assert "jax" not in sys.modules diff --git a/test_autonerves/test_jax_wrapper.py b/test_autonerves/test_jax_wrapper.py index 3063682..f48f42f 100644 --- a/test_autonerves/test_jax_wrapper.py +++ b/test_autonerves/test_jax_wrapper.py @@ -1,12 +1,16 @@ """Tests for the env-var handling in autonerves.jax_wrapper. -The wrapper's env logic runs at import time, so each test reloads the module -under a controlled os.environ. No test imports jax — the wrapper only sets -environment variables. +The wrapper's env logic runs at import time, so each in-process test reloads the +module under a controlled os.environ and does not import jax. The PYAUTO_SETUP and +JAX_ENABLE_X64 tests at the end import autonerves (and jax) in a fresh subprocess, +because both only take effect before JAX initialises. """ import importlib +import json import os +import subprocess +import sys import pytest @@ -23,6 +27,7 @@ def clean_env(monkeypatch): "JAX_COMPILATION_CACHE_DIR", "JAX_PERSISTENT_CACHE_MIN_COMPILE_TIME_SECS", "XDG_CACHE_HOME", + "PYAUTO_SETUP", ): monkeypatch.delenv(key, raising=False) yield monkeypatch @@ -138,3 +143,112 @@ def test_autotune_composes_with_user_flags(clean_env): assert CONSTANT_FOLDING in flags assert AUTOTUNE_OFF in flags assert TRITON_OFF in flags + + +def test_x64_explicit_false_respected(clean_env): + clean_env.setenv("JAX_ENABLE_X64", "False") + reload_wrapper() + assert os.environ["JAX_ENABLE_X64"] == "False" + + +def test_x64_explicit_one_left_alone(clean_env): + clean_env.setenv("JAX_ENABLE_X64", "1") + reload_wrapper() + assert os.environ["JAX_ENABLE_X64"] == "1" + + +# --- subprocess import tests: PYAUTO_SETUP and JAX_ENABLE_X64 ----------------- + +SETUP_VARS = ( + "PYAUTO_SETUP", + "JAX_PLATFORMS", + "OMP_NUM_THREADS", + "MKL_NUM_THREADS", + "OPENBLAS_NUM_THREADS", + "NUMBA_NUM_THREADS", + "JAX_ENABLE_X64", + "SLURM_CPUS_PER_TASK", +) +THREAD_VARS = SETUP_VARS[2:6] + + +def _run(code, **env_overrides): + """Run ``code`` in a fresh interpreter with a controlled environment. + + ``-S`` skips the ``site`` module, so no ``.pth`` hook or ``sitecustomize`` in + the venv can set JAX_PLATFORMS / *_NUM_THREADS / JAX_ENABLE_X64 behind the + test's back; this process's ``sys.path`` is passed on instead so the same + packages import. + """ + env = {k: v for k, v in os.environ.items() if k not in SETUP_VARS} + env["PYTHONPATH"] = os.pathsep.join(p for p in sys.path if p) + env.update(env_overrides) + return subprocess.run( + [sys.executable, "-S", "-c", code], + env=env, + capture_output=True, + text=True, + timeout=300, + ) + + +def _env_after_import(**env_overrides): + code = ( + "import json, os, autonerves; " + f"print(json.dumps({{k: os.environ.get(k) for k in {list(SETUP_VARS)!r}}}))" + ) + result = _run(code, **env_overrides) + assert result.returncode == 0, result.stderr + return json.loads(result.stdout.strip().splitlines()[-1]) + + +@pytest.mark.parametrize("value", ["cpu", "numba_cpu_sparse_fp64", "jax_cpu_dense_fp64_nufft"]) +def test_setup_cpu_sets_platform_and_threads(value): + env = _env_after_import(PYAUTO_SETUP=value, SLURM_CPUS_PER_TASK="3") + assert env["JAX_PLATFORMS"] == "cpu" + for key in THREAD_VARS: + assert env[key] == "3", key + + +def test_setup_cpu_never_overwrites_user_values(): + env = _env_after_import( + PYAUTO_SETUP="cpu", + SLURM_CPUS_PER_TASK="3", + OMP_NUM_THREADS="1", + JAX_PLATFORMS="cuda,cpu", + ) + assert env["OMP_NUM_THREADS"] == "1" + assert env["JAX_PLATFORMS"] == "cuda,cpu" + assert env["MKL_NUM_THREADS"] == "3" + + +@pytest.mark.parametrize("value", [None, "", "auto", "gpu", "jax_gpu_dense_fp64"]) +def test_setup_auto_gpu_and_unset_set_nothing(value): + overrides = {} if value is None else {"PYAUTO_SETUP": value} + env = _env_after_import(**overrides) + assert env["JAX_PLATFORMS"] is None + for key in THREAD_VARS: + assert env[key] is None, key + + +def test_setup_invalid_raises_at_import(): + result = _run("import autonerves", PYAUTO_SETUP="tpu_turbo") + assert result.returncode != 0 + assert "ValueError" in result.stderr + assert "PYAUTO_SETUP" in result.stderr + + +@pytest.mark.parametrize( + "value, expected", + [("False", False), ("0", False), ("false", False), (None, True), ("True", True), ("1", True)], +) +def test_x64_respected_by_jax(value, expected): + pytest.importorskip("jax") + overrides = {"JAX_PLATFORMS": "cpu"} + if value is not None: + overrides["JAX_ENABLE_X64"] = value + result = _run( + "import autonerves, jax; print(jax.config.read('jax_enable_x64'))", **overrides + ) + assert result.returncode == 0, result.stderr + assert result.stdout.strip().splitlines()[-1] == str(expected)