"""Hardware detection (static, for planning) and live stats (for the dashboard).""" import os import platform import re import shutil import subprocess from . import paths def run(cmd, timeout=10): try: r = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout) return r.stdout.strip() if r.returncode == 0 else "" except (OSError, subprocess.TimeoutExpired): return "" def _ram_gib(): if paths.IS_MAC: out = run(["sysctl", "-n", "hw.memsize"]) return int(out) / 2**30 if out.isdigit() else 0.0 try: with open("/proc/meminfo") as f: for line in f: if line.startswith("MemTotal:"): return int(line.split()[1]) / 2**20 except OSError: pass return 0.0 def _disk_free_gib(): p = paths.hf_hub_dir() while not p.exists() and p != p.parent: p = p.parent return shutil.disk_usage(p).free / 2**30 def _nvidia_gpus(): if not shutil.which("nvidia-smi"): return [] out = run(["nvidia-smi", "--query-gpu=index,name,memory.total,memory.used,compute_cap,driver_version", "--format=csv,noheader,nounits"]) gpus = [] for line in out.splitlines(): parts = [x.strip() for x in line.split(",")] if len(parts) < 6: continue try: gpus.append({ "index": int(parts[0]), "name": parts[1], "vram_gib": float(parts[2]) / 1024, "used_gib": float(parts[3]) / 1024, "compute_cap": float(parts[4]), "driver": parts[5], }) except ValueError: continue return gpus def apple_gpu_budget_gib(ram_gib): """How much unified memory the GPU may wire. macOS defaults to ~2/3 of RAM on small machines and ~3/4 on larger ones; an explicit iogpu.wired_limit_mb wins.""" out = run(["sysctl", "-n", "iogpu.wired_limit_mb"]) if out.isdigit() and int(out) > 0: return int(out) / 1024 return ram_gib * (0.75 if ram_gib > 36 else 0.67) def detect(): info = { "os": platform.system(), "arch": platform.machine(), "cpus": os.cpu_count() or 1, "ram_gib": round(_ram_gib(), 1), "disk_free_gib": round(_disk_free_gib(), 1), "kind": None, "gpus": [], "notes": [], } if paths.IS_MAC: if info["arch"] == "arm64": chip = run(["sysctl", "-n", "machdep.cpu.brand_string"]) or "Apple Silicon" info["kind"] = "apple" info["gpus"] = [{"index": 0, "name": chip, "vram_gib": round(apple_gpu_budget_gib(info["ram_gib"]), 1)}] else: info["notes"].append("Intel Macs aren't supported (MLX needs Apple Silicon).") return info gpus = _nvidia_gpus() if gpus: info["kind"] = "nvidia" info["gpus"] = gpus if not shutil.which("cc") and not shutil.which("gcc"): info["notes"].append("No C compiler found; Triton needs one (Debian/Ubuntu: sudo apt install build-essential).") return info if shutil.which("rocm-smi") or os.path.exists("/dev/kfd"): info["notes"].append("AMD/ROCm GPU detected; ROCm isn't supported yet.") elif shutil.which("nvidia-smi"): info["notes"].append("nvidia-smi is installed but can't talk to the driver.") else: info["notes"].append("No supported GPU found (need an NVIDIA GPU on Linux, or Apple Silicon).") return info def simulate(spec): """Fake hardware for `llmhost plan --simulate`, e.g. nvidia:24:8.9, nvidia:80:9.0:4, apple:64.""" parts = spec.split(":") kind = parts[0] base = {"os": "Darwin" if kind == "apple" else "Linux", "arch": "arm64" if kind == "apple" else "x86_64", "cpus": 16, "disk_free_gib": 2000.0, "kind": kind, "notes": ["simulated"]} if kind == "nvidia": vram = float(parts[1]); cc = float(parts[2]) if len(parts) > 2 else 8.9 count = int(parts[3]) if len(parts) > 3 else 1 base["ram_gib"] = max(64.0, vram * count) base["gpus"] = [{"index": i, "name": f"Simulated {vram:g}GiB sm_{cc}", "vram_gib": vram, "used_gib": 0.0, "compute_cap": cc, "driver": "sim"} for i in range(count)] elif kind == "apple": ram = float(parts[1]) base["ram_gib"] = ram base["gpus"] = [{"index": 0, "name": f"Simulated Apple {ram:g}GB", "vram_gib": round(ram * (0.75 if ram > 36 else 0.67), 1)}] else: raise SystemExit(f"unknown simulate kind {kind!r} (use nvidia:VRAM[:CC[:COUNT]] or apple:RAM)") return base # ---------- live stats ---------- def live_stats(kind): if kind == "nvidia": out = run(["nvidia-smi", "--query-gpu=name,memory.used,memory.total,utilization.gpu,temperature.gpu,power.draw,power.limit", "--format=csv,noheader,nounits"]) rows = [[x.strip() for x in l.split(",")] for l in out.splitlines() if l.strip()] if not rows: return None def num(x): try: return float(x) except ValueError: return None cols = list(zip(*rows)) vals = [[num(v) for v in c] for c in cols[1:]] def tot(c): xs = [v for v in vals[c] if v is not None] return sum(xs) if xs else None def avg(c): xs = [v for v in vals[c] if v is not None] return sum(xs) / len(xs) if xs else None def mx(c): xs = [v for v in vals[c] if v is not None] return max(xs) if xs else None name = rows[0][0] + (f" ×{len(rows)}" if len(rows) > 1 else "") return {"name": name, "mem_used": tot(0), "mem_total": tot(1), "util": avg(2), "temp": mx(3), "power": tot(4), "power_limit": tot(5)} if kind == "apple": # ioreg needs no sudo; temperature and power need powermetrics (sudo), so they're omitted. out = run(["ioreg", "-r", "-d", "1", "-w", "0", "-c", "IOAccelerator"]) util = re.search(r'"Device Utilization %"=(\d+)', out) used = re.search(r'"In use system memory"=(\d+)', out) ram = _ram_gib() return {"name": run(["sysctl", "-n", "machdep.cpu.brand_string"]) or "Apple GPU", "mem_used": int(used.group(1)) / 2**20 if used else None, "mem_total": apple_gpu_budget_gib(ram) * 1024, "util": float(util.group(1)) if util else None, "temp": None, "power": None, "power_limit": None} return None