Skip to content

The agent that grows with you

refactor(local_runtime): unify split-GGUF id/scan helpers (gguf.model_id_from_stem, bootstrap.staged_in, binaries.manifest_verified); split generate_presets into per-model phases; drop dead /health probe in _state_endpoint (pid was already the sole verdict)

Teknium0244f7fa7ead
diff --git a/hermes_cli/local_runtime/binaries.py b/hermes_cli/local_runtime/binaries.py
index ea67131e2e6..ce83ef39952 100644
--- a/hermes_cli/local_runtime/binaries.py
+++ b/hermes_cli/local_runtime/binaries.py
@@ -19,20 +19,16 @@ logger = logging.getLogger(__name__)
RELEASE_URL = "https://github.com/ggml-org/llama.cpp/releases/download/{tag}/{asset}"
-# Windows CUDA zips ship per CUDA major; the runtime zip must be paired with
-# its cudart zip so end users need no toolkit. 13.3 verified on 13.1 and
-# 13.2 drivers.
+# Windows CUDA zips ship per CUDA major; the runtime zip must be paired with its cudart zip so
+# end users need no toolkit. 13.3 verified on 13.1 and 13.2 drivers.
_WIN_CUDA_VERSION = "13.3"
-# arm64 Windows CUDA prebuilts landed upstream (~b1036x) on CUDA 13.4 —
-# verified against live asset lists (b10362, b10630, b10679). Tags at or before
-# b10290 don't have them; resolution succeeds and the download 404s
-# honestly on such tags, which only arises if a user pins backward.
+# arm64 Windows CUDA prebuilts landed upstream (~b1036x) on CUDA 13.4. Tags at or before b10290
+# don't have them; resolution succeeds and the download 404s honestly if a user pins backward.
_WIN_CUDA_VERSION_ARM64 = "13.4"
-# Fallback when the config section is missing entirely (deep-merge normally
-# guarantees the key). Single source: DEFAULT_CONFIG owns the shipped tag.
def default_tag() -> str:
+ """Fallback when the config section is missing entirely; DEFAULT_CONFIG owns the shipped tag."""
from hermes_cli.config_defaults import DEFAULT_CONFIG
return DEFAULT_CONFIG["local_runtime"]["tag"]
@@ -56,48 +52,46 @@ class AssetPlan:
def runtimes_root() -> Path:
- """Machine-scoped, deliberately NOT profile-scoped. Engine binaries, presets, and server state
+ """Machine-scoped, deliberately NOT profile-scoped: engine binaries, presets and server state
describe this machine's hardware and its one managed server (stable port) — a second profile
re-downloading the engine or fighting over the port would be the bug. Profile-scoped things
- (which model is the default, enabled) live in each profile's config.yaml as ever.
- """
+ (default model, enabled) live in each profile's config.yaml."""
from hermes_constants import get_default_hermes_root
return get_default_hermes_root() / "runtimes" / "llamacpp"
+def manifest_verified(manifest: Path) -> bool:
+ """True when an install manifest records a verified_version (missing/damaged -> False)."""
+ try:
+ return bool(json.loads(manifest.read_text(encoding="utf-8")).get("verified_version"))
+ except (json.JSONDecodeError, OSError):
+ return False
+
+
+def _release_number(tag: str) -> int:
+ digits = "".join(ch for ch in tag if ch.isdigit())
+ return int(digits) if digits else 0
+
+
def installed_tags() -> list[str]:
- """Tags with a verified install (manifest carries verified_version),
- newest first by release number. The boot ladder and the update check
- both read installed-ness from here — one resolver, every caller."""
+ """Tags with a verified install, newest first by release number. The boot ladder and the
+ update check both read installed-ness from here — one resolver, every caller."""
root = runtimes_root()
if not root.exists():
return []
- found: list[str] = []
- for entry in root.iterdir():
- if not entry.is_dir() or entry.name == "downloads":
- continue
- for manifest in entry.glob("*/manifest.json"):
- try:
- if json.loads(manifest.read_text(encoding="utf-8")).get("verified_version"):
- found.append(entry.name)
- break
- except (json.JSONDecodeError, OSError):
- continue
-
- def _release_number(tag: str) -> int:
- digits = "".join(ch for ch in tag if ch.isdigit())
- return int(digits) if digits else 0
-
- return sorted(set(found), key=_release_number, reverse=True)
+ found = {entry.name for entry in root.iterdir()
+ if entry.is_dir() and entry.name != "downloads"
+ and any(manifest_verified(m) for m in entry.glob("*/manifest.json"))}
+ return sorted(found, key=_release_number, reverse=True)
def _host_os_arch() -> tuple[str, str]:
"""(os, arch) normalized to release-asset vocabulary.
- PITFALL: PROCESSOR_ARCHITECTURE lies under x64 emulation on ARM64 Windows. platform.machine()
- reads the same env on some Pythons, so on Windows prefer PROCESSOR_IDENTIFIER's text when
- present.
+ PITFALL: PROCESSOR_ARCHITECTURE lies under x64 emulation on ARM64 Windows, and
+ platform.machine() reads the same env on some Pythons — so on Windows prefer
+ PROCESSOR_IDENTIFIER's text when present.
"""
system = platform.system().lower()
os_name = {"windows": "win", "darwin": "macos", "linux": "ubuntu"}.get(system, system)
@@ -112,9 +106,8 @@ def _host_os_arch() -> tuple[str, str]:
def select_backend(gpu_vendor: str | None, os_name: str | None = None) -> str:
- """Backend choice per design: CUDA if NVIDIA, Metal on macOS, Vulkan if
- a non-NVIDIA GPU is present, else CPU. ``--list-devices`` validates the
- choice post-install; the supervisor's touch generation is ground truth."""
+ """CUDA if NVIDIA, Metal on macOS, Vulkan if a non-NVIDIA GPU is present, else CPU.
+ ``--list-devices`` validates post-install; the supervisor's touch generation is ground truth."""
if os_name is None:
os_name, _ = _host_os_arch()
if os_name == "macos":
@@ -127,8 +120,8 @@ def select_backend(gpu_vendor: str | None, os_name: str | None = None) -> str:
return "cpu"
-# Per-OS (human label, {backend: asset-name templates}). Windows CUDA pairs the
-# runtime zip with its cudart zip; ubuntu ships tarballs, win ships zips.
+# Per-OS (human label, {backend: asset-name templates}). Windows CUDA pairs the runtime zip with
+# its cudart zip; ubuntu ships tarballs, win ships zips.
_ASSET_TEMPLATES = {
"ubuntu": ("linux", {
"vulkan": ["llama-{tag}-bin-ubuntu-vulkan-{arch}.tar.gz"],
@@ -147,11 +140,8 @@ _ASSET_TEMPLATES = {
def resolve_assets(tag: str, backend: str, os_name: str | None = None,
arch: str | None = None) -> AssetPlan:
- """Compose the asset list for (tag, backend, platform).
-
- Raises BinaryResolutionError for platform/backend pairs the release ships no artifact for;
- callers fall back down the backend ladder cuda -> vulkan -> cpu.
- """
+ """Compose the asset list for (tag, backend, platform). Raises BinaryResolutionError for pairs
+ the release ships no artifact for; callers fall back down the ladder cuda -> vulkan -> cpu."""
host_os, host_arch = _host_os_arch()
os_name = os_name or host_os
arch = arch or host_arch
@@ -161,8 +151,8 @@ def resolve_assets(tag: str, backend: str, os_name: str | None = None,
if os_name not in _ASSET_TEMPLATES:
raise BinaryResolutionError(f"unsupported platform {os_name}-{arch}")
if os_name == "ubuntu" and backend == "cuda":
- # No prebuilt Linux CUDA zips at current tags — Linux CUDA users
- # build from source or use vulkan; resolver is honest about it.
+ # No prebuilt Linux CUDA zips at current tags — Linux CUDA users build from source or
+ # use vulkan; the resolver is honest about it.
raise BinaryResolutionError(
f"no prebuilt linux CUDA asset at {tag}; use vulkan/cpu or a source build")
if os_name == "win" and backend == "vulkan" and arch == "arm64":
@@ -185,9 +175,8 @@ def _sha256(path: Path) -> str:
def _download(url: str, dest: Path,
progress: "Callable[[int, int], None] | None" = None) -> None:
- """Stream url -> dest. ``progress(done_bytes, total_bytes)`` ticks per
- chunk (total 0 when the server sends no Content-Length) — a several-
- hundred-MB archive on a slow line must never look hung."""
+ """Stream url -> dest. ``progress(done_bytes, total_bytes)`` ticks per chunk (total 0 when
+ the server sends no Content-Length) — a several-hundred-MB archive must never look hung."""
logger.info("downloading %s", url)
tmp = dest.with_suffix(dest.suffix + ".part")
with urllib.request.urlopen(url, timeout=120) as r, open(tmp, "wb") as f:
@@ -206,8 +195,7 @@ def _download(url: str, dest: Path,
def _extract(archive: Path, dest: Path,
progress: "Callable[[int, int], None] | None" = None) -> None:
- """Extract member by member so ``progress(done, total)`` can tick in
- uncompressed bytes — big archives take real time on laptop disks."""
+ """Extract member by member so ``progress(done, total)`` can tick in uncompressed bytes."""
if archive.name.endswith(".zip"):
opener, list_members, size = zipfile.ZipFile, "infolist", "file_size"
kwargs = {}
@@ -227,8 +215,8 @@ def _extract(archive: Path, dest: Path,
def server_binary(install_dir: Path) -> Path:
- """Locate llama-server within an extracted runtime (zips differ in
- whether they nest a build/bin directory)."""
+ """Locate llama-server within an extracted runtime (zips differ in whether they nest a
+ build/bin directory)."""
names = ("llama-server.exe", "llama-server")
for name in names:
direct = install_dir / name
@@ -242,8 +230,7 @@ def server_binary(install_dir: Path) -> Path:
def verify_install(install_dir: Path, tag: str) -> str:
- """Run --version; require the tag's build number in the output.
- (The binary prints the tag WITHOUT the 'b' prefix.)"""
+ """Run --version; require the tag's build number in the output (printed WITHOUT the 'b')."""
exe = server_binary(install_dir)
out = subprocess.run([str(exe), "--version"], capture_output=True,
text=True, encoding="utf-8", errors="replace",
@@ -256,8 +243,8 @@ def verify_install(install_dir: Path, tag: str) -> str:
def prune_old_tags(keep: list[str]) -> None:
- """Retain only the tags in ``keep`` (current + previous — N-1 rollback).
- The shared ``downloads/`` archive cache is not a tag and always survives."""
+ """Retain only the tags in ``keep`` (current + previous — N-1 rollback). The shared
+ ``downloads/`` archive cache is not a tag and always survives."""
root = runtimes_root()
if not root.exists():
return
@@ -270,28 +257,28 @@ def prune_old_tags(keep: list[str]) -> None:
def ensure_runtime_installed(tag: str, backend: str,
expected_sha256: dict[str, str] | None = None,
progress: "Callable[[str, int, int, str], None] | None" = None) -> Path:
- """Idempotent: resolve, download, verify, extract, version-check.
+ """Idempotent: resolve, download, verify, extract, version-check. Returns the install dir.
- ``expected_sha256`` pins hashes per asset when the catalog has them; without pins the computed
- hash is recorded in the manifest (trust on first download, verified on every reinstall).
- ``progress(stage, done, total, label)`` ticks through download/extract/verify. Returns the
- install dir containing llama-server.
+ ``expected_sha256`` pins hashes per asset; without pins the computed hash is recorded in the
+ manifest (trust on first download, verified on every reinstall). ``progress(stage, done,
+ total, label)`` ticks through download/extract/verify.
"""
plan = resolve_assets(tag, backend)
install_dir = plan.install_dir
manifest_path = install_dir / "manifest.json"
- if manifest_path.exists():
- try:
- manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
- if manifest.get("verified_version"):
- return install_dir
- except (json.JSONDecodeError, OSError):
- pass # damaged manifest -> reinstall
+ if manifest_verified(manifest_path):
+ return install_dir
install_dir.mkdir(parents=True, exist_ok=True)
downloads = runtimes_root() / "downloads"
downloads.mkdir(parents=True, exist_ok=True)
+ def stage_progress(stage: str, label: str):
+ if progress is None:
+ return None
+ tick = progress
+ return lambda d, t: tick(stage, d, t, label)
+
recorded: dict[str, str] = {}
n_assets = len(plan.assets)
for i, asset in enumerate(plan.assets, 1):
@@ -299,8 +286,7 @@ def ensure_runtime_installed(tag: str, backend: str,
archive = downloads / asset
if not archive.exists():
_download(RELEASE_URL.format(tag=tag, asset=asset), archive,
- progress=(lambda d, t, _l=label: progress("download", d, t, _l))
- if progress is not None else None)
+ progress=stage_progress("download", label))
if progress is not None:
progress("verify", 0, 0, label)
digest = _sha256(archive)
@@ -310,9 +296,7 @@ def ensure_runtime_installed(tag: str, backend: str,
raise BinaryResolutionError(
f"sha256 mismatch for {asset}: expected {expected}, got {digest}")
recorded[asset] = digest
- _extract(archive, install_dir,
- progress=(lambda d, t, _l=label: progress("extract", d, t, _l))
- if progress is not None else None)
+ _extract(archive, install_dir, progress=stage_progress("extract", label))
if progress is not None:
progress("verify", 0, 0, "")
diff --git a/hermes_cli/local_runtime/bootstrap.py b/hermes_cli/local_runtime/bootstrap.py
index d204b48ee38..a08fbeb43cc 100644
--- a/hermes_cli/local_runtime/bootstrap.py
+++ b/hermes_cli/local_runtime/bootstrap.py
@@ -1,8 +1,7 @@
"""Bootstrap for the managed runtime: config -> installed binaries -> running supervised server.
-One public call, ``ensure_local_runtime(config)``, safe to call at any session start: - disabled or
-already-running (state file answers /health) -> no-op - enabled -> install binaries if missing
-(idempotent), spawn supervisor
+One public call, ``ensure_local_runtime(config)``, safe at any session start: disabled or
+already-running -> no-op; enabled -> install binaries if missing (idempotent), spawn supervisor.
Kept import-light: callers gate on config before importing this module so sessions with
local_runtime disabled never pay the import.
@@ -12,13 +11,13 @@ from __future__ import annotations
import logging
import os
-import re
import signal
import subprocess
import time
from pathlib import Path
from hermes_cli.local_runtime.binaries import runtimes_root
+from hermes_cli.local_runtime.gguf import SPLIT_PART_RE, model_id_from_stem
logger = logging.getLogger(__name__)
@@ -26,10 +25,9 @@ _SUPERVISOR = None # process-wide singleton; one router per Hermes process
def _detect_gpu_vendor() -> str | None:
- """Best-effort GPU vendor for backend selection. NVIDIA via nvidia-smi (resolved by the hardware
- probe's PATH-independent ladder — a stripped service PATH must not demote an NVIDIA box to
- vulkan/cpu); anything else defers to select_backend's fallback ladder.
- """
+ """Best-effort GPU vendor for backend selection. NVIDIA via nvidia-smi resolved by the hardware
+ probe's PATH-independent ladder (a stripped service PATH must not demote an NVIDIA box to
+ vulkan/cpu); anything else defers to select_backend's fallback ladder."""
from hermes_cli.local_runtime.hardware import _nvidia_smi_path
smi = _nvidia_smi_path()
@@ -47,52 +45,52 @@ def _detect_gpu_vendor() -> str | None:
def models_dir() -> Path:
- """Machine-scoped, deliberately NOT profile-scoped: a 20 GB GGUF is a
- machine asset, and every profile shares the one managed server that
- serves it. See runtimes_root() for the same rule on the engine."""
+ """Machine-scoped, deliberately NOT profile-scoped: a 20 GB GGUF is a machine asset, and every
+ profile shares the one managed server that serves it (same rule as runtimes_root())."""
from hermes_constants import get_default_hermes_root
return get_default_hermes_root() / "models"
def assets_dir() -> Path:
- """Non-model companion files (mmproj vision projectors, spec-decode
- draft models). A subdirectory so the router's model listing — and our
- staged_models() — never mistakes an asset for a servable model."""
+ """Non-model companion files (mmproj projectors, spec-decode drafts). A subdirectory so the
+ router's model listing — and staged_models() — never mistakes an asset for a servable model."""
return models_dir() / "assets"
-def staged_models() -> "list[Path]":
- """Servable staged models: single-file GGUFs count when present; a split GGUF counts once, by its
- first part, and only when EVERY part is on disk — a mid-download split is not servable and must
- not surface anywhere as a model. Continuation parts and assets/ never count.
- """
- part = re.compile(r"-(\d{5})-of-(\d{5})\.gguf$")
- files = sorted(models_dir().glob("*.gguf"))
+def staged_in(models_dir: Path, *, require_complete: bool = True) -> "list[Path]":
+ """Servable GGUFs in a directory: single files, plus split GGUFs once by their first part.
+ With ``require_complete`` a split counts only when EVERY part is on disk — a mid-download split
+ is not servable and must not surface anywhere as a model."""
+ files = sorted(models_dir.glob("*.gguf"))
names = {p.name for p in files}
out = []
for p in files:
- m = part.search(p.name)
+ m = SPLIT_PART_RE.search(p.name)
if m is None:
out.append(p)
continue
if m.group(1) != "00001":
continue
- stem = p.name[: m.start()]
- total = int(m.group(2))
- if all(f"{stem}-{i:05d}-of-{m.group(2)}.gguf" in names
- for i in range(2, total + 1)):
+ stem, total = p.name[: m.start()], int(m.group(2))
+ if not require_complete or all(f"{stem}-{i:05d}-of-{m.group(2)}.gguf" in names
+ for i in range(2, total + 1)):
out.append(p)
return out
+def staged_models() -> "list[Path]":
+ """Servable staged models (continuation parts, incomplete splits and assets/ never count)."""
+ return staged_in(models_dir())
+
+
def staged_model_ids() -> "list[str]":
- return [re.sub(r"-\d{5}-of-\d{5}$", "", p.stem) for p in staged_models()]
+ return [model_id_from_stem(p.stem) for p in staged_models()]
def _presets_stale() -> bool:
- """True when a staged model has no section in the preset INI — it
- would autoload with stock fit instead of a policy decision."""
+ """True when a staged model has no section in the preset INI — it would autoload with stock
+ fit instead of a policy decision."""
try:
from hermes_cli.local_runtime.presets import read_preset_decisions
@@ -104,8 +102,8 @@ def _presets_stale() -> bool:
def _stop_state_server(state: dict) -> None:
"""Best-effort stop of the server the state file points at (an incumbent this process doesn't
- supervise). The state pid is ours by contract — the file only ever describes the managed server.
- """
+ supervise). The state pid is ours by contract — the file only ever describes the managed
+ server."""
from hermes_cli.local_runtime.endpoint import _pid_alive
try:
@@ -118,9 +116,8 @@ def _stop_state_server(state: dict) -> None:
os.kill(pid, signal.SIGTERM)
except (OSError, ValueError):
return
- # Give it a moment to release the port and the GPU. Liveness via
- # psutil — on Windows os.kill(pid, 0) TERMINATES the process, it is
- # not a probe (the endpoint.py pitfall note; #local-models review).
+ # Give it a moment to release the port and the GPU. Liveness via psutil — on Windows
+ # os.kill(pid, 0) TERMINATES the process, it is not a probe.
for _ in range(50):
if not _pid_alive(pid):
return
@@ -128,12 +125,9 @@ def _stop_state_server(state: dict) -> None:
def refresh_local_runtime() -> bool:
- """Restart the managed server so it rescans the models directory.
-
- The router's model list is SPAWN-ONLY: a GGUF added after start is invisible to GET /models and
- 400s on completion, so anything that changes the staged set while the server runs must bounce
- it.
- """
+ """Restart the managed server so it rescans the models directory. The router's model list is
+ SPAWN-ONLY: a GGUF added after start is invisible to GET /models and 400s on completion, so
+ anything that changes the staged set while the server runs must bounce it."""
global _SUPERVISOR
try:
from hermes_cli.config import load_config
@@ -155,11 +149,41 @@ def refresh_local_runtime() -> bool:
return False
+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.
+
+ Priced against CAPACITY, not live free VRAM: this runs while the outgoing server instance may
+ still hold the card (restart, refresh after a download), and its memory is freed before the new
+ instance loads anything. Pricing against live-free once pinned a fitting model's weights to CPU.
+
+ Degradation ladder on failure: a STALE policy still beats no policy — stock fit (f16 KV at max
+ context, no placement) is the silent-busy-wait failure on Windows. Keep serving with the
+ previous INI when one exists; only a first boot with no INI at all falls to stock fit.
+ """
+ from hermes_cli.local_runtime.hardware import probe_budget
+ from hermes_cli.local_runtime.presets import generate_presets
+
+ try:
+ for entry in generate_presets(mdir, probe_budget(planning=True), preset_path):
+ if entry.refusal:
+ logger.warning("model refused by physics check: %s", entry.refusal)
+ return preset_path
+ except Exception as exc: # noqa: BLE001 — policy failure must not block serving
+ if preset_path.exists():
+ logger.error("preset generation failed (%s); serving with the "
+ "PREVIOUS launch policies — models staged since "
+ "the last successful generation run unpoliced "
+ "until this is fixed", exc)
+ return preset_path
+ logger.error("preset generation failed (%s) and no previous "
+ "policy file exists; router runs stock fit", exc)
+ return None
+
+
def ensure_local_runtime(config: dict, force: bool = False) -> "object | None":
"""Idempotent boot of the managed runtime. Returns the supervisor (or None when
disabled/unavailable). Never raises into a session start — failures log and return None; chat
- falls back to configured providers.
- """
+ falls back to configured providers."""
global _SUPERVISOR
section = (config or {}).get("local_runtime") or {}
if not force and not section.get("enabled"):
@@ -167,21 +191,17 @@ def ensure_local_runtime(config: dict, force: bool = False) -> "object | None":
if _SUPERVISOR is not None:
return _SUPERVISOR
- # Residency: no staged models means nothing to serve — don't boot an
- # empty server. The walked-away story handled with zero configuration
- # (delete your last model and boots stop); Use force-boots as ever.
+ # Residency: no staged models means nothing to serve — don't boot an empty server (delete
+ # your last model and boots stop). force boots as ever.
if not force and not staged_models():
logger.info("local runtime enabled but no models staged; not booting")
return None
- # Another Hermes process may already be supervising — reuse via state,
- # but ONLY while its launch policy still covers every staged model. A
- # server whose preset file predates a download serves the new model
- # with no policy at all (--models-autoload + stock fit: f16 KV at max
- # context, no placement — the silent-demotion busy-wait on WDDM). A
- # stale incumbent gets stopped and replaced by a fresh boot with
- # regenerated presets; sessions ride through exactly like any other
- # supervised restart (stable port + persisted key).
+ # Another Hermes process may already be supervising — reuse via state, but ONLY while its
+ # launch policy still covers every staged model. A server whose preset file predates a
+ # download serves the new model with no policy at all (--models-autoload + stock fit). A stale
+ # incumbent gets stopped and replaced by a fresh boot with regenerated presets; sessions ride
+ # through like any other supervised restart (stable port + persisted key).
from hermes_cli.local_runtime.endpoint import _state_endpoint
state = _state_endpoint()
@@ -200,20 +220,16 @@ def ensure_local_runtime(config: dict, force: bool = False) -> "object | None":
installed_tags,
select_backend,
)
- from hermes_cli.local_runtime.hardware import probe_budget
- from hermes_cli.local_runtime.presets import generate_presets
from hermes_cli.local_runtime.supervisor import LlamaServerSupervisor
backend = section.get("backend", "auto")
if backend == "auto":
backend = select_backend(_detect_gpu_vendor())
- # Boot ladder: serve what is INSTALLED, never download here. The
- # configured tag (config root-of-trust; deep-merge supplies the
- # Hermes-release default when unpinned) is preferred; when it isn't
- # installed yet, the newest installed tag serves and the status
- # endpoint reports the pending update — the download is a deliberate
- # button click in the pane, not a boot-path surprise (a multi-minute
- # inline download here is exactly how the onboarding bounce returns).
+ # Boot ladder: serve what is INSTALLED, never download here. The configured tag is
+ # preferred; when it isn't installed yet, the newest installed tag serves and the status
+ # endpoint reports the pending update — the download is a deliberate click in the pane,
+ # not a boot-path surprise (a multi-minute inline download here is exactly how the
+ # onboarding bounce returns).
tag = section.get("tag") or default_tag()
have = installed_tags()
if tag not in have:
@@ -228,35 +244,7 @@ def ensure_local_runtime(config: dict, force: bool = False) -> "object | None":
mdir = models_dir()
mdir.mkdir(parents=True, exist_ok=True)
-
- # Context policy: one launch decision per staged model, carried to
- # the router via the preset INI. Priced against CAPACITY, not live
- # free VRAM: this runs while the outgoing server instance may still
- # hold the card (restart, refresh after a download), and its memory
- # is freed before the new instance loads anything. Pricing against
- # live-free here once pinned a fitting model's weights to CPU
- # because the probe saw the predecessor's VRAM as gone.
- preset_path = runtimes_root() / "presets.ini"
- try:
- entries = generate_presets(mdir, probe_budget(planning=True), preset_path)
- for entry in entries:
- if entry.refusal:
- logger.warning("model refused by physics check: %s", entry.refusal)
- except Exception as exc: # noqa: BLE001 — policy failure must not block serving
- # Degradation ladder: a STALE policy still beats no policy —
- # stock fit (f16 KV at max context, no placement) is the
- # silent-busy-wait failure on Windows. Keep serving with the
- # previous INI when one exists; only a first boot with no INI
- # at all falls to stock fit.
- if preset_path.exists():
- logger.error("preset generation failed (%s); serving with the "
- "PREVIOUS launch policies — models staged since "
- "the last successful generation run unpoliced "
- "until this is fixed", exc)
- else:
- logger.error("preset generation failed (%s) and no previous "
- "policy file exists; router runs stock fit", exc)
- preset_path = None
+ preset_path = _generate_presets(mdir, runtimes_root() / "presets.ini")
sup = LlamaServerSupervisor(
install_dir, mdir,
@@ -267,9 +255,8 @@ def ensure_local_runtime(config: dict, force: bool = False) -> "object | None":
try:
sup.start()
except Exception:
- # start() can fail after the router process exists (health
- # timeout, spawn error): leaving it running unsupervised
- # strands its VRAM behind a port nothing will clean up.
+ # start() can fail after the router process exists (health timeout): leaving it
+ # running unsupervised strands its VRAM behind a port nothing will clean up.
try:
sup.stop()
except Exception: # noqa: BLE001 — cleanup is best-effort
@@ -293,15 +280,14 @@ def shutdown_local_runtime() -> None:
def get_supervisor():
- """The process-local supervisor, or None (server may still be running
- under another process — check the state file)."""
+ """The process-local supervisor, or None (a server may still run under another process —
+ check the state file)."""
return _SUPERVISOR
def _start_idle_sweeper(sup) -> None:
- """Idle-residency loop: every couple of minutes, unload non-primary
- models idle past the supervisor's threshold. Daemon thread tied to the
- supervisor's lifetime — exits when the server stops."""
+ """Idle-residency loop: every couple of minutes, unload models idle past the supervisor's
+ threshold. Daemon thread tied to the supervisor's lifetime — exits when the server stops."""
import threading
def _loop():
diff --git a/hermes_cli/local_runtime/catalog.py b/hermes_cli/local_runtime/catalog.py
index 8d96cd25602..ae47fa58ae0 100644
--- a/hermes_cli/local_runtime/catalog.py
+++ b/hermes_cli/local_runtime/catalog.py
@@ -12,7 +12,6 @@ from __future__ import annotations
import json
import logging
-import re
import threading
import time
import urllib.request
@@ -31,11 +30,10 @@ from hermes_cli.local_runtime.estimator import (
ModelProfile,
ctx_bytes,
)
+from hermes_cli.local_runtime.gguf import model_id_from_stem
logger = logging.getLogger(__name__)
-_PART_SUFFIX = re.compile(r"-\d{5}-of-\d{5}$")
-
@dataclass(frozen=True)
class AssetFile:
@@ -66,8 +64,7 @@ class QuantVariant:
@property
def model_id(self) -> str:
- stem = PurePosixPath(self.files[0].path).name.removesuffix(".gguf")
- return _PART_SUFFIX.sub("", stem)
+ return model_id_from_stem(PurePosixPath(self.files[0].path).name.removesuffix(".gguf"))
@property
def size_bytes(self) -> int:
diff --git a/hermes_cli/local_runtime/endpoint.py b/hermes_cli/local_runtime/endpoint.py
index 01734465bf2..9ce50c431af 100644
--- a/hermes_cli/local_runtime/endpoint.py
+++ b/hermes_cli/local_runtime/endpoint.py
@@ -1,7 +1,8 @@
"""Endpoint resolution for llamacpp-alias requests (provider integration).
-The seam between the existing provider mechanism and the managed runtime: ``provider: llamacpp``
-with no explicit base_url resolves, in order, to
+``provider: llamacpp`` with no explicit base_url resolves, in order, to the managed server (state
+file), a detected external llama-server, or — during a backend boot race — the managed server once
+its state file appears.
"""
from __future__ import annotations
@@ -10,8 +11,6 @@ import json
import logging
import threading
import time
-import urllib.error
-import urllib.request
LLAMACPP_ALIASES = frozenset({"llamacpp", "llama.cpp", "llama-cpp"})
@@ -19,11 +18,8 @@ logger = logging.getLogger(__name__)
def _pid_alive(pid: int) -> bool:
- """Liveness for the state file's supervisor-child pid.
-
- psutil when available; otherwise fall back to True (optimistic) — on Windows ``os.kill(pid, 0)``
- TERMINATES the process, so it must never be used as a probe (windows-git-bash interop pitfall).
- """
+ """Liveness for the state file's supervisor-child pid: psutil when available, else True
+ (optimistic). On Windows ``os.kill(pid, 0)`` TERMINATES the process — never use it as a probe."""
if not pid or pid < 0:
return False
try:
@@ -47,30 +43,16 @@ def _state_endpoint() -> dict | None:
base_url = state.get("base_url", "")
if not base_url:
return None
- endpoint = {"base_url": base_url, "api_key": state.get("api_key", "")}
- # Ownership proof: the stable port means a SECOND install (different
- # HERMES_HOME — a scratch profile, say) can own 127.0.0.1:18434 with a
- # different api key while this install's state file still points there.
- # /health is a public route, so it answers 200 for ANYONE's server —
- # trusting it alone sent every chat request and the load-progress
- # watcher at a server that 401s our key, silently. The recorded
- # supervisor pid is the tiebreaker: health-200 from a server whose
- # recorded child is DEAD is someone else's server, never a starting one.
- pid_ok = _pid_alive(int(state.get("pid") or 0))
- # Healthy server: done (when it's ours).
- try:
- health = base_url.rsplit("/v1", 1)[0] + "/health"
- with urllib.request.urlopen(health, timeout=3) as r:
- if r.status == 200:
- return endpoint if pid_ok else None
- except (urllib.error.URLError, OSError, TimeoutError):
- pass
- # Not healthy YET: a live supervisor child is a STARTING server (state
- # is written at spawn; llama-server takes seconds to listen). Resolve
- # optimistically so readiness probes racing the boot see a configured
- # provider, not missing credentials. A dead pid is a crashed-without-
- # cleanup leftover — ignore it so requests don't blackhole.
- return endpoint if pid_ok else None
+ # Ownership proof: on the stable port a SECOND install (different HERMES_HOME) can own
+ # 127.0.0.1:18434 with a different api key while this install's state file still points
+ # there. /health is public and answers 200 for ANYONE's server — trusting it sent every
+ # request at a server that 401s our key, silently — so the recorded supervisor pid is the
+ # ONLY tiebreaker: a live pid is ours (healthy, or STARTING — state is written at spawn, and
+ # readiness probes racing the boot must see a configured provider, not missing credentials);
+ # a dead pid is a crashed-without-cleanup leftover, ignored so requests don't blackhole.
+ if not _pid_alive(int(state.get("pid") or 0)):
+ return None
+ return {"base_url": base_url, "api_key": state.get("api_key", "")}
def resolve_llamacpp_endpoint(config: dict | None = None,
@@ -78,8 +60,8 @@ def resolve_llamacpp_endpoint(config: dict | None = None,
"""Managed-first, detection-second endpoint for llamacpp aliases.
Boot-race rung: on a fresh backend start there is NO state file yet — the lifespan boot thread
- is still spawning the server (config load + preset generation + spawn ≈ 1-3 s) while the
- desktop's readiness probe fires the moment the WebSocket connects.
+ is still spawning the server (≈1-3 s) while the desktop's readiness probe fires the moment the
+ WebSocket connects.
"""
managed = _state_endpoint()
if managed:
@@ -115,11 +97,8 @@ def _load_config_if_none(config: dict | None) -> dict | None:
def _kick_managed_boot(config: dict | None) -> None:
- """Actively start the managed server when resolution finds it missing.
-
- The wait loop above assumes some OTHER thread is bringing the server up — true only at backend
- start (the lifespan boot thread).
- """
+ """Actively start the managed server when resolution finds it missing — the wait loop assumes
+ some OTHER thread is bringing it up, which is true only at backend start."""
if not _KICK_LOCK.acquire(blocking=False):
return # a kick is already in flight
@@ -138,24 +117,15 @@ def _kick_managed_boot(config: dict | None) -> None:
def _boot_in_flight(config: dict | None) -> bool:
- """True when the managed runtime is enabled and installed — the state
-
- Installed-ness is a verified-manifest scan under runtimes_root(), NOT a bare ``server_binary()``
- call: that helper needs an install_dir, and calling it bare made this gate throw-and-return
- False forever, silently disabling the boot wait.
- """
+ """True when the managed runtime is enabled and installed (a verified-manifest scan under
+ runtimes_root(), NOT a bare ``server_binary()`` call — that needs an install_dir, and calling
+ it bare once made this gate throw-and-return False forever, disabling the boot wait)."""
try:
config = _load_config_if_none(config)
if not ((config or {}).get("local_runtime") or {}).get("enabled"):
return False
- from hermes_cli.local_runtime.binaries import runtimes_root
-
- for manifest in runtimes_root().glob("*/*/manifest.json"):
- try:
- if json.loads(manifest.read_text(encoding="utf-8")).get("verified_version"):
- return True
- except (ValueError, OSError):
- continue
- return False
+ from hermes_cli.local_runtime.binaries import manifest_verified, runtimes_root
+
+ return any(manifest_verified(m) for m in runtimes_root().glob("*/*/manifest.json"))
except Exception: # noqa: BLE001
return False
diff --git a/hermes_cli/local_runtime/gguf.py b/hermes_cli/local_runtime/gguf.py
index e73e67dd2d1..816c085d64b 100644
--- a/hermes_cli/local_runtime/gguf.py
+++ b/hermes_cli/local_runtime/gguf.py
@@ -6,12 +6,22 @@ run at picker time on multi-GB files.
from __future__ import annotations
+import re
import struct
from dataclasses import dataclass, field
from pathlib import Path
_GGUF_MAGIC = b"GGUF"
+# Split GGUF naming: "<stem>-00001-of-00003.gguf"; the part suffix is not part of the model id.
+SPLIT_PART_RE = re.compile(r"-(\d{5})-of-(\d{5})\.gguf$")
+_PART_SUFFIX_RE = re.compile(r"-\d{5}-of-\d{5}$")
+
+
+def model_id_from_stem(stem: str) -> str:
+ """Model id from a GGUF file stem (split-part suffix stripped)."""
+ return _PART_SUFFIX_RE.sub("", stem)
+
# ggml tensor type sizes: type_id -> (block_bytes, block_elems).
# IQ-family sizes verified against ggml-common.h.
_GGML_TYPE_SIZES = {
diff --git a/hermes_cli/local_runtime/presets.py b/hermes_cli/local_runtime/presets.py
index a4008c22a9a..6f2f36c81c8 100644
--- a/hermes_cli/local_runtime/presets.py
+++ b/hermes_cli/local_runtime/presets.py
@@ -5,7 +5,7 @@ launch decisions.
from __future__ import annotations
import logging
-from dataclasses import dataclass
+from dataclasses import dataclass, replace
from pathlib import Path
from hermes_cli.local_runtime.context_policy import (
@@ -17,15 +17,16 @@ from hermes_cli.local_runtime.context_policy import (
)
from hermes_cli.local_runtime.estimator import (
HardwareBudget,
+ ModelProfile,
PhysicsRefusal,
+ ctx_bytes,
profile_from_gguf,
)
-from hermes_cli.local_runtime.gguf import read_gguf_header
+from hermes_cli.local_runtime.gguf import model_id_from_stem, read_gguf_header
logger = logging.getLogger(__name__)
-# args list -> INI keys. Flags the policy owns; everything else stays out
-# of the preset (recipe sampling defaults merge in a later pass).
+# args list -> INI keys. Flags the policy owns; everything else stays out of the preset.
_FLAG_TO_KEY = {
"-c": "ctx-size",
"-b": "batch-size",
@@ -52,8 +53,7 @@ def _args_to_keys(args: list[str]) -> dict[str, str]:
keys: dict[str, str] = {}
i = 0
while i < len(args):
- flag = args[i]
- key = _FLAG_TO_KEY.get(flag)
+ key = _FLAG_TO_KEY.get(args[i])
if key is None:
i += 1
continue
@@ -62,147 +62,143 @@ def _args_to_keys(args: list[str]) -> dict[str, str]:
return keys
+def _asset_path(asset) -> "Path | None":
+ """On-disk path of a catalog companion asset, or None when it isn't downloaded."""
+ from hermes_cli.local_runtime.bootstrap import assets_dir
+
+ if asset is None:
+ return None
+ path = assets_dir() / asset.local_name
+ return path if path.exists() else None
+
+
+def _choose_mtp_posture(profile: ModelProfile, budget: HardwareBudget,
+ fixed_overhead: int) -> tuple[bool, int]:
+ """(mtp_prefill, logits_bytes) for an MTP model — window first, prefill second.
+
+ Price the launch under both postures and keep whichever grants the larger window: the stacked
+ posture's bigger compute buffer buys ~3x short-prompt prefill but costs ~2 GiB that would
+ otherwise be window (measured at 256K the ub512 posture still prefills at 2.7K tok/s), so
+ never trade context away for prefill. Same window -> stacked.
+ """
+ plain_logits = ub_logits_bytes(profile.n_vocab, mtp_capable=True)
+ stacked_logits = ub_logits_bytes(profile.n_vocab, mtp_capable=True, mtp_prefill=True)
+ stacked = initial_window(profile, budget, overhead_bytes=fixed_overhead + stacked_logits)
+ plain = initial_window(profile, budget, overhead_bytes=fixed_overhead + plain_logits)
+ if (not isinstance(stacked, PhysicsRefusal) and not stacked.spilled
+ and (isinstance(plain, PhysicsRefusal) or stacked.window >= plain.window)):
+ return True, stacked_logits
+ return False, plain_logits
+
+
+def _restore_grown_window(model_id: str, profile: ModelProfile, budget: HardwareBudget,
+ decision: WindowDecision, overhead: int) -> WindowDecision:
+ """Session growth (growth.py): a persisted override lifts the launch window to where the ladder
+ last grew it — capped at native, and only when physics still clears the bigger window on THIS
+ boot's budget (a smaller-VRAM day re-fits honestly back down)."""
+ try:
+ from hermes_cli.local_runtime.growth import load_window_overrides
+
+ override = load_window_overrides().get(model_id)
+ native = profile.n_ctx_train or decision.window
+ if override and override > decision.window:
+ target = min(int(override), native)
+ kv = ctx_bytes(profile, target)
+ need = profile.weights_bytes + kv + overhead
+ if need <= budget.usable_vram_bytes + budget.ram_available_bytes:
+ return WindowDecision(
+ window=target, spill_bytes=max(0, need - budget.usable_vram_bytes),
+ kv_on_gpu=kv <= budget.usable_vram_bytes,
+ reasons=[f"grown window restored ({target // 1024}K)"])
+ except Exception as exc: # noqa: BLE001 — overrides are advisory
+ logger.debug("window override skipped for %s: %s", model_id, exc)
+ return decision
+
+
+def _preset_for(gguf: Path, budget: HardwareBudget,
+ mtp_capable: set[str]) -> PresetEntry | None:
+ """The launch decision for one staged model, or None when its header is unreadable."""
+ from hermes_cli.local_runtime.catalog import find_entry_for_model
+
+ model_id = model_id_from_stem(gguf.stem)
+ try:
+ header = read_gguf_header(gguf)
+ profile = profile_from_gguf(header)
+ except (ValueError, OSError) as exc:
+ logger.warning("preset skip %s: %s", gguf.name, exc)
+ return None
+ hit = find_entry_for_model(model_id)
+ entry = hit[0] if hit is not None else None
+ is_mtp = entry.mtp if entry is not None else model_id in mtp_capable
+ if is_mtp and profile.kv_scale == 1.0:
+ # Header-derived profiles don't know about MTP's draft context; apply the calibrated KV
+ # multiplier so the launch fit prices what the server will actually allocate.
+ profile = replace(profile, kv_scale=1.2)
+ mmproj_path = _asset_path(entry.mmproj) if entry is not None else None
+ # Overhead beyond weights+KV: runtime buffers, the vision projector when present, and the
+ # logits buffers of whichever microbatch/MTP posture launch_args will choose — flag and price
+ # decided together, from the same facts.
+ fixed_overhead = RUNTIME_OVERHEAD_BYTES + (
+ entry.mmproj.size_bytes if entry is not None and mmproj_path is not None else 0)
+ if is_mtp:
+ mtp_prefill, logits_bytes = _choose_mtp_posture(profile, budget, fixed_overhead)
+ else:
+ mtp_prefill, logits_bytes = False, ub_logits_bytes(profile.n_vocab, mtp_capable=False)
+ overhead = fixed_overhead + logits_bytes
+ decision = initial_window(profile, budget, overhead_bytes=overhead)
+ if isinstance(decision, PhysicsRefusal):
+ return PresetEntry(model_id=model_id, window=0, spilled=False, refusal=decision.message)
+ decision = _restore_grown_window(model_id, profile, budget, decision, overhead)
+
+ # The launch flags MUST match the pricing above (same entry/is_mtp/posture).
+ keys = _args_to_keys(launch_args(
+ profile, decision, mtp_capable=is_mtp,
+ mtp_draft_depth=entry.mtp_draft_depth if entry is not None else 3,
+ uma=budget.uma, mtp_prefill=mtp_prefill))
+ if entry is not None and is_mtp:
+ # Integrated-MTP targets sample on the backend, and so does the draft (pairing validated
+ # against the vendor's published llama.cpp recipes).
+ keys["backend-sampling"] = "on"
+ keys["spec-draft-backend-sampling"] = "on"
+
+ # Sampling deference ladder, under the policy keys (policy wins on clash): the GGUF's own
+ # general.sampling.* metadata is the publisher's recommendation and covers models the catalog
+ # has never heard of; catalog sampling applies only where the file is silent; a model
+ # carrying neither runs llama.cpp defaults.
+ for k, v in header.sampling_defaults.items():
+ keys.setdefault(k, v)
+ if entry is not None:
+ for k, v in (entry.sampling or {}).items():
+ keys.setdefault(k, v)
+ if mmproj_path is not None:
+ keys["mmproj"] = str(mmproj_path)
+ draft_path = _asset_path(entry.draft) if decision.spilled else None
+ if draft_path is not None:
+ keys["model-draft"] = str(draft_path)
+ keys["spec-type"] = "draft-dspark"
+ # Unsloth's measured cliff: acceptance 83% at 2-3 drafts, collapses at 4.
+ keys["spec-draft-n-max"] = "3"
+ return PresetEntry(model_id=model_id, window=decision.window,
+ spilled=decision.spilled, keys=keys)
+
+
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. Refused models get
- no section (the router simply won't have policy for them; the picker surfaces the refusal +
- smaller-quant suggestion from the returned entries).
- """
- from hermes_cli.local_runtime.bootstrap import assets_dir
- from hermes_cli.local_runtime.catalog import find_entry_for_model
+ """Walk the staged models, run the launch decision per model, and write one INI. Refused
+ models get no section (the picker surfaces the refusal from the returned entries)."""
+ from hermes_cli.local_runtime.bootstrap import staged_in
entries: list[PresetEntry] = []
sections: list[str] = []
- for gguf in _staged_in(models_dir):
- model_id = _strip_part(gguf.stem)
- try:
- header = read_gguf_header(gguf)
- profile = profile_from_gguf(header)
- except (ValueError, OSError) as exc:
- logger.warning("preset skip %s: %s", gguf.name, exc)
- continue
- # Overhead beyond weights+KV: runtime buffers, the vision projector
- # when this model ships one, and the logits buffers of whichever
- # microbatch/MTP posture launch_args will choose — flag and price
- # decided together, from the same facts.
- hit = find_entry_for_model(model_id)
- entry = hit[0] if hit is not None else None
- is_mtp = (entry.mtp if entry is not None
- else model_id in (mtp_capable or set()))
- if is_mtp and profile.kv_scale == 1.0:
- # Header-derived profiles don't know about MTP's draft
- # context; apply the calibrated KV multiplier here so the
- # launch fit prices what the server will actually allocate.
- import dataclasses
-
- profile = dataclasses.replace(profile, kv_scale=1.2)
- mmproj_bytes = 0
- if entry is not None and entry.mmproj is not None:
- mmproj_path = assets_dir() / entry.mmproj.local_name
- if mmproj_path.exists():
- mmproj_bytes = entry.mmproj.size_bytes
- # MTP posture ladder — window first, prefill second: price the
- # launch under both postures and keep whichever grants the larger
- # window (the stacked posture's bigger compute buffer buys ~3x
- # short-prompt prefill but costs ~2 GiB that would otherwise be
- # window; measured at 256K the ub512 posture still prefills at
- # 2.7K tok/s, so window wins ties only one way: never trade
- # context away for prefill). Same window -> stacked.
- mtp_prefill = False
- logits_bytes = ub_logits_bytes(profile.n_vocab, mtp_capable=is_mtp)
- if is_mtp:
- stacked_logits = ub_logits_bytes(profile.n_vocab, mtp_capable=True,
- mtp_prefill=True)
- stacked_probe = initial_window(
- profile, budget,
- overhead_bytes=(RUNTIME_OVERHEAD_BYTES + mmproj_bytes
- + stacked_logits))
- plain_probe = initial_window(
- profile, budget,
- overhead_bytes=(RUNTIME_OVERHEAD_BYTES + mmproj_bytes
- + logits_bytes))
- if (not isinstance(stacked_probe, PhysicsRefusal)
- and not stacked_probe.spilled
- and (isinstance(plain_probe, PhysicsRefusal)
- or stacked_probe.window >= plain_probe.window)):
- mtp_prefill = True
- logits_bytes = stacked_logits
- decision = initial_window(
- profile, budget,
- overhead_bytes=RUNTIME_OVERHEAD_BYTES + mmproj_bytes + logits_bytes)
- if isinstance(decision, PhysicsRefusal):
- entries.append(PresetEntry(model_id=model_id, window=0,
- spilled=False, refusal=decision.message))
+ for gguf in staged_in(models_dir, require_complete=False):
+ entry = _preset_for(gguf, budget, mtp_capable or set())
+ if entry is None:
continue
-
- # Session growth (growth.py): a persisted override lifts the launch
- # window to where the ladder last grew it — capped at native, and
- # only when physics still clears the bigger window on THIS boot's
- # budget (a smaller-VRAM day re-fits honestly back down).
- try:
- from hermes_cli.local_runtime.estimator import ctx_bytes
- from hermes_cli.local_runtime.growth import load_window_overrides
-
- override = load_window_overrides().get(model_id)
- native = profile.n_ctx_train or decision.window
- if override and override > decision.window:
- target = min(int(override), native)
- kv = ctx_bytes(profile, target)
- need = (profile.weights_bytes + kv
- + RUNTIME_OVERHEAD_BYTES + mmproj_bytes + logits_bytes)
- if need <= budget.usable_vram_bytes + budget.ram_available_bytes:
- spill = max(0, need - budget.usable_vram_bytes)
- decision = WindowDecision(
- window=target, spill_bytes=spill,
- kv_on_gpu=kv <= budget.usable_vram_bytes,
- reasons=[f"grown window restored ({target // 1024}K)"])
- except Exception as exc: # noqa: BLE001 — overrides are advisory
- logger.debug("window override skipped for %s: %s", model_id, exc)
-
- # (entry and is_mtp resolved above, where the overhead was priced —
- # the launch flags below MUST match that pricing.)
- args = launch_args(profile, decision, mtp_capable=is_mtp,
- mtp_draft_depth=(entry.mtp_draft_depth
- if entry is not None else 3),
- uma=budget.uma, mtp_prefill=mtp_prefill)
- keys = _args_to_keys(args)
-
- if entry is not None and is_mtp:
- # Integrated-MTP targets sample on the backend, and so does
- # the draft (pairing validated against the vendor's published
- # llama.cpp recipes for these models).
- keys["backend-sampling"] = "on"
- keys["spec-draft-backend-sampling"] = "on"
-
- # Sampling deference ladder, under the policy keys (policy wins
- # on clash). The GGUF's own general.sampling.* metadata is the
- # publisher's recommendation — it arrives with the file, updates
- # with every re-upload, and covers models the catalog has never
- # heard of. Catalog sampling applies only where the file is
- # silent; a model carrying neither runs llama.cpp defaults.
- for k, v in header.sampling_defaults.items():
- keys.setdefault(k, v)
- if entry is not None:
- for k, v in (entry.sampling or {}).items():
- keys.setdefault(k, v)
- if entry.mmproj is not None:
- mmproj_path = assets_dir() / entry.mmproj.local_name
- if mmproj_path.exists():
- keys["mmproj"] = str(mmproj_path)
- if entry.draft is not None and decision.spilled:
- draft_path = assets_dir() / entry.draft.local_name
- if draft_path.exists():
- keys["model-draft"] = str(draft_path)
- keys["spec-type"] = "draft-dspark"
- # Unsloth's measured cliff: acceptance 83% at 2-3
- # drafts, collapses at 4.
- keys["spec-draft-n-max"] = "3"
-
- entries.append(PresetEntry(model_id=model_id, window=decision.window,
- spilled=decision.spilled, keys=keys))
- body = "\n".join(f"{k} = {v}" for k, v in keys.items())
- sections.append(f"[{model_id}]\n{body}\n")
+ entries.append(entry)
+ if entry.keys is not None:
+ body = "\n".join(f"{k} = {v}" for k, v in entry.keys.items())
+ sections.append(f"[{entry.model_id}]\n{body}\n")
preset_path.parent.mkdir(parents=True, exist_ok=True)
preset_path.write_text("\n".join(sections), encoding="utf-8")
@@ -211,9 +207,8 @@ def generate_presets(models_dir: Path, budget: HardwareBudget,
def read_preset_decisions(preset_path: Path | None = None) -> dict[str, PresetEntry]:
- """The launch decisions the running server was actually given, read back from the preset INI (the
- INI is the record — it's what spawned the children). Missing/unparseable file returns {}.
- """
+ """The launch decisions the running server was actually given, read back from the preset INI
+ (the INI is the record — it's what spawned the children). Missing/unparseable -> {}."""
import configparser
if preset_path is None:
@@ -225,31 +220,9 @@ def read_preset_decisions(preset_path: Path | None = None) -> dict[str, PresetEn
parser = configparser.ConfigParser()
parser.read(preset_path, encoding="utf-8")
for section in parser.sections():
- window = parser.getint(section, "ctx-size", fallback=0)
- spilled = parser.has_option(section, "override-tensor")
- out[section] = PresetEntry(model_id=section, window=window,
- spilled=spilled)
+ out[section] = PresetEntry(
+ model_id=section, window=parser.getint(section, "ctx-size", fallback=0),
+ spilled=parser.has_option(section, "override-tensor"))
except Exception as exc: # noqa: BLE001
logger.debug("preset read-back failed: %s", exc)
return out
-
-
-def _strip_part(stem: str) -> str:
- import re
-
- return re.sub(r"-\d{5}-of-\d{5}$", "", stem)
-
-
-def _staged_in(models_dir: Path) -> "list[Path]":
- """Servable models in an arbitrary directory (split first-parts only) —
- the validation harness points at non-default dirs."""
- import re
-
- part = re.compile(r"-(\d{5})-of-\d{5}\.gguf$")
- out = []
- for p in sorted(models_dir.glob("*.gguf")):
- m = part.search(p.name)
- if m and m.group(1) != "00001":
- continue
- out.append(p)
- return out