"""Content-addressed snapshot and admission for the installed GPU environment.""" from __future__ import annotations import importlib import importlib.metadata import json import platform import re import sys from pathlib import Path from typing import Any from ..atomic_io import atomic_write_json _NORMALIZE_NAME = re.compile(r"[-_.]+") def _name(value: str) -> str: return _NORMALIZE_NAME.sub("-", value).lower() def installed_distributions() -> dict[str, str]: """Return every installed distribution as a canonical name/version map.""" values: dict[str, str] = {} for distribution in importlib.metadata.distributions(): raw_name = distribution.metadata.get("Name") if not raw_name: continue name = _name(str(raw_name)) version = str(distribution.version) previous = values.get(name) if previous is not None and previous != version: raise RuntimeError(f"multiple installed versions for {name}: {previous}, {version}") values[name] = version return dict(sorted(values.items())) def current_environment_snapshot() -> dict[str, Any]: """Capture Python, every wheel version, torch/CUDA, and visible GPU facts.""" torch_record: dict[str, Any] | None = None try: torch = importlib.import_module("torch") except ImportError: torch = None if torch is not None: cuda = torch.cuda devices = [] if bool(cuda.is_available()): for index in range(int(cuda.device_count())): properties = cuda.get_device_properties(index) devices.append( { "index": index, "name": str(properties.name), "capability": list(cuda.get_device_capability(index)), "total_memory": int(properties.total_memory), } ) cudnn = getattr(torch.backends, "cudnn", None) torch_record = { "version": str(torch.__version__), "compiled_cuda": str(torch.version.cuda), "cudnn_version": int(cudnn.version()) if cudnn is not None and cudnn.version() is not None else None, "cuda_available": bool(cuda.is_available()), "devices": devices, } return { "schema_version": 1, "kind": "training_environment_lock", "python": { "version": platform.python_version(), "implementation": platform.python_implementation(), "executable": str(Path(sys.executable).resolve()), }, "platform": platform.platform(), "distributions": installed_distributions(), "torch": torch_record, } def write_environment_snapshot(path: str | Path) -> dict[str, Any]: destination = Path(path) if destination.exists(): raise FileExistsError(f"refusing to overwrite environment lock: {destination}") snapshot = current_environment_snapshot() atomic_write_json(destination, snapshot) return snapshot def environment_lock_errors(path: str | Path) -> list[str]: """Compare the current process against an immutable environment snapshot.""" source = Path(path) try: expected = json.loads(source.read_text(encoding="utf-8")) except (OSError, json.JSONDecodeError) as exc: return [f"cannot read training environment lock: {exc}"] if not isinstance(expected, dict) or expected.get("schema_version") != 1: return ["training environment lock must use schema_version=1"] if expected.get("kind") != "training_environment_lock": return ["environment lock has the wrong kind"] actual = current_environment_snapshot() errors: list[str] = [] for field in ("python", "platform", "distributions", "torch"): if expected.get(field) != actual.get(field): errors.append(f"installed environment differs from lock field {field}") return errors