The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(local-runtime): size AMD/Intel GPUs by the engine's own device type
teknium12e6924bd1088
diff --git a/hermes_cli/local_runtime/devices.py b/hermes_cli/local_runtime/devices.pynew file mode 100644index 00000000000..93bab78c8c3--- /dev/null+++ b/hermes_cli/local_runtime/devices.py@@ -0,0 +1,88 @@+"""Ask the installed llama.cpp build which accelerators it sees, in a disposable process.++ggml's device type is the engine's own integrated-vs-discrete verdict (Vulkan reads it from+VkPhysicalDeviceType), and llama.cpp places layers on discrete devices whenever one exists, so the+budget can follow the same rule. Loading a GPU driver can crash or hang the caller, hence a child+with a deadline that imports only the standard library (``-I``). Run directly:+``python -I devices.py <engine dir> <backend>`` prints the device list as JSON.+"""++from __future__ import annotations++import ctypes+import json+import os+from pathlib import Path+import subprocess+import sys++# enum ggml_backend_dev_type (ggml-backend.h): CPU, GPU, IGPU, ACCEL.+GGML_DEVICE_GPU = 1+GGML_DEVICE_IGPU = 2+++def probe_devices(engine_dir: Path, backend: str) -> list[dict]:+ """GPU/iGPU devices the ``backend`` library in ``engine_dir`` registers; [] on any failure."""+ from hermes_cli._subprocess_compat import windows_hide_flags++ try:+ out = subprocess.run(+ [sys.executable, "-I", str(Path(__file__).resolve()), str(engine_dir), backend],+ stdin=subprocess.DEVNULL, capture_output=True, text=True, encoding="utf-8",+ errors="replace", timeout=20, creationflags=windows_hide_flags())+ devices = json.loads(out.stdout) if out.returncode == 0 else []+ except (OSError, ValueError, subprocess.TimeoutExpired):+ return []+ if not isinstance(devices, list):+ return []+ return [d for d in devices if isinstance(d, dict)+ and d.get("type") in (GGML_DEVICE_GPU, GGML_DEVICE_IGPU)+ and isinstance(d.get("total"), int) and d["total"] > 0+ and isinstance(d.get("description"), str)]+++def _library(directory: Path, name: str) -> Path:+ return directory / (f"{name}.dll" if os.name == "nt" else f"lib{name}.so")+++def _read_devices(directory: Path, backend: str) -> list[dict]:+ dll_directory = os.add_dll_directory(str(directory)) if os.name == "nt" else None+ try:+ base = ctypes.CDLL(str(_library(directory, "ggml-base")), mode=ctypes.RTLD_GLOBAL)+ core = ctypes.CDLL(str(_library(directory, "ggml")), mode=ctypes.RTLD_GLOBAL)+ core.ggml_backend_load.argtypes = [ctypes.c_char_p]+ core.ggml_backend_load.restype = ctypes.c_void_p+ registry = core.ggml_backend_load(os.fsencode(_library(directory, f"ggml-{backend}")))+ if not registry:+ return []+ signatures = {+ "ggml_backend_reg_dev_count": ([ctypes.c_void_p], ctypes.c_size_t),+ "ggml_backend_reg_dev_get": ([ctypes.c_void_p, ctypes.c_size_t], ctypes.c_void_p),+ "ggml_backend_dev_description": ([ctypes.c_void_p], ctypes.c_char_p),+ "ggml_backend_dev_type": ([ctypes.c_void_p], ctypes.c_int),+ "ggml_backend_dev_memory": ([ctypes.c_void_p, ctypes.POINTER(ctypes.c_size_t),+ ctypes.POINTER(ctypes.c_size_t)], None),+ }+ for name, (arguments, result) in signatures.items():+ function = getattr(base, name)+ function.argtypes, function.restype = arguments, result+ devices = []+ for index in range(min(base.ggml_backend_reg_dev_count(registry), 64)):+ device = base.ggml_backend_reg_dev_get(registry, index)+ if not device:+ continue+ free, total = ctypes.c_size_t(), ctypes.c_size_t()+ base.ggml_backend_dev_memory(device, ctypes.byref(free), ctypes.byref(total))+ devices.append({+ "description": base.ggml_backend_dev_description(device).decode("utf-8", errors="replace"),+ "type": base.ggml_backend_dev_type(device),+ "free": min(free.value, total.value), "total": total.value,+ })+ return devices+ finally:+ if dll_directory is not None:+ dll_directory.close()+++if __name__ == "__main__":+ print(json.dumps(_read_devices(Path(sys.argv[1]), sys.argv[2])))diff --git a/hermes_cli/local_runtime/hardware.py b/hermes_cli/local_runtime/hardware.pyindex ccba506c45a..7c19d4c59f1 100644--- a/hermes_cli/local_runtime/hardware.py+++ b/hermes_cli/local_runtime/hardware.py@@ -20,6 +20,7 @@ import timefrom dataclasses import replacefrom pathlib import Path+from hermes_cli.local_runtime.devices import GGML_DEVICE_GPUfrom hermes_cli.local_runtime.estimator import HardwareBudgetlogger = logging.getLogger(__name__)@@ -56,11 +57,8 @@ _POOL_NEGATIVE_TTL_S = 60.0_pool_probe_cache: tuple[float, "tuple[int, bool | None] | None"] | None = None# ' CUDA0: NVIDIA Example Device (1234-core Example GPU) (46464 MiB, 46284 MiB free)'-# ' Vulkan0: AMD Radeon RX 6800 XT (16368 MiB, 14692 MiB free)'-# — greedy name pins the LAST parenthesized group, so names with parentheses parse.-_DEVICE_LINE_RE = re.compile(- r"^\s*(?P<backend>[A-Za-z]+)\d+:\s*(?P<name>.*)\s+"- r"\((?P<total>\d+)\s*MiB,\s*(?P<free>\d+)\s*MiB free\)\s*$")+# — greedy .* pins the LAST parenthesized group, so device names with parentheses parse.+_DEVICE_LINE_RE = re.compile(r"CUDA\d+:.*\((\d+)\s*MiB,\s*\d+\s*MiB free\)\s*$")def _stdout(*argv: str) -> str:@@ -299,8 +297,10 @@ def _cuda_driver_pool() -> "tuple[int, bool | None] | None":return None-def _engine_device_info() -> "tuple[int, int, str, str] | None":- """Return total, free, backend and name from an accelerated runtime."""+def _engine_device_pool() -> "tuple[int, bool | None] | None":+ """(engine_total_bytes, None) from the installed runtime's own --list-devices, or None. The+ fallback when the driver API is unreachable: asks the exact binary that will do the+ allocating. Carries no integrated verdict — callers must gate it."""with suppress(Exception): # a probe miss must never block budgetingfrom hermes_cli.config import get_config_valuefrom hermes_cli.local_runtime.binaries import installed_engine@@ -314,19 +314,12 @@ def _engine_device_info() -> "tuple[int, int, str, str] | None":if out.returncode != 0:return Nonefor line in (out.stdout + out.stderr).splitlines():- if (match := _DEVICE_LINE_RE.search(line)) is not None:- return (int(match.group("total")) << 20,- int(match.group("free")) << 20,- match.group("backend"), match.group("name").strip())+ m = _DEVICE_LINE_RE.search(line)+ if m:+ return int(m.group(1)) << 20, Nonereturn None-def _engine_device_pool() -> "tuple[int, bool | None] | None":- """Allocator total from an accelerated runtime, without an integrated verdict."""- info = _engine_device_info()- return (info[0], None) if info is not None else None--def _device_pool_view() -> "tuple[int, bool | None] | None":"""Best available allocator-side view, cached: a hit is permanent for the process, a missretries after a short TTL (the engine binary can appear mid-session via a pane install)."""@@ -341,6 +334,36 @@ def _device_pool_view() -> "tuple[int, bool | None] | None":return view+_accelerator_cache: "dict[str, tuple[float, dict | None]]" = {}+++def _accelerator_device() -> "dict | None":+ """The device a Vulkan/HIP engine will place layers on, or None (no such engine, probe miss).++ Mirrors llama.cpp's own placement: discrete devices whenever one exists, an integrated one only+ otherwise; among discrete devices the largest. Cached per engine binary like+ ``_device_pool_view`` (a hit lasts the process, a miss retries after the TTL): the hardware+ endpoint polls this every few seconds and each probe initializes the GPU driver.+ """+ with suppress(Exception): # a probe miss must never block budgeting+ from hermes_cli.config import get_config_value+ from hermes_cli.local_runtime.binaries import installed_engine+ from hermes_cli.local_runtime.devices import probe_devices++ engine = installed_engine(get_config_value("local_runtime.backend", "auto"))+ if engine is None or engine.backend not in ("vulkan", "hip"):+ return None+ key, now = str(engine.binary), time.monotonic()+ cached = _accelerator_cache.get(key)+ if cached is not None and (cached[1] is not None or now - cached[0] < _POOL_NEGATIVE_TTL_S):+ return cached[1]+ devices = probe_devices(engine.binary.parent, engine.backend)+ device = max(devices, key=lambda d: (d["type"] == GGML_DEVICE_GPU, d["total"]), default=None)+ _accelerator_cache[key] = (now, device)+ return device+ return None++def _unified_pool_bytes(smi_total: int, ram_total: int) -> int | None:"""The real pool size when this NVIDIA device is unified memory behind a carve-out, else None.@@ -376,23 +399,14 @@ def probe_budget(*, planning: bool = False) -> HardwareBudget:large. The managed server unloads/relaunches itself, so capacity is real."""ram_total, ram_avail = _ram_bytes()- nvidia_vram = _nvidia_vram()- vram = nvidia_vram- engine_info = _engine_device_info() if vram is None else None- if engine_info is not None and engine_info[2].lower() in ("vulkan", "hip"):- # llama.cpp is allocator truth for discrete AMD/Intel devices. WMI AdapterRAM is a- # legacy 32-bit field and cannot represent modern cards accurately.- vram = engine_info[0], engine_info[1], engine_info[3], None- unified = None- else:- # Preserve NVIDIA's no-smi path: the CUDA driver can still identify UMA.- unified = _unified_pool_bytes(nvidia_vram[0] if nvidia_vram else 0, ram_total)+ vram = _nvidia_vram()# Unified-memory NVIDIA: the CUDA allocator pool is the real capacity. Classification comes# from the driver API/engine and must not require nvidia-smi (stripped-PATH sessions lose smi# but nvcuda loads via the system loader). Crossing the carve-out costs nothing — it is an OS# accounting knob, not a GPU limit. Deliberately NOT clamped to OS RAM: carved-out memory is# invisible to GlobalMemoryStatusEx, so a RAM clamp would throw away exactly that capacity.+ unified = _unified_pool_bytes(vram[0] if vram else 0, ram_total)if unified is not None:logger.info("unified-memory NVIDIA device: allocator pool %.1f GiB "@@ -411,7 +425,16 @@ def probe_budget(*, planning: bool = False) -> HardwareBudget:gpu_pci_id=vram[3] if vram else None)if vram is None:- # Metal and CPU paths budget from RAM as UMA; unknown accelerators stay conservative.+ device = _accelerator_device()+ if device is not None and device["type"] == GGML_DEVICE_GPU:+ # Discrete AMD/Intel card behind a Vulkan/HIP engine: its own memory, with system RAM+ # as spill. Capacity serves the live view too; no per-poll free query exists here.+ total = device["total"]+ margin = max(_MARGIN_FLOOR, int(total * _MARGIN_FRACTION))+ return HardwareBudget(usable_vram_bytes=max(0, total - margin), total_device_bytes=total,+ ram_available_bytes=ram_total if planning else ram_avail,+ uma=False, gpu_name=device["description"], platform=sys.platform)+ # Integrated GPU, Metal, CPU, or no answer: budget from RAM as unified memory.return _uma_budget(ram_total if planning else ram_avail, ram_total)total, free, gpu_name, gpu_pci_id = vramdiff --git a/tests/hermes_cli/test_unified_pool_quirk.py b/tests/hermes_cli/test_unified_pool_quirk.pyindex 16f3b985f5d..e15890c1d18 100644--- a/tests/hermes_cli/test_unified_pool_quirk.py+++ b/tests/hermes_cli/test_unified_pool_quirk.py@@ -180,23 +180,29 @@ def test_engine_fallback_without_smi_stays_conservative(monkeypatch):assert b.total_device_bytes == UMA_RAM # RAM path, not the pool-def test_vulkan_device_is_budgeted_as_discrete_vram(monkeypatch):- """An accelerated Vulkan runtime is allocator truth for a discrete AMD card;- system RAM must not be relabeled as its graphics memory."""- total, free = 16368 << 20, 7347 << 20++[email protected]("device_type, discrete", [(1, True), (2, False)])+def test_vulkan_device_type_decides_discrete_vs_unified(monkeypatch, device_type, discrete):+ """A discrete AMD/Intel card behind a Vulkan engine budgets its own memory with RAM as spill;+ an integrated one (ggml IGPU) keeps the RAM-as-unified budget, never both pools."""+ total = 16304 << 20monkeypatch.setattr(hw, "_nvidia_vram", lambda: None)+ monkeypatch.setattr(hw, "_device_pool_view", lambda: None)monkeypatch.setattr(hw, "_ram_bytes", lambda: (32 * GIB, 20 * GIB))- monkeypatch.setattr(hw, "_engine_device_info", lambda: (- total, free, "Vulkan", "AMD Radeon RX 6800 XT"))+ monkeypatch.setattr(hw, "_accelerator_device", lambda: {+ "description": "AMD Radeon RX 9060 XT", "type": device_type, "free": total, "total": total})- planning = hw.probe_budget(planning=True)- live = hw.probe_budget(planning=False)+ b = hw.probe_budget(planning=True)- assert planning.uma is False- assert planning.total_device_bytes == total- assert planning.ram_available_bytes == 32 * GIB- assert live.total_device_bytes == total- assert live.usable_vram_bytes == max(0, free - hw._MARGIN_FLOOR)+ assert b.uma is (not discrete)+ if discrete:+ assert b.total_device_bytes == total+ assert b.usable_vram_bytes == total - hw._MARGIN_FLOOR+ assert b.ram_available_bytes == 32 * GIB+ else:+ assert b.total_device_bytes == 32 * GIB+ assert b.ram_available_bytes == 0@pytest.mark.platforms("linux")@@ -265,33 +271,10 @@ def test_pool_probe_miss_retries_after_ttl(monkeypatch):# ── device-line parsing (engine fallback) ────────────────────-def test_vulkan_device_line_reports_total_and_free_vram():- line = " Vulkan0: AMD Radeon RX 6800 XT (16368 MiB, 7347 MiB free)"- match = hw._DEVICE_LINE_RE.search(line)- assert match- assert match.group("backend") == "Vulkan"- assert match.group("name") == "AMD Radeon RX 6800 XT"- assert int(match.group("total")) == 16368- assert int(match.group("free")) == 7347---def test_metal_device_stays_uma(monkeypatch):- monkeypatch.setattr(hw, "_nvidia_vram", lambda: None)- monkeypatch.setattr(hw, "_ram_bytes", lambda: (32 * GIB, 20 * GIB))- monkeypatch.setattr(hw, "_engine_device_info", lambda: (- 32 * GIB, 20 * GIB, "Metal", "Apple GPU"))- monkeypatch.setattr(hw, "_device_pool_view", lambda: None)-- budget = hw.probe_budget(planning=True)-- assert budget.uma is True- assert budget.total_device_bytes == 32 * GIB--def test_device_line_regex_handles_parenthesized_names():"""Device names may contain their own parentheses — the LASTparenthesized group must win."""line = (" CUDA0: NVIDIA Example Device (1234-core Example GPU) ""(46464 MiB, 46284 MiB free)")m = hw._DEVICE_LINE_RE.search(line)- assert m and int(m.group("total")) == 46464+ assert m and int(m.group(1)) == 46464diff --git a/website/docs/user-guide/local-models.md b/website/docs/user-guide/local-models.mdindex 7519399caad..5038a98845d 100644--- a/website/docs/user-guide/local-models.md+++ b/website/docs/user-guide/local-models.md@@ -179,6 +179,10 @@ Selecting a local model as your main model uses the standard**Linux:** Vulkan or CPU; the pinned release has no prebuilt CUDA archive.**macOS:** Metal or CPU. HIP/ROCm is an explicit choice on supported x64targets. Unsupported backend/target pairs fail before any download.+- `backend: auto` picks CUDA for NVIDIA, Vulkan for AMD and Intel GPUs, and+ CPU only when no GPU is found. Behind a Vulkan or HIP engine, a discrete+ card is sized from its own memory (system RAM is spill space); an integrated+ GPU shares system RAM and is sized from that.- A GPU with 8 GB+ of memory runs the small catalog models comfortably;16 GB+ runs the 27–35B models at high quality.- Model completeness is checked against the server's response, not catalog