The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(local-runtime): run DFlash drafts on one slot when they fit
emozilla30b94a5ad67a
diff --git a/hermes_cli/local_runtime/bootstrap.py b/hermes_cli/local_runtime/bootstrap.pyindex e553fee980d..725fba842e5 100644--- a/hermes_cli/local_runtime/bootstrap.py+++ b/hermes_cli/local_runtime/bootstrap.py@@ -230,7 +230,7 @@ def _admitted_models_max(mdir: Path, configured: int) -> int:return cap-def _generate_presets(mdir: Path, preset_path: Path) -> Path | None:+def _generate_presets(mdir: Path, preset_path: Path, engine_tag: str | None = None) -> Path | None:"""Write the launch-policy INI for every staged model; returns the path to hand the router.Priced against CAPACITY, not live free VRAM: this runs while the outgoing server instance may@@ -249,7 +249,8 @@ def _generate_presets(mdir: Path, preset_path: Path) -> Path | None:try:capacity = probe_budget(planning=True)- for entry in generate_presets(mdir, capacity, preset_path, live=_launch_budget(capacity)):+ for entry in generate_presets(mdir, capacity, preset_path, live=_launch_budget(capacity),+ engine_tag=engine_tag):if entry.refusal:logger.warning("model refused by physics check: %s", entry.refusal)return preset_path@@ -303,7 +304,8 @@ def refit_idle_presets(sup) -> bool:last = sup._refit_usableif last is not None and abs(live.usable_vram_bytes - last) < _REFIT_STEP_BYTES:return False- text = render_presets(plan_presets(models_dir(), capacity, live=live))+ text = render_presets(plan_presets(models_dir(), capacity, live=live,+ engine_tag=_SERVING_ENGINE.tag if _SERVING_ENGINE is not None else None))# Held across the write and the reload so a restart can't spawn between them; everything# slow ran above.with sup._lifecycle_lock:@@ -453,7 +455,7 @@ def ensure_local_runtime(config: dict, force: bool = False) -> object | None:mdir = models_dir()mdir.mkdir(parents=True, exist_ok=True)- preset_path = _generate_presets(mdir, runtimes_root() / "presets.ini")+ preset_path = _generate_presets(mdir, runtimes_root() / "presets.ini", engine.tag)sup = LlamaServerSupervisor(engine.binary, mdir, preset_path=preset_path,models_max=_admitted_models_max(diff --git a/hermes_cli/local_runtime/catalog.json b/hermes_cli/local_runtime/catalog.jsonindex 4316dd26c19..7fcda3169d7 100644--- a/hermes_cli/local_runtime/catalog.json+++ b/hermes_cli/local_runtime/catalog.json@@ -1,5 +1,5 @@{- "schema_version": 2,+ "schema_version": 3,"models": [{"id": "qwen3.8-27b",@@ -37,7 +37,16 @@"min-p": "0.0"},"quality": 90,- "decode_fraction": 1.0+ "decode_fraction": 1.0,+ "draft": {+ "path": "Qwen3.8-27B-DFlash2-Q4_K_M.gguf",+ "size_bytes": 1143006816,+ "repo": "z-lab/Qwen3.8-27B-DFlash2-GGUF",+ "revision": "2d9571f8ce46e151f61c6499c99dee6079e1d610"+ },+ "draft_spec_type": "draft-dflash",+ "draft_depth": 7,+ "draft_min_engine": "b11370"},{"id": "qwen3.8-flash-next",diff --git a/hermes_cli/local_runtime/catalog.py b/hermes_cli/local_runtime/catalog.pyindex 9ec277542c1..9167d8c5abf 100644--- a/hermes_cli/local_runtime/catalog.py+++ b/hermes_cli/local_runtime/catalog.py@@ -103,6 +103,12 @@ class CatalogEntry:architecture: str = ""mmproj: AssetFile | None = None # vision projector, downloads with modeldraft: AssetFile | None = None # spec-decode draft model (e.g. DSpark)+ # How the draft decodes. draft-dspark drafts only for a model spilled past GPU memory;+ # draft-dflash replaces MTP whenever it fits, on one slot (each slot keeps a recurrent-state+ # copy per draft position). Optional: a missing draft leaves the model as it was.+ draft_spec_type: str = "draft-dspark"+ draft_depth: int = 3+ draft_min_engine: str = "" # oldest llama.cpp release that loads the draft# MTP head shipped as its own file (the model carries none): the engine loads it as the# draft for MTP spec decode. Downloads with the model.mtp_head: AssetFile | None = None@@ -153,6 +159,12 @@ class CatalogEntry:def download_bytes(self, variant: QuantVariant) -> int:return sum(f.size_bytes for f in self.download_files(variant))+ def install_files(self, variant: QuantVariant) -> tuple:+ """The files a variant needs to count as downloaded. The draft is optional: a model+ installed before its draft joined the catalog stays installed."""+ extras = tuple(a for a in (self.mmproj, self.mtp_head) if a is not None)+ return tuple(variant.files) + extras+@dataclass(frozen=True)class VariantChoice:@@ -290,7 +302,7 @@ def recommended_entry(budget: HardwareBudget,_CATALOG_URL = ("https://raw.githubusercontent.com/NousResearch/hermes-agent""/main/hermes_cli/local_runtime/catalog.json")-_SCHEMA_VERSION = 2 # bump when an older app would read a newer catalog but launch its entries wrongly+_SCHEMA_VERSION = 3 # bump when an older app would read a newer catalog but launch its entries wrongly_REFRESH_TTL_S = 6 * 3600_refresh_lock = threading.Lock()# None = never attempted: monotonic() counts from boot, so a 0.0 sentinel read as "refreshed at@@ -313,6 +325,7 @@ _SCALAR_FIELDS = {"moe": (bool, False), "mtp": (bool, False), "mtp_draft_depth": (int, 3),"n_vocab": (int, 0), "sampling": (dict, {}), "min_engine": (str, ""),"quality": (int, 0), "decode_fraction": (float, 1.0), "architecture": (str, ""),+ "draft_spec_type": (str, "draft-dspark"), "draft_depth": (int, 3), "draft_min_engine": (str, ""),}diff --git a/hermes_cli/local_runtime/presets.py b/hermes_cli/local_runtime/presets.pyindex 7a57a7bd5a7..a4939303638 100644--- a/hermes_cli/local_runtime/presets.py+++ b/hermes_cli/local_runtime/presets.py@@ -6,7 +6,7 @@ from __future__ import annotationsimport jsonimport logging-from dataclasses import dataclass+from dataclasses import dataclass, replacefrom pathlib import Pathfrom hermes_cli.local_runtime.context_policy import (@@ -98,13 +98,73 @@ def _draft_fits(path: Path, profile, budget: HardwareBudget, window: int, overheand ctx_bytes(profile, window) + overhead + draft_need <= budget.usable_vram_bytes)+# The draft model's own context beside the target's: its KV and compute buffers. Without it the+# price below still covered every measured server (b11671, -ub 2048, one slot) by 0.2 GiB+# (Nemotron 3.5 Bolt) to 2.7 GiB (Qwen3.8 27B); this keeps the thinnest case clear.+_DRAFT_CONTEXT_BYTES = 512 << 20+++def _engine_build(tag: str | None) -> int | None:+ try:+ return int(str(tag).removeprefix("b")) if tag else None+ except ValueError:+ return None+++def _dflash_extra_bytes(entry, profile) -> int:+ """Fixed bytes a one-slot DFlash draft adds beside its target: the draft's weights, a copy of+ the recurrent state per draft position, and the draft's own context."""+ copies = entry.draft_depth + 1+ return entry.draft.size_bytes + profile.recurrent_state_bytes * copies + _DRAFT_CONTEXT_BYTES+++def _runs_dflash(entry) -> Path | None:+ """The entry's DFlash draft on disk, or None."""+ if entry is None or entry.draft is None or entry.draft_spec_type != "draft-dflash":+ return None+ return _asset_path(entry.draft)+++def _dflash_plan(entry, profile, budget: HardwareBudget, live: HardwareBudget | None, *,+ fixed_overhead: int, requested_window: int | None, engine_tag: str | None,+ window_without: int):+ """The launch plan with the entry's DFlash draft in place of MTP, or None.++ The draft runs on one slot: each slot keeps a recurrent-state copy per draft position, and+ the router's default four slots hold enough copies to push weights off the GPU. It may+ shrink the window to half native, never below what the model gets without it when that is+ smaller; a requested (grown) window it can't hold keeps the model as it was.+ """+ if _runs_dflash(entry) is None:+ return None+ build = _engine_build(engine_tag)+ if build is None or build < (_engine_build(entry.draft_min_engine) or 0):+ return None+ lean = replace(profile, kv_scale=1.0)+ 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:+ plan = fit_to_free_memory(plan, lean, live, mtp_capable=False, fixed_overhead=overhead)+ decision = plan.decision+ if isinstance(decision, PhysicsRefusal) or decision.spilled:+ return None+ native = profile.n_ctx_train or decision.window+ if requested_window and decision.window < min(requested_window, native):+ return None+ if decision.window < min(window_without, native // 2):+ return None+ return plan++def preset_for_model(gguf: Path, budget: HardwareBudget,mtp_capable: set[str], *, requested_window: int | None = None,- live: HardwareBudget | None = None) -> PresetEntry | None:+ live: HardwareBudget | None = None,+ engine_tag: str | None = None) -> PresetEntry | None:"""The launch decision for one staged model, or None when its header is unreadable.``budget`` is the card's capacity; ``live`` (from ``hardware.launch_budget``) narrows the- window to what fits beside other programs now.+ window to what fits beside other programs now. ``engine_tag`` is the installed llama.cpp+ release; without it no draft that needs a minimum release runs."""from hermes_cli.local_runtime.catalog import entry_for_modelfrom hermes_cli.local_runtime.growth import load_window_overrides@@ -121,9 +181,9 @@ def preset_for_model(gguf: Path, budget: HardwareBudget,is_mtp = _runs_mtp(entry, companions) if entry is not None else model_id in mtp_capablefixed_overhead = RUNTIME_OVERHEAD_BYTES + companions.nbytes+ requested = load_window_overrides().get(model_id) if requested_window is None else requested_windowplan = plan_launch(profile, budget, mtp_capable=is_mtp, fixed_overhead=fixed_overhead,- requested_window=(load_window_overrides().get(model_id)- if requested_window is None else requested_window))+ requested_window=requested)if live is not None:plan = fit_to_free_memory(plan, profile, live, mtp_capable=is_mtp,fixed_overhead=fixed_overhead)@@ -131,9 +191,15 @@ def preset_for_model(gguf: Path, budget: HardwareBudget,if isinstance(decision, PhysicsRefusal):return PresetEntry(model_id=model_id, window=0, spilled=False, refusal=decision.message)+ dflash = None if decision.spilled else _dflash_plan(+ entry, profile, budget, live, fixed_overhead=fixed_overhead, requested_window=requested,+ engine_tag=engine_tag, window_without=decision.window)+ if dflash is not None:+ plan, decision = dflash, dflash.decision# Router discovery is preset-only: refused files must never autoload with stock fit.keys = _args_to_keys(launch_args(- profile, decision, mtp_capable=is_mtp, uma=budget.uma, mtp_prefill=plan.mtp_prefill,+ profile, decision, mtp_capable=is_mtp and dflash is None, uma=budget.uma,+ mtp_prefill=plan.mtp_prefill,mtp_draft_depth=entry.mtp_draft_depth if entry is not None else 3))keys["model"] = str(gguf)if profile.lazy_bytes:@@ -160,7 +226,13 @@ def preset_for_model(gguf: Path, budget: HardwareBudget,if companions.mtp_head is not None:# The model carries no MTP layers: draft-mtp drafts from the shipped head instead.keys["model-draft"] = str(companions.mtp_head)- draft_path = _asset_path(entry.draft) if decision.spilled else None+ if dflash is not None:+ keys["model-draft"] = str(_runs_dflash(entry))+ keys["spec-type"] = "draft-dflash"+ keys["spec-draft-n-max"] = str(entry.draft_depth)+ keys["parallel"] = "1"+ draft_path = (_asset_path(entry.draft) if decision.spilled+ and entry.draft_spec_type == "draft-dspark" else None)if draft_path is not None and _draft_fits(draft_path, plan.profile, budget, decision.window,plan.overhead_bytes):keys["model-draft"] = str(draft_path)@@ -211,8 +283,10 @@ def _launch_footprint(gguf: Path, budget: HardwareBudget) -> int | None: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(plan.profile, plan.decision.window, overhead_bytes=plan.overhead_bytes)+ # the device, and over-counting errs toward the side that cannot thrash. A DFlash draft on+ # disk counts whether or not this machine runs it, for the same reason.+ draft = _dflash_extra_bytes(entry, profile) if _runs_dflash(entry) is not None else 0+ return footprint_bytes(plan.profile, plan.decision.window, overhead_bytes=plan.overhead_bytes) + draftdef admitted_residency_count(models_dir: Path, budget: HardwareBudget, configured: int) -> int:@@ -245,21 +319,23 @@ def admitted_residency_count(models_dir: Path, budget: HardwareBudget, configuredef plan_presets(models_dir: Path, budget: HardwareBudget, mtp_capable: set[str] | None = None,- *, live: HardwareBudget | None = None) -> list[PresetEntry]:+ *, live: HardwareBudget | None = None,+ engine_tag: str | None = None) -> list[PresetEntry]:"""The launch decision for every staged model; unreadable headers are skipped."""from hermes_cli.local_runtime.bootstrap import staged_in- entries = (preset_for_model(gguf, budget, mtp_capable or set(), live=live)+ entries = (preset_for_model(gguf, budget, mtp_capable or set(), live=live, engine_tag=engine_tag)for gguf in staged_in(models_dir))return [entry for entry in entries if entry is not None]def generate_presets(models_dir: Path, budget: HardwareBudget, preset_path: Path,mtp_capable: set[str] | None = None, *,- live: HardwareBudget | None = None) -> list[PresetEntry]:+ live: HardwareBudget | None = None,+ engine_tag: str | None = None) -> list[PresetEntry]:"""Plan every staged model and write one INI. Refused models get no section (the pickersurfaces the refusal from the returned entries)."""- entries = plan_presets(models_dir, budget, mtp_capable, live=live)+ entries = plan_presets(models_dir, budget, mtp_capable, live=live, engine_tag=engine_tag)write_presets(entries, preset_path)return entriesdiff --git a/hermes_cli/web_routers/local_models.py b/hermes_cli/web_routers/local_models.pyindex 44ad06134ab..8edb177522f 100644--- a/hermes_cli/web_routers/local_models.py+++ b/hermes_cli/web_routers/local_models.py@@ -425,6 +425,26 @@ def _download_plan(entry, variant) -> list:return plan+def _missing_drafts(engine_tag: str) -> list:+ """Download-plan rows for the DFlash drafts of downloaded models that ``engine_tag`` can load+ but that aren't on disk: models downloaded before their draft joined the catalog."""+ staged = set(bootstrap.staged_model_ids())+ build = int(engine_tag.removeprefix("b"))+ plan = []+ for entry in catalog.CATALOG:+ asset = entry.draft+ if asset is None or entry.draft_spec_type != "draft-dflash":+ continue+ if not any(v.model_id in staged for v in entry.variants):+ continue+ if entry.draft_min_engine and build < int(entry.draft_min_engine.removeprefix("b")):+ continue+ dest = bootstrap.assets_dir() / asset.local_name+ if not dest.is_file():+ plan.append((_hf_url(asset.repo or entry.repo, asset.path, asset.revision), dest, asset.size_bytes))+ return plan++def _run_download_plan(job: dict[str, Any], plan: list, label: str) -> None:"""The downloader counts completed files and every part of this plan."""_step(job, "downloading", f"Downloading {label}")@@ -564,11 +584,17 @@ _QUANT_REASONS = {_QUANT_REASON_COMPACT = "Compact build sized for this machine ({quant}) — larger than GPU memory, runs slower"+def _installed(entry, variant) -> bool:+ """Every file the variant needs is on disk. The draft is optional: a model downloaded before+ its draft joined the catalog stays downloaded."""+ return all(((bootstrap.models_dir() if f in variant.files else bootstrap.assets_dir())+ / f.local_name).is_file() for f in entry.install_files(variant))++def _catalog_row(entry, budget, recommended, recommended_reason, staged_ids) -> dict[str, Any]:choice = catalog.select_variant(entry, budget)# Any variant of this family on disk counts as downloaded.- dl = next((v for v in entry.variants if v.model_id in staged_ids- and all(dest.is_file() for _, dest, _ in _download_plan(entry, v))), None)+ dl = next((v for v in entry.variants if v.model_id in staged_ids and _installed(entry, v)), None)row: dict[str, Any] = {"id": entry.id, "display_name": entry.display_name, "description": entry.description,"native_context": entry.n_ctx_train, "native_context_label": _k_label(entry.n_ctx_train),@@ -668,9 +694,14 @@ def local_models_runtime_install(body: RuntimeInstallBody, profile: Optional[strwith _config_profile_scope(profile):previous = binaries.installed_engine(backend)engine = _install_engine_job(job, backend)+ drafts = _missing_drafts(engine.tag)+ if drafts:+ _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:- _step(job, "restarting", "Switching the running server to the pinned build")+ if running is not None and (previous != engine or drafts):+ _step(job, "restarting", "Switching the running server to the pinned build"+ if previous != engine else "Restarting the local server")bootstrap.refresh_local_runtime()_finish(job, f"llama.cpp {tag} ready ({backend})")diff --git a/tests/hermes_cli/test_local_external_draft.py b/tests/hermes_cli/test_local_external_draft.pynew file mode 100644index 00000000000..5f614e33242--- /dev/null+++ b/tests/hermes_cli/test_local_external_draft.py@@ -0,0 +1,219 @@+"""An external DFlash draft on a recurrent model: replaces MTP when it fits, on one slot.++Speculative decoding keeps one copy of a recurrent model's state per slot per draft position, so a+depth-7 draft on the router's four slots holds 32 copies (4.7 GiB on Qwen3.8 27B, enough for+llama.cpp's fit to push weights to host memory on Nemotron 3.5 Bolt). One slot holds 8. The draft+is optional: a missing file or an older engine leaves the model on its own MTP heads.+"""++from __future__ import annotations++from dataclasses import replace+from types import SimpleNamespace++import pytest++from hermes_cli.local_runtime import bootstrap, catalog, presets+from hermes_cli.local_runtime.catalog import AssetFile, CatalogEntry, QuantVariant+from hermes_cli.local_runtime.estimator import HardwareBudget+from tests.hermes_cli import test_local_download_jobs+from tests.hermes_cli.test_local_download_jobs import poll++client = test_local_download_jobs.client # the download-jobs app, for this file's route tests++GIB = 1 << 30+MIB = 1 << 20+NATIVE = 262144+BUILD = QuantVariant(quant="Q4_K_M", files=(AssetFile("Hybrid-Q4_K_M.gguf", 16 * GIB),))+ENTRY = CatalogEntry(+ id="hybrid", display_name="Hybrid", description="", repo="org/Hybrid-GGUF", variants=(BUILD,),+ n_ctx_train=NATIVE, full_layers=16, recurrent_layers=48, per_layer_f16=4096, mtp=True,+ n_vocab=248320, mtp_draft_depth=2,+ draft=AssetFile("Hybrid-DFlash.gguf", GIB, repo="lab/Hybrid-DFlash-GGUF", revision="0123abc"),+ draft_spec_type="draft-dflash", draft_depth=7, draft_min_engine="b11370")+ROOMY = HardwareBudget(usable_vram_bytes=int(128 * GIB * 0.8), total_device_bytes=128 * GIB,+ ram_available_bytes=0, uma=True)+++def model(tmp_path, monkeypatch):+ """A staged hybrid model; returns (gguf path, draft path, setter for the active entry)."""+ active = {"entry": ENTRY, "state": 150 * MIB}+ monkeypatch.setattr(catalog, "entry_for_model",+ lambda model_id: active["entry"] if model_id == BUILD.model_id else None)+ monkeypatch.setattr(presets, "read_gguf_header", lambda p: SimpleNamespace(sampling_defaults={}))+ monkeypatch.setattr(presets, "profile_from_gguf", lambda h: replace(+ active["entry"].profile(BUILD), kv_scale=1.0, recurrent_state_bytes=active["state"]))+ draft = bootstrap.assets_dir() / ENTRY.draft.local_name+ draft.parent.mkdir(parents=True, exist_ok=True)+ draft.touch()++ def use(entry=None, *, state=None):+ active["entry"] = entry or active["entry"]+ active["state"] = active["state"] if state is None else state+ return tmp_path / f"{BUILD.model_id}.gguf", draft, use+++def _discrete(gib: float) -> HardwareBudget:+ return HardwareBudget(usable_vram_bytes=int(gib * GIB), total_device_bytes=int(gib * GIB),+ ram_available_bytes=64 * GIB)+++def _drafts(preset) -> bool:+ return preset.keys.get("spec-type") == "draft-dflash"+++def test_the_draft_replaces_mtp_on_one_slot_when_it_fits(model):+ gguf, draft, _ = model++ preset = presets.preset_for_model(gguf, ROOMY, set(), engine_tag="b11671")++ assert preset.window == NATIVE and not preset.spilled+ assert preset.keys["spec-type"] == "draft-dflash"+ assert preset.keys["spec-draft-n-max"] == "7"+ assert preset.keys["model-draft"] == str(draft)+ assert preset.keys["parallel"] == "1"+++def test_a_missing_draft_or_an_older_engine_keeps_mtp(model):+ gguf, draft, _ = model++ for tag in (None, "b11000"):+ preset = presets.preset_for_model(gguf, ROOMY, set(), engine_tag=tag)+ assert preset.keys["spec-type"] == "draft-mtp" and "parallel" not in preset.keys+ draft.unlink()+ preset = presets.preset_for_model(gguf, ROOMY, set(), engine_tag="b11671")+ assert preset.keys["spec-type"] == "draft-mtp" and "model-draft" not in preset.keys+++def test_the_draft_may_shrink_the_window_to_half_native_and_no_further(model):+ """Each budget either keeps the MTP preset exactly, or drafts resident at no less than the+ smaller of the MTP window and half the native window. Growth past it drops the draft."""+ gguf, _, _ = model+ shrank = declined_with_room = 0+ for tenths in range(160, 400, 2):+ budget = _discrete(tenths / 10)+ mtp = presets.preset_for_model(gguf, budget, set())+ preset = presets.preset_for_model(gguf, budget, set(), engine_tag="b11671")+ if mtp.refusal:+ continue+ if _drafts(preset):+ assert not preset.spilled+ assert preset.window >= min(mtp.window, NATIVE // 2)+ assert preset.keys["parallel"] == "1"+ shrank += preset.window < mtp.window+ else:+ assert preset == mtp+ declined_with_room += not mtp.spilled+ assert shrank and declined_with_room+++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."""+ gguf, _, _ = model+ live = next(b for b in (_discrete(t / 10) for t in range(160, 400, 2))+ if _drafts(p := presets.preset_for_model(gguf, b, set(), engine_tag="b11671"))+ and p.window < presets.preset_for_model(gguf, b, set()).window)+ mtp = presets.preset_for_model(gguf, ROOMY, set(), requested_window=NATIVE, live=live)++ grown = presets.preset_for_model(gguf, ROOMY, set(), requested_window=NATIVE, live=live,+ engine_tag="b11671")++ assert grown == mtp and grown.keys["spec-type"] == "draft-mtp"+++def test_each_draft_position_prices_a_copy_of_the_recurrent_state(model):+ """The same card that fits the draft beside 150 MiB of state per copy declines it at 1 GiB+ per copy: eight copies are 7 GiB more."""+ gguf, _, use = model+ budget = _discrete(32)+ assert _drafts(presets.preset_for_model(gguf, budget, set(), engine_tag="b11671"))++ use(state=GIB)++ assert not _drafts(presets.preset_for_model(gguf, budget, set(), engine_tag="b11671"))+++def test_a_spilled_model_never_takes_the_draft(model):+ gguf, _, _ = model++ preset = presets.preset_for_model(gguf, _discrete(12), set(), engine_tag="b11671")++ assert preset.spilled and not _drafts(preset)+++def test_a_model_without_mtp_drafts_without_backend_sampling(model):+ """Bolt's shape: no MTP heads, so nothing to replace and no backend sampling to keep."""+ gguf, _, use = model+ use(replace(ENTRY, mtp=False, draft_min_engine="b11671"))++ preset = presets.preset_for_model(gguf, ROOMY, set(), engine_tag="b11671")++ assert _drafts(preset) and preset.keys["parallel"] == "1"+ assert "backend-sampling" not in preset.keys+++def test_the_residency_price_includes_the_draft_once_it_is_on_disk(model):+ gguf, draft, _ = model+ with_draft = presets._launch_footprint(gguf, ROOMY)+ draft.unlink()++ assert with_draft >= presets._launch_footprint(gguf, ROOMY) + ENTRY.draft.size_bytes+++def _staged(monkeypatch, *entries):+ from hermes_cli.web_routers import local_models as lm++ monkeypatch.setattr(lm.catalog, "CATALOG", entries)+ monkeypatch.setattr(lm.bootstrap, "staged_model_ids", lambda: [e.variants[0].model_id for e in entries])+ return lm+++def test_installed_models_missing_their_draft_get_it_from_the_engine_update(monkeypatch):+ """A Spark that downloaded the 27B before its draft joined the catalog: the update the app+ already offers fetches the draft. Models not on disk, drafts already on disk, and drafts the+ engine can't load are left alone."""+ unstaged = replace(ENTRY, id="other", variants=(replace(BUILD, files=(AssetFile("Other.gguf", GIB),)),))+ newer = replace(ENTRY, id="newer", variants=(replace(BUILD, files=(AssetFile("Newer.gguf", GIB),)),),+ draft=AssetFile("Newer-DFlash.gguf", GIB), draft_min_engine="b99999")+ lm = _staged(monkeypatch, ENTRY, newer)+ monkeypatch.setattr(lm.catalog, "CATALOG", (ENTRY, newer, unstaged))+ dest = lm.bootstrap.assets_dir() / ENTRY.draft.local_name++ plan = lm._missing_drafts("b11671")++ assert plan == [("https://huggingface.co/lab/Hybrid-DFlash-GGUF/resolve/0123abc/Hybrid-DFlash.gguf",+ dest, GIB)]+ dest.parent.mkdir(parents=True, exist_ok=True)+ dest.touch()+ assert lm._missing_drafts("b11671") == []+++def test_the_update_job_downloads_missing_drafts_then_restarts_the_server(client, monkeypatch):+ 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)+ fetched, events = [], []+ monkeypatch.setattr(lm, "_download_job", lambda job, plan: fetched.extend(plan))+ monkeypatch.setattr(lm.bootstrap, "get_supervisor", lambda: object())+ monkeypatch.setattr(lm.bootstrap, "refresh_local_runtime", lambda: events.append("restart"))++ 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 [dest.name for _, dest, _ in fetched] == [ENTRY.draft.local_name]+ 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+ model.parent.mkdir(parents=True, exist_ok=True)+ model.touch()++ row = lm._catalog_row(ENTRY, ROOMY, None, None, {BUILD.model_id})++ assert row["downloaded"] and row["size_bytes"] == ENTRY.download_bytes(BUILD)diff --git a/tests/hermes_cli/test_local_launch_budget.py b/tests/hermes_cli/test_local_launch_budget.pyindex 037cec796c7..42640769af9 100644--- a/tests/hermes_cli/test_local_launch_budget.py+++ b/tests/hermes_cli/test_local_launch_budget.py@@ -261,6 +261,28 @@ def test_idle_router_gets_windows_for_the_current_desktop(hermes_home, monkeypatassert bootstrap.refit_idle_presets(router) is False and router.reloads == 1+def test_a_replan_keeps_the_draft_the_serving_engine_loads(hermes_home, monkeypatch, capacity_probe):+ """The idle re-plan decides for the engine the server runs, as boot did: a staged DFlash draft+ stays in the preset, not the MTP fallback an unknown engine gets."""+ from hermes_cli.local_runtime import bootstrap, catalog++ mdir, _gguf = _stage_27b(hermes_home, monkeypatch)+ draft = catalog.catalog_by_id()["qwen3.8-27b"].draft+ (bootstrap.assets_dir() / draft.local_name).touch()+ engine = SimpleNamespace(tag="b11671")+ monkeypatch.setattr(bootstrap, "_SERVING_ENGINE", engine)+ _card(monkeypatch, 2.0)+ path = hermes_home / "presets.ini"+ bootstrap._generate_presets(mdir, path, engine.tag)+ assert "spec-type = draft-dflash" in path.read_text(encoding="utf-8")++ _card(monkeypatch, 0.0) # the user closed the heavy apps+ bootstrap.refit_idle_presets(_Router(path, {MODEL_ID: "unloaded"}))++ text = path.read_text(encoding="utf-8")+ assert "spec-type = draft-dflash" in text and "parallel = 1" in text++@pytest.mark.parametrize("status", ["loaded", "loading", "sleeping"])def test_never_rewrites_while_a_model_holds_memory(hermes_home, monkeypatch, capacity_probe, status):"""The router unloads a loaded model whose launch flags change on reload."""diff --git a/tests/hermes_cli/test_local_preset_admission.py b/tests/hermes_cli/test_local_preset_admission.pyindex 4e8cf34f545..f448977bc9c 100644--- a/tests/hermes_cli/test_local_preset_admission.py+++ b/tests/hermes_cli/test_local_preset_admission.py@@ -35,7 +35,7 @@ def test_optional_draft_is_enabled_only_with_room_at_the_selected_window(tmp_patfrom hermes_cli.local_runtime import bootstrap, catalogmonkeypatch.setenv("HERMES_HOME", str(tmp_path))- entry = next(e for e in catalog.CATALOG if e.draft)+ entry = next(e for e in catalog.CATALOG if e.draft and e.draft_spec_type == "draft-dspark")main = tmp_path / f"{entry.variants[0].model_id}.gguf"draft = bootstrap.assets_dir() / entry.draft.local_namedraft.parent.mkdir(parents=True, exist_ok=True)diff --git a/tests/hermes_cli/test_local_residency_admission.py b/tests/hermes_cli/test_local_residency_admission.pyindex dcf5ffc68cf..41b6e8c43cb 100644--- a/tests/hermes_cli/test_local_residency_admission.py+++ b/tests/hermes_cli/test_local_residency_admission.py@@ -83,7 +83,7 @@ def test_boot_hands_the_router_the_derived_cap(tmp_path, monkeypatch, configuredmonkeypatch.setattr(bs, "models_dir", lambda: mdir)monkeypatch.setattr(hardware, "probe_budget", probe)monkeypatch.setattr(bs, "_SUPERVISOR", None)- monkeypatch.setattr(bs, "_generate_presets", lambda mdir, preset_path: None)+ monkeypatch.setattr(bs, "_generate_presets", lambda mdir, preset_path, engine_tag=None: None)monkeypatch.setattr(bs, "_detect_gpu_vendor", lambda: None)monkeypatch.setattr(binaries, "installed_engine",lambda backend="auto", **k: binaries.Engine("cpu", "build-1", tmp_path / "install" / "llama-server"))diff --git a/tests/hermes_cli/test_local_runtime.py b/tests/hermes_cli/test_local_runtime.pyindex 4f12e1d6d5d..d9c7af97347 100644--- a/tests/hermes_cli/test_local_runtime.py+++ b/tests/hermes_cli/test_local_runtime.py@@ -1004,8 +1004,8 @@ def test_boot_prices_the_engine_it_serves(tmp_path, monkeypatch):monkeypatch.setattr("hermes_cli.config.load_config_readonly",lambda: {"local_runtime": {"backend": "cpu"}}) # another profile's configpriced: list = []- monkeypatch.setattr(bootstrap, "_generate_presets",- lambda mdir, path: priced.append(hardware._configured_engine()) or path)+ monkeypatch.setattr(bootstrap, "_generate_presets", lambda mdir, path, engine_tag=None: priced.append(+ (hardware._configured_engine(), engine_tag)) or path)monkeypatch.setattr(bootstrap, "_admitted_models_max", lambda mdir, configured: configured)class _NoStart:@@ -1021,5 +1021,6 @@ def test_boot_prices_the_engine_it_serves(tmp_path, monkeypatch):monkeypatch.setattr("hermes_cli.local_runtime.supervisor.LlamaServerSupervisor", _NoStart)assert bootstrap.ensure_local_runtime({"local_runtime": {"enabled": True, "backend": "vulkan"}}) is None- assert priced == [vulkan]+ # The release reaches the presets too: drafts gate on the engine that will load them.+ assert priced == [(vulkan, "b1")]assert bootstrap.serving_engine() is None # a failed boot serves nothing