The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(local-runtime): fit drafts to free memory and keep update restarts
emozilla90ab2404835b
diff --git a/hermes_cli/local_runtime/growth.py b/hermes_cli/local_runtime/growth.pyindex 78367028952..8ad250078f4 100644--- a/hermes_cli/local_runtime/growth.py+++ b/hermes_cli/local_runtime/growth.py@@ -117,9 +117,13 @@ def maybe_grow_window(model_id: str, *, base_url: str, session_tokens: int,logger.debug("growth %s: %s (%s)", model_id, decision.action, decision.reason)return None- # The grown instance loads after this one exits, so the model's own memory counts as free.- # Other loaded models still count as held, which errs toward a smaller window.- live = _launch_budget(budget, own_bytes=resident_footprint(gguf, budget, current_window) or 0)+ # The grown instance loads after this one exits, so the model's own memory counts as free,+ # draft included when its running preset has one. Other loaded models still count as held,+ # which errs toward a smaller window.+ running = read_preset_decisions().get(model_id)+ drafting = running is not None and (running.keys or {}).get("spec-type") == "draft-dflash"+ own_bytes = resident_footprint(gguf, budget, current_window, drafting=drafting) or 0+ live = _launch_budget(budget, own_bytes=own_bytes)plan = preset_for_model(gguf, budget, set(), requested_window=decision.next_window, live=live)if plan is None or plan.refusal or plan.window < decision.next_window:logger.debug("growth %s: the next rung does not fit beside other programs' GPU memory",diff --git a/hermes_cli/local_runtime/presets.py b/hermes_cli/local_runtime/presets.pyindex a4939303638..82764e54909 100644--- a/hermes_cli/local_runtime/presets.py+++ b/hermes_cli/local_runtime/presets.py@@ -144,6 +144,11 @@ def _dflash_plan(entry, profile, budget: HardwareBudget, live: HardwareBudget |overhead = fixed_overhead + _dflash_extra_bytes(entry, lean)plan = plan_launch(lean, budget, fixed_overhead=overhead, requested_window=requested_window)if live is not None:+ # fit_to_free_memory holds a too-busy card at the floor rather than move weights off it on a+ # live reading. The draft never rides on that hold: it runs only where it fits now.+ now = plan_launch(lean, live, fixed_overhead=overhead)+ if isinstance(now.decision, PhysicsRefusal) or now.decision.spilled:+ return Noneplan = fit_to_free_memory(plan, lean, live, mtp_capable=False, fixed_overhead=overhead)decision = plan.decisionif isinstance(decision, PhysicsRefusal) or decision.spilled:@@ -243,8 +248,9 @@ def preset_for_model(gguf: Path, budget: HardwareBudget,spilled=decision.spilled, keys=keys)-def resident_footprint(gguf: Path, budget: HardwareBudget, window: int) -> int | None:- """Estimated bytes one staged model holds while loaded at ``window``, or None when unreadable."""+def resident_footprint(gguf: Path, budget: HardwareBudget, window: int, *, drafting: bool = False) -> int | None:+ """Estimated bytes one staged model holds while loaded at ``window``, or None when unreadable.+ ``drafting`` prices the one-slot DFlash launch its preset runs instead of MTP."""from hermes_cli.local_runtime.catalog import entry_for_modelmodel_id = model_id_from_stem(gguf.stem)@@ -255,10 +261,14 @@ def resident_footprint(gguf: Path, budget: HardwareBudget, window: int) -> int |return Noneentry = entry_for_model(model_id)companions = _companions(entry)- is_mtp = _runs_mtp(entry, companions)- plan = plan_launch(profile, budget, mtp_capable=is_mtp,- fixed_overhead=RUNTIME_OVERHEAD_BYTES + companions.nbytes,- requested_window=window)+ fixed_overhead = RUNTIME_OVERHEAD_BYTES + companions.nbytes+ if drafting and _runs_dflash(entry) is not None:+ lean = replace(profile, kv_scale=1.0)+ plan = plan_launch(lean, budget, fixed_overhead=fixed_overhead + _dflash_extra_bytes(entry, lean),+ requested_window=window)+ else:+ plan = plan_launch(profile, budget, mtp_capable=_runs_mtp(entry, companions),+ fixed_overhead=fixed_overhead, requested_window=window)return footprint_bytes(plan.profile, window, overhead_bytes=plan.overhead_bytes)diff --git a/hermes_cli/web_routers/local_models.py b/hermes_cli/web_routers/local_models.pyindex 42172220d7f..16b359570e1 100644--- a/hermes_cli/web_routers/local_models.py+++ b/hermes_cli/web_routers/local_models.py@@ -689,6 +689,7 @@ def _install_engine_job(job: dict[str, Any], backend: str):def local_models_runtime_install(body: RuntimeInstallBody, profile: Optional[str] = None):tag, backend = _runtime_target(body.backend)job = _job("runtime-install", f"llama.cpp {tag} ({backend})")+ owed = {"restart": False} # survives a pause: resume runs this job's ``run`` againdef run():with _config_profile_scope(profile):@@ -696,13 +697,17 @@ def local_models_runtime_install(body: RuntimeInstallBody, profile: Optional[strengine = _install_engine_job(job, backend)drafts = _missing_drafts(engine.tag)if drafts:+ owed["restart"] = True # the restart is what loads them_step(job, "downloading", "Downloading draft models that speed up generation")_download_job(job, drafts)running = bootstrap.get_supervisor()- if running is not None and (previous != engine or drafts):+ serving = bootstrap.serving_engine()+ stale = previous != engine or (serving is not None and serving.tag != engine.tag)+ if running is not None and (stale or owed["restart"]):_step(job, "restarting", "Switching the running server to the pinned build"- if previous != engine else "Restarting the local server")+ if stale else "Restarting the local server")bootstrap.refresh_local_runtime()+ owed["restart"] = False_finish(job, f"llama.cpp {tag} ready ({backend})")_spawn_job(job, "lr-runtime-install", run, fail_msg="runtime install failed: %s", resumable=True)diff --git a/tests/hermes_cli/test_local_external_draft.py b/tests/hermes_cli/test_local_external_draft.pyindex 5f614e33242..00354fe93bc 100644--- a/tests/hermes_cli/test_local_external_draft.py+++ b/tests/hermes_cli/test_local_external_draft.py@@ -108,6 +108,24 @@ def test_the_draft_may_shrink_the_window_to_half_native_and_no_further(model):assert shrank and declined_with_room+def test_the_draft_runs_only_where_it_fits_beside_other_programs(model):+ """A card too busy for even the floor window holds the model at the floor rather than move+ weights off it on a live reading. The draft never rides on that: it runs only where the model+ and the draft fit the free memory on their own."""+ gguf, _, _ = model+ capacity = _discrete(32)+ busy = drafted = 0+ for quarters in range(56, 120):+ live = replace(capacity, usable_vram_bytes=int(quarters / 4 * GIB))+ preset = presets.preset_for_model(gguf, capacity, set(), live=live, engine_tag="b11671")+ alone = presets.preset_for_model(gguf, live, set(), engine_tag="b11671")+ busy += alone.spilled+ if _drafts(preset):+ drafted += 1+ assert _drafts(alone) and not alone.spilled, quarters / 4+ assert busy and drafted++def test_a_grown_window_wins_over_the_draft(model):"""Growth restored the native window on a roomy card, and other programs now hold part of it:whatever window still fits goes to the model as it was, not to the draft."""@@ -135,6 +153,34 @@ def test_each_draft_position_prices_a_copy_of_the_recurrent_state(model):assert not _drafts(presets.preset_for_model(gguf, budget, set(), engine_tag="b11671"))+def test_growth_counts_the_outgoing_draft_as_freed_memory(model, monkeypatch):+ """The grown instance loads after the drafting one exits, so all of that instance's memory,+ draft included, counts as free when growth fits the next window."""+ from hermes_cli.local_runtime import estimator, gguf as gguf_module, growth, hardware++ path, _, _ = model+ budget = _discrete(28)+ running = presets.preset_for_model(path, budget, set(), engine_tag="b11671")+ assert _drafts(running) and running.window < NATIVE+ monkeypatch.setattr(bootstrap, "staged_models", lambda: [path])+ monkeypatch.setattr(bootstrap, "get_supervisor", lambda: SimpleNamespace(is_idle=lambda m: True))+ monkeypatch.setattr(growth, "is_managed_endpoint", lambda url: True)+ monkeypatch.setattr(gguf_module, "read_gguf_header", presets.read_gguf_header)+ monkeypatch.setattr(estimator, "profile_from_gguf", presets.profile_from_gguf)+ monkeypatch.setattr(hardware, "probe_budget", lambda **kw: budget)+ monkeypatch.setattr(presets, "read_preset_decisions", lambda *a: {BUILD.model_id: running})+ freed = []+ monkeypatch.setattr(bootstrap, "_launch_budget", lambda b, own_bytes=0: freed.append(own_bytes) or b)+ monkeypatch.setattr(bootstrap, "refresh_local_runtime", lambda: False)++ growth.maybe_grow_window(BUILD.model_id, base_url="http://127.0.0.1:1/v1",+ session_tokens=running.window, current_window=running.window)++ drafting = presets.resident_footprint(path, budget, running.window, drafting=True)+ assert freed == [drafting]+ assert drafting > presets.resident_footprint(path, budget, running.window)++def test_a_spilled_model_never_takes_the_draft(model):gguf, _, _ = model@@ -208,6 +254,55 @@ def test_the_update_job_downloads_missing_drafts_then_restarts_the_server(clientassert events == ["restart"]+def _update_job(monkeypatch, *, serving: str, on_download=None):+ """The engine update over a running server on ``serving``, with b11671 already installed."""+ lm = _staged(monkeypatch, ENTRY)+ engine = SimpleNamespace(tag="b11671", backend="cpu")+ monkeypatch.setattr(lm, "_runtime_target", lambda backend=None: ("b11671", "cpu"))+ monkeypatch.setattr(lm.binaries, "installed_engine", lambda backend: engine)+ monkeypatch.setattr(lm, "_install_engine_job", lambda job, backend: engine)+ monkeypatch.setattr(lm, "_download_job", on_download or (lambda job, plan: None))+ monkeypatch.setattr(lm.bootstrap, "get_supervisor", lambda: object())+ monkeypatch.setattr(lm.bootstrap, "serving_engine", lambda: SimpleNamespace(tag=serving, backend="cpu"))+ events = []+ monkeypatch.setattr(lm.bootstrap, "refresh_local_runtime", lambda: events.append("restart"))+ return lm, events+++def test_a_pause_between_the_drafts_and_the_restart_still_restarts_on_resume(client, monkeypatch):+ """The pause lands as the last draft finishes. On resume no draft is missing, and the server+ still needs the restart that loads them."""+ def download(job, plan):+ for _, dest, _ in plan:+ dest.parent.mkdir(parents=True, exist_ok=True)+ dest.touch()+ lm._RUNNING[job["job_id"]]["pause"].set()++ lm, events = _update_job(monkeypatch, serving="b11671", on_download=download)+ job_id = client.post("/api/local-models/runtime/install", json={"backend": "cpu"}).json()["job_id"]+ assert poll(client, job_id, until=("paused", "done", "error"))["status"] == "paused"+ assert events == []++ assert client.post("/api/local-models/download/resume", json={"job_id": job_id}).json()["resumed"]++ assert poll(client, job_id, until=("done", "error"))["status"] == "done"+ assert events == ["restart"]+++def test_the_update_restarts_a_server_still_on_an_older_build(client, monkeypatch):+ """An earlier update installed b11671 and stopped before its restart: the server still runs+ the old build, and the next update switches it over."""+ draft = bootstrap.assets_dir() / ENTRY.draft.local_name+ draft.parent.mkdir(parents=True, exist_ok=True)+ draft.touch()+ _, events = _update_job(monkeypatch, serving="b11370")++ job_id = client.post("/api/local-models/runtime/install", json={"backend": "cpu"}).json()["job_id"]++ assert poll(client, job_id, until=("done", "error"))["status"] == "done"+ assert events == ["restart"]++def test_an_installed_model_without_its_draft_still_reads_as_downloaded(monkeypatch):lm = _staged(monkeypatch, ENTRY)model = lm.bootstrap.models_dir() / BUILD.files[0].local_name