The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(local-models): calibrate Spark recommendations with stable GPU names
emozilla4fd0da3b828b
diff --git a/hermes_cli/local_runtime/catalog.py b/hermes_cli/local_runtime/catalog.pyindex 9650e3937a8..cc586e758c8 100644--- a/hermes_cli/local_runtime/catalog.py+++ b/hermes_cli/local_runtime/catalog.py@@ -175,10 +175,27 @@ _HOST_BANDWIDTH_GB_S = 80.0 # spilled weights stream over host DRAM# compress floor, which marks unusable, not unpleasant.PLEASANT_FLOOR_TOK_S = 20.0+# Shipped short-context reference rates, not benchmarks run during recommendation.+# Windows N1X / b10964 CUDA: MTP2 measured 21.76–21.96 tok/s over four 512-token+# prose probes; a four-slot smoke measured 21.89. At 32K input the reference was+# 18.82 tok/s: this is a baseline estimate, not a context-independent guarantee.+# Unmatched hardware, backend, quant or draft depth retains the bandwidth estimate.+_MEASURED_DECODE_TOK_S = {+ ("win32", "cuda", "NVIDIA RTX Spark N1X",+ "qwen3.8-27b", "UD-Q4_K_M", 2): 21.9,+}+def predicted_decode_tok_s(entry: CatalogEntry, variant: QuantVariant, budget: HardwareBudget, *,- spilled: bool = False) -> float:- """Memory-bound decode prediction for ordering and floor-gating."""+ spilled: bool = False, backend: str = "auto") -> float:+ """Shipped measured baseline where matched, otherwise the memory-bound estimate."""+ # A named NVIDIA device uses CUDA under the normal automatic backend policy.+ effective_backend = "cuda" if backend == "auto" and budget.gpu_name else backend+ # Drivers may append a parenthesized description to the stable device name.+ gpu_name = budget.gpu_name.partition(" (")[0]+ key = (budget.platform, effective_backend, gpu_name, entry.id, variant.quant, entry.mtp_draft_depth)+ if budget.uma and entry.mtp and not spilled and (measured := _MEASURED_DECODE_TOK_S.get(key)) is not None:+ return measuredbandwidth = (_HOST_BANDWIDTH_GB_S if spilledelse _UMA_BANDWIDTH_GB_S if budget.umaelse _DISCRETE_BANDWIDTH_GB_S)@@ -187,7 +204,7 @@ def predicted_decode_tok_s(entry: CatalogEntry, variant: QuantVariant, budget: Hdef recommended_entry(budget: HardwareBudget,- entries: "tuple[CatalogEntry, ...] | None" = None+ entries: "tuple[CatalogEntry, ...] | None" = None, *, backend: str = "auto") -> "tuple[CatalogEntry, str] | None":"""The catalog's default pick for THIS machine, with its reason key.@@ -203,7 +220,7 @@ def recommended_entry(budget: HardwareBudget,return Nonedef speed(t, spilled=False):- return predicted_decode_tok_s(t[0], t[1].variant, budget, spilled=spilled)+ return predicted_decode_tok_s(t[0], t[1].variant, budget, spilled=spilled, backend=backend)resident = [(e, c) for e, c in fitting if c.zero_spill]pleasant = [t for t in resident if speed(t) >= PLEASANT_FLOOR_TOK_S]diff --git a/hermes_cli/local_runtime/estimator.py b/hermes_cli/local_runtime/estimator.pyindex e7418639fd7..d61298bc711 100644--- a/hermes_cli/local_runtime/estimator.py+++ b/hermes_cli/local_runtime/estimator.py@@ -71,6 +71,8 @@ class HardwareBudget:total_device_bytes: intram_available_bytes: intuma: bool = False+ gpu_name: str = "" # detected identity for shipped performance estimates+ platform: str = "" # sys.platform of the machine being priceddef profile_from_gguf(header: GGUFHeader) -> ModelProfile:diff --git a/hermes_cli/local_runtime/hardware.py b/hermes_cli/local_runtime/hardware.pyindex 3252e97744e..29072a60c2a 100644--- a/hermes_cli/local_runtime/hardware.py+++ b/hermes_cli/local_runtime/hardware.py@@ -9,6 +9,7 @@ stripped PATH — gateway and service sessions don't inherit the interactive envfrom __future__ import annotationsfrom contextlib import suppress+import csvimport loggingimport osimport re@@ -194,20 +195,20 @@ def _nvidia_smi_path() -> str | None:return found-def _nvidia_vram() -> tuple[int, int] | None:- """(total, free) MiB->bytes from nvidia-smi, or None."""+def _nvidia_vram() -> tuple[int, int, str] | None:+ """(total bytes, free bytes, name) from the same nvidia-smi query, or None."""exe = _nvidia_smi_path()if exe is None:return Nonewith suppress(OSError, ValueError, subprocess.TimeoutExpired):out = subprocess.run(- [exe, "--query-gpu=memory.total,memory.free",+ [exe, "--query-gpu=memory.total,memory.free,name","--format=csv,noheader,nounits"],capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=10)if out.returncode != 0 or not out.stdout.strip():return None- total_mib, free_mib = (int(x) for x in out.stdout.strip().splitlines()[0].split(","))- return total_mib << 20, free_mib << 20+ total_mib, free_mib, name = next(csv.reader(out.stdout.strip().splitlines()))+ return int(total_mib) << 20, int(free_mib) << 20, name.strip()return None@@ -300,10 +301,10 @@ def _unified_pool_bytes(smi_total: int, ram_total: int) -> int | None:return None-def _uma_budget(base: int, total: int) -> HardwareBudget:+def _uma_budget(base: int, total: int, *, gpu_name: str = "") -> HardwareBudget:usable = max(0, int(base * (1 - _UMA_HEADROOM_FRACTION)))return HardwareBudget(usable_vram_bytes=usable, total_device_bytes=total,- ram_available_bytes=0, uma=True)+ ram_available_bytes=0, uma=True, gpu_name=gpu_name, platform=sys.platform)def probe_budget(*, planning: bool = False) -> HardwareBudget:@@ -337,16 +338,16 @@ def probe_budget(*, planning: bool = False) -> HardwareBudget:# measured soft cliff: decode collapses ~3.5x when concurrent demand hits it).live = (vram[1] + ram_avail) if vram else ram_availbase = min(unified, live)- return _uma_budget(base, unified)+ return _uma_budget(base, unified, gpu_name=vram[2] if vram else "")if vram is None:# No NVIDIA device visible: Metal/Vulkan/CPU paths budget from RAM as UMA (Apple# Silicon) — conservative for discrete AMD until a vendor probe lands.return _uma_budget(ram_total if planning else ram_avail, ram_total)- total, free = vram+ total, free, gpu_name = vrammargin = max(_MARGIN_FLOOR, int(total * _MARGIN_FRACTION))return HardwareBudget(usable_vram_bytes=max(0, (total if planning else free) - margin),total_device_bytes=total,ram_available_bytes=ram_total if planning else ram_avail,- uma=False)+ uma=False, gpu_name=gpu_name, platform=sys.platform)diff --git a/hermes_cli/web_routers/local_models.py b/hermes_cli/web_routers/local_models.pyindex b2ac709d4f6..344bd38e705 100644--- a/hermes_cli/web_routers/local_models.py+++ b/hermes_cli/web_routers/local_models.py@@ -623,7 +623,8 @@ def local_models_catalog():budget = hardware.probe_budget(planning=True)# The reason key ships with the row so the Recommended badge's tooltip is the branch that actually# fired, not a re-derivation that can drift.- recommended, recommended_reason = catalog.recommended_entry(budget, _eligible_entries()) or (None, None)+ recommended, recommended_reason = catalog.recommended_entry(+ budget, _eligible_entries(), backend=_runtime_section().get("backend", "auto")) or (None, None)recommended_id = recommended.id if recommended is not None else None# Completeness-checked staging (split parts all present) — same answer the picker and router see, so a# mid-download model never reads as downloaded.@@ -756,7 +757,8 @@ def _quickstart_target(body: QuickstartBody, budget):if body.model_id:candidates = [_entry_or_404(body.model_id)]else:- picked = catalog.recommended_entry(budget, _eligible_entries())+ picked = catalog.recommended_entry(+ budget, _eligible_entries(), backend=_runtime_section().get("backend", "auto"))if picked is None:raise HTTPException(status_code=409,diff --git a/tests/hermes_cli/test_local_models_routes.py b/tests/hermes_cli/test_local_models_routes.pyindex 278e29846b6..1e7d4626957 100644--- a/tests/hermes_cli/test_local_models_routes.py+++ b/tests/hermes_cli/test_local_models_routes.py@@ -170,6 +170,38 @@ def test_catalog_prices_every_entry_for_this_machine(client):assert isinstance(row["downloaded"], bool)[email protected]("backend, expected", [+ ("auto", "qwen3.8-27b"), ("cuda", "qwen3.8-27b"),+ ("vulkan", "qwen3.6-35b-a3b"), ("cpu", "qwen3.6-35b-a3b"),+])+def test_calibrated_catalog_and_quickstart_respect_backend(client, monkeypatch, backend, expected):+ from hermes_cli.local_runtime import binaries, bootstrap, catalog, hardware+ from hermes_cli.local_runtime.estimator import HardwareBudget+ from hermes_cli.web_routers import local_models++ budget = HardwareBudget(int(48 * (1 << 30) * .8), 48 << 30, 0, uma=True,+ gpu_name="NVIDIA RTX Spark N1X (5120-core Blackwell RTX GPU)", platform="win32")+ monkeypatch.setattr(hardware, "probe_budget", lambda **kw: budget)+ monkeypatch.setattr(catalog, "refresh_catalog_soon", lambda: None)+ monkeypatch.setattr(bootstrap, "staged_model_ids", lambda: set())+ monkeypatch.setattr(binaries, "installed_engine",+ lambda *args, **kwargs: binaries.Engine("cuda", "b10964", Path("unused")))+ monkeypatch.setattr(local_models, "_load_config", lambda: {"local_runtime": {"backend": backend}})++ def no_probe(*args, **kwargs):+ raise AssertionError("recommendation must not launch a model or run another hardware probe")++ monkeypatch.setattr(bootstrap, "_detect_gpu_vendor", no_probe)+ monkeypatch.setattr(bootstrap, "ensure_local_runtime", no_probe)+ response = client.get("/api/local-models/catalog")+ assert response.status_code == 200+ chosen = [row["id"] for row in response.json()["models"] if row["recommended"]]+ assert chosen == [expected]+ assert local_models._quickstart_target(local_models.QuickstartBody(), budget)[0].id == expected+ explicit = local_models.QuickstartBody(model_id="qwen3.8-27b")+ assert local_models._quickstart_target(explicit, budget)[0].id == "qwen3.8-27b"++def test_catalog_never_hides_unaffordable_models(client, monkeypatch):"""Unaffordable entries stay visible with a plain reason — hiding themis how users conclude the feature is broken."""diff --git a/tests/hermes_cli/test_local_recommendation.py b/tests/hermes_cli/test_local_recommendation.pyindex 9781f3b29ae..8944600c00b 100644--- a/tests/hermes_cli/test_local_recommendation.py+++ b/tests/hermes_cli/test_local_recommendation.py@@ -118,6 +118,67 @@ def test_recommendation_decision_table(size_gb, kind, expected, expected_reason)assert (picked[0].id, picked[1]) == (expected, expected_reason)[email protected]("gpu_name", [+ "NVIDIA RTX Spark N1X",+ "NVIDIA RTX Spark N1X (5120-core Blackwell RTX GPU)",+ "NVIDIA RTX Spark N1X (updated device description)",+])[email protected]("capacity", [24, 48, 256])+def test_measured_n1x_profile_changes_speed_eligibility_not_fit_or_quality(monkeypatch, capacity, gpu_name):+ import subprocess+ import urllib.request++ def no_io(*args, **kwargs):+ raise AssertionError("calibration must use shipped data, not a runtime benchmark")++ monkeypatch.setattr(subprocess, "run", no_io)+ monkeypatch.setattr(urllib.request, "urlopen", no_io)+ budget = _unified(capacity)+ budget.gpu_name = gpu_name+ budget.platform = "win32"+ entry = next(e for e in CATALOG if e.id == "qwen3.8-27b")+ assert predicted_decode_tok_s(entry, entry.variants[0], budget) >= PLEASANT_FLOOR_TOK_S+ picked = recommended_entry(budget)+ expected = {24: None, 48: "qwen3.8-27b", 256: "qwen3.8-flash-next"}[capacity]+ assert (picked[0].id if picked else None) == expected++[email protected]("budget_changes, entry_changes, quant, backend, spilled", [+ ({"gpu_name": ""}, {}, "UD-Q4_K_M", "cuda", False),+ ({"gpu_name": "NVIDIA Other Device"}, {}, "UD-Q4_K_M", "cuda", False),+ ({"gpu_name": "NVIDIA RTX Spark N1X2"}, {}, "UD-Q4_K_M", "cuda", False),+ ({"gpu_name": "NVIDIA RTX Spark N1X Pro"}, {}, "UD-Q4_K_M", "cuda", False),+ ({"platform": "linux"}, {}, "UD-Q4_K_M", "cuda", False),+ ({"uma": False}, {}, "UD-Q4_K_M", "cuda", False),+ ({}, {}, "UD-Q4_K_M", "vulkan", False),+ ({}, {}, "UD-Q4_K_M", "cpu", False),+ ({}, {"mtp": False}, "UD-Q4_K_M", "cuda", False),+ ({}, {"mtp_draft_depth": 3}, "UD-Q4_K_M", "cuda", False),+ ({}, {}, "Q8_0", "cuda", False),+ ({}, {}, "UD-Q4_K_M", "cuda", True),+])+def test_unmatched_or_spilled_profiles_keep_the_existing_estimate(+ monkeypatch, budget_changes, entry_changes, quant, backend, spilled):+ from dataclasses import replace+ import subprocess+ import urllib.request++ budget = replace(_unified(48), gpu_name="NVIDIA RTX Spark N1X (5120-core Blackwell RTX GPU)",+ platform="win32")+ budget = replace(budget, **budget_changes)+ entry = replace(next(e for e in CATALOG if e.id == "qwen3.8-27b"), **entry_changes)+ variant = replace(entry.variants[0], quant=quant)++ def no_io(*args, **kwargs):+ raise AssertionError("speed selection must be an offline lookup and arithmetic")++ monkeypatch.setattr(subprocess, "run", no_io)+ monkeypatch.setattr(urllib.request, "urlopen", no_io)+ fallback = predicted_decode_tok_s(entry, variant, replace(budget, gpu_name=""),+ spilled=spilled, backend=backend)+ assert predicted_decode_tok_s(entry, variant, budget, spilled=spilled, backend=backend) == fallback++# ── invariants behind the table (survive catalog changes) ──diff --git a/tests/hermes_cli/test_unified_pool_quirk.py b/tests/hermes_cli/test_unified_pool_quirk.pyindex 18ab0c53873..74581c8520b 100644--- a/tests/hermes_cli/test_unified_pool_quirk.py+++ b/tests/hermes_cli/test_unified_pool_quirk.py@@ -94,7 +94,7 @@ def test_no_probe_available_stays_discrete(monkeypatch):def _uma_machine(monkeypatch, *, view):_no_cache(monkeypatch)monkeypatch.setattr(hw, "_nvidia_vram",- lambda: (UMA_SMI_TOTAL, 14848 << 20))+ lambda: (UMA_SMI_TOTAL, 14848 << 20, ""))monkeypatch.setattr(hw, "_ram_bytes",lambda: (UMA_RAM, 32 * GIB))monkeypatch.setattr(hw, "_device_pool_view", lambda: view)@@ -191,6 +191,31 @@ def test_smi_resolver_uses_wsl_driver_path_when_path_is_empty(monkeypatch):assert hw._nvidia_smi_path() == str(wsl_smi)+def test_memory_probe_carries_identity_without_another_process(monkeypatch):+ from types import SimpleNamespace+ import sys++ calls = []+ name = "NVIDIA RTX Spark N1X (5120-core Blackwell RTX GPU)"+ monkeypatch.setattr(hw, "_nvidia_smi_path", lambda: "nvidia-smi")+ monkeypatch.setattr(hw, "_ram_bytes", lambda: (64 * GIB, 22 * GIB))+ monkeypatch.setattr(hw, "_device_pool_view", lambda: (UMA_POOL, True))++ def run(argv, **kwargs):+ calls.append(argv)+ assert argv[0] == "nvidia-smi"+ output = f"32704, 31423, {name}\n" if argv[1].endswith(",name") else "32704, 31423\n"+ return SimpleNamespace(returncode=0, stdout=output)++ monkeypatch.setattr(hw.subprocess, "run", run)+ budget = hw.probe_budget(planning=True)+ assert budget.gpu_name == name+ assert budget.platform == sys.platform+ assert budget.total_device_bytes == UMA_POOL+ assert budget.usable_vram_bytes == int(UMA_POOL * .8)+ assert len(calls) == 1++# ── probe cache ──────────────────────────────────────────────