The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(local-models): size a Windows integrated GPU from what Windows lets it allocate
emozilla7cc440395e1d
diff --git a/hermes_cli/local_runtime/hardware.py b/hermes_cli/local_runtime/hardware.pyindex 6023ad5cffd..49c7cfe2034 100644--- a/hermes_cli/local_runtime/hardware.py+++ b/hermes_cli/local_runtime/hardware.py@@ -51,6 +51,9 @@ _POOL_RAM_FRACTION = 0.75# cuDeviceGetAttribute enum: device is integrated with host memory._CU_DEVICE_ATTRIBUTE_INTEGRATED = 18+_NVIDIA_VENDOR_ID = 0x10DE+# Engines whose devices the ggml probe reports; the CPU, CUDA and Metal builds answer elsewhere.+_GPU_ENGINE_BACKENDS = ("vulkan", "hip")# One probe per process once a device answers (silicon doesn't change); a miss retries after this# long so a runtime installed mid-session gets picked up by the engine fallback.@@ -362,7 +365,7 @@ def _accelerator_device(*, fresh: bool = False) -> "dict | None":from hermes_cli.local_runtime.devices import probe_devicesengine = _configured_engine()- if engine is None or engine.backend not in ("vulkan", "hip"):+ if engine is None or engine.backend not in _GPU_ENGINE_BACKENDS:return Nonekey, now = str(engine.binary), time.monotonic()cached = _accelerator_cache.get(key)@@ -401,6 +404,39 @@ def _uma_budget(base: int, total: int, *, gpu_name: str = "",gpu_pci_id=gpu_pci_id, lazy_reads=lazy_reads)+def _gpu_engine_runs_the_model() -> bool:+ """Whether a Vulkan/HIP engine runs the model: the serving or installed engine, else the one+ setup would install for ``local_runtime.backend``. False when the engine can't be resolved."""+ with suppress(Exception):+ engine = _configured_engine()+ if engine is not None:+ return engine.backend in _GPU_ENGINE_BACKENDS+ from hermes_cli.config import load_config_readonly+ from hermes_cli.local_runtime.binaries import resolve_backend++ section = load_config_readonly().get("local_runtime") or {}+ return resolve_backend(section.get("backend") or "auto") in _GPU_ENGINE_BACKENDS+ return False+++def _windows_igpu_bytes(device: "dict | None") -> int | None:+ """What Windows lets the integrated GPU allocate (Task Manager's GPU memory), or None.++ The adapter is the one the engine named, else the only non-NVIDIA hardware adapter when a+ Vulkan/HIP engine will run the model; the CPU engine (chosen, or the only build for a Snapdragon)+ keeps the model in system RAM. Not the engine's own figure: ggml-vulkan sums every memory heap+ of an integrated GPU, host-visible ones included, so it can exceed what Windows grants.+ """+ from hermes_platform.host.gpu_adapters import windows_gpu_adapters++ hardware = [a for a in windows_gpu_adapters() if not a.software]+ named = [a for a in hardware if device is not None and a.description == device["description"]]+ candidates = named or [a for a in hardware if a.vendor_id != _NVIDIA_VENDOR_ID]+ if len(candidates) != 1 or (device is None and not _gpu_engine_runs_the_model()):+ return None+ return candidates[0].memory_bytes++def probe_budget(*, planning: bool = False) -> HardwareBudget:"""Construct the budget per the source rules above.@@ -445,10 +481,12 @@ def probe_budget(*, planning: bool = False) -> HardwareBudget: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. llama.cpp- # loads lazy tensors up front on an AMD/Intel integrated GPU, where reading them on demand- # halved prefill (#28160).- return _uma_budget(ram_total if planning else ram_avail, ram_total,+ # Integrated GPU, Metal, CPU, or no answer: budget from RAM as unified memory, capped at what+ # Windows lets an integrated GPU allocate (18 GB of 31.5 on an Arc B390). llama.cpp loads+ # lazy tensors up front on an AMD/Intel integrated GPU, where reading them on demand halved+ # prefill (#28160).+ pool = min(ram_total, _windows_igpu_bytes(device) or ram_total)+ return _uma_budget(pool if planning else min(pool, ram_avail), pool,lazy_reads=gpu_class() not in ("amd", "intel"))total, free, gpu_name, gpu_pci_id = vramdiff --git a/hermes_platform/host/gpu_adapters.py b/hermes_platform/host/gpu_adapters.pynew file mode 100644index 00000000000..78327f252b6--- /dev/null+++ b/hermes_platform/host/gpu_adapters.py@@ -0,0 +1,85 @@+"""Windows graphics adapters as DXGI reports them.++Task Manager's "GPU memory" for an adapter is DXGI's dedicated video memory plus shared system+memory, and that sum is what Windows lets the adapter allocate. An integrated GPU has almost no+dedicated memory, so its shared allowance is its real pool: an Intel Arc B390 on a 31.5 GB machine+gets 18 GB. Read through ctypes without environment-variable input or subprocesses.+"""++from __future__ import annotations++import ctypes+import functools+from contextlib import suppress+from ctypes import wintypes+from dataclasses import dataclass++_SOFTWARE_FLAG = 0x2 # DXGI_ADAPTER_FLAG_SOFTWARE (Microsoft Basic Render Driver)+_MAX_ADAPTERS = 16+# vtable slots: IUnknown::Release, IDXGIFactory1::EnumAdapters1, IDXGIAdapter1::GetDesc1.+_RELEASE, _ENUM_ADAPTERS1, _GET_DESC1 = 2, 12, 10+++@dataclass(frozen=True)+class Adapter:+ description: str+ vendor_id: int+ dedicated_bytes: int+ shared_bytes: int+ software: bool++ @property+ def memory_bytes(self) -> int:+ """What Windows lets this adapter allocate (Task Manager's GPU memory)."""+ return self.dedicated_bytes + self.shared_bytes+++class _Guid(ctypes.Structure):+ _fields_ = [("Data1", wintypes.DWORD), ("Data2", wintypes.WORD), ("Data3", wintypes.WORD),+ ("Data4", ctypes.c_ubyte * 8)]+++class _Luid(ctypes.Structure):+ _fields_ = [("LowPart", wintypes.DWORD), ("HighPart", wintypes.LONG)]+++class _AdapterDesc1(ctypes.Structure):+ _fields_ = [("Description", ctypes.c_wchar * 128), ("VendorId", wintypes.UINT),+ ("DeviceId", wintypes.UINT), ("SubSysId", wintypes.UINT), ("Revision", wintypes.UINT),+ ("DedicatedVideoMemory", ctypes.c_size_t), ("DedicatedSystemMemory", ctypes.c_size_t),+ ("SharedSystemMemory", ctypes.c_size_t), ("AdapterLuid", _Luid), ("Flags", wintypes.UINT)]+++_IID_DXGI_FACTORY1 = _Guid(0x770AAE78, 0xF26F, 0x4DBA, (ctypes.c_ubyte * 8)(0xA8, 0x29, 0x25, 0x3C, 0x83, 0xD1, 0xB3, 0x87))+++def _method(obj: ctypes.c_void_p, slot: int, *argtypes):+ vtable = ctypes.cast(obj, ctypes.POINTER(ctypes.POINTER(ctypes.c_void_p)))[0]+ return ctypes.WINFUNCTYPE(ctypes.c_long, ctypes.c_void_p, *argtypes)(vtable[slot])+++def windows_gpu_adapters() -> "tuple[Adapter, ...]":+ """Every adapter DXGI enumerates, in its order; empty off Windows or when DXGI can't answer."""+ with suppress(OSError, AttributeError):+ factory = ctypes.c_void_p()+ if ctypes.WinDLL("dxgi").CreateDXGIFactory1(ctypes.byref(_IID_DXGI_FACTORY1), ctypes.byref(factory)) != 0:+ return ()+ found: list[Adapter] = []+ try:+ enum = _method(factory, _ENUM_ADAPTERS1, wintypes.UINT, ctypes.POINTER(ctypes.c_void_p))+ for index in range(_MAX_ADAPTERS):+ adapter = ctypes.c_void_p()+ if enum(factory, index, ctypes.byref(adapter)) != 0: # DXGI_ERROR_NOT_FOUND ends the list+ break+ try:+ desc = _AdapterDesc1()+ if _method(adapter, _GET_DESC1, ctypes.POINTER(_AdapterDesc1))(adapter, ctypes.byref(desc)) == 0:+ found.append(Adapter(desc.Description, desc.VendorId, desc.DedicatedVideoMemory,+ desc.SharedSystemMemory, bool(desc.Flags & _SOFTWARE_FLAG)))+ finally:+ _method(adapter, _RELEASE)(adapter)+ finally:+ _method(factory, _RELEASE)(factory)+ return tuple(found)+ return ()diff --git a/tests/hermes_cli/test_local_windows_igpu_pool.py b/tests/hermes_cli/test_local_windows_igpu_pool.pynew file mode 100644index 00000000000..740b91ad709--- /dev/null+++ b/tests/hermes_cli/test_local_windows_igpu_pool.py@@ -0,0 +1,83 @@+"""An integrated GPU on Windows is budgeted from what Windows lets it allocate, never all of RAM.++Windows caps an integrated GPU's allocations at its GPU memory (Task Manager; dedicated plus+shared): 18 GB of 31.5 on an Intel Arc B390. Budgeting all of RAM there showed "31.5 GB GPU memory"+and recommended a 27B the GPU cannot hold. The cap holds only when a GPU engine runs the model.+"""++from __future__ import annotations++from pathlib import Path++import pytest++import hermes_cli.local_runtime.hardware as hw+from hermes_cli.local_runtime import binaries+from hermes_cli.local_runtime.binaries import Engine+from hermes_cli.local_runtime.catalog import CATALOG, select_variant+from hermes_cli.local_runtime.devices import GGML_DEVICE_IGPU+from hermes_platform.host import gpu_adapters+from hermes_platform.host.gpu_adapters import Adapter++GIB = 1 << 30+RAM = int(31.5 * GIB)+B390 = Adapter("Intel(R) Arc(TM) B390 GPU", 0x8086, 128 << 20, 18 * GIB - (128 << 20), software=False)+ADRENO = Adapter("Qualcomm(R) Adreno(TM) X1-85 GPU", 0x4D4F4351, 0, 15 * GIB, software=False)+SOFTWARE = Adapter("Microsoft Basic Render Driver", 0x1414, 0, 16 * GIB, software=True)+# ggml-vulkan sums every heap of an integrated GPU, so the engine reports more than Windows grants.+ENGINE_B390 = {"description": B390.description, "type": GGML_DEVICE_IGPU, "total": 34 * GIB, "free": 30 * GIB}+++def _machine(monkeypatch, adapters, device, *, installed="vulkan", planned="vulkan"):+ """``installed`` is the engine on disk (None before setup); ``planned`` is what setup installs."""+ monkeypatch.setattr(hw, "_nvidia_vram", lambda: None)+ monkeypatch.setattr(hw, "_device_pool_view", lambda: None)+ monkeypatch.setattr(hw, "_ram_bytes", lambda: (RAM, 20 * GIB))+ monkeypatch.setattr(hw, "_accelerator_device", lambda **_: device)+ monkeypatch.setattr(gpu_adapters, "windows_gpu_adapters", lambda: tuple(adapters))+ engine = None if installed is None else Engine(installed, "b11370", Path("llama-server"))+ monkeypatch.setattr(hw, "_configured_engine", lambda: engine)+ monkeypatch.setattr(binaries, "resolve_backend", lambda *_, **__: planned)++[email protected](("device", "installed"), [(ENGINE_B390, "vulkan"), (None, None)],+ ids=["engine-named", "before-the-engine"])+def test_an_integrated_gpu_gets_what_windows_lets_it_allocate(monkeypatch, device, installed):+ _machine(monkeypatch, [B390, SOFTWARE], device, installed=installed)++ capacity = hw.probe_budget(planning=True)+ live = hw.probe_budget(planning=False)++ assert capacity.uma and capacity.total_device_bytes == B390.memory_bytes+ assert live.usable_vram_bytes <= capacity.usable_vram_bytes+ qwen_27b = next(e for e in CATALOG if e.id == "qwen3.8-27b")+ assert select_variant(qwen_27b, capacity) is None+++def test_the_engine_named_adapter_wins_among_several(monkeypatch):+ discrete = Adapter("Intel(R) Arc(TM) A380 Graphics", 0x8086, 6 * GIB, 15 * GIB, software=False)++ _machine(monkeypatch, [discrete, B390, SOFTWARE], ENGINE_B390)+ assert hw.probe_budget(planning=True).total_device_bytes == B390.memory_bytes++ _machine(monkeypatch, [discrete, B390, SOFTWARE], None) # ambiguous without the engine's answer+ assert hw.probe_budget(planning=True).total_device_bytes == RAM++[email protected](("adapter", "installed", "planned"), [+ (B390, "cpu", "cpu"), # local_runtime.backend: cpu+ (ADRENO, None, "cpu"), # a Snapdragon: setup installs the CPU build+], ids=["cpu-engine-installed", "cpu-engine-planned"])+def test_a_cpu_engine_keeps_the_ram_budget(monkeypatch, adapter, installed, planned):+ _machine(monkeypatch, [adapter, SOFTWARE], None, installed=installed, planned=planned)+ assert hw.probe_budget(planning=True).total_device_bytes == RAM++[email protected]("adapters", [+ [SOFTWARE], # no GPU: CPU inference+ [Adapter("AMD Radeon(TM) 8060S Graphics", 0x1002, 96 * GIB, 16 * GIB, software=False), SOFTWARE],+ [], # DXGI did not answer+], ids=["cpu-only", "allowance-above-ram", "no-dxgi"])+def test_the_pool_never_grows_past_ram(monkeypatch, adapters):+ _machine(monkeypatch, adapters, None)+ assert hw.probe_budget(planning=True).total_device_bytes == RAMdiff --git a/tests/hermes_cli/test_unified_pool_quirk.py b/tests/hermes_cli/test_unified_pool_quirk.pyindex 7f8ba53146b..545d079bf57 100644--- a/tests/hermes_cli/test_unified_pool_quirk.py+++ b/tests/hermes_cli/test_unified_pool_quirk.py@@ -19,6 +19,7 @@ from pathlib import Pathimport pytestimport hermes_cli.local_runtime.hardware as hw+from hermes_platform.host import gpu_adaptersGIB = 1 << 30@@ -175,6 +176,7 @@ def test_engine_fallback_without_smi_stays_conservative(monkeypatch):monkeypatch.setattr(hw, "_nvidia_vram", lambda: None)monkeypatch.setattr(hw, "_ram_bytes", lambda: (UMA_RAM, 32 * GIB))monkeypatch.setattr(hw, "_device_pool_view", lambda: (UMA_POOL, None))+ monkeypatch.setattr(gpu_adapters, "windows_gpu_adapters", tuple)b = hw.probe_budget(planning=True)assert b.uma is Trueassert b.total_device_bytes == UMA_RAM # RAM path, not the pool@@ -205,6 +207,7 @@ def test_vulkan_device_type_decides_discrete_vs_unified(monkeypatch, tmp_path, dmonkeypatch.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(gpu_adapters, "windows_gpu_adapters", tuple)b = hw.probe_budget(planning=True)diff --git a/tests/hermes_platform/test_gpu_adapters.py b/tests/hermes_platform/test_gpu_adapters.pynew file mode 100644index 00000000000..278d14db01a--- /dev/null+++ b/tests/hermes_platform/test_gpu_adapters.py@@ -0,0 +1,20 @@+"""DXGI's adapter list, read live on Windows."""++from __future__ import annotations++import pytest++from hermes_platform.host.gpu_adapters import windows_gpu_adapters++[email protected]("windows")+def test_dxgi_lists_this_machines_adapters() -> None:+ found = windows_gpu_adapters()+ assert found, "DXGI lists at least Microsoft's software adapter"+ assert any(a.software for a in found)+ assert all(a.shared_bytes > 0 and a.dedicated_bytes >= 0 for a in found)++[email protected]("not windows")+def test_dxgi_answers_empty_off_windows() -> None:+ assert windows_gpu_adapters() == ()diff --git a/tests/hermes_platform/test_import_hygiene.py b/tests/hermes_platform/test_import_hygiene.pyindex 3cbf732f71f..7c145598626 100644--- a/tests/hermes_platform/test_import_hygiene.py+++ b/tests/hermes_platform/test_import_hygiene.py@@ -12,6 +12,7 @@ def test_platform_modules_only_import_stdlib_and_hermes_platform() -> None:import sysbefore = set(sys.modules)import hermes_platform.host.facts+import hermes_platform.host.gpu_adaptersimport hermes_platform.host.runtimeimport hermes_platform.host.productsimport hermes_platform.declaration