The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(local-runtime): cap resident models by the hardware budget, not a count
finn763eaa5523f115b
diff --git a/hermes_cli/local_runtime/bootstrap.py b/hermes_cli/local_runtime/bootstrap.pyindex 5f4dfcb41fa..892e28aed7c 100644--- a/hermes_cli/local_runtime/bootstrap.py+++ b/hermes_cli/local_runtime/bootstrap.py@@ -142,6 +142,28 @@ def refresh_local_runtime() -> bool:return False+def _admitted_models_max(mdir: Path, configured: int) -> int:+ """Residency cap to hand the router: derived from the hardware budget, ``models_max`` as a ceiling.++ A cap of "four" on a card that holds one model is how a second child ends up paged (WDDM) and+ silently slow — llama.cpp evicts its LRU before an incoming load only when the cap says the+ card is full. A probe miss or an unpriceable model keeps the configured count: this must never+ block a boot.+ """+ try:+ from hermes_cli.local_runtime.hardware import probe_budget+ from hermes_cli.local_runtime.presets import admitted_residency_count++ cap = admitted_residency_count(mdir, probe_budget(planning=True), configured)+ except Exception as exc: # noqa: BLE001+ logger.warning("residency cap probe failed (%s); using models_max=%s", exc, configured)+ return configured+ if cap != configured:+ logger.info("residency cap: %s resident model(s) on this card (models_max=%s)",+ cap, configured)+ return cap++def _generate_presets(mdir: Path, preset_path: Path) -> Path | None:"""Write the launch-policy INI for every staged model; returns the path to hand the router.@@ -310,7 +332,8 @@ def ensure_local_runtime(config: dict, force: bool = False) -> "object | None":preset_path = _generate_presets(mdir, runtimes_root() / "presets.ini")sup = LlamaServerSupervisor(install_dir, mdir, preset_path=preset_path,- models_max=int(section.get("models_max", 4)),+ models_max=_admitted_models_max(+ mdir, int(section.get("models_max", 4))),port=int(section.get("port", 0)) or None)try:sup.start()diff --git a/hermes_cli/local_runtime/presets.py b/hermes_cli/local_runtime/presets.pyindex fecd6ebb888..28abe7a3420 100644--- a/hermes_cli/local_runtime/presets.py+++ b/hermes_cli/local_runtime/presets.py@@ -134,6 +134,61 @@ def preset_for_model(gguf: Path, budget: HardwareBudget,spilled=decision.spilled, keys=keys)+def _launch_footprint(gguf: Path, budget: HardwareBudget) -> int | None:+ """Estimated resident bytes for one staged model at the window this policy grants it, or None+ when it cannot be priced: an unreadable header, or a model the physics check refuses outright+ (it never loads, so it must not shrink the residency cap)."""+ from hermes_cli.local_runtime.catalog import entry_for_model+ from hermes_cli.local_runtime.growth import load_window_overrides++ model_id = model_id_from_stem(gguf.stem)+ try:+ profile = profile_from_gguf(read_gguf_header(gguf))+ except (ValueError, OSError) as exc:+ logger.debug("footprint skip %s: %s", gguf.name, exc)+ return None+ entry = entry_for_model(model_id)+ is_mtp = entry.mtp if entry is not None else False+ mmproj = entry.mmproj.size_bytes if entry is not None and _asset_path(entry.mmproj) else 0+ plan = plan_launch(profile, budget, mtp_capable=is_mtp,+ fixed_overhead=RUNTIME_OVERHEAD_BYTES + mmproj,+ requested_window=load_window_overrides().get(model_id))+ if isinstance(plan.decision, PhysicsRefusal):+ return None+ # Priced whole even when the plan spills: a spilled model still holds part of its weights on+ # the device, and over-counting errs toward the side that cannot thrash.+ return footprint_bytes(profile, plan.decision.window, overhead_bytes=plan.overhead_bytes)+++def admitted_residency_count(models_dir: Path, budget: HardwareBudget, configured: int) -> int:+ """How many models the card may hold resident at once: priced against the budget, not a count.++ Residency used to be bounded by a count alone, so a second model was admitted against an+ already-full card. On Windows/WDDM that over-commit is not refused — the allocation is paged+ to host memory, and that child decodes at a third of its speed for the rest of its life: no+ error, no UI hint, and ejecting the incumbent afterwards does not repair it (only a clean+ reload does). Capping the count instead has llama.cpp evict its LRU *before* the incoming+ child allocates, which is the only placement that fits.++ The cap rises above one only while the LARGEST staged model still fits TWICE — any pair of+ staged models then fits by construction. ``configured`` stays a ceiling (a user's smaller+ number is honoured), and an unpriceable input (no usable device memory, no readable model)+ keeps today's behaviour.+ """+ from hermes_cli.local_runtime.bootstrap import staged_in++ if configured <= 1 or budget.usable_vram_bytes <= 0:+ return configured+ largest = 0+ for gguf in staged_in(models_dir):+ need = _launch_footprint(gguf, budget)+ if need:+ largest = max(largest, need)+ if largest <= 0:+ return configured+ return max(1, min(configured, budget.usable_vram_bytes // largest))++def generate_presets(models_dir: Path, budget: HardwareBudget, preset_path: Path,mtp_capable: set[str] | None = None) -> list[PresetEntry]:"""Walk the staged models, run the launch decision per model, and write one INI. Refuseddiff --git a/tests/hermes_cli/test_local_residency_admission.py b/tests/hermes_cli/test_local_residency_admission.pynew file mode 100644index 00000000000..1575e3a8625--- /dev/null+++ b/tests/hermes_cli/test_local_residency_admission.py@@ -0,0 +1,136 @@+"""Residency admission is priced against the card, not a constant count.++Residency was bounded by ``models_max`` alone, so a second model was admitted against an+already-full card; on Windows/WDDM the over-commit is paged instead of refused and that child+decodes at a third of its speed for the rest of its life. The cap handed to the router is now+derived from the hardware budget, with the configured value as a ceiling. The budgets and model+sizes here are injected — the logic must hold on a machine with no GPU at all.+"""+from pathlib import Path+from types import SimpleNamespace++import pytest++from hermes_cli.local_runtime import presets+from hermes_cli.local_runtime.estimator import HardwareBudget, ModelProfile++GIB = 1 << 30++# The card from the report: RTX 3070 Laptop, 8 GiB, desktop co-residents reserved away. A 6 GiB+# model plus runtime overhead fits once, never twice.+TIGHT = HardwareBudget(usable_vram_bytes=6 * GIB, total_device_bytes=8 * GIB,+ ram_available_bytes=8 * GIB)+# A 48 GiB card: four 6 GiB models fit with room to spare.+ROOMY = HardwareBudget(usable_vram_bytes=48 * GIB, total_device_bytes=48 * GIB,+ ram_available_bytes=64 * GIB)+++def _staged(tmp_path, monkeypatch, weights: dict[str, int]):+ """A models dir of touched GGUFs whose parsed weights are the given bytes (keyed by stem)."""+ mdir = tmp_path / "models"+ mdir.mkdir(parents=True, exist_ok=True)+ for stem in weights:+ (mdir / f"{stem}.gguf").touch()+ monkeypatch.setattr(presets, "read_gguf_header",+ lambda p: SimpleNamespace(path=p, sampling_defaults={}))+ monkeypatch.setattr(presets, "profile_from_gguf", lambda h: ModelProfile(+ name=Path(h.path).stem, weights_bytes=weights[Path(h.path).stem],+ embd_table_bytes=0, n_ctx_train=65536, layers=[]))+ return mdir+++def test_two_models_that_cannot_share_the_card_cap_residency_at_one(tmp_path, monkeypatch):+ """The report's exact shape: 6 GiB and 3.9 GiB staged on an 8 GiB card. Admitting both pages+ the second one; the cap must say one so llama.cpp evicts before the load."""+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))+ mdir = _staged(tmp_path, monkeypatch, {"nine-b": 6 * GIB, "gemma-e4b": int(3.9 * GIB)})+ assert presets.admitted_residency_count(mdir, TIGHT, 4) == 1+++def test_a_card_with_room_keeps_the_configured_count(tmp_path, monkeypatch):+ """No regression for big cards: the budget raises nothing, and 4 residents fit."""+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))+ mdir = _staged(tmp_path, monkeypatch, {"a": 6 * GIB, "b": 6 * GIB})+ assert presets.admitted_residency_count(mdir, ROOMY, 4) == 4+++def test_a_lower_configured_count_is_never_raised(tmp_path, monkeypatch):+ """``models_max`` stays a ceiling — the user's knob still means what it said."""+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))+ mdir = _staged(tmp_path, monkeypatch, {"a": 1 * GIB})+ assert presets.admitted_residency_count(mdir, ROOMY, 1) == 1+++def test_unpriceable_input_keeps_todays_count(tmp_path, monkeypatch):+ """Backward compatibility: no usable device memory (no probe), or an unreadable model, must+ leave the count exactly as configured."""+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))+ mdir = _staged(tmp_path, monkeypatch, {"a": 6 * GIB})+ no_device = HardwareBudget(usable_vram_bytes=0, total_device_bytes=0, ram_available_bytes=8 * GIB)+ assert presets.admitted_residency_count(mdir, no_device, 4) == 4++ def _unreadable(_path):+ raise ValueError("not a gguf")++ monkeypatch.setattr(presets, "read_gguf_header", _unreadable)+ assert presets.admitted_residency_count(mdir, TIGHT, 4) == 4+++def test_a_refused_model_does_not_shrink_the_cap(tmp_path, monkeypatch):+ """A model the physics check refuses outright never loads, so it must not force evictions of+ the models that do."""+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))+ # 200 GiB against 48 GiB + 64 GiB: refused (it cannot load at any window), not merely spilled.+ mdir = _staged(tmp_path, monkeypatch, {"tiny": 2 * GIB, "huge": 200 * GIB})+ assert presets.admitted_residency_count(mdir, ROOMY, 4) == 4++[email protected]("configured,expected", [(4, 1), (1, 1)])+def test_boot_hands_the_router_the_derived_cap(tmp_path, monkeypatch, configured, expected):+ """The wiring, not just the math: what ``ensure_local_runtime`` passes as ``--models-max``."""+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))+ import hermes_cli.local_runtime.bootstrap as bs+ from hermes_cli.local_runtime import binaries, hardware, supervisor+ from hermes_cli.local_runtime import endpoint++ mdir = _staged(tmp_path, monkeypatch, {"nine-b": 6 * GIB})+ monkeypatch.setattr(bs, "models_dir", lambda: mdir)+ monkeypatch.setattr(hardware, "probe_budget", lambda **kw: TIGHT)+ monkeypatch.setattr(bs, "_SUPERVISOR", None)+ monkeypatch.setattr(bs, "_generate_presets", lambda mdir, preset_path: None)+ monkeypatch.setattr(bs, "_detect_gpu_vendor", lambda: None)+ monkeypatch.setattr(binaries, "installed_tags", lambda: ["build-1"])+ monkeypatch.setattr(binaries, "default_tag", lambda: "build-1")+ monkeypatch.setattr(binaries, "select_backend", lambda vendor: "cpu")+ monkeypatch.setattr(binaries, "ensure_runtime_installed",+ lambda tag, backend: tmp_path / "install")+ monkeypatch.setattr(endpoint, "_state_endpoint", lambda: None)++ captured: dict = {}++ class FakeSupervisor:+ def __init__(self, install_dir, models_dir, **kwargs):+ captured.update(kwargs)+ self.proc = None+ self.base_url = "http://127.0.0.1:1/v1"++ def start(self) -> None:+ return None++ monkeypatch.setattr(supervisor, "LlamaServerSupervisor", FakeSupervisor)+ config = {"local_runtime": {"enabled": True, "models_max": configured}}+ assert bs.ensure_local_runtime(config) is not None+ assert captured["models_max"] == expected+++def test_a_broken_probe_does_not_block_the_boot(tmp_path, monkeypatch):+ """The cap is policy, not a prerequisite: a probe failure must fall back to the config."""+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))+ import hermes_cli.local_runtime.bootstrap as bs+ from hermes_cli.local_runtime import hardware++ def _boom(**_kw):+ raise OSError("nvidia-smi vanished mid-session")++ monkeypatch.setattr(hardware, "probe_budget", _boom)+ assert bs._admitted_models_max(tmp_path, 4) == 4