The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(local-runtime): derive the recommended model from memory size and bandwidth
emozillab361fadd49db
diff --git a/hermes_cli/local_runtime/catalog.json b/hermes_cli/local_runtime/catalog.jsonindex 7971d5cde90..587606e6339 100644--- a/hermes_cli/local_runtime/catalog.json+++ b/hermes_cli/local_runtime/catalog.json@@ -35,7 +35,8 @@"top-k": "20","min-p": "0.0"},- "recommended": true+ "quality": 90,+ "decode_fraction": 1.0},{"id": "qwen3.8-flash-next",@@ -76,7 +77,9 @@"size_bytes": 907542944,"local": "mmproj-Qwen3.8-Flash-Next-BF16.gguf"},- "min_engine": "b10678"+ "min_engine": "b10678",+ "quality": 95,+ "decode_fraction": 0.08},{"id": "qwen3.6-35b-a3b",@@ -113,7 +116,9 @@"top-p": "0.95","top-k": "20","min-p": "0.0"- }+ },+ "quality": 80,+ "decode_fraction": 0.15},{"id": "deepseek-v4-flash",@@ -161,7 +166,9 @@"temp": "1.0","top-p": "0.95","min-p": "0.01"- }+ },+ "quality": 85,+ "decode_fraction": 0.1}]}diff --git a/hermes_cli/local_runtime/catalog.py b/hermes_cli/local_runtime/catalog.pyindex 713dfeab117..bfe48d5b03b 100644--- a/hermes_cli/local_runtime/catalog.py+++ b/hermes_cli/local_runtime/catalog.py@@ -155,7 +155,19 @@ class CatalogEntry:# architectures need the release where their support landed). Empty# means any installed engine. The pane gates download/activate on it.min_engine: str = ""- recommended: bool = False # the catalog's default pick, one entry+ # Editorial quality ordering (higher = smarter), authored once,+ # globally, at catalog-authoring time — Artificial Analysis-informed+ # where they cover the model (scripts/aa_quality_sync.py proposes,+ # the commit decides), editorial elsewhere. Ranks entries for the+ # per-machine recommendation; never displayed as a score (it grades+ # the full-precision model, not our Q4 build).+ quality: int = 0+ # Fraction of the build's bytes read per decoded token: 1.0 for dense+ # models (every weight streams every token), the active slice for MoE+ # (attention + shared + routed experts over total). With memory+ # bandwidth this predicts decode speed — the physics half of the+ # recommendation.+ decode_fraction: float = 1.0def profile(self, variant: QuantVariant) -> ModelProfile:layers = ([(LayerKind.FULL, self.per_layer_f16)] * self.full_layers@@ -220,6 +232,88 @@ def select_variant(entry: CatalogEntry, budget: HardwareBudget) -> VariantChoicereturn None+# ── recommendation: best quality that fits and isn't miserably slow ──+#+# Two axes, each living where it belongs. QUALITY is a judgment made once,+# globally, at authoring time (entry.quality — AA-informed, editorially+# owned). SPEED is physics computed per machine: decode is memory-bound,+# so predicted tok/s ≈ bandwidth / bytes-read-per-token, and the bytes per+# token are the build's size scaled by its decode fraction (dense reads+# everything; MoE reads the active slice). The pick: highest quality among+# entries that run resident and clear a pleasant speed floor; else the+# fastest resident entry; else the least-painful spilled one.+#+# The bandwidth axis is the `uma` flag for now: every discrete card that+# matters is 900+ GB/s GDDR while the unified-memory class measures ~1/5th+# of that, so the flag IS the high/low split. A measured per-machine+# bandwidth (one cached memcpy probe) can replace these class constants+# without touching the rule; predictions order candidates and gate the+# floor — they are not display values.++_DISCRETE_BANDWIDTH_GB_S = 1000.0 # representative GDDR6X/GDDR7 class+_UMA_BANDWIDTH_GB_S = 210.0 # measured on unified-memory NVIDIA+_HOST_BANDWIDTH_GB_S = 80.0 # spilled weights stream over host DRAM++# The one editorial constant in the tree: below this predicted decode+# speed a model stops feeling pleasant for agentic use (roughly reading+# speed with headroom for tool-call bursts). Distinct from the growth+# policy's 6 tok/s compress floor, which marks unusable, not unpleasant.+PLEASANT_FLOOR_TOK_S = 20.0+++def predicted_decode_tok_s(entry: CatalogEntry, variant: QuantVariant,+ budget: HardwareBudget, *,+ spilled: bool = False) -> float:+ """Memory-bound decode prediction for ordering and floor-gating."""+ bandwidth = (_HOST_BANDWIDTH_GB_S if spilled+ else _UMA_BANDWIDTH_GB_S if budget.uma+ else _DISCRETE_BANDWIDTH_GB_S)+ bytes_per_token = max(1.0, variant.size_bytes * entry.decode_fraction)+ return bandwidth * 1e9 / bytes_per_token+++def recommended_entry(budget: HardwareBudget,+ entries: "tuple[CatalogEntry, ...] | None" = None+ ) -> CatalogEntry | None:+ """The catalog's default pick for THIS machine.++ Callers pass pre-filtered entries when some are ineligible for+ reasons the catalog can't know (engine too old); default is the full+ catalog. Returns None only when nothing fits at all.+ """+ pool = CATALOG if entries is None else entries+ fitting: list[tuple[CatalogEntry, VariantChoice]] = []+ for entry in pool:+ choice = select_variant(entry, budget)+ if choice is not None:+ fitting.append((entry, choice))+ if not fitting:+ return None++ resident = [(e, c) for e, c in fitting if c.zero_spill]+ pleasant = [+ (e, c) for e, c in resident+ if predicted_decode_tok_s(e, c.variant, budget) >= PLEASANT_FLOOR_TOK_S+ ]+ if pleasant:+ return max(pleasant, key=lambda t: (t[0].quality, -t[1].variant.size_bytes))[0]+ if resident:+ return max(resident,+ key=lambda t: predicted_decode_tok_s(t[0], t[1].variant, budget))[0]+ # Everything spills: take the least painful — fastest predicted decode+ # from host memory (MoE wins here by construction; a dense spill+ # streams every weight over the host bus).+ return max(fitting,+ key=lambda t: predicted_decode_tok_s(t[0], t[1].variant, budget,+ spilled=True))[0]+++def recommended_id(budget: HardwareBudget,+ entries: "tuple[CatalogEntry, ...] | None" = None) -> str | None:+ entry = recommended_entry(budget, entries)+ return entry.id if entry is not None else None++# ── catalog data: packaged JSON, refreshed from GitHub in memory ─## The catalog DATA lives in catalog.json (checked in beside this module@@ -276,7 +370,8 @@ def _load_catalog(doc: dict) -> "tuple[CatalogEntry, ...]":draft=_asset_from(m.get("draft")),sampling=dict(m.get("sampling", {})),min_engine=str(m.get("min_engine", "")),- recommended=bool(m.get("recommended")),+ quality=int(m.get("quality", 0)),+ decode_fraction=float(m.get("decode_fraction", 1.0)),))return tuple(entries)diff --git a/hermes_cli/web_routers/local_models.py b/hermes_cli/web_routers/local_models.pyindex 146298a2199..a9f4c433e21 100644--- a/hermes_cli/web_routers/local_models.py+++ b/hermes_cli/web_routers/local_models.py@@ -486,6 +486,7 @@ async def local_models_catalog():entry is hidden; unaffordable models show WHY."""from hermes_cli.local_runtime.catalog import (CATALOG,+ recommended_id,refresh_catalog_soon,select_variant,)@@ -505,6 +506,11 @@ async def local_models_catalog():# Planning budget: price against machine capacity, not live-free VRAM.# A loaded model must not make the catalog call every row unaffordable.budget = probe_budget(planning=True)+ # The default pick for THIS machine: quality-ranked, fit- and+ # speed-gated (recommended_entry). Engine-gated entries can't be+ # activated today, so they can't be the recommendation either.+ eligible = tuple(e for e in CATALOG if not _engine_too_old(e.min_engine))+ recommended = recommended_id(budget, eligible)# Completeness-checked staging (split parts all present) — the same# answer the picker and the router see, so a mid-download model never# reads as downloaded here.@@ -524,7 +530,7 @@ async def local_models_catalog():"description": entry.description,"native_context": entry.n_ctx_train,"native_context_label": f"{entry.n_ctx_train // 1024}K",- "recommended": entry.recommended,+ "recommended": entry.id == recommended,"downloaded": downloaded_variant is not None,"downloaded_model_id": downloaded_variant.model_id if downloaded_variant else None,"downloaded_quant": downloaded_variant.quant if downloaded_variant else None,@@ -900,10 +906,16 @@ async def local_models_quickstart(body: QuickstartBody):assets_dir,staged_model_ids,)- from hermes_cli.local_runtime.catalog import CATALOG, catalog_by_id, select_variant+ from hermes_cli.local_runtime.catalog import (+ CATALOG,+ catalog_by_id,+ recommended_entry,+ select_variant,+ )from hermes_cli.local_runtime.hardware import probe_budget- # Resolve the target entry: explicit id, else recommended, else the+ # Resolve the target entry: explicit id, else this machine's+ # recommendation (quality-ranked, fit- and speed-gated), else the# first catalog entry this machine can serve.budget = probe_budget(planning=True)entry = None@@ -914,7 +926,10 @@ async def local_models_quickstart(body: QuickstartBody):detail=f"unknown model {body.model_id}")candidates = [entry]else:- candidates = sorted(CATALOG, key=lambda e: not e.recommended)+ eligible = tuple(e for e in CATALOG if not _engine_too_old(e.min_engine))+ best = recommended_entry(budget, eligible)+ candidates = ([best] if best is not None else []) + [+ e for e in CATALOG if best is None or e.id != best.id]chosen = Nonefor candidate in candidates:choice = select_variant(candidate, budget)diff --git a/scripts/aa_quality_sync.py b/scripts/aa_quality_sync.pynew file mode 100644index 00000000000..66e61c7f7d1--- /dev/null+++ b/scripts/aa_quality_sync.py@@ -0,0 +1,94 @@+"""Propose catalog quality updates from Artificial Analysis.++Authoring-time helper — NEVER called at runtime (their terms forbid+client-side keys, the fleet would burn the rate limit, and a+recommendation must not change because a third-party endpoint+hiccuped). Run it when adding a model or refreshing the ordering;+review the printed diff and edit catalog.json yourself. The script+proposes, the commit decides.++The catalog's `quality` stays OUR field: AA-informed where they cover a+model, editorially set where they don't (day-0 releases lag their evals;+some entries never appear). AA's Intelligence Index grades the+full-precision cloud model, not our Q4 build — fine for ordering, never+for display.++Usage:+ export AA_API_KEY=... # from https://artificialanalysis.ai (free tier)+ python scripts/aa_quality_sync.py++Attribution: scores by Artificial Analysis (https://artificialanalysis.ai).+"""++from __future__ import annotations++import json+import os+import sys+import urllib.request+from pathlib import Path++REPO_ROOT = Path(__file__).resolve().parent.parent+CATALOG_PATH = REPO_ROOT / "hermes_cli" / "local_runtime" / "catalog.json"+AA_URL = "https://artificialanalysis.ai/api/v2/data/llms/models"++# Catalog entry id -> AA slug. Hand-maintained: AA's naming rarely matches+# HF repo names, and a wrong match silently mis-ranks a model. An entry+# absent here (or mapped to None) is editorial-only and never overwritten.+AA_SLUG_BY_ENTRY = {+ "qwen3.8-27b": "qwen3-8-27b",+ "qwen3.8-flash-next": "qwen3-8-flash-next",+ "qwen3.6-35b-a3b": "qwen3-6-35b-a3b",+ "deepseek-v4-flash": "deepseek-v4-flash",+}+++def fetch_aa_models(api_key: str) -> dict[str, dict]:+ req = urllib.request.Request(AA_URL, headers={"x-api-key": api_key})+ with urllib.request.urlopen(req, timeout=30) as r:+ doc = json.load(r)+ return {m["slug"]: m for m in doc.get("data", [])}+++def main() -> int:+ api_key = os.environ.get("AA_API_KEY", "").strip()+ if not api_key:+ print("AA_API_KEY not set — create a free key at "+ "https://artificialanalysis.ai and export it.", file=sys.stderr)+ return 2++ catalog = json.loads(CATALOG_PATH.read_text(encoding="utf-8"))+ aa = fetch_aa_models(api_key)++ print(f"{'entry':24s} {'catalog q':>9s} {'AA index':>9s} note")+ print("-" * 70)+ for model in catalog["models"]:+ entry_id = model["id"]+ current = model.get("quality", 0)+ slug = AA_SLUG_BY_ENTRY.get(entry_id)+ if not slug:+ print(f"{entry_id:24s} {current:>9d} {'—':>9s} editorial only (no AA mapping)")+ continue+ hit = aa.get(slug)+ if hit is None:+ print(f"{entry_id:24s} {current:>9d} {'—':>9s} not in AA data (slug {slug!r})")+ continue+ index = (hit.get("evaluations") or {}).get(+ "artificial_analysis_intelligence_index")+ if index is None:+ print(f"{entry_id:24s} {current:>9d} {'—':>9s} AA row lacks the index")+ continue+ proposed = round(float(index))+ marker = "" if proposed == current else " <-- proposes change"+ print(f"{entry_id:24s} {current:>9d} {proposed:>9d}{marker}")++ print("\nReview against the decision table before editing: a quality "+ "change that flips cells in tests/hermes_cli/"+ "test_local_recommendation.py is the actual decision being made.")+ print("Attribution: scores by Artificial Analysis "+ "(https://artificialanalysis.ai).")+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tests/hermes_cli/test_local_quickstart.py b/tests/hermes_cli/test_local_quickstart.pyindex c6e1855bcdb..f6a8f56193a 100644--- a/tests/hermes_cli/test_local_quickstart.py+++ b/tests/hermes_cli/test_local_quickstart.py@@ -158,14 +158,15 @@ def quickstart_ready(monkeypatch):installed and every entry's first variant is servable, so the POSTreaches the single-flight lock instead of 409ing at fit/enginepreflight on machines where nothing fits."""- from types import SimpleNamespace+ from hermes_cli.local_runtime.catalog import VariantChoicemonkeypatch.setattr("hermes_cli.local_runtime.binaries.installed_tags", lambda: ["b10362"])monkeypatch.setattr("hermes_cli.local_runtime.catalog.select_variant",- lambda entry, budget: SimpleNamespace(variant=entry.variants[0],- reason_key="best-fits"))+ lambda entry, budget: VariantChoice(variant=entry.variants[0],+ zero_spill=True,+ reason_key="best-fits"))monkeypatch.setattr("hermes_cli.web_routers.local_models._engine_too_old",lambda min_engine: False)diff --git a/tests/hermes_cli/test_local_recommendation.py b/tests/hermes_cli/test_local_recommendation.pynew file mode 100644index 00000000000..dae4f0c8563--- /dev/null+++ b/tests/hermes_cli/test_local_recommendation.py@@ -0,0 +1,161 @@+"""The recommendation decision table — the reviewable matrix.++The recommendation itself is DERIVED (catalog.recommended_entry: best+quality among resident entries clearing the pleasant speed floor, else+fastest resident, else least-painful spilled), so nobody hand-maintains+per-hardware-class picks. This table is the editorial control on that+derivation: it enumerates the real memory size classes x {discrete,+unified} and pins every cell. A catalog change (new model, quality+re-rank, quant swap) flips cells HERE, and the diff of this file in+review IS the sign-off on what each machine class gets.++These are decision pins, not change-detectors: each cell is a choice a+human approved, exactly like a golden file. When a cell flips on+purpose, update it in the same commit and say why. When one flips by+surprise, that is the test doing its job.++Budgets mirror hardware.probe_budget's planning-mode shapes (margins,+UMA headroom) so the cells match what a real machine of that class+resolves.+"""++from __future__ import annotations++import pytest++from hermes_cli.local_runtime.catalog import (+ CATALOG,+ PLEASANT_FLOOR_TOK_S,+ predicted_decode_tok_s,+ recommended_id,+ select_variant,+)+from hermes_cli.local_runtime.estimator import HardwareBudget++_GIB = 1 << 30+++def _discrete(size_gb: int) -> HardwareBudget:+ total = size_gb * _GIB+ margin = max(2 * _GIB, int(total * 0.09))+ return HardwareBudget(usable_vram_bytes=max(0, total - margin),+ total_device_bytes=total,+ ram_available_bytes=64 * _GIB, uma=False)+++def _unified(size_gb: int) -> HardwareBudget:+ total = size_gb * _GIB+ return HardwareBudget(usable_vram_bytes=int(total * 0.80),+ total_device_bytes=total,+ ram_available_bytes=0, uma=True)+++# The decision table. Cells were generated by the resolver and then+# reviewed as editorial decisions (2026-08-29):+#+# VRAM | discrete | unified+# -----+-------------------------+------------------------+# 8 | qwen3.6-35b-a3b spilled | (none fits)+# 16 | qwen3.6-35b-a3b spilled | (none fits)+# 24 | qwen3.8-27b | (none fits)+# 32 | qwen3.8-27b | qwen3.6-35b-a3b+# 48 | qwen3.8-27b | qwen3.6-35b-a3b+# 96 | qwen3.8-27b | qwen3.6-35b-a3b+# 128 | qwen3.8-flash-next | qwen3.6-35b-a3b+# 256 | qwen3.8-flash-next | qwen3.8-flash-next+# 512 | qwen3.8-flash-next | qwen3.8-flash-next+#+# Reading guide for reviewers:+# - Discrete <=16 GB: nothing runs resident; the 35B MoE is the least+# painful spill (active slice streams from host; a dense spill reads+# every weight over the bus).+# - Discrete 24-96 GB: the 27B is the flagship experience — dense reads+# at ~1 TB/s clear the floor easily, so quality decides.+# - Discrete/unified where Flash Next fits resident (128 GB discrete,+# 256+ GB unified): the frontier model is the pick — highest quality,+# and its sparse decode clears the floor even at UMA bandwidth+# (~24 tok/s predicted at 210 GB/s).+# - Unified 32-128 GB — the Spark class, the reason this resolver+# exists: the dense 27B predicts ~13 tok/s at UMA bandwidth (below+# the pleasant floor), so the 35B-A3B (~60 tok/s) wins.+# - Unified <=24 GB: no entry passes the physics check inside the UMA+# budget (spilling is impossible on UMA by construction — the pool IS+# the RAM). The pane's browse flow is the path for those machines+# until a small catalog entry lands (revisit when one does).+DECISION_TABLE = [+ (8, "discrete", "qwen3.6-35b-a3b"),+ (8, "unified", None),+ (16, "discrete", "qwen3.6-35b-a3b"),+ (16, "unified", None),+ (24, "discrete", "qwen3.8-27b"),+ (24, "unified", None),+ (32, "discrete", "qwen3.8-27b"),+ (32, "unified", "qwen3.6-35b-a3b"),+ (48, "discrete", "qwen3.8-27b"),+ (48, "unified", "qwen3.6-35b-a3b"),+ (96, "discrete", "qwen3.8-27b"),+ (96, "unified", "qwen3.6-35b-a3b"),+ (128, "discrete", "qwen3.8-flash-next"),+ (128, "unified", "qwen3.6-35b-a3b"),+ (256, "discrete", "qwen3.8-flash-next"),+ (256, "unified", "qwen3.8-flash-next"),+ (512, "discrete", "qwen3.8-flash-next"),+ (512, "unified", "qwen3.8-flash-next"),+]+++ ("size_gb", "kind", "expected"),+ DECISION_TABLE,+ ids=[f"{s}GB-{k}" for s, k, _ in DECISION_TABLE])+def test_recommendation_decision_table(size_gb, kind, expected):+ budget = _discrete(size_gb) if kind == "discrete" else _unified(size_gb)+ assert recommended_id(budget) == expected+++# ── invariants behind the table (survive catalog changes) ──+++def test_every_entry_carries_the_recommendation_axes():+ """quality and decode_fraction are authoring requirements: an entry+ without them silently loses every quality comparison (quality=0) or+ prices as dense (decode_fraction=1.0)."""+ for entry in CATALOG:+ assert entry.quality > 0, f"{entry.id} has no quality ordering"+ assert 0.0 < entry.decode_fraction <= 1.0, entry.id+ if not entry.moe:+ assert entry.decode_fraction == 1.0, (+ f"{entry.id} is dense — it reads every weight per token")+++def test_unified_never_recommends_a_below_floor_dense_model():+ """The Spark rule, as an invariant: whatever the catalog holds, a+ unified-memory machine must not be told to run a model whose+ predicted decode is below the pleasant floor while a resident+ alternative clears it."""+ budget = _unified(128)+ pick = recommended_id(budget)+ assert pick is not None+ entry = next(e for e in CATALOG if e.id == pick)+ choice = select_variant(entry, budget)+ assert choice is not None and choice.zero_spill+ clears = [+ e for e in CATALOG+ if (c := select_variant(e, budget)) is not None and c.zero_spill+ and predicted_decode_tok_s(e, c.variant, budget) >= PLEASANT_FLOOR_TOK_S+ ]+ if clears:+ assert predicted_decode_tok_s(entry, choice.variant, budget) >= PLEASANT_FLOOR_TOK_S+++def test_quality_decides_where_speed_permits():+ """On big discrete hardware every resident entry clears the floor, so+ the pick must be the highest-quality fitting entry — the axis that+ justifies carrying an editorial field at all."""+ budget = _discrete(512)+ pick = recommended_id(budget)+ resident = [+ e for e in CATALOG+ if (c := select_variant(e, budget)) is not None and c.zero_spill+ ]+ assert pick == max(resident, key=lambda e: e.quality).id