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
63 changes: 38 additions & 25 deletions autonerves/setup_colab.py
Original file line number Diff line number Diff line change
Expand Up @@ -205,11 +205,12 @@ def check_jax_using_gpu(log_gpu_warning: bool = True) -> bool:
#: 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"]
_JAX_SPECS = ["jax>=0.12.0,<0.13", "jaxlib>=0.12.0,<0.13"]
_NUMPY_SPEC = "numpy>=2.2"


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


def _version_tuple(text):
Expand All @@ -233,46 +234,58 @@ 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.
Versions are read from package metadata, never by importing jax. Only what is
below the floor is upgraded: jax and jaxlib together (plus the matching CUDA
plugin on a GPU runtime), NumPy only if it is older than 2.2.

A package already imported into the kernel cannot be replaced in place, so
:class:`ColabRestartRequired` is raised only when an UPGRADED package is
already loaded. Importing this module loads NumPy but not jax, so on a
Colab whose NumPy already meets the floor the upgrade completes without a
restart (PyAutoNerves#217). Otherwise the user restarts once and re-runs the
setup cell, and on that second run the floor is met.
"""
import subprocess

jax_v, jaxlib_v, numpy_v = (_dist_version(n) for n in ("jax", "jaxlib", "numpy"))
too_old = (
jax_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:
numpy_old = numpy_v is None or _version_tuple(numpy_v) < _NUMPY_FLOOR
if not (jax_old or numpy_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",
]

specs, upgraded = [], []
if jax_old:
specs += _JAX_SPECS
upgraded += ["jax", "jaxlib"]
# 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",
]
if numpy_old:
specs.append(_NUMPY_SPEC)
upgraded.append("numpy")

what = " and ".join(n for n, old in (("JAX", jax_old), ("NumPy", numpy_old)) if old)
print(
f"Upgrading JAX for PyAuto (found jax {jax_v}, jaxlib {jaxlib_v}, "
f"Upgrading {what} 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:
loaded = [name for name in upgraded if name in sys.modules]
if loaded:
raise ColabRestartRequired(
"JAX and NumPy were upgraded. Restart the runtime "
"(Runtime > Restart session) and run this setup cell again."
f"{', '.join(loaded)} was upgraded but is already loaded in this "
"runtime. Restart the runtime (Runtime > Restart session) and run "
"this setup cell again."
)


Expand Down
48 changes: 34 additions & 14 deletions test_autonerves/test_setup_colab.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,35 +65,55 @@ def test_floor_met_installs_nothing(self, jax_floor_met):
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
def test_live_colab_upgrades_jax_without_restart(self, jax_floor_met, monkeypatch):
"""Colab 2026-11-12: jax 0.11.1, NumPy 2.4.6. Importing setup_colab loads
NumPy but not jax, so only jax is upgraded and no restart is needed
(the 2026.11.12.1 bootstrap demanded one: PyAutoNerves#217)."""
jax_floor_met.update(jax="0.11.1", jaxlib="0.11.1", numpy="2.4.6")
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"):
monkeypatch.delitem(sys.modules, "jax", raising=False)
monkeypatch.delitem(sys.modules, "jaxlib", raising=False)
with mock.patch.object(subprocess, "check_call") as check_call:
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)
assert {"jax>=0.12.0,<0.13", "jaxlib>=0.12.0,<0.13"} <= set(args)
assert not any(a.startswith("numpy") for a in args)

@pytest.mark.parametrize("old", [{"jax": "0.11.1"}, {"jaxlib": "0.11.2"}])
def test_jax_upgrade_asks_for_restart_only_if_jax_is_loaded(self, jax_floor_met, monkeypatch, old):
jax_floor_met.update(old)
monkeypatch.setitem(sys.modules, "jax", types.ModuleType("jax"))
with mock.patch.object(subprocess, "check_call"), \
pytest.raises(setup_colab.ColabRestartRequired, match="jax.*Restart the runtime"):
setup_colab._ensure_jax_floor()

def test_old_numpy_is_upgraded_and_restarts_only_if_loaded(self, jax_floor_met, monkeypatch):
jax_floor_met["numpy"] = "2.1.3"
monkeypatch.setitem(sys.modules, "numpy", types.ModuleType("numpy"))
with mock.patch.object(subprocess, "check_call") as check_call, \
pytest.raises(setup_colab.ColabRestartRequired, match="numpy"):
setup_colab._ensure_jax_floor()
args = check_call.call_args.args[0]
assert "numpy>=2.2" in args
assert not any(a.startswith(("jax>", "jaxlib>")) for a in 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):
monkeypatch.delitem(sys.modules, "jax", raising=False)
monkeypatch.delitem(sys.modules, "jaxlib", raising=False)
with mock.patch.object(subprocess, "check_call") as check_call:
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)
jax_floor_met.update(jax="0.11.1", numpy="2.1.3")
for name in ("jax", "jaxlib", "numpy"):
monkeypatch.delitem(sys.modules, name, raising=False)
with mock.patch.object(subprocess, "check_call") as check_call:
setup_colab._ensure_jax_floor()
check_call.assert_called_once()
Expand Down
Loading