"""Device and runtime diagnostics for local Apple ML work.""" from __future__ import annotations import importlib import importlib.metadata as im import json import platform import subprocess import sys from collections.abc import Callable from typing import Any def _optional_import(module: str) -> tuple[Any | None, dict[str, Any]]: try: imported = importlib.import_module(module) except Exception as exc: # pragma: no cover - exercised by missing deps return None, {"available": False, "error": repr(exc)} return imported, {"available": True} def _safe_call(func: Callable[[], Any]) -> Any: try: return func() except Exception as exc: # pragma: no cover - backend-specific diagnostics return {"error": repr(exc)} def _sysctl_int(name: str) -> int | None: try: result = subprocess.run( ["sysctl", "-n", name], check=True, capture_output=True, text=True, ) except Exception: return None value = result.stdout.strip() return int(value) if value.isdigit() else None def cpu_info() -> dict[str, Any]: memory_bytes = _sysctl_int("hw.memsize") return { "python": sys.version.split()[0], "platform": platform.platform(), "machine": platform.machine(), "processor": platform.processor(), "memory_bytes": memory_bytes, } def numpy_info() -> dict[str, Any]: numpy, info = _optional_import("numpy") if numpy is not None: info["version"] = numpy.__version__ return info def torch_info() -> dict[str, Any]: torch, info = _optional_import("torch") if torch is None: return info mps = getattr(getattr(torch, "backends", None), "mps", None) info.update( { "version": torch.__version__, "mps_built": bool(_safe_call(mps.is_built)) if mps else False, "mps_available": bool(_safe_call(mps.is_available)) if mps else False, "selected_device": "mps" if mps and mps.is_available() else "cpu", } ) if hasattr(torch, "mps") and hasattr(torch.mps, "current_allocated_memory"): info["mps_current_allocated_memory"] = _safe_call( torch.mps.current_allocated_memory ) return info def mlx_info() -> dict[str, Any]: mlx, mlx_module_info = _optional_import("mlx") mx, info = _optional_import("mlx.core") info["package_available"] = mlx_module_info["available"] if mlx is not None: info["version"] = im.version("mlx") if mx is None: return info info["default_device"] = str(_safe_call(mx.default_device)) metal = getattr(mx, "metal", None) if metal is None: info["metal_available"] = False return info info["metal_available"] = bool(_safe_call(metal.is_available)) memory_functions = { "active_memory": getattr(mx, "get_active_memory", None) or getattr(metal, "get_active_memory", None), "peak_memory": getattr(mx, "get_peak_memory", None) or getattr(metal, "get_peak_memory", None), "cache_memory": getattr(mx, "get_cache_memory", None) or getattr(metal, "get_cache_memory", None), "memory_limit": getattr(mx, "get_memory_limit", None) or getattr(metal, "get_memory_limit", None), } for name, func in memory_functions.items(): if callable(func): info[name] = _safe_call(func) return info def collect_device_report() -> dict[str, Any]: return { "cpu": cpu_info(), "numpy": numpy_info(), "torch": torch_info(), "mlx": mlx_info(), } def print_device_report() -> None: print(json.dumps(collect_device_report(), indent=2, sort_keys=True))