The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(local-runtime): unified-pool vendor quirk — budget Spark-class NVIDIA from the allocator, not the WDDM carve-out
emozilla4e881a85b622
diff --git a/hermes_cli/local_runtime/hardware.py b/hermes_cli/local_runtime/hardware.pyindex 90d5ec149c1..44fcc93556a 100644--- a/hermes_cli/local_runtime/hardware.py+++ b/hermes_cli/local_runtime/hardware.py@@ -5,12 +5,24 @@ honest within rounding); unified-memory devices must budget from OS freephysical memory minus headroom — their device queries have been observedoff by 3x in both directions. The probe classifies the device andconstructs the right HardwareBudget for the estimator.++Vendor probe quirk (RTX-Spark-class WDDM carve-out): on unified-memory+NVIDIA devices under Windows, nvidia-smi answers from the legacy+dedicated-VRAM carve-out (measured 16 GiB reported vs a 45.4 GiB pool the+allocator addresses uniformly at full bandwidth). The CUDA driver API is+the tiebreaker: cuDeviceGetAttribute(INTEGRATED) is the vendor's own+declaration and always wins — 1 budgets unified, 0 stays discrete no+matter what any other number says. Only when the driver API is+unreachable does the engine's --list-devices view apply, and then only+behind two independent conditions no discrete card can meet."""from __future__ import annotationsimport logging+import reimport subprocess+import timefrom hermes_cli.local_runtime.estimator import HardwareBudget@@ -21,11 +33,36 @@ _GIB = 1 << 30# 1 GiB is regressive on 8 GB cards and generous on 24 GB ones._MARGIN_FLOOR = 512 << 20_MARGIN_FRACTION = 0.07-# UMA headroom: on unified-memory machines (Apple Silicon) the model shares-# physical memory with the OS and every app, so budget from RAM minus this-# fraction.+# UMA headroom: on unified-memory machines (Apple Silicon, Spark-class+# NVIDIA) the model shares physical memory with the OS and every app, so+# budget from RAM minus this fraction._UMA_HEADROOM_FRACTION = 0.20+# Engine-fallback gates for the unified-pool quirk — BOTH must hold, and+# no discrete card can meet either: (1) the allocator's pool exceeds the+# smi report by well past rounding/ECC slack (discrete cards agree within+# ~2%; measured Spark disagreement is 2.85x), and (2) the pool is+# system-RAM-sized — a workstation card in a RAM-matched box fails (1)+# because its smi and allocator AGREE, and a big discrete card in a+# bigger box fails (2). The driver's INTEGRATED attribute, when+# readable, bypasses both gates in whichever direction it points.+_POOL_DISAGREEMENT_FACTOR = 1.5+_POOL_RAM_FRACTION = 0.75++# cuDeviceGetAttribute enum: device is integrated with host memory.+_CU_DEVICE_ATTRIBUTE_INTEGRATED = 18++# 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.+_POOL_NEGATIVE_TTL_S = 60.0+_pool_probe_cache: tuple[float, "tuple[int, bool | None] | None"] | None = None++# ' CUDA0: NVIDIA RTX Spark N1X (5120-core Blackwell RTX GPU) (46464 MiB, 46284 MiB free)'+# — greedy .* pins the LAST parenthesized group, so device names carrying+# their own parentheses parse correctly.+_DEVICE_LINE_RE = re.compile(r"CUDA\d+:.*\((\d+)\s*MiB,\s*\d+\s*MiB free\)\s*$")+def _ram_bytes() -> tuple[int, int]:"""(total, available) physical memory, cross-platform stdlib."""@@ -82,6 +119,115 @@ def _nvidia_vram() -> tuple[int, int] | None:return None+def _cuda_driver_pool() -> "tuple[int, bool | None] | None":+ """(allocator_total_bytes, integrated_or_None) from the CUDA driver+ API, or None when unreachable. ctypes against the driver's own DLL/SO+ — no toolkit, no subprocess, ~ms. INTEGRATED is the vendor's own+ unified-memory declaration; total is the pool the allocator will+ actually hand out (observed 45.4 GiB where nvidia-smi says 16 on+ Spark-class firmware)."""+ import ctypes++ for name in ("nvcuda.dll", "libcuda.so.1", "libcuda.so"):+ try:+ cuda = ctypes.CDLL(name)+ break+ except OSError:+ continue+ else:+ return None+ try:+ if cuda.cuInit(0) != 0:+ return None+ dev = ctypes.c_int()+ if cuda.cuDeviceGet(ctypes.byref(dev), 0) != 0:+ return None+ total = ctypes.c_size_t()+ getter = getattr(cuda, "cuDeviceTotalMem_v2", None) or cuda.cuDeviceTotalMem+ if getter(ctypes.byref(total), dev) != 0 or total.value <= 0:+ return None+ integrated: bool | None = None+ attr = ctypes.c_int()+ if cuda.cuDeviceGetAttribute(+ ctypes.byref(attr), _CU_DEVICE_ATTRIBUTE_INTEGRATED, dev) == 0:+ integrated = bool(attr.value)+ return total.value, integrated+ except (OSError, AttributeError):+ return None+++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 truth source when the driver+ API is unreachable: asks the exact binary that will do the+ allocating. Carries no integrated verdict — callers must gate it."""+ try:+ from hermes_cli.local_runtime.binaries import (+ installed_tags,+ runtimes_root,+ server_binary,+ )++ tags = installed_tags()+ if not tags:+ return None+ tag_dir = runtimes_root() / tags[0]+ backend_dirs = [d for d in tag_dir.iterdir() if d.is_dir()]+ if not backend_dirs:+ return None+ exe = server_binary(backend_dirs[0])+ out = subprocess.run([str(exe), "--list-devices"], capture_output=True,+ text=True, timeout=30, cwd=str(exe.parent))+ if out.returncode != 0:+ return None+ for line in (out.stdout + out.stderr).splitlines():+ m = _DEVICE_LINE_RE.search(line)+ if m:+ return int(m.group(1)) << 20, None+ return None+ except Exception: # noqa: BLE001 — a probe miss must never block budgeting+ return None+++def _device_pool_view() -> "tuple[int, bool | None] | None":+ """Best available allocator-side view, cached: a hit is permanent for+ the process, a miss retries after a short TTL (the engine binary can+ appear mid-session via a pane install)."""+ global _pool_probe_cache+ now = time.monotonic()+ if _pool_probe_cache is not None:+ stamp, view = _pool_probe_cache+ if view is not None or now - stamp < _POOL_NEGATIVE_TTL_S:+ return view+ view = _cuda_driver_pool() or _engine_device_pool()+ _pool_probe_cache = (now, view)+ return view+++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 WDDM carve-out, else None (trust nvidia-smi as ever).++ The driver's INTEGRATED attribute decides when readable — in BOTH+ directions (0 pins discrete even if the numbers look weird; a driver+ that declares integrated is believed even at modest pool sizes). Only+ an attribute-less view (engine fallback) needs the two numeric gates;+ both must hold and no discrete card meets either.+ """+ view = _device_pool_view()+ if view is None:+ return None+ pool, integrated = view+ if integrated is False:+ return None+ if integrated is True:+ return pool+ if (smi_total > 0 and pool >= int(smi_total * _POOL_DISAGREEMENT_FACTOR)+ and ram_total > 0 and pool >= int(ram_total * _POOL_RAM_FRACTION)):+ return pool+ return None++def probe_budget(*, planning: bool = False) -> HardwareBudget:"""Construct the budget per the source rules above.@@ -111,6 +257,28 @@ def probe_budget(*, planning: bool = False) -> HardwareBudget:ram_available_bytes=0, uma=True)total, free = vram++ # Spark-class quirk: nvidia-smi answers from the WDDM carve-out while+ # the allocator addresses the whole unified pool at full bandwidth+ # (measured flat ~200 GB/s effective 8 GiB past the carve-out).+ # Budget like Apple Silicon: the pool minus headroom IS the budget,+ # ram_available=0 so host memory never double-counts as spill room.+ unified = _unified_pool_bytes(total, ram_total)+ if unified is not None:+ logger.info(+ "unified-memory NVIDIA device: allocator pool %.1f GiB "+ "(nvidia-smi carve-out %.1f GiB); budgeting from the pool",+ unified / _GIB, total / _GIB)+ # The allocator's pool can slightly exceed what the OS will really+ # give it (firmware reserve); budget from the smaller of the two+ # views, live-clamped by OS availability outside planning.+ pool_total = min(unified, ram_total) if ram_total else unified+ base = pool_total if planning else min(pool_total, ram_avail)+ usable = max(0, int(base * (1 - _UMA_HEADROOM_FRACTION)))+ return HardwareBudget(usable_vram_bytes=usable,+ total_device_bytes=pool_total,+ ram_available_bytes=0, uma=True)+margin = max(_MARGIN_FLOOR, int(total * _MARGIN_FRACTION))base = total if planning else freereturn HardwareBudget(usable_vram_bytes=max(0, base - margin),diff --git a/tests/hermes_cli/test_unified_pool_quirk.py b/tests/hermes_cli/test_unified_pool_quirk.pynew file mode 100644index 00000000000..bfe4338414f--- /dev/null+++ b/tests/hermes_cli/test_unified_pool_quirk.py@@ -0,0 +1,185 @@+"""The unified-pool vendor quirk must never misclassify a discrete card.++Spark-class devices (RTX Spark N1X, measured): nvidia-smi answers from a+16 GiB WDDM carve-out while the CUDA allocator addresses the whole+45.4 GiB unified pool at full bandwidth — decode stays ~200 GB/s+effective 8 GiB past the carve-out. Budgeting from smi there produces+false "larger than your GPU memory" rows and -ot CPU pinning measured+2.3x SLOWER than letting the allocator place everything.++The other direction is the regression this file guards: a workstation+card must never be budgeted as UMA. The driver's INTEGRATED attribute+decides when readable (both directions); the attribute-less engine+fallback needs two independent numeric gates, each alone unmeetable by+any discrete card."""++from __future__ import annotations++import hermes_cli.local_runtime.hardware as hw++GIB = 1 << 30++# Measured Spark N1X shape.+SPARK_SMI_TOTAL = 16320 << 20+SPARK_POOL = 46464 << 20+SPARK_RAM = 48 * GIB+++def _no_cache(monkeypatch):+ monkeypatch.setattr(hw, "_pool_probe_cache", None)+++# ── _unified_pool_bytes: the classification gate ─────────────+++def test_integrated_attribute_wins_positive(monkeypatch):+ """Driver says integrated=True -> unified, no numeric gates needed."""+ monkeypatch.setattr(hw, "_device_pool_view", lambda: (SPARK_POOL, True))+ assert hw._unified_pool_bytes(SPARK_SMI_TOTAL, SPARK_RAM) == SPARK_POOL+++def test_integrated_attribute_wins_negative(monkeypatch):+ """Driver says integrated=False -> discrete, even when the numbers+ would pass both fallback gates (attribute outranks arithmetic)."""+ monkeypatch.setattr(hw, "_device_pool_view", lambda: (SPARK_POOL, False))+ assert hw._unified_pool_bytes(SPARK_SMI_TOTAL, SPARK_RAM) is None+++def test_engine_fallback_spark_shape_passes(monkeypatch):+ """Attribute unreadable (engine fallback): the measured Spark shape+ passes both gates — 2.85x disagreement, pool ~= RAM."""+ monkeypatch.setattr(hw, "_device_pool_view", lambda: (SPARK_POOL, None))+ assert hw._unified_pool_bytes(SPARK_SMI_TOTAL, SPARK_RAM) == SPARK_POOL+++def test_discrete_card_agreeing_within_rounding_stays_discrete(monkeypatch):+ """A healthy discrete card: allocator and smi agree within rounding.+ Fails the disagreement gate regardless of box RAM."""+ smi = 24 * GIB+ monkeypatch.setattr(hw, "_device_pool_view",+ lambda: (smi + (200 << 20), None))+ assert hw._unified_pool_bytes(smi, 24 * GIB) is None+ assert hw._unified_pool_bytes(smi, 256 * GIB) is None+++def test_ram_matched_workstation_card_stays_discrete(monkeypatch):+ """THE case commit 6f5ccf16d7 feared: a 48 GB card in a 48 GB box.+ smi and the allocator AGREE (both say 48), so the disagreement gate+ fails even though pool == RAM would pass the size gate."""+ monkeypatch.setattr(hw, "_device_pool_view", lambda: (48 * GIB, None))+ assert hw._unified_pool_bytes(48 * GIB, 48 * GIB) is None+++def test_pool_smaller_than_ram_fraction_stays_discrete(monkeypatch):+ """Disagreement without the RAM-sized-pool signature stays discrete:+ a hypothetical card whose allocator over-reports 2x in a huge-RAM box+ is a driver bug to distrust, not a unified pool."""+ monkeypatch.setattr(hw, "_device_pool_view", lambda: (32 * GIB, None))+ assert hw._unified_pool_bytes(16 * GIB, 128 * GIB) is None+++def test_no_probe_available_stays_discrete(monkeypatch):+ """No driver API, no engine binary -> exactly today's behavior."""+ monkeypatch.setattr(hw, "_device_pool_view", lambda: None)+ assert hw._unified_pool_bytes(SPARK_SMI_TOTAL, SPARK_RAM) is None+++# ── probe_budget wiring ──────────────────────────────────────+++def _spark_machine(monkeypatch, *, view):+ _no_cache(monkeypatch)+ monkeypatch.setattr(hw, "_nvidia_vram",+ lambda: (SPARK_SMI_TOTAL, 14848 << 20))+ monkeypatch.setattr(hw, "_ram_bytes",+ lambda: (SPARK_RAM, 32 * GIB))+ monkeypatch.setattr(hw, "_device_pool_view", lambda: view)+++def test_budget_unified_pool_planning(monkeypatch):+ """Planning budget on Spark: pool (clamped to OS RAM) minus headroom,+ uma=True, ram_available=0 — host memory must not double-count as+ spill room on top of a pool that already IS host memory."""+ _spark_machine(monkeypatch, view=(SPARK_POOL, True))+ b = hw.probe_budget(planning=True)+ assert b.uma is True+ assert b.ram_available_bytes == 0+ pool_total = min(SPARK_POOL, SPARK_RAM)+ assert b.total_device_bytes == pool_total+ assert b.usable_vram_bytes == int(pool_total * (1 - hw._UMA_HEADROOM_FRACTION))+ # The whole point: the budget must dwarf the 16 GiB carve-out.+ assert b.usable_vram_bytes > 2 * SPARK_SMI_TOTAL+++def test_budget_unified_pool_live_clamps_to_available(monkeypatch):+ """Live budget budgets from what the OS can actually still give."""+ _spark_machine(monkeypatch, view=(SPARK_POOL, True))+ b = hw.probe_budget(planning=False)+ assert b.uma is True+ assert b.usable_vram_bytes == int(32 * GIB * (1 - hw._UMA_HEADROOM_FRACTION))+++def test_budget_discrete_unchanged_when_probe_says_discrete(monkeypatch):+ """integrated=False keeps the existing discrete path bit-for-bit."""+ _spark_machine(monkeypatch, view=(SPARK_POOL, False))+ b = hw.probe_budget(planning=True)+ assert b.uma is False+ assert b.total_device_bytes == SPARK_SMI_TOTAL+ margin = max(hw._MARGIN_FLOOR, int(SPARK_SMI_TOTAL * hw._MARGIN_FRACTION))+ assert b.usable_vram_bytes == SPARK_SMI_TOTAL - margin+ assert b.ram_available_bytes == SPARK_RAM+++def test_budget_discrete_unchanged_when_probe_unavailable(monkeypatch):+ _spark_machine(monkeypatch, view=None)+ b = hw.probe_budget(planning=True)+ assert b.uma is False+ assert b.ram_available_bytes == SPARK_RAM+++# ── probe cache ──────────────────────────────────────────────+++def test_pool_probe_hit_is_cached_for_process(monkeypatch):+ _no_cache(monkeypatch)+ calls = []++ def probe():+ calls.append(1)+ return (SPARK_POOL, True)++ monkeypatch.setattr(hw, "_cuda_driver_pool", probe)+ monkeypatch.setattr(hw, "_engine_device_pool", lambda: None)+ assert hw._device_pool_view() == (SPARK_POOL, True)+ assert hw._device_pool_view() == (SPARK_POOL, True)+ assert len(calls) == 1+++def test_pool_probe_miss_retries_after_ttl(monkeypatch):+ """A miss must not be permanent: the engine binary can appear+ mid-session via the pane's runtime install."""+ _no_cache(monkeypatch)+ monkeypatch.setattr(hw, "_cuda_driver_pool", lambda: None)+ answers = [None, (SPARK_POOL, None)]+ monkeypatch.setattr(hw, "_engine_device_pool", lambda: answers.pop(0))++ now = [1000.0]+ monkeypatch.setattr(hw.time, "monotonic", lambda: now[0])+ assert hw._device_pool_view() is None+ now[0] += 1.0 # inside TTL: cached miss, no re-probe+ assert hw._device_pool_view() is None+ now[0] += hw._POOL_NEGATIVE_TTL_S + 1.0+ assert hw._device_pool_view() == (SPARK_POOL, None)+ assert not answers+++# ── device-line parsing (engine fallback) ────────────────────+++def test_device_line_regex_handles_parenthesized_names():+ """Real Spark line: the device name itself contains parentheses —+ the LAST group must win."""+ line = (" CUDA0: NVIDIA RTX Spark N1X (5120-core Blackwell RTX GPU) "+ "(46464 MiB, 46284 MiB free)")+ m = hw._DEVICE_LINE_RE.search(line)+ assert m and int(m.group(1)) == 46464