Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 31 additions & 20 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -118,26 +118,37 @@ Nothing on the board edits config.

## JAX compatibility

The package retains JAX/JAXlib `>=0.7,<0.12`, excluding `0.10.*` and `0.11.0`.
Those excluded releases contain CPU batched LAPACK scheduling that can deadlock
while materializing a vectorized likelihood (PyAutoHeart#274). The failure was
captured on 0.10.2; tagged source identifies the same path in the other excluded
releases. Open-source builds disable it from 0.11.1. This restriction does not
replace the separate historical FFT/Eigen workaround.

The compatibility diagnostics exercise **0.9.2** as an older endpoint and
**0.11.2** as the recommended validation baseline. They do not certify every
version permitted by the retained range or promise identical performance across
versions. A new minimum of 0.11.2 is deliberately avoided: it would unnecessarily
force newer NumPy/SciPy requirements on users with working older environments.

Updated family packages require `autonerves>2026.10.4.1` so their resolver cannot
fall back to a Nerves release without the exclusions. This is a release ordering
requirement: publish a Nerves wheel containing this policy before the corresponding
family wheels. No release version is chosen by this bound, and existing published
wheels are not retroactively repaired. An unpinned family package can still be
backtracked to an entirely older family release; select the repaired family
release explicitly when applying the fix to a constrained environment.
PyAutoNerves requires **JAX and JAXlib 0.12** (`>=0.12.0,<0.13`). Both are
pinned, because jax 0.12.0 on its own would still accept the older jaxlib 0.11.2.

Why 0.12: on the CPU, jax 0.11.2 can freeze a likelihood. A call never returns
and the process sits at 0 % CPU. It happened every time on 4 cores, sometimes on
8 and never on 16, so laptops, CI runners and small containers are the most
exposed (PyAutoNerves#213; the evidence is in PyAutoDNA
`decisions/jax-cpu-policy-2026-11.md`). jax 0.12.0 and 0.12.0.1 ran 30,000 calls
with no freeze. Part of the fix is upstream (jax-ml/jax#41265, fixed in XLA for
0.12.0).

No XLA flag is set for you. On 0.12 none is needed, and the
`--xla_cpu_multi_thread_eigen=false` flag that hid the problem on 0.11 slows
pixelized likelihoods by roughly 20-50 %.

What this means for your install:

- **Python** 3.12 or newer (unchanged).
- **NumPy** 2.2 or newer, because jax 0.12 requires it.
- **x86-64 CPUs** must be Intel Haswell / AMD equivalent (2013) or newer; jaxlib
0.12 wheels use those instructions. Apple Silicon and Linux on ARM are fine.
- **Intel macOS** still installs without JAX (there are no jaxlib wheels for it)
and runs the NumPy path.
- **Google Colab** ships an older jax. The PyAuto Colab setup cell upgrades jax,
jaxlib and NumPy, and asks you to restart the runtime once if they were already
loaded.

Updated family packages require a PyAutoNerves newer than `2026.11.9.1`, the last
release that still allowed jax 0.11, so pip cannot pair them with the old range.
Publish this Nerves before the family packages. Existing published wheels are not
repaired; if you pin old family releases, upgrade them together.

Keep JAX, JAXlib and any CUDA plugin on a mutually compatible version. Use pip's
resolver rather than `--no-deps`, and verify the resulting environment with
Expand Down
80 changes: 80 additions & 0 deletions autonerves/setup_colab.py
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,82 @@ def check_jax_using_gpu(log_gpu_warning: bool = True) -> bool:
return no_gpu


#: The JAX floor (PyAutoNerves#215): jax 0.11.x can freeze XLA:CPU likelihoods,
#: and Colab ships an older jax. The package install below is ``--no-deps``,
#: so it would never upgrade jax by itself; :func:`_ensure_jax_floor` does.
_JAX_FLOOR = (0, 12, 0)
_NUMPY_FLOOR = (2, 2, 0) # jax 0.12 requires numpy>=2.2
_JAX_SPECS = ["jax>=0.12.0,<0.13", "jaxlib>=0.12.0,<0.13", "numpy>=2.2"]


class ColabRestartRequired(RuntimeError):
"""Raised after upgrading jax / NumPy in a kernel that already loaded them."""


def _version_tuple(text):
parts = []
for piece in str(text).split(".")[:3]:
digits = "".join(ch for ch in piece if ch.isdigit())
parts.append(int(digits) if digits else 0)
return tuple(parts + [0] * (3 - len(parts)))


def _dist_version(name: str):
try:
from importlib.metadata import version

return version(name)
except Exception:
return None


def _ensure_jax_floor() -> None:
"""
Upgrade Colab's preinstalled jax / jaxlib / NumPy to the supported range.

Versions are read from package metadata, never by importing jax, because
a jax already imported into the kernel cannot be replaced in place. When an
upgrade happens and jax or NumPy is already loaded, raise
:class:`ColabRestartRequired` so the user restarts the runtime once and
re-runs the setup cell; on that second run the floor is met and setup
continues.
"""
import subprocess

jax_v, jaxlib_v, numpy_v = (_dist_version(n) for n in ("jax", "jaxlib", "numpy"))
too_old = (
jax_v is None
or jaxlib_v is None
or _version_tuple(jax_v) < _JAX_FLOOR
or _version_tuple(jaxlib_v) < _JAX_FLOOR
or numpy_v is None
or _version_tuple(numpy_v) < _NUMPY_FLOOR
)
if not too_old:
return

specs = list(_JAX_SPECS)
# A GPU runtime carries a CUDA plugin that must match jaxlib exactly.
for cuda in ("cuda12", "cuda13"):
if _dist_version(f"jax-{cuda}-plugin") is not None:
specs += [
f"jax-{cuda}-plugin[with-cuda]>=0.12.0,<0.13",
f"jax-{cuda}-pjrt>=0.12.0,<0.13",
]

print(
f"Upgrading JAX for PyAuto (found jax {jax_v}, jaxlib {jaxlib_v}, "
f"numpy {numpy_v}; PyAuto needs jax 0.12 and numpy 2.2 or newer)."
)
subprocess.check_call([sys.executable, "-m", "pip", "install", *specs])

if "jax" in sys.modules or "numpy" in sys.modules:
raise ColabRestartRequired(
"JAX and NumPy were upgraded. Restart the runtime "
"(Runtime > Restart session) and run this setup cell again."
)


def _running_in_ipython() -> bool:
"""
True only when an IPython interactive shell (Jupyter notebook, IPython
Expand Down Expand Up @@ -333,6 +409,10 @@ def _colab_setup(

return

# Before anything imports jax: Colab's preinstalled jax is older than the
# floor, and the --no-deps install below never upgrades it.
_ensure_jax_floor()

# JAX performance tweak, applied only on Colab.
os.environ["XLA_FLAGS"] = _XLA_FLAGS

Expand Down
17 changes: 10 additions & 7 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,16 @@ dependencies = [
# wheels for >=0.7), so the markers let Intel Macs resolve to the
# NumPy-only path instead of failing at install. jax_wrapper warns loudly
# at import when JAX is absent.
# CPU batched LAPACK can deadlock in 0.10.x / 0.11.0 (Heart#274).
# Preserve older versions; 0.9.2 and 0.11.2 are compatibility witnesses.
# jax 0.11 note: 0.11 requires numpy>=2.1 and scipy>=1.15, so this cap
# widen also raises those effective floors for every install that
# resolves jax (PyAutoFit#1510).
'jax>=0.7.0,<0.12.0,!=0.10.*,!=0.11.0; sys_platform != "darwin" or platform_machine == "arm64"',
'jaxlib>=0.7.0,<0.12.0,!=0.10.*,!=0.11.0; sys_platform != "darwin" or platform_machine == "arm64"',
# jax 0.12 floor (PyAutoNerves#213/#215; PyAutoDNA
# decisions/jax-cpu-policy-2026-11.md): 0.11.2 deadlocks XLA:CPU
# likelihoods (every call at 4 cores on RAL job 415009); 0.12.0 and
# 0.12.0.1 ran 30,000 calls with no hang and no XLA flag. Pin jaxlib
# too: jax 0.12.0 itself still accepts jaxlib 0.11.2. This replaces the
# old 0.7 floor and the 0.10.* / 0.11.0 exclusions (Heart#274). jax 0.12
# raises the effective numpy floor to 2.2 and needs a Haswell-or-newer
# x86-64 CPU. Do not add a default XLA:CPU flag: none is needed on 0.12.
'jax>=0.12.0,<0.13; sys_platform != "darwin" or platform_machine == "arm64"',
'jaxlib>=0.12.0,<0.13; sys_platform != "darwin" or platform_machine == "arm64"',
'jaxnnls==1.0.1; sys_platform != "darwin" or platform_machine == "arm64"'
]

Expand Down
10 changes: 5 additions & 5 deletions test_autonerves/test_dependency_policy.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
"""Installer contract: exclude the CPU deadlock without discarding older JAX."""
"""Installer contract: require jax/jaxlib 0.12 (XLA:CPU deadlock on <=0.11.2, PyAutoNerves#213)."""
from pathlib import Path
import tomllib

Expand All @@ -14,11 +14,11 @@ def requirement(request):


@pytest.mark.parametrize('version,allowed', [
('0.7.0', True), ('0.9.2', True), ('0.10.0', False), ('0.10.1', False),
('0.10.2', False), ('0.10.99', False), ('0.11.0', False), ('0.11.1', True),
('0.11.2', True), ('0.12.0', False),
('0.7.0', False), ('0.9.2', False), ('0.10.2', False), ('0.11.1', False),
('0.11.2', False), ('0.12.0', True), ('0.12.0.1', True), ('0.12.9', True),
('0.13.0', False),
])
def test_cpu_deadlock_exclusion_keeps_older_versions(requirement, version, allowed):
def test_jax_and_jaxlib_require_0_12(requirement, version, allowed):
assert (version in requirement.specifier) is allowed


Expand Down
60 changes: 60 additions & 0 deletions test_autonerves/test_setup_colab.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,66 @@ def _split_requirement(requirement):
)


_FLOOR_MET = {"jax": "0.12.0.1", "jaxlib": "0.12.0.1", "numpy": "2.3.0"}


@pytest.fixture(autouse=True)
def jax_floor_met(monkeypatch):
"""
Report a jax/jaxlib/NumPy stack that already meets the floor, so the
version gate (``_ensure_jax_floor``) is a no-op in every test that is not
about it. The tests below override this mapping.
"""
versions = dict(_FLOOR_MET)
monkeypatch.setattr(setup_colab, "_dist_version", versions.get)
return versions


class TestEnsureJaxFloor:
def test_floor_met_installs_nothing(self, jax_floor_met):
with mock.patch.object(subprocess, "check_call") as check_call:
setup_colab._ensure_jax_floor()
check_call.assert_not_called()

@pytest.mark.parametrize("name,old", [
("jax", "0.11.1"), ("jaxlib", "0.11.2"), ("numpy", "2.1.3"),
])
def test_old_stack_upgrades_then_asks_for_restart(self, jax_floor_met, monkeypatch, name, old):
jax_floor_met[name] = old
monkeypatch.setitem(sys.modules, "numpy", types.ModuleType("numpy"))
with mock.patch.object(subprocess, "check_call") as check_call, \
pytest.raises(setup_colab.ColabRestartRequired, match="Restart the runtime"):
setup_colab._ensure_jax_floor()
args = check_call.call_args.args[0]
assert "--no-deps" not in args
assert {"jax>=0.12.0,<0.13", "jaxlib>=0.12.0,<0.13", "numpy>=2.2"} <= set(args)

def test_gpu_runtime_upgrades_its_matching_cuda_plugin(self, jax_floor_met, monkeypatch):
jax_floor_met.update(jax="0.11.1", jaxlib="0.11.1")
jax_floor_met["jax-cuda12-plugin"] = "0.11.1"
monkeypatch.setitem(sys.modules, "numpy", types.ModuleType("numpy"))
with mock.patch.object(subprocess, "check_call") as check_call, \
pytest.raises(setup_colab.ColabRestartRequired):
setup_colab._ensure_jax_floor()
args = check_call.call_args.args[0]
assert "jax-cuda12-plugin[with-cuda]>=0.12.0,<0.13" in args
assert "jax-cuda12-pjrt>=0.12.0,<0.13" in args
assert not any("cuda13" in a for a in args)

def test_fresh_process_upgrades_without_restart(self, jax_floor_met, monkeypatch):
jax_floor_met["jax"] = "0.11.1"
monkeypatch.delitem(sys.modules, "jax", raising=False)
monkeypatch.delitem(sys.modules, "numpy", raising=False)
with mock.patch.object(subprocess, "check_call") as check_call:
setup_colab._ensure_jax_floor()
check_call.assert_called_once()

def test_setup_checks_the_floor_before_importing_jax(self):
source = Path(setup_colab.__file__).read_text()
body = source[source.index("def _colab_setup("):]
assert body.index("_ensure_jax_floor()") < body.index("check_jax_using_gpu(")


@pytest.fixture(name="no_ipython")
def make_no_ipython(monkeypatch):
"""A plain-interpreter run: no IPython module loaded at all."""
Expand Down
Loading