Initial llm-host: hardware-aware local LLM server with dashboard

Detects the GPU (NVIDIA on Linux, Apple Silicon on macOS), picks the
catalog models and builds that fit, installs vLLM or MLX without sudo,
and runs the model server plus a web dashboard as user services.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QaE1hpvyZTJixEbUUMj9Ca
This commit is contained in:
neil 2026-11-02 03:51:06 -08:00
commit 5b9586ac80
19 changed files with 2458 additions and 0 deletions

3
.gitignore vendored Normal file
View file

@ -0,0 +1,3 @@
__pycache__/
*.pyc
.DS_Store

110
README.md Normal file
View file

@ -0,0 +1,110 @@
# llm-host
Turn a machine with a decent GPU into a local LLM server for coding agents like opencode.
llm-host detects the hardware, picks the models (and the right build of each) that fit,
installs the inference backend, and runs it as a background service with a web dashboard.
- **Linux + NVIDIA** → [vLLM](https://github.com/vllm-project/vllm)
- **macOS on Apple Silicon** → [MLX](https://github.com/ml-explore/mlx-lm), behind a small proxy that adds API keys
Either way you get the same OpenAI-compatible API (with an API key) on port 8000 and a dashboard on port 8080.
Everything installs into your home directory; no sudo, Docker or system CUDA toolkit needed.
## Install
On the machine that will run the models:
```bash
/bin/bash -c "$(curl -fsSL https://git.neilbantoc.dev/pub/llm-host/raw/branch/main/install.sh)"
```
It shows the plan (which models fit, which build, how much context) and asks before installing.
Pass setup options after `--`:
```bash
/bin/bash -c "$(curl -fsSL https://git.neilbantoc.dev/pub/llm-host/raw/branch/main/install.sh)" -- --yes --default ornith-1.5-35b
```
Preview what a machine would get without installing anything (needs only Python 3.11+):
```bash
git clone https://git.neilbantoc.dev/pub/llm-host.git && cd llm-host
PYTHONPATH=. python3 -P -m llmhost plan # this machine
PYTHONPATH=. python3 -P -m llmhost plan --simulate nvidia:24:8.9 # an RTX 4090
PYTHONPATH=. python3 -P -m llmhost plan --simulate apple:64 # a 64 GB Mac
```
## Use
| Command | |
|---|---|
| `llmhost status` | service state and URLs |
| `llmhost models` | models that fit this machine (`*` = active) |
| `llmhost switch <model>` | serve a different model (downloads it first if needed) |
| `llmhost download <model>` | download ahead of time |
| `llmhost logs -f` | follow the model server log |
| `llmhost start` / `stop` / `restart` | control the model server (stop frees the GPU) |
| `llmhost key` | print the API key |
| `llmhost opencode-config` | print what to add to opencode on your client machine |
| `llmhost update` | pull the latest llm-host and re-plan (`--backend` also upgrades vLLM/MLX) |
| `llmhost uninstall [--purge]` | remove services and backends (downloaded models are kept) |
The dashboard (`http://<host>.local:8080`) shows the active model, throughput, KV cache, GPU utilization,
temperature and power with 10-minute charts, the server log, and buttons to switch models or stop the server.
## Connecting opencode
Run `llmhost opencode-config` on the server. It prints a provider block for `~/.config/opencode/opencode.json`
and a one-liner that copies the API key to the client. Only one model is loaded at a time; pick the one
the server is currently running.
## How models are chosen
`llmhost/catalog.json` lists each model with every build of it (FP8, BF16, NVFP4, AWQ, MLX 8/6/4-bit),
its size, and its KV-cache cost per token (measured on real hardware). For each model, llm-host tries
builds in preference order and keeps the first that fits:
weights + ~3 GiB overhead + KV cache for 32k tokens ≤ usable GPU memory
- **NVIDIA**: usable = VRAM × 0.90 (0.95 if needed), summed over GPUs with tensor parallelism. Builds are
filtered by compute capability (NVFP4 needs Blackwell; FP8 and BF16 need Ampere or newer).
vLLM then sizes the context window to the memory that's actually left (`--max-model-len -1`).
- **Apple Silicon**: usable = the GPU's share of unified memory (macOS allows ~67–75% by default,
or `iogpu.wired_limit_mb` if you've raised it). MLX keeps an fp16 KV cache, so it's counted double.
`--prefer` changes the order: `balanced` (default: FP8 on NVIDIA, 6-bit on Mac), `quality` (BF16 / 8-bit),
or `speed` (NVFP4 / 4-bit).
To add a model: add an entry to `catalog.json` (copy an existing one; vLLM flags such as the tool-call and
reasoning parsers come from the model card or the [vLLM recipes](https://recipes.vllm.ai)), then run
`python3 tools/refresh_catalog.py --write` to fill in sizes, and `llmhost update` on each server.
## What setup does on Linux + NVIDIA
These avoid problems that come up on a fresh desktop install without sudo:
- vLLM goes in its own venv built on uv's Python (distro Pythons often lack the headers Triton needs).
- vLLM compiles some GPU kernels at startup and needs `nvcc`. Setup installs the CUDA compiler from pip,
pinned to the CUDA version torch was built for, and assembles a CUDA toolkit directory from the pip wheels.
- Kernel builds are limited to one compile job per ~12 GB of RAM (unlimited builds can exhaust memory).
- `loginctl enable-linger` keeps the services running when you're logged out (and starts them at boot).
## Files
| Path | |
|---|---|
| `~/.local/bin/llmhost` | launcher |
| `~/.local/share/llm-host/` | this repo (`src/`), backend venvs, the assembled CUDA toolkit |
| `~/.config/llm-host/config.json` | the plan: backend, fitting models, active model, ports |
| `~/.config/llm-host/api_key` | API key (mode 600) |
| `~/.cache/huggingface/hub/` | downloaded models |
| Linux: `~/.config/systemd/user/llm-host-{model,web}.service` | services (`journalctl --user -u llm-host-model`) |
| macOS: `~/Library/LaunchAgents/dev.llm-host.{model,web}.plist` | services; logs in `~/Library/Logs/llm-host/` |
On macOS the services are launchd agents, so they run while you're logged in.
## Limitations
- One model loaded at a time.
- AMD (ROCm), Intel and CPU-only machines aren't supported yet.
- The API and dashboard use plain HTTP and are meant for a trusted LAN. Don't expose them to the internet.

95
install.sh Executable file
View file

@ -0,0 +1,95 @@
#!/bin/bash
# llm-host installer.
#
# /bin/bash -c "$(curl -fsSL https://git.neilbantoc.dev/pub/llm-host/raw/branch/main/install.sh)"
#
# Pass setup options after `--`, e.g. ... install.sh)" -- --default ornith-1.5-35b --yes
# Environment overrides: LLMHOST_REPO, LLMHOST_REF, LLMHOST_HOME.
#
# Installs only into your home directory (no sudo): uv, a private Python, this repo,
# the inference backend (vLLM on Linux+NVIDIA, MLX on Apple Silicon) and user services.
# Written for bash 3.2 so it runs on stock macOS.
set -euo pipefail
REPO="${LLMHOST_REPO:-https://git.neilbantoc.dev/pub/llm-host.git}"
REF="${LLMHOST_REF:-main}"
DATA="${LLMHOST_HOME:-$HOME/.local/share/llm-host}"
SRC="$DATA/src"
BIN="$HOME/.local/bin"
if [ -t 1 ]; then B=$'\033[1m'; R=$'\033[31m'; Y=$'\033[33m'; G=$'\033[32m'; N=$'\033[0m'; else B=""; R=""; Y=""; G=""; N=""; fi
say() { printf '%s==>%s %s\n' "$B" "$N" "$*"; }
warn() { printf '%sWarning:%s %s\n' "$Y" "$N" "$*" >&2; }
die() { printf '%sError:%s %s\n' "$R" "$N" "$*" >&2; exit 1; }
[ "${1:-}" = "--" ] && shift
# ---- platform checks: fail early with a useful message ----
OS="$(uname -s)"; ARCH="$(uname -m)"
case "$OS" in
Darwin)
[ "$ARCH" = "arm64" ] || die "llm-host needs Apple Silicon on macOS (MLX doesn't run on Intel Macs)."
if ! xcode-select -p >/dev/null 2>&1; then
die "Xcode Command Line Tools are needed for git. Run: xcode-select --install then re-run this installer."
fi
;;
Linux)
if ! command -v nvidia-smi >/dev/null 2>&1; then
die "No NVIDIA driver found (nvidia-smi is missing). llm-host on Linux needs an NVIDIA GPU with its driver installed."
fi
if ! nvidia-smi -L >/dev/null 2>&1; then
die "nvidia-smi can't talk to the NVIDIA driver. Fix the driver (a reboot after driver updates often helps), then re-run."
fi
if ! command -v cc >/dev/null 2>&1 && ! command -v gcc >/dev/null 2>&1; then
die "No C compiler found; vLLM's Triton kernels need one. Debian/Ubuntu/Pop!_OS: sudo apt install build-essential"
fi
;;
*) die "Unsupported OS: $OS (llm-host supports Linux with NVIDIA, and macOS on Apple Silicon)." ;;
esac
for tool in curl git; do
command -v "$tool" >/dev/null 2>&1 || die "$tool is required but not installed."
done
mkdir -p "$BIN" "$DATA"
# ---- uv (Python + package manager), installed per-user ----
UV="$(command -v uv 2>/dev/null || true)"
[ -z "$UV" ] && [ -x "$BIN/uv" ] && UV="$BIN/uv"
if [ -z "$UV" ]; then
say "Installing uv"
curl -LsSf https://astral.sh/uv/install.sh | env UV_NO_MODIFY_PATH=1 UV_INSTALL_DIR="$BIN" sh >/dev/null
UV="$BIN/uv"
fi
[ -x "$UV" ] || die "uv install failed"
# ---- llm-host itself ----
if [ -d "$SRC/.git" ]; then
say "Updating llm-host in $SRC"
git -C "$SRC" fetch --quiet --depth 1 origin "$REF"
git -C "$SRC" reset --quiet --hard FETCH_HEAD
else
say "Downloading llm-host to $SRC"
rm -rf "$SRC"
git clone --quiet --depth 1 --branch "$REF" "$REPO" "$SRC"
fi
# ---- a private Python for llm-host (stdlib only, no venv needed) ----
say "Setting up Python"
"$UV" python install 3.12 >/dev/null 2>&1 || die "couldn't install Python 3.12 with uv"
PY="$("$UV" python find --managed-python 3.12)"
[ -x "$PY" ] || die "couldn't locate the uv-managed Python"
cat > "$BIN/llmhost" <<EOF
#!/bin/sh
# llm-host launcher (generated by install.sh)
PYTHONPATH="$SRC" exec "$PY" -P -m llmhost "\$@"
EOF
chmod +x "$BIN/llmhost"
case ":$PATH:" in
*":$BIN:"*) ;;
*) warn "$BIN isn't on your PATH. Add this to your shell profile: export PATH=\"$BIN:\$PATH\"" ;;
esac
say "Running setup"
exec "$BIN/llmhost" setup "$@"

1
llmhost/__init__.py Normal file
View file

@ -0,0 +1 @@
"""llm-host: serve local LLMs sized to the hardware."""

3
llmhost/__main__.py Normal file
View file

@ -0,0 +1,3 @@
from .cli import main
main()

View file

200
llmhost/backends/mlx.py Normal file
View file

@ -0,0 +1,200 @@
"""MLX backend (Apple Silicon).
mlx_lm.server has no API-key support and loads whatever model a request names, so it
listens on localhost only and this module runs a small proxy on the public port that:
- checks the API key (like vLLM's --api-key),
- rewrites the request's "model" to the loaded one and answers /v1/models with the
served name, so clients see the same API as on vLLM,
- counts in-flight requests and generated tokens for the dashboard (/llmhost/metrics).
"""
import hmac
import http.client
import json
import os
import shutil
import signal
import subprocess
import sys
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from .. import paths
VENV = paths.DATA / "venv-mlx"
PY = VENV / "bin/python"
def install(hw, log=print):
u = shutil.which("uv") or str(paths.BIN_DIR / "uv")
if not PY.exists():
log(f"$ uv venv {VENV}")
subprocess.run([u, "venv", "--managed-python", "--python", "3.12", str(VENV)], check=True)
spec = os.environ.get("LLMHOST_MLX_SPEC", "mlx-lm")
log(f"$ uv pip install {spec}")
subprocess.run([u, "pip", "install", "--python", str(PY), spec, "huggingface_hub[cli]"], check=True)
return {}
class Stats:
def __init__(self):
self.lock = threading.Lock()
self.running = 0
self.gen_total = 0
self.prompt_total = 0
self.requests_total = 0
def snapshot(self):
with self.lock:
return {"running": self.running, "gen_total": self.gen_total,
"prompt_total": self.prompt_total, "requests_total": self.requests_total}
def make_handler(inner_port, served_name, context, key, stats):
class Proxy(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def log_message(self, fmt, *a):
sys.stderr.write("proxy: %s - %s\n" % (self.address_string(), fmt % a))
def _json(self, code, obj):
body = json.dumps(obj).encode()
self.send_response(code)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def _authed(self):
h = self.headers.get("Authorization", "")
tok = h[7:] if h.startswith("Bearer ") else ""
if hmac.compare_digest(tok.encode(), key.encode()):
return True
self._json(401, {"error": {"message": "invalid API key", "type": "auth"}})
return False
def do_GET(self):
if self.path == "/health":
return self._forward("GET", None)
if self.path == "/llmhost/metrics":
if self.client_address[0] not in ("127.0.0.1", "::1"):
return self._json(403, {"error": "local only"})
return self._json(200, stats.snapshot())
if not self._authed():
return
if self.path.startswith("/v1/models"):
return self._json(200, {"object": "list", "data": [
{"id": served_name, "object": "model", "owned_by": "llm-host", "max_model_len": context}]})
self._forward("GET", None)
def do_POST(self):
if not self._authed():
return
n = int(self.headers.get("Content-Length") or 0)
raw = self.rfile.read(n) if n else b""
try:
body = json.loads(raw or b"{}")
if isinstance(body, dict):
body["model"] = "default_model"
raw = json.dumps(body).encode()
except ValueError:
pass
self._forward("POST", raw)
def _forward(self, method, raw):
with stats.lock:
stats.running += 1
stats.requests_total += 1
try:
conn = http.client.HTTPConnection("127.0.0.1", inner_port, timeout=3600)
headers = {"Content-Type": self.headers.get("Content-Type", "application/json")}
if raw is not None:
headers["Content-Length"] = str(len(raw))
try:
conn.request(method, self.path, body=raw, headers=headers)
resp = conn.getresponse()
except OSError:
return self._json(503, {"error": {"message": "model server not ready", "type": "unavailable"}})
self.send_response(resp.status)
ctype = resp.getheader("Content-Type", "application/json")
self.send_header("Content-Type", ctype)
streaming = "text/event-stream" in ctype
if streaming:
self.send_header("Cache-Control", "no-cache")
self.send_header("Connection", "close")
self.end_headers()
self.close_connection = True
buf = b""
while True:
chunk = resp.read1(65536) if hasattr(resp, "read1") else resp.read(4096)
if not chunk:
break
self.wfile.write(chunk)
self.wfile.flush()
buf += chunk
while b"\n\n" in buf:
event, buf = buf.split(b"\n\n", 1)
self._count_event(event)
else:
data = resp.read()
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
try:
u = json.loads(data).get("usage") or {}
with stats.lock:
stats.gen_total += int(u.get("completion_tokens") or 0)
stats.prompt_total += int(u.get("prompt_tokens") or 0)
except (ValueError, AttributeError):
pass
except (BrokenPipeError, ConnectionResetError):
pass
finally:
with stats.lock:
stats.running -= 1
def _count_event(self, event):
if not event.startswith(b"data: {"):
return
try:
d = json.loads(event[6:])
except ValueError:
return
u = d.get("usage")
with stats.lock:
if u: # final usage chunk (stream_options.include_usage) is exact; prefer it
stats.prompt_total += int(u.get("prompt_tokens") or 0)
for c in d.get("choices") or []:
delta = c.get("delta") or {}
if delta.get("content") or delta.get("reasoning") or delta.get("reasoning_content") or delta.get("tool_calls"):
stats.gen_total += 1 # mlx streams one token per chunk
return Proxy
def run_server(cfg, entry, choice, args):
"""Start mlx_lm.server as a child on api_port+1 and the auth proxy on api_port."""
port = cfg["api_port"]
inner = port + 1
exe = str(VENV / "bin/mlx_lm.server")
child = subprocess.Popen([exe, *args])
def stop(*_):
child.terminate()
try:
child.wait(timeout=20)
except subprocess.TimeoutExpired:
child.kill()
os._exit(0)
signal.signal(signal.SIGTERM, stop)
signal.signal(signal.SIGINT, stop)
stats = Stats()
srv = ThreadingHTTPServer(("0.0.0.0", port),
make_handler(inner, entry["name"], choice.get("est_context", entry["context"]),
paths.api_key(), stats))
threading.Thread(target=srv.serve_forever, daemon=True).start()
print(f"llm-host: proxy on :{port} -> mlx_lm.server on 127.0.0.1:{inner}", flush=True)
rc = child.wait()
print(f"llm-host: mlx_lm.server exited with {rc}", flush=True)
time.sleep(1)
os._exit(rc or 1)

155
llmhost/backends/vllm.py Normal file
View file

@ -0,0 +1,155 @@
"""vLLM backend (Linux + NVIDIA). Installs without sudo or a system CUDA toolkit.
Hard-won details this encodes:
- The venv uses uv's own Python: distro Pythons often lack headers, and Triton compiles C at startup.
- vLLM JIT-compiles FlashInfer kernels and needs nvcc. We pip-install the compiler pinned to
torch's CUDA version (mixing versions makes ptxas reject the PTX), then merge every
nvidia/* wheel into one CUDA_HOME-shaped tree, with the unversioned lib*.so links the linker wants.
- Unthrottled ninja builds run nproc+2 nvcc jobs at several GB each and can OOM the machine,
so MAX_JOBS is derived from RAM.
- DeepGEMM wants a full toolkit; it's disabled (FP8 MoE falls back to other kernels).
"""
import glob
import os
import shutil
import subprocess
from pathlib import Path
from .. import paths
VENV = paths.DATA / "venv-vllm"
CUDA_DIR = paths.DATA / "cuda"
PY = VENV / "bin/python"
def uv():
exe = shutil.which("uv") or str(paths.BIN_DIR / "uv")
if not os.path.exists(exe):
raise SystemExit("uv not found; run install.sh first.")
return exe
def site_packages():
found = glob.glob(str(VENV / "lib/python3*/site-packages"))
if not found:
raise SystemExit("vLLM venv missing; run `llmhost setup`.")
return Path(found[0])
def _sh(cmd, log, check=True, **kw):
log("$ " + " ".join(str(c) for c in cmd))
r = subprocess.run([str(c) for c in cmd], **kw)
if check and r.returncode != 0:
raise SystemExit(f"command failed ({r.returncode}): {' '.join(map(str, cmd))}")
return r
def _link_tree(src: Path, dst: Path):
"""Symlink src's entries into dst, merging directories that already exist."""
dst.mkdir(parents=True, exist_ok=True)
for e in sorted(src.iterdir()):
t = dst / e.name
if not os.path.lexists(t):
t.symlink_to(e)
elif e.is_dir() and t.is_dir():
if t.is_symlink(): # turn the earlier symlinked dir into a real one so both can merge
prev = t.resolve()
t.unlink()
t.mkdir()
_link_tree(prev, t)
_link_tree(e, t)
def build_cuda_home(log=print):
nv = site_packages() / "nvidia"
if CUDA_DIR.exists():
shutil.rmtree(CUDA_DIR)
CUDA_DIR.mkdir(parents=True)
# Toolkit-ish packages first so their files win name clashes.
pkgs = sorted(nv.iterdir(), key=lambda p: (not (p.name.startswith("cu1") or p.name.startswith("cuda")), p.name))
for pkg in pkgs:
if not pkg.is_dir():
continue
for sub, target in (("bin", "bin"), ("include", "include"), ("lib", "lib64"), ("lib64", "lib64"), ("nvvm", "nvvm")):
if (pkg / sub).is_dir():
_link_tree(pkg / sub, CUDA_DIR / target)
lib = CUDA_DIR / "lib64"
if lib.is_dir():
for f in lib.glob("lib*.so.*"):
base = lib / (f.name.split(".so.")[0] + ".so")
if not os.path.lexists(base):
base.symlink_to(f.name)
log(f"CUDA_HOME assembled at {CUDA_DIR}")
def torch_cuda():
out = subprocess.run([str(PY), "-c", "import torch;print(torch.version.cuda or '')"],
capture_output=True, text=True)
return out.stdout.strip()
def install(hw, log=print):
u = uv()
if not PY.exists():
_sh([u, "venv", "--managed-python", "--python", "3.12", VENV], log)
spec = os.environ.get("LLMHOST_VLLM_SPEC", "vllm")
_sh([u, "pip", "install", "--python", PY, spec, "--torch-backend=auto"], log)
cuda = torch_cuda()
if not cuda:
raise SystemExit("torch was installed without CUDA support; check the NVIDIA driver.")
mm = ".".join(cuda.split(".")[:2])
major = int(mm.split(".")[0])
log(f"torch is built for CUDA {mm}; installing a matching compiler toolchain")
if major >= 13:
pkgs = [f"nvidia-cuda-nvcc=={mm}.*", f"nvidia-nvvm=={mm}.*", f"nvidia-cuda-crt=={mm}.*", f"nvidia-cuda-cccl=={mm}.*"]
else:
pkgs = [f"nvidia-cuda-nvcc-cu{major}=={mm}.*", f"nvidia-cuda-cccl-cu{major}=={mm}.*"]
r = _sh([u, "pip", "install", "--python", PY, *pkgs], log, check=False)
build_cuda_home(log)
ok = r.returncode == 0 and self_test(log)
if not ok:
log("WARNING: kernel compilation self-test failed; disabling FlashInfer's JIT sampler as a fallback.")
return {"cuda": mm, "jit_ok": ok}
def self_test(log=print):
nvcc = CUDA_DIR / "bin/nvcc"
if not nvcc.exists():
log("nvcc not found in the merged toolkit")
return False
tmp = paths.DATA / "nvcc-test"
tmp.mkdir(exist_ok=True)
(tmp / "t.cu").write_text("__global__ void k(){}\nint main(){k<<<1,1>>>();return (int)cudaDeviceSynchronize();}\n")
env = run_env({"vllm": {"jit_ok": True}}, hw=None, include_key=False)
r = subprocess.run([str(nvcc), str(tmp / "t.cu"), "-o", str(tmp / "t")], env=env, capture_output=True, text=True)
if r.returncode != 0:
log("nvcc failed:\n" + r.stderr[-800:])
return False
r = subprocess.run([str(tmp / "t")], env=env, capture_output=True, text=True)
log("nvcc self-test: " + ("compiled and ran a kernel" if r.returncode == 0 else f"kernel run failed ({r.returncode})"))
return r.returncode == 0
def max_jobs(ram_gib, cpus):
# Each nvcc job on CUTLASS-heavy FlashInfer sources can take ~6-8 GB.
return max(1, min(cpus, int(ram_gib // 12)))
def run_env(cfg, hw=None, include_key=True):
env = dict(os.environ)
vcfg = cfg.get("vllm", {})
env["CUDA_HOME"] = str(CUDA_DIR)
env["PATH"] = f"{CUDA_DIR}/bin:{VENV}/bin:" + env.get("PATH", "/usr/bin:/bin")
env["VLLM_USE_DEEP_GEMM"] = "0"
env["MAX_JOBS"] = str(cfg.get("max_jobs", 4))
if not vcfg.get("jit_ok", True):
env["VLLM_USE_FLASHINFER_SAMPLER"] = "0"
if include_key:
env["VLLM_API_KEY"] = paths.api_key()
return env
def exec_server(cfg, args):
"""Replace this process with `vllm serve` (so the service manager tracks vLLM directly)."""
exe = str(VENV / "bin/vllm")
os.execve(exe, [exe, "serve", *args], run_env(cfg))

83
llmhost/catalog.json Normal file
View file

@ -0,0 +1,83 @@
{
"_comment": "kv_kib_per_token = KV cache cost per token with an fp8 cache, measured on vLLM 0.32 (MLX uses ~2x). Models llm-host knows how to serve. Order = preference for the default model. 'gb' is decimal GB of weights on disk (tools/refresh_catalog.py updates it). Formats: fp8/bf16/nvfp4/awq are vLLM builds for NVIDIA, mlx-* are Apple Silicon builds. 'mtp' marks builds that ship multi-token-prediction weights.",
"models": [
{
"name": "qwen3.8-27b",
"kv_kib_per_token": 37.2,
"title": "Qwen3.8 27B",
"about": "Dense 27B, hybrid attention, strong general coding and tool use.",
"context": 262144,
"hybrid": true,
"reasoning": true,
"vllm": {"tool_parser": "qwen3_coder", "reasoning_parser": "qwen3", "kv_cache_dtype": "fp8", "mtp_tokens": 3},
"mlx": {},
"variants": {
"fp8": {"repo": "Qwen/Qwen3.8-27B-FP8", "gb": 30.9, "mtp": true},
"bf16": {"repo": "Qwen/Qwen3.8-27B", "gb": 55.6, "mtp": true},
"nvfp4": {"repo": "nvidia/Qwen3.8-27B-NVFP4", "gb": 21.9},
"awq": {"repo": "cyankiwi/Qwen3.8-27B-AWQ-INT4", "gb": 21.0},
"mlx-8bit": {"repo": "lmstudio-community/Qwen3.8-27B-MLX-8bit", "gb": 29.5},
"mlx-6bit": {"repo": "lmstudio-community/Qwen3.8-27B-MLX-6bit", "gb": 22.8},
"mlx-4bit": {"repo": "lmstudio-community/Qwen3.8-27B-MLX-4bit", "gb": 16.1}
}
},
{
"name": "ornith-1.5-35b",
"kv_kib_per_token": 10.6,
"title": "Ornith 1.5 35B A3B",
"about": "35B mixture-of-experts with 3B active: very fast.",
"context": 262144,
"hybrid": true,
"reasoning": true,
"vllm": {"tool_parser": "qwen3_xml", "reasoning_parser": "qwen3", "kv_cache_dtype": "fp8", "trust_remote_code": true},
"mlx": {"trust_remote_code": true},
"variants": {
"fp8": {"repo": "ornith-ai/Ornith-1.5-35B-A3B-FP8", "gb": 39.4},
"bf16": {"repo": "ornith-ai/Ornith-1.5-35B-A3B", "gb": 71.9},
"nvfp4": {"repo": "ornith-ai/Ornith-1.5-35B-A3B-NVFP4", "gb": 23.4},
"awq": {"repo": "cyankiwi/Ornith-1.5-35B-A3B-AWQ-INT4", "gb": 26.1},
"mlx-8bit": {"repo": "ornith-ai/Ornith-1.5-35B-A3B-MLX-8bit", "gb": 36.8},
"mlx-6bit": {"repo": "ornith-ai/Ornith-1.5-35B-A3B-MLX-6bit", "gb": 28.2},
"mlx-4bit": {"repo": "ornith-ai/Ornith-1.5-35B-A3B-MLX-4bit", "gb": 19.5}
}
},
{
"name": "qwen3-coder",
"kv_kib_per_token": 48.0,
"title": "Qwen3 Coder 30B A3B",
"about": "Coding-tuned mixture-of-experts, no reasoning phase.",
"context": 262144,
"hybrid": false,
"reasoning": false,
"vllm": {"tool_parser": "qwen3_coder", "kv_cache_dtype": "fp8"},
"mlx": {},
"variants": {
"fp8": {"repo": "Qwen/Qwen3-Coder-30B-A3B-Instruct-FP8", "gb": 31.2},
"bf16": {"repo": "Qwen/Qwen3-Coder-30B-A3B-Instruct", "gb": 61.1},
"awq": {"repo": "cyankiwi/Qwen3-Coder-30B-A3B-Instruct-AWQ-4bit", "gb": 18.1},
"mlx-8bit": {"repo": "lmstudio-community/Qwen3-Coder-30B-A3B-Instruct-MLX-8bit", "gb": 32.4},
"mlx-6bit": {"repo": "lmstudio-community/Qwen3-Coder-30B-A3B-Instruct-MLX-6bit", "gb": 24.8},
"mlx-4bit": {"repo": "lmstudio-community/Qwen3-Coder-30B-A3B-Instruct-MLX-4bit", "gb": 17.2}
}
},
{
"name": "ornith-1.5-122b",
"kv_kib_per_token": 13.2,
"title": "Ornith 1.5 122B",
"about": "Largest option; needs ~80 GB of GPU memory even at 4-bit.",
"context": 262144,
"hybrid": true,
"reasoning": true,
"vllm": {"tool_parser": "qwen3_xml", "reasoning_parser": "qwen3", "kv_cache_dtype": "fp8", "trust_remote_code": true},
"mlx": {"trust_remote_code": true},
"variants": {
"fp8": {"repo": "ornith-ai/Ornith-1.5-122B-FP8", "gb": 132.9},
"bf16": {"repo": "ornith-ai/Ornith-1.5-122B", "gb": 250.2},
"nvfp4": {"repo": "ornith-ai/Ornith-1.5-122B-NVFP4", "gb": 77.6},
"awq": {"repo": "cyankiwi/Ornith-1.5-122B-AWQ-INT4", "gb": 85.3},
"mlx-8bit": {"repo": "ornith-ai/Ornith-1.5-122B-MLX-8bit", "gb": 130.6},
"mlx-4bit": {"repo": "ornith-ai/Ornith-1.5-122B-MLX-4bit", "gb": 69.6}
}
}
]
}

348
llmhost/cli.py Normal file
View file

@ -0,0 +1,348 @@
"""llmhost command-line interface."""
import argparse
import json
import os
import shutil
import socket
import subprocess
import sys
import time
import urllib.request
from . import hfcache, hw, paths, plan, service
from .backends import vllm as vllm_backend # stdlib-only module; safe to import anywhere
VERSION = "0.1.0"
def say(msg=""):
print(msg, flush=True)
def backend_module(name):
if name == "vllm":
from .backends import vllm
return vllm
from .backends import mlx
return mlx
def hardware_name(info):
g = info["gpus"]
if not g:
return "no GPU"
if info["kind"] == "apple":
return f"{g[0]['name']}, {info['ram_gib']:.0f} GB unified memory"
names = {x["name"] for x in g}
return f"{len(g)}× {names.pop()}" if len(g) > 1 and len(names) == 1 else ", ".join(x["name"] for x in g)
def print_plan(info, p):
say(f"Hardware: {hardware_name(info)}")
if p.get("backend"):
tp = f" across {p['tp']} GPUs" if p.get("tp", 1) > 1 else ""
say(f"Backend: {'vLLM' if p['backend'] == 'vllm' else 'MLX'} · {p['budget_gib']} GiB usable{tp} · preference: {p['prefer']}")
for n in info.get("notes", []):
say(f"Note: {n}")
if p["models"]:
say("\nModels that fit:")
for m in p["models"]:
dl = "downloaded" if hfcache.is_downloaded(m["repo"]) else f"{m['weights_gib']} GiB to download"
say(f" {m['name']:18} {m['format']:9} ~{m['est_context'] // 1024}k ctx {m['repo']} ({dl})")
if p["excluded"]:
say("\nToo big for this hardware:")
for e in p["excluded"]:
say(f" {e['name']:18} {e['reason']}")
def cmd_detect(a):
say(json.dumps(hw.detect(), indent=2))
def cmd_plan(a):
info = hw.simulate(a.simulate) if a.simulate else hw.detect()
p = plan.plan(info, paths.load_catalog(), a.prefer)
if a.json:
say(json.dumps(p, indent=2))
return
print_plan(info, p)
if not p["models"]:
say("\nNothing fits. " + (p.get("reason") or ""))
def cmd_setup(a):
info = hw.detect()
cat = paths.load_catalog()
old = paths.load_config()
prefer = a.prefer or old.get("prefer", "balanced")
p = plan.plan(info, cat, prefer)
print_plan(info, p)
if not p["models"]:
raise SystemExit("\nNothing can run on this machine: " + (p.get("reason") or "no model fits"))
names = [m["name"] for m in p["models"]]
active = a.default or old.get("active")
if active not in names:
if a.default:
raise SystemExit(f"--default {a.default} doesn't fit this hardware (fits: {', '.join(names)})")
active = names[0]
first = next(m for m in p["models"] if m["name"] == active)
need = 0 if hfcache.is_downloaded(first["repo"]) else first["weights_gib"] + 5
if info["disk_free_gib"] < need:
raise SystemExit(f"\nNot enough disk: {active} needs ~{need:.0f} GiB free in {paths.hf_hub_dir()}, "
f"{info['disk_free_gib']:.0f} GiB available.")
say(f"\nDefault model: {active}")
if not a.yes and sys.stdin.isatty():
if input("Continue with setup? [Y/n] ").strip().lower() not in ("", "y", "yes"):
raise SystemExit("aborted")
say(f"\n== Installing {p['backend']} (this can take several minutes) ==")
backend_info = {} if a.skip_backend else backend_module(p["backend"]).install(info, say)
cfg = {
"version": 1, "kind": info["kind"], "backend": p["backend"],
"hardware_name": hardware_name(info), "budget_gib": p["budget_gib"], "tp": p["tp"],
"prefer": prefer, "api_port": a.api_port or old.get("api_port", 8000),
"web_port": a.web_port or old.get("web_port", 8080),
"max_jobs": vllm_backend.max_jobs(info["ram_gib"], info["cpus"]),
"models": p["models"], "excluded": p["excluded"], "active": active,
p["backend"]: {**old.get(p["backend"], {}), **backend_info},
}
paths.save_config(cfg)
key = paths.api_key(create=True)
say("\n== Installing services ==")
for name in service.NAMES:
service.install(name)
if not paths.IS_MAC and not service.enable_linger():
say("Note: couldn't enable lingering, so the server stops when you log out. Fix: sudo loginctl enable-linger $USER")
if not a.no_start:
service.restart("web")
service.restart("model")
host = default_host()
say(f"""
Done.
API: http://{host}:{cfg['api_port']}/v1 (OpenAI-compatible)
Dashboard: http://{host}:{cfg['web_port']}
API key: {paths.KEY_FILE} (show it with: llmhost key)
Model: {active} — {"loading" if hfcache.is_downloaded(first["repo"]) else "downloading, then loading"}; watch with: llmhost logs -f
Connect opencode: run `llmhost opencode-config` and follow what it prints.""")
def default_host():
h = socket.gethostname()
return h if "." in h else h + ".local"
def _service_check():
cfg = paths.load_config()
if not cfg:
raise SystemExit("Not set up yet; run `llmhost setup`.")
return cfg
def cmd_status(a):
cfg = _service_check()
host = default_host()
for name in service.NAMES:
st, up = service.state(name)
upt = f" (up {int(up // 3600)}h{int(up % 3600 // 60):02d}m)" if up else ""
say(f"{name:6} {st}{upt}")
try:
req = urllib.request.Request(f"http://127.0.0.1:{cfg['api_port']}/v1/models",
headers={"Authorization": f"Bearer {paths.api_key()}"})
served = [m["id"] for m in json.load(urllib.request.urlopen(req, timeout=3))["data"]]
say(f"serving {', '.join(served)}")
except Exception:
say(f"active model {cfg['active']} is not answering yet")
say(f"api http://{host}:{cfg['api_port']}/v1\ndashboard http://{host}:{cfg['web_port']}")
def cmd_models(a):
cfg = _service_check()
for m in cfg["models"]:
mark = "*" if m["name"] == cfg["active"] else " "
dl = "downloaded" if hfcache.is_downloaded(m["repo"]) else f"{m['weights_gib']} GiB to download"
say(f"{mark} {m['name']:18} {m['format']:9} ~{m['est_context'] // 1024}k ctx {m['repo']} ({dl})")
for e in cfg.get("excluded", []):
say(f" {e['name']:18} (doesn't fit: {e['reason']})")
def cmd_switch(a):
cfg = _service_check()
names = [m["name"] for m in cfg["models"]]
if a.model not in names:
raise SystemExit(f"{a.model} isn't available here. Choose from: {', '.join(names)}")
cfg["active"] = a.model
paths.save_config(cfg)
service.restart("model")
say(f"Switched to {a.model}. Watch it load with: llmhost logs -f")
def cmd_ctl(a):
_service_check()
getattr(service, a.cmd)("model")
say(f"model server: {a.cmd} requested")
def cmd_logs(a):
_service_check()
if a.follow:
os.execvp(service.log_command("model")[0], service.log_command("model"))
for line in service.logs("web" if a.web else "model", a.n):
say(line)
def cmd_key(a):
say(paths.api_key())
def cmd_download(a):
cfg = _service_check()
m = next((x for x in cfg["models"] if x["name"] == a.model), None)
if not m:
raise SystemExit(f"{a.model} isn't available here; see `llmhost models`")
venv = paths.DATA / ("venv-vllm" if cfg["backend"] == "vllm" else "venv-mlx")
hf = venv / "bin/hf"
os.execv(str(hf), [str(hf), "download", m["repo"]])
def cmd_opencode(a):
cfg = _service_check()
host = a.host or default_host()
prov = a.provider or f"llmhost-{host.split('.')[0]}"
keyfile = f"~/.config/opencode/{prov}.key"
models = {}
for m in cfg["models"]:
entry = {"name": f"{m['name']} ({host.split('.')[0]})", "tool_call": True,
"limit": {"context": m["est_context"], "output": min(65536, m["est_context"] // 2)}}
if m.get("reasoning"):
entry["reasoning"] = True
models[m["name"]] = entry
snippet = {
"$schema": "https://opencode.ai/config.json",
"provider": {prov: {
"npm": "@ai-sdk/openai-compatible", "name": f"llm-host ({host})",
"options": {"baseURL": f"http://{host}:{cfg['api_port']}/v1", "apiKey": "{file:" + keyfile + "}"},
"models": models}},
"model": f"{prov}/{cfg['active']}",
}
if a.json:
say(json.dumps(snippet, indent=2))
return
say(f"""On the machine running opencode:
1. Save the API key:
mkdir -p ~/.config/opencode && ssh {os.environ.get('USER', 'you')}@{host} 'cat {paths.KEY_FILE}' > {keyfile} && chmod 600 {keyfile}
(or paste the output of `llmhost key` into {keyfile})
2. Merge this into ~/.config/opencode/opencode.json:
""")
say(json.dumps(snippet, indent=2))
say(f"\nOnly the active model answers at a time; switch with `llmhost switch <name>` or the dashboard.")
def cmd_update(a):
if (paths.SRC / ".git").exists():
subprocess.run(["git", "-C", str(paths.SRC), "pull", "--ff-only"], check=True)
cfg = paths.load_config()
args = [str(paths.SHIM), "setup", "--yes"]
if not a.backend:
args.append("--skip-backend")
if cfg.get("active"):
args += ["--default", cfg["active"]]
os.execv(args[0], args)
def cmd_uninstall(a):
for name in service.NAMES:
service.uninstall(name)
for d in ("venv-vllm", "venv-mlx", "cuda", "nvcc-test"):
shutil.rmtree(paths.DATA / d, ignore_errors=True)
say("Removed services and backend environments.")
if a.purge:
shutil.rmtree(paths.CONFIG_DIR, ignore_errors=True)
shutil.rmtree(paths.DATA, ignore_errors=True)
paths.SHIM.unlink(missing_ok=True)
say("Removed config, API key and llm-host itself.")
say(f"Downloaded models were kept in {paths.hf_hub_dir()} (delete with `hf cache rm`).")
def cmd_run_model(a):
cfg = _service_check()
cat = paths.load_catalog()
choice = next(m for m in cfg["models"] if m["name"] == cfg["active"])
entry = plan.catalog_entry(cat, cfg["active"])
service.trim_log("model")
say(f"llm-host {VERSION}: starting {entry['name']} ({choice['repo']}, {choice['format']}) on {cfg['backend']}")
if cfg["backend"] == "vllm":
from .backends import vllm
vllm.exec_server(cfg, plan.vllm_args(entry, choice, cfg["api_port"], cfg.get("tp", 1)))
else:
from .backends import mlx
mlx.run_server(cfg, entry, choice, plan.mlx_args(entry, choice, cfg["api_port"] + 1))
def cmd_run_web(a):
_service_check()
service.trim_log("web")
from .web import server
server.serve()
def main(argv=None):
ap = argparse.ArgumentParser(prog="llmhost", description="Serve local LLMs over an OpenAI-compatible API, sized to this machine's hardware.")
ap.add_argument("--version", action="version", version=f"llm-host {VERSION}")
sub = ap.add_subparsers(dest="cmd", required=True, metavar="COMMAND")
s = sub.add_parser("setup", help="detect hardware, install the backend and services, start serving")
s.add_argument("--yes", "-y", action="store_true", help="don't ask for confirmation")
s.add_argument("--default", help="model to serve first")
s.add_argument("--prefer", choices=["balanced", "quality", "speed"], help="how to trade quality for speed when picking builds")
s.add_argument("--api-port", type=int)
s.add_argument("--web-port", type=int)
s.add_argument("--no-start", action="store_true", help="install everything but don't start the services")
s.add_argument("--skip-backend", action="store_true", help=argparse.SUPPRESS)
s.set_defaults(fn=cmd_setup)
s = sub.add_parser("plan", help="show which models fit this (or simulated) hardware, without installing")
s.add_argument("--simulate", metavar="SPEC", help="fake hardware: nvidia:VRAM_GIB[:COMPUTE_CAP[:COUNT]] or apple:RAM_GB")
s.add_argument("--prefer", choices=["balanced", "quality", "speed"], default="balanced")
s.add_argument("--json", action="store_true")
s.set_defaults(fn=cmd_plan)
sub.add_parser("detect", help="print detected hardware as JSON").set_defaults(fn=cmd_detect)
sub.add_parser("status", help="show service state and URLs").set_defaults(fn=cmd_status)
sub.add_parser("models", help="list models available on this machine").set_defaults(fn=cmd_models)
s = sub.add_parser("switch", help="serve a different model")
s.add_argument("model")
s.set_defaults(fn=cmd_switch)
for c in ("start", "stop", "restart"):
sub.add_parser(c, help=f"{c} the model server").set_defaults(fn=cmd_ctl)
s = sub.add_parser("logs", help="show model server logs")
s.add_argument("-f", "--follow", action="store_true")
s.add_argument("-n", type=int, default=100)
s.add_argument("--web", action="store_true", help="dashboard logs instead")
s.set_defaults(fn=cmd_logs)
sub.add_parser("key", help="print the API key").set_defaults(fn=cmd_key)
s = sub.add_parser("download", help="download a model ahead of time")
s.add_argument("model")
s.set_defaults(fn=cmd_download)
s = sub.add_parser("opencode-config", help="print opencode setup for connecting to this server")
s.add_argument("--host", help="hostname clients use (default: <hostname>.local)")
s.add_argument("--provider", help="opencode provider id")
s.add_argument("--json", action="store_true", help="print only the JSON")
s.set_defaults(fn=cmd_opencode)
s = sub.add_parser("update", help="pull the latest llm-host and re-plan")
s.add_argument("--backend", action="store_true", help="also reinstall/upgrade the backend")
s.set_defaults(fn=cmd_update)
s = sub.add_parser("uninstall", help="remove services and backends (keeps downloaded models)")
s.add_argument("--purge", action="store_true", help="also remove config, API key and llm-host itself")
s.set_defaults(fn=cmd_uninstall)
sub.add_parser("run-model").set_defaults(fn=cmd_run_model)
sub.add_parser("run-web").set_defaults(fn=cmd_run_web)
a = ap.parse_args(argv)
a.fn(a)

47
llmhost/hfcache.py Normal file
View file

@ -0,0 +1,47 @@
"""Read-only checks against the Hugging Face cache (no huggingface_hub dependency)."""
import json
import os
from . import paths
def repo_dir(repo):
return paths.hf_hub_dir() / ("models--" + repo.replace("/", "--"))
def is_downloaded(repo):
"""True when a snapshot has every weight file its index lists (or a single-file model)."""
snaps = repo_dir(repo) / "snapshots"
if not snaps.is_dir():
return False
for snap in snaps.iterdir():
idx = snap / "model.safetensors.index.json"
if idx.exists():
try:
files = set(json.loads(idx.read_text())["weight_map"].values())
except (OSError, ValueError, KeyError):
continue
if files and all(os.path.exists(snap / f) for f in files):
return True
elif (snap / "model.safetensors").exists():
return True
return False
def disk_gib(repo):
"""Size of this repo's downloaded files, in GiB. Measured through the snapshot symlinks
because newer huggingface_hub versions keep large blobs in a shared hub/blobs directory."""
seen, total = set(), 0
snaps = repo_dir(repo) / "snapshots"
if snaps.is_dir():
for root, _dirs, files in os.walk(snaps):
for name in files:
real = os.path.realpath(os.path.join(root, name))
if real in seen:
continue
seen.add(real)
try:
total += os.stat(real).st_size
except OSError:
pass
return total / 2**30

167
llmhost/hw.py Normal file
View file

@ -0,0 +1,167 @@
"""Hardware detection (static, for planning) and live stats (for the dashboard)."""
import os
import platform
import re
import shutil
import subprocess
from . import paths
def run(cmd, timeout=10):
try:
r = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout)
return r.stdout.strip() if r.returncode == 0 else ""
except (OSError, subprocess.TimeoutExpired):
return ""
def _ram_gib():
if paths.IS_MAC:
out = run(["sysctl", "-n", "hw.memsize"])
return int(out) / 2**30 if out.isdigit() else 0.0
try:
with open("/proc/meminfo") as f:
for line in f:
if line.startswith("MemTotal:"):
return int(line.split()[1]) / 2**20
except OSError:
pass
return 0.0
def _disk_free_gib():
p = paths.hf_hub_dir()
while not p.exists() and p != p.parent:
p = p.parent
return shutil.disk_usage(p).free / 2**30
def _nvidia_gpus():
if not shutil.which("nvidia-smi"):
return []
out = run(["nvidia-smi", "--query-gpu=index,name,memory.total,memory.used,compute_cap,driver_version",
"--format=csv,noheader,nounits"])
gpus = []
for line in out.splitlines():
parts = [x.strip() for x in line.split(",")]
if len(parts) < 6:
continue
try:
gpus.append({
"index": int(parts[0]), "name": parts[1],
"vram_gib": float(parts[2]) / 1024, "used_gib": float(parts[3]) / 1024,
"compute_cap": float(parts[4]), "driver": parts[5],
})
except ValueError:
continue
return gpus
def apple_gpu_budget_gib(ram_gib):
"""How much unified memory the GPU may wire. macOS defaults to ~2/3 of RAM on
small machines and ~3/4 on larger ones; an explicit iogpu.wired_limit_mb wins."""
out = run(["sysctl", "-n", "iogpu.wired_limit_mb"])
if out.isdigit() and int(out) > 0:
return int(out) / 1024
return ram_gib * (0.75 if ram_gib > 36 else 0.67)
def detect():
info = {
"os": platform.system(), "arch": platform.machine(),
"cpus": os.cpu_count() or 1, "ram_gib": round(_ram_gib(), 1),
"disk_free_gib": round(_disk_free_gib(), 1),
"kind": None, "gpus": [], "notes": [],
}
if paths.IS_MAC:
if info["arch"] == "arm64":
chip = run(["sysctl", "-n", "machdep.cpu.brand_string"]) or "Apple Silicon"
info["kind"] = "apple"
info["gpus"] = [{"index": 0, "name": chip,
"vram_gib": round(apple_gpu_budget_gib(info["ram_gib"]), 1)}]
else:
info["notes"].append("Intel Macs aren't supported (MLX needs Apple Silicon).")
return info
gpus = _nvidia_gpus()
if gpus:
info["kind"] = "nvidia"
info["gpus"] = gpus
if not shutil.which("cc") and not shutil.which("gcc"):
info["notes"].append("No C compiler found; Triton needs one (Debian/Ubuntu: sudo apt install build-essential).")
return info
if shutil.which("rocm-smi") or os.path.exists("/dev/kfd"):
info["notes"].append("AMD/ROCm GPU detected; ROCm isn't supported yet.")
elif shutil.which("nvidia-smi"):
info["notes"].append("nvidia-smi is installed but can't talk to the driver.")
else:
info["notes"].append("No supported GPU found (need an NVIDIA GPU on Linux, or Apple Silicon).")
return info
def simulate(spec):
"""Fake hardware for `llmhost plan --simulate`, e.g. nvidia:24:8.9, nvidia:80:9.0:4, apple:64."""
parts = spec.split(":")
kind = parts[0]
base = {"os": "Darwin" if kind == "apple" else "Linux", "arch": "arm64" if kind == "apple" else "x86_64",
"cpus": 16, "disk_free_gib": 2000.0, "kind": kind, "notes": ["simulated"]}
if kind == "nvidia":
vram = float(parts[1]); cc = float(parts[2]) if len(parts) > 2 else 8.9
count = int(parts[3]) if len(parts) > 3 else 1
base["ram_gib"] = max(64.0, vram * count)
base["gpus"] = [{"index": i, "name": f"Simulated {vram:g}GiB sm_{cc}", "vram_gib": vram,
"used_gib": 0.0, "compute_cap": cc, "driver": "sim"} for i in range(count)]
elif kind == "apple":
ram = float(parts[1])
base["ram_gib"] = ram
base["gpus"] = [{"index": 0, "name": f"Simulated Apple {ram:g}GB",
"vram_gib": round(ram * (0.75 if ram > 36 else 0.67), 1)}]
else:
raise SystemExit(f"unknown simulate kind {kind!r} (use nvidia:VRAM[:CC[:COUNT]] or apple:RAM)")
return base
# ---------- live stats ----------
def live_stats(kind):
if kind == "nvidia":
out = run(["nvidia-smi", "--query-gpu=name,memory.used,memory.total,utilization.gpu,temperature.gpu,power.draw,power.limit",
"--format=csv,noheader,nounits"])
rows = [[x.strip() for x in l.split(",")] for l in out.splitlines() if l.strip()]
if not rows:
return None
def num(x):
try:
return float(x)
except ValueError:
return None
cols = list(zip(*rows))
vals = [[num(v) for v in c] for c in cols[1:]]
def tot(c):
xs = [v for v in vals[c] if v is not None]
return sum(xs) if xs else None
def avg(c):
xs = [v for v in vals[c] if v is not None]
return sum(xs) / len(xs) if xs else None
def mx(c):
xs = [v for v in vals[c] if v is not None]
return max(xs) if xs else None
name = rows[0][0] + (f" ×{len(rows)}" if len(rows) > 1 else "")
return {"name": name, "mem_used": tot(0), "mem_total": tot(1), "util": avg(2),
"temp": mx(3), "power": tot(4), "power_limit": tot(5)}
if kind == "apple":
# ioreg needs no sudo; temperature and power need powermetrics (sudo), so they're omitted.
out = run(["ioreg", "-r", "-d", "1", "-w", "0", "-c", "IOAccelerator"])
util = re.search(r'"Device Utilization %"=(\d+)', out)
used = re.search(r'"In use system memory"=(\d+)', out)
ram = _ram_gib()
return {"name": run(["sysctl", "-n", "machdep.cpu.brand_string"]) or "Apple GPU",
"mem_used": int(used.group(1)) / 2**20 if used else None,
"mem_total": apple_gpu_budget_gib(ram) * 1024,
"util": float(util.group(1)) if util else None,
"temp": None, "power": None, "power_limit": None}
return None

68
llmhost/paths.py Normal file
View file

@ -0,0 +1,68 @@
"""Filesystem layout and config persistence.
Layout (overridable with LLMHOST_HOME / LLMHOST_CONFIG):
~/.local/share/llm-host/src this repo (cloned by install.sh)
~/.local/share/llm-host/venv-* backend virtualenvs
~/.local/share/llm-host/cuda merged CUDA toolkit built from pip wheels (NVIDIA)
~/.config/llm-host/config.json plan + settings
~/.config/llm-host/api_key API key (0600)
"""
import json
import os
import platform
import secrets
import tempfile
from pathlib import Path
HOME = Path.home()
IS_MAC = platform.system() == "Darwin"
SRC = Path(__file__).resolve().parent.parent
DATA = Path(os.environ.get("LLMHOST_HOME", HOME / ".local/share/llm-host"))
CONFIG_DIR = Path(os.environ.get("LLMHOST_CONFIG", HOME / ".config/llm-host"))
CONFIG_FILE = CONFIG_DIR / "config.json"
KEY_FILE = CONFIG_DIR / "api_key"
LOG_DIR = (HOME / "Library/Logs/llm-host") if IS_MAC else (DATA / "logs")
BIN_DIR = HOME / ".local/bin"
SHIM = BIN_DIR / "llmhost"
CATALOG_FILE = Path(__file__).resolve().parent / "catalog.json"
def hf_hub_dir() -> Path:
if os.environ.get("HF_HUB_CACHE"):
return Path(os.environ["HF_HUB_CACHE"])
if os.environ.get("HF_HOME"):
return Path(os.environ["HF_HOME"]) / "hub"
return HOME / ".cache/huggingface/hub"
def load_config() -> dict:
try:
return json.loads(CONFIG_FILE.read_text())
except (OSError, ValueError):
return {}
def save_config(cfg: dict) -> None:
CONFIG_DIR.mkdir(parents=True, exist_ok=True)
fd, tmp = tempfile.mkstemp(dir=CONFIG_DIR, prefix=".config.")
with os.fdopen(fd, "w") as f:
json.dump(cfg, f, indent=2)
f.write("\n")
os.replace(tmp, CONFIG_FILE)
def load_catalog() -> dict:
return json.loads(CATALOG_FILE.read_text())
def api_key(create: bool = False) -> str:
if KEY_FILE.exists():
return KEY_FILE.read_text().strip()
if not create:
raise SystemExit(f"No API key at {KEY_FILE}; run `llmhost setup` first.")
CONFIG_DIR.mkdir(parents=True, exist_ok=True)
key = "sk-" + secrets.token_urlsafe(32)
fd = os.open(KEY_FILE, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
with os.fdopen(fd, "w") as f:
f.write(key + "\n")
return key

147
llmhost/plan.py Normal file
View file

@ -0,0 +1,147 @@
"""Pick a build of each catalog model that fits the hardware, and turn it into backend flags.
Fit rule: weights + overhead + KV cache for MIN_CONTEXT tokens must fit in the GPU budget.
KV cost per token comes from the catalog (measured on a real card); overhead covers
activations, CUDA graphs and the MTP head, and was ~3-4 GiB for every model we measured.
"""
import json
GB = 1e9 / 2**30 # decimal GB -> GiB
MIN_CONTEXT = 32768 # tokens of context a coding agent needs to be useful
UTILS = (0.90, 0.95) # vLLM gpu-memory-utilization; try the safer one first
# Order to try builds in, per preference. bf16 only wins over fp8 under "quality":
# fp8 is near-lossless and about twice as fast on dense models.
ORDERS = {
"nvidia": {
"balanced": ["fp8", "bf16", "nvfp4", "awq"],
"quality": ["bf16", "fp8", "nvfp4", "awq"],
"speed": ["nvfp4", "fp8", "awq", "bf16"],
},
"apple": {
"balanced": ["mlx-6bit", "mlx-4bit"],
"quality": ["mlx-8bit", "mlx-6bit", "mlx-4bit"],
"speed": ["mlx-4bit", "mlx-6bit"],
},
}
# Minimum CUDA compute capability per format (FP8 runs on Ampere via Marlin kernels).
MIN_CC = {"fp8": 8.0, "bf16": 8.0, "nvfp4": 10.0, "awq": 7.5}
BACKEND = {"nvidia": "vllm", "apple": "mlx"}
def _tp_size(n):
tp = 1
while tp * 2 <= n:
tp *= 2
return tp
def _overhead_gib(weights_gib, tp):
return 3.0 * tp + 0.02 * weights_gib
def plan(hw, catalog, prefer="balanced"):
"""Returns {"backend", "tp", "budget_gib", "models": [...fitting], "excluded": [...]}."""
kind = hw.get("kind")
if kind not in ORDERS:
return {"backend": None, "models": [], "excluded": [], "reason": "; ".join(hw.get("notes", [])) or "unsupported hardware"}
gpus = hw["gpus"]
if kind == "nvidia":
tp = _tp_size(len(gpus))
per_gpu = min(g["vram_gib"] for g in gpus[:tp])
cc = min(g["compute_cap"] for g in gpus[:tp])
total = per_gpu * tp
else:
tp, cc, total = 1, None, gpus[0]["vram_gib"]
fitting, excluded = [], []
for m in catalog["models"]:
choice, why_not = None, []
for fmt in ORDERS[kind][prefer]:
v = m["variants"].get(fmt)
if not v:
continue
if kind == "nvidia" and cc < MIN_CC[fmt]:
why_not.append(f"{fmt} needs compute capability {MIN_CC[fmt]}")
continue
w = v["gb"] * GB
# MLX keeps the KV cache in fp16: about twice the fp8 cost vLLM pays.
kv_kib = m["kv_kib_per_token"] * (2 if kind == "apple" else 1)
for util in (UTILS if kind == "nvidia" else (1.0,)):
free = total * util - w - _overhead_gib(w, tp)
ctx = int(free * 2**20 / kv_kib) if free > 0 else 0
if ctx >= MIN_CONTEXT:
choice = {"format": fmt, "repo": v["repo"], "weights_gib": round(w, 1),
"util": util, "est_context": min(ctx, m["context"]), "mtp": bool(v.get("mtp"))}
break
if choice:
break
why_not.append(f"{fmt} ({w:.0f} GiB) leaves too little memory")
if choice:
fitting.append({"name": m["name"], "title": m["title"], "about": m.get("about", ""),
"context": m["context"], "reasoning": m.get("reasoning", False), **choice})
else:
usable = set(ORDERS[kind]["quality"]) | set(ORDERS[kind]["speed"])
if kind == "nvidia":
usable = {f for f in usable if cc >= MIN_CC[f]}
sizes = [v["gb"] * GB for f, v in m["variants"].items() if f in usable]
if sizes:
smallest = min(sizes)
kv_kib = m["kv_kib_per_token"] * (2 if kind == "apple" else 1)
need = smallest + _overhead_gib(smallest, tp) + MIN_CONTEXT * kv_kib / 2**20
usable_gib = total * (max(UTILS) if kind == "nvidia" else 1.0)
reason = f"needs ~{need:.1f} GiB of GPU memory; {usable_gib:.1f} GiB usable here"
else:
smallest, reason = 0, "no build this GPU can run"
excluded.append({"name": m["name"], "title": m["title"], "reason": reason,
"smallest_gib": round(smallest, 1)})
return {"backend": BACKEND[kind], "kind": kind, "tp": tp, "budget_gib": round(total, 1),
"prefer": prefer, "models": fitting, "excluded": excluded}
def catalog_entry(catalog, name):
for m in catalog["models"]:
if m["name"] == name:
return m
raise KeyError(name)
# ---------- backend command lines ----------
def vllm_args(entry, choice, port, tp):
"""Arguments after `vllm serve`."""
v = entry.get("vllm", {})
args = [choice["repo"], "--served-model-name", entry["name"],
"--host", "0.0.0.0", "--port", str(port),
"--max-model-len", "-1", # let vLLM fit the context to free memory (capped at native)
"--gpu-memory-utilization", f"{choice['util']:.2f}",
"--enable-prefix-caching"]
if tp > 1:
args += ["--tensor-parallel-size", str(tp)]
if entry.get("hybrid"):
# Hybrid (Mamba-style) layers need one state slot per sequence; vLLM's default of
# 1024 concurrent sequences doesn't fit. A personal server never needs that many.
args += ["--max-num-seqs", "32"]
if v.get("kv_cache_dtype"):
args += ["--kv-cache-dtype", v["kv_cache_dtype"]]
if v.get("trust_remote_code"):
args += ["--trust-remote-code"]
if v.get("tool_parser"):
args += ["--enable-auto-tool-choice", "--tool-call-parser", v["tool_parser"]]
if v.get("reasoning_parser"):
args += ["--reasoning-parser", v["reasoning_parser"]]
if choice.get("mtp") and v.get("mtp_tokens"):
args += ["--speculative-config", json.dumps({"method": "mtp", "num_speculative_tokens": v["mtp_tokens"]})]
args += v.get("extra_args", [])
return args
def mlx_args(entry, choice, port):
"""Arguments for `mlx_lm.server` (bound to localhost; the auth proxy faces the network)."""
x = entry.get("mlx", {})
args = ["--model", choice["repo"], "--host", "127.0.0.1", "--port", str(port),
"--max-tokens", "32768"] # mlx_lm defaults to 512, which truncates coding answers
if x.get("trust_remote_code"):
args += ["--trust-remote-code"]
args += x.get("extra_args", [])
return args

219
llmhost/service.py Normal file
View file

@ -0,0 +1,219 @@
"""Background services: systemd --user on Linux, launchd agents on macOS.
Two services: "model" (the inference server) and "web" (dashboard). Both run `llmhost run-<name>`.
"""
import os
import re
import subprocess
import time
from pathlib import Path
from . import paths
NAMES = ("model", "web")
def _run(cmd, timeout=60):
try:
r = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout)
return r.returncode, r.stdout.strip(), r.stderr.strip()
except (OSError, subprocess.TimeoutExpired) as e:
return 1, "", str(e)
# ---------------- systemd ----------------
def _unit(name):
return f"llm-host-{name}"
def _unit_path(name):
return paths.HOME / ".config/systemd/user" / f"{_unit(name)}.service"
def _systemd_install(name):
desc = {"model": "llm-host model server", "web": "llm-host dashboard"}[name]
extra = "TimeoutStartSec=1800\nTimeoutStopSec=60\n" if name == "model" else ""
p = _unit_path(name)
p.parent.mkdir(parents=True, exist_ok=True)
p.write_text(f"""[Unit]
Description={desc}
After=network-online.target
[Service]
ExecStart={paths.SHIM} run-{name}
Restart=on-failure
RestartSec=10
{extra}
[Install]
WantedBy=default.target
""")
# ---------------- launchd ----------------
def _label(name):
return f"dev.llm-host.{name}"
def _plist_path(name):
return paths.HOME / "Library/LaunchAgents" / f"{_label(name)}.plist"
def _domain():
return f"gui/{os.getuid()}"
def _launchd_install(name):
paths.LOG_DIR.mkdir(parents=True, exist_ok=True)
log = paths.LOG_DIR / f"{name}.log"
path_env = f"{paths.BIN_DIR}:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"
p = _plist_path(name)
p.parent.mkdir(parents=True, exist_ok=True)
p.write_text(f"""<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key><string>{_label(name)}</string>
<key>ProgramArguments</key>
<array><string>{paths.SHIM}</string><string>run-{name}</string></array>
<key>RunAtLoad</key><true/>
<key>KeepAlive</key><dict><key>SuccessfulExit</key><false/></dict>
<key>ThrottleInterval</key><integer>10</integer>
<key>StandardOutPath</key><string>{log}</string>
<key>StandardErrorPath</key><string>{log}</string>
<key>EnvironmentVariables</key><dict><key>PATH</key><string>{path_env}</string></dict>
</dict>
</plist>
""")
def _launchd_loaded(name):
rc, out, _ = _run(["launchctl", "print", f"{_domain()}/{_label(name)}"])
return rc == 0, out
# ---------------- public API ----------------
def install(name):
if paths.IS_MAC:
_launchd_install(name)
else:
_systemd_install(name)
_run(["systemctl", "--user", "daemon-reload"])
_run(["systemctl", "--user", "enable", _unit(name)])
def enable_linger():
"""Keep user services running without a login session (Linux). Often allowed without sudo."""
if paths.IS_MAC:
return True
user = os.environ.get("USER") or os.getlogin()
_run(["loginctl", "enable-linger", user])
rc, out, _ = _run(["loginctl", "show-user", user, "-p", "Linger"])
return out.strip() == "Linger=yes"
def start(name):
if paths.IS_MAC:
loaded, _ = _launchd_loaded(name)
if loaded:
return _run(["launchctl", "kickstart", f"{_domain()}/{_label(name)}"])[0] == 0
return _run(["launchctl", "bootstrap", _domain(), str(_plist_path(name))])[0] == 0
return _run(["systemctl", "--user", "start", _unit(name)], timeout=120)[0] == 0
def stop(name):
if paths.IS_MAC:
loaded, _ = _launchd_loaded(name)
return (not loaded) or _run(["launchctl", "bootout", f"{_domain()}/{_label(name)}"])[0] == 0
return _run(["systemctl", "--user", "stop", _unit(name)], timeout=120)[0] == 0
def restart(name):
if paths.IS_MAC:
loaded, _ = _launchd_loaded(name)
if loaded:
return _run(["launchctl", "kickstart", "-k", f"{_domain()}/{_label(name)}"])[0] == 0
return start(name)
return _run(["systemctl", "--user", "restart", _unit(name)], timeout=120)[0] == 0
def uninstall(name):
stop(name)
if paths.IS_MAC:
_plist_path(name).unlink(missing_ok=True)
else:
_run(["systemctl", "--user", "disable", _unit(name)])
_unit_path(name).unlink(missing_ok=True)
_run(["systemctl", "--user", "daemon-reload"])
def _etime_seconds(s):
# ps etime: [[dd-]hh:]mm:ss
days = 0
if "-" in s:
d, s = s.split("-", 1)
days = int(d)
parts = [int(x) for x in s.split(":")]
while len(parts) < 3:
parts.insert(0, 0)
h, m, sec = parts
return days * 86400 + h * 3600 + m * 60 + sec
def state(name):
"""Returns (state, uptime_seconds). state is one of active, activating, inactive, failed."""
if paths.IS_MAC:
loaded, out = _launchd_loaded(name)
if not loaded:
return "inactive", None
pid = re.search(r"\bpid = (\d+)", out)
if pid:
rc, et, _ = _run(["ps", "-o", "etime=", "-p", pid.group(1)])
return "active", (_etime_seconds(et.strip()) if rc == 0 and et.strip() else None)
last = re.search(r"last exit code = (\d+)", out)
return ("failed" if last and last.group(1) != "0" else "activating"), None
rc, out, _ = _run(["systemctl", "--user", "show", _unit(name), "-p", "ActiveState,ActiveEnterTimestampMonotonic"])
props = dict(l.split("=", 1) for l in out.splitlines() if "=" in l)
st = props.get("ActiveState", "inactive")
mono = int(props.get("ActiveEnterTimestampMonotonic", "0") or 0)
up = time.monotonic() - mono / 1e6 if st == "active" and mono else None
return st, up
def logs(name, n=200):
if paths.IS_MAC:
log = paths.LOG_DIR / f"{name}.log"
try:
with open(log, "rb") as f:
f.seek(0, 2)
size = f.tell()
f.seek(max(0, size - 256 * 1024))
lines = f.read().decode(errors="replace").splitlines()
return lines[-n:]
except OSError:
return []
rc, out, _ = _run(["journalctl", "--user", "-u", _unit(name), "-n", str(n), "--no-pager", "-o", "short-iso"])
return out.splitlines()
def log_command(name):
if paths.IS_MAC:
return ["tail", "-n", "100", "-F", str(paths.LOG_DIR / f"{name}.log")]
return ["journalctl", "--user", "-u", _unit(name), "-n", "100", "-f", "-o", "cat"]
def trim_log(name, max_bytes=50 * 2**20):
"""launchd never rotates; keep the log from growing forever."""
if not paths.IS_MAC:
return
log = paths.LOG_DIR / f"{name}.log"
try:
if log.stat().st_size > max_bytes:
with open(log, "rb") as f:
f.seek(-5 * 2**20, 2)
tail = f.read()
log.write_bytes(tail)
except OSError:
pass

0
llmhost/web/__init__.py Normal file
View file

486
llmhost/web/index.html Normal file
View file

@ -0,0 +1,486 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>llm-host</title>
<style>
:root {
--bg: #f6f7f9; --panel: #ffffff; --panel-2: #f0f2f5; --border: #e2e5ea;
--text: #16191d; --muted: #646c78; --faint: #9aa1ac;
--accent: #3b6ef5; --accent-weak: #e6edfe;
--ok: #1f9d55; --ok-weak: #e3f5ea; --warn: #b7791f; --warn-weak: #fbf1dc;
--bad: #d64545; --bad-weak: #fbe5e5;
--c1: #3b6ef5; --c2: #0f9d8a; --c3: #c2620f; --c4: #d13d5e; --c5: #8a5cf0;
--mono: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
color-scheme: light;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #0e1013; --panel: #161a1f; --panel-2: #1d2228; --border: #262c34;
--text: #e7eaee; --muted: #9099a5; --faint: #5f6873;
--accent: #6d93ff; --accent-weak: #1c2640;
--ok: #3ccf7f; --ok-weak: #143022; --warn: #e3a94a; --warn-weak: #33280f;
--bad: #f07272; --bad-weak: #3a1818;
--c1: #6d93ff; --c2: #3fc9b4; --c3: #f0954a; --c4: #f2708c; --c5: #a98bff;
color-scheme: dark;
}
}
* { box-sizing: border-box; }
body {
margin: 0; background: var(--bg); color: var(--text);
font: 14px/1.45 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
}
.wrap { max-width: 1120px; margin: 0 auto; padding: 20px 16px 48px; }
header { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; margin-bottom: 18px; }
h1 { font-size: 18px; font-weight: 650; margin: 0; letter-spacing: -0.01em; }
h1 span { color: var(--muted); font-weight: 500; }
.pill {
display: inline-flex; align-items: center; gap: 7px; padding: 3px 10px; border-radius: 999px;
font-size: 12.5px; font-weight: 600; background: var(--panel-2); color: var(--muted);
}
.pill::before { content: ""; width: 7px; height: 7px; border-radius: 50%; background: currentColor; }
.pill.ready { background: var(--ok-weak); color: var(--ok); }
.pill.loading { background: var(--warn-weak); color: var(--warn); }
.pill.loading::before { animation: pulse 1.2s infinite ease-in-out; }
.pill.failed { background: var(--bad-weak); color: var(--bad); }
@keyframes pulse { 50% { opacity: .25; } }
.spacer { flex: 1; }
.meta { color: var(--muted); font-size: 12.5px; }
.grid { display: grid; gap: 14px; }
.top { grid-template-columns: minmax(0, 1.25fr) minmax(0, 1fr); }
@media (max-width: 820px) { .top { grid-template-columns: minmax(0, 1fr); } }
.panel { background: var(--panel); border: 1px solid var(--border); border-radius: 12px; padding: 16px; min-width: 0; }
.panel h2 { font-size: 12px; text-transform: uppercase; letter-spacing: .06em; color: var(--muted); margin: 0 0 12px; font-weight: 600; }
.current .name { font-size: 22px; font-weight: 650; letter-spacing: -0.015em; overflow-wrap: anywhere; }
.current .hwline { font-size: 12.5px; color: var(--muted); margin-top: 10px; }
.current .repo { font-family: var(--mono); font-size: 12.5px; color: var(--muted); overflow-wrap: anywhere; margin-top: 2px; }
.loadline {
margin-top: 12px; padding: 9px 11px; border-radius: 8px; background: var(--warn-weak); color: var(--text);
font-family: var(--mono); font-size: 12px; overflow-wrap: anywhere; display: none;
}
.loadline b { color: var(--warn); font-family: system-ui, sans-serif; margin-right: 6px; }
.btns { display: flex; gap: 8px; margin-top: 14px; flex-wrap: wrap; }
button {
font: inherit; font-size: 13px; font-weight: 550; padding: 7px 13px; border-radius: 8px; cursor: pointer;
border: 1px solid var(--border); background: var(--panel-2); color: var(--text);
}
button:hover:not(:disabled) { border-color: var(--faint); }
button:disabled { opacity: .45; cursor: default; }
button.primary { background: var(--accent); border-color: var(--accent); color: #fff; }
button.danger { color: var(--bad); }
.profiles { display: flex; flex-direction: column; gap: 8px; }
.prof {
display: flex; align-items: center; gap: 12px; padding: 10px 12px; border-radius: 10px;
border: 1px solid var(--border); background: var(--panel);
}
.prof.active { border-color: var(--accent); background: var(--accent-weak); }
.prof .info { flex: 1; min-width: 0; }
.prof .pn { font-weight: 600; }
.prof .pm { font-family: var(--mono); font-size: 11.5px; color: var(--muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.prof .dl { font-size: 11.5px; color: var(--warn); font-weight: 600; }
.excluded { margin-top: 12px; font-size: 12px; color: var(--faint); }
.excluded b { color: var(--muted); font-weight: 600; }
.prof .tag { font-size: 11.5px; color: var(--accent); font-weight: 600; white-space: nowrap; }
.tiles { grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); margin-top: 14px; }
.tile { background: var(--panel); border: 1px solid var(--border); border-radius: 12px; padding: 12px 14px; min-width: 0; }
.tile .k { font-size: 12px; color: var(--muted); }
.tile .v { font-size: 22px; font-weight: 650; font-variant-numeric: tabular-nums; letter-spacing: -0.01em; margin-top: 2px; white-space: nowrap; }
.tile .v small { font-size: 12.5px; font-weight: 500; color: var(--muted); margin-left: 3px; }
.tile .s { font-size: 11.5px; color: var(--faint); margin-top: 1px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.bar { height: 4px; border-radius: 2px; background: var(--panel-2); margin-top: 8px; overflow: hidden; }
.bar i { display: block; height: 100%; background: var(--accent); width: 0; transition: width .4s; }
.charts { grid-template-columns: repeat(3, minmax(0, 1fr)); margin-top: 14px; }
.charts.two { grid-template-columns: repeat(2, minmax(0, 1fr)); }
@media (max-width: 820px) { .charts, .charts.two { grid-template-columns: minmax(0, 1fr); } }
.chart .head { display: flex; justify-content: space-between; align-items: baseline; margin-bottom: 6px; }
.chart .head span { font-size: 12px; color: var(--muted); }
.chart .head b { font-size: 13px; font-variant-numeric: tabular-nums; }
.chart svg { width: 100%; height: 90px; display: block; touch-action: pan-y; cursor: crosshair; }
.plot { position: relative; }
.plot .tip {
position: absolute; z-index: 2; pointer-events: none; display: none; white-space: nowrap;
background: var(--text); color: var(--bg); border-radius: 6px; padding: 4px 8px;
font-size: 12.5px; font-weight: 600; font-variant-numeric: tabular-nums;
}
.plot .tip small { display: block; font-size: 11px; font-weight: 400; opacity: .72; }
.plot .dot {
position: absolute; z-index: 1; pointer-events: none; display: none;
width: 9px; height: 9px; border-radius: 50%; border: 2px solid var(--panel); transform: translate(-50%, -50%);
}
.chart .axis { display: flex; justify-content: space-between; font-size: 11px; color: var(--faint); margin-top: 4px; }
details.logs { margin-top: 14px; }
details.logs summary { cursor: pointer; font-size: 12px; text-transform: uppercase; letter-spacing: .06em; color: var(--muted); font-weight: 600; list-style: none; }
details.logs summary::before { content: "▸ "; }
details.logs[open] summary::before { content: "▾ "; }
pre {
margin: 12px 0 0; padding: 12px; border-radius: 8px; background: var(--panel-2); max-height: 380px; overflow: auto;
font: 11.5px/1.5 var(--mono); white-space: pre-wrap; overflow-wrap: anywhere;
}
.overlay { position: fixed; inset: 0; background: rgba(0,0,0,.45); display: none; align-items: center; justify-content: center; padding: 16px; z-index: 10; }
.overlay.show { display: flex; }
.dialog { background: var(--panel); border: 1px solid var(--border); border-radius: 14px; padding: 20px; width: 100%; max-width: 420px; }
.dialog h3 { margin: 0 0 6px; font-size: 16px; }
.dialog p { margin: 0 0 14px; color: var(--muted); font-size: 13px; }
.dialog input {
width: 100%; font: 13px var(--mono); padding: 9px 10px; border-radius: 8px; border: 1px solid var(--border);
background: var(--panel-2); color: var(--text); margin-bottom: 12px;
}
.dialog .err { color: var(--bad); font-size: 12.5px; min-height: 18px; margin: -6px 0 8px; }
.toast { position: fixed; bottom: 18px; left: 50%; transform: translateX(-50%); background: var(--text); color: var(--bg);
padding: 8px 14px; border-radius: 8px; font-size: 13px; opacity: 0; transition: opacity .25s; pointer-events: none; }
.toast.show { opacity: 1; }
</style>
</head>
<body>
<div class="wrap">
<header>
<h1>llm-host <span id="host"></span></h1>
<span id="phase" class="pill">…</span>
<span class="spacer"></span>
<span class="meta" id="uptime"></span>
<button id="logout" title="Forget API key">Sign out</button>
</header>
<div class="grid top">
<section class="panel current">
<h2>Serving</h2>
<div class="name" id="cur-name">—</div>
<div class="repo" id="cur-repo"></div>
<div class="hwline" id="hwline"></div>
<div class="loadline" id="loadline"><b id="load-title">Loading</b><span id="load-text"></span></div>
<div class="btns">
<button id="btn-restart">Restart</button>
<button id="btn-stop" class="danger">Stop</button>
<button id="btn-start" class="primary">Start</button>
</div>
</section>
<section class="panel">
<h2>Models</h2>
<div class="profiles" id="profiles"></div>
<div class="excluded" id="excluded"></div>
</section>
</div>
<div class="grid tiles">
<div class="tile"><div class="k">Generation</div><div class="v" id="t-gen">—</div><div class="s" id="t-gen-s"></div></div>
<div class="tile"><div class="k">Prompt processing</div><div class="v" id="t-prompt">—</div><div class="s" id="t-prompt-s"></div></div>
<div class="tile"><div class="k">Requests</div><div class="v" id="t-req">—</div><div class="s" id="t-req-s"></div></div>
<div class="tile"><div class="k">KV cache</div><div class="v" id="t-kv">—</div><div class="bar"><i id="b-kv"></i></div></div>
<div class="tile"><div class="k">GPU</div><div class="v" id="t-util">—</div><div class="s" id="t-util-s"></div></div>
<div class="tile"><div class="k">VRAM</div><div class="v" id="t-mem">—</div><div class="bar"><i id="b-mem"></i></div></div>
<div class="tile"><div class="k">MTP acceptance</div><div class="v" id="t-spec">—</div><div class="s">speculative tokens kept</div></div>
<div class="tile"><div class="k">Prefix cache hits</div><div class="v" id="t-prefix">—</div><div class="s">prompt tokens reused</div></div>
</div>
<div class="grid charts two">
<div class="panel chart"><div class="head"><span>Generation tok/s</span><b id="c-gen-v"></b></div><svg id="c-gen" viewBox="0 0 300 90" preserveAspectRatio="none"></svg><div class="axis"><span>10 min ago</span><span>now</span></div></div>
<div class="panel chart"><div class="head"><span>KV cache %</span><b id="c-kv-v"></b></div><svg id="c-kv" viewBox="0 0 300 90" preserveAspectRatio="none"></svg><div class="axis"><span>10 min ago</span><span>now</span></div></div>
</div>
<div class="grid charts">
<div class="panel chart"><div class="head"><span>GPU utilization %</span><b id="c-util-v"></b></div><svg id="c-util" viewBox="0 0 300 90" preserveAspectRatio="none"></svg><div class="axis"><span>10 min ago</span><span>now</span></div></div>
<div class="panel chart"><div class="head"><span>GPU temperature °C</span><b id="c-temp-v"></b></div><svg id="c-temp" viewBox="0 0 300 90" preserveAspectRatio="none"></svg><div class="axis"><span>10 min ago</span><span id="c-temp-max">0–100 °C</span><span>now</span></div></div>
<div class="panel chart"><div class="head"><span>GPU power W</span><b id="c-power-v"></b></div><svg id="c-power" viewBox="0 0 300 90" preserveAspectRatio="none"></svg><div class="axis"><span>10 min ago</span><span id="c-power-max"></span><span>now</span></div></div>
</div>
<details class="panel logs" id="logs">
<summary>Server log</summary>
<pre id="log-text">…</pre>
</details>
</div>
<div class="overlay" id="auth">
<form class="dialog" id="auth-form">
<h3>API key</h3>
<p>Enter the API key from <code>~/.config/llm-host/api_key</code> on the server (or run <code>llmhost key</code>). It's kept in this browser only.</p>
<input id="auth-key" type="password" autocomplete="current-password" placeholder="sk-…" required>
<div class="err" id="auth-err"></div>
<button class="primary" type="submit">Continue</button>
</form>
</div>
<div class="toast" id="toast"></div>
<script>
const $ = (id) => document.getElementById(id);
let KEY = null;
try { KEY = localStorage.getItem("llmhost-key"); } catch (e) {}
let state = null;
let logTimer = null;
$("host").textContent = "· " + location.hostname;
function toast(msg) {
const t = $("toast"); t.textContent = msg; t.classList.add("show");
clearTimeout(t._h); t._h = setTimeout(() => t.classList.remove("show"), 2600);
}
async function api(path, opts = {}) {
const r = await fetch(path, { ...opts, headers: { "Authorization": "Bearer " + KEY, "Content-Type": "application/json" } });
if (r.status === 401) { showAuth("That key was rejected."); throw new Error("unauthorized"); }
const body = await r.json();
if (!r.ok) throw new Error(body.error || r.statusText);
return body;
}
function showAuth(err = "") { $("auth-err").textContent = err; $("auth").classList.add("show"); $("auth-key").focus(); }
$("auth-form").addEventListener("submit", (e) => {
e.preventDefault();
KEY = $("auth-key").value.trim();
try { localStorage.setItem("llmhost-key", KEY); } catch (e) {}
$("auth").classList.remove("show");
poll();
});
$("logout").onclick = () => { try { localStorage.removeItem("llmhost-key"); } catch (e) {} KEY = null; showAuth(); };
const fmt = {
n: (v, d = 0) => v == null ? "—" : v.toLocaleString(undefined, { maximumFractionDigits: d, minimumFractionDigits: d }),
pct: (v) => v == null ? "—" : Math.round(v) + "%",
big: (v) => v == null ? "—" : v >= 1e9 ? (v / 1e9).toFixed(2) + "B" : v >= 1e6 ? (v / 1e6).toFixed(1) + "M" : v >= 1e3 ? (v / 1e3).toFixed(1) + "k" : String(Math.round(v)),
dur: (s) => { if (s == null) return ""; s = Math.floor(s); const d = Math.floor(s / 86400), h = Math.floor(s % 86400 / 3600), m = Math.floor(s % 3600 / 60);
return d ? `${d}d ${h}h` : h ? `${h}h ${m}m` : m ? `${m}m ${s % 60}s` : `${s}s`; },
ctx: (n) => n == null ? "" : n >= 1024 ? Math.round(n / 1024) + "k ctx" : n + " ctx",
};
function setV(id, value, unit) { $(id).innerHTML = value + (unit && value !== "—" ? `<small>${unit}</small>` : ""); }
function render(s) {
if (!s.models) return; // sampler hasn't run yet
state = s;
const busy = !!s.action || s.phase === "loading";
const ph = $("phase");
const labels = { ready: "Ready", loading: "Loading", stopped: "Stopped", failed: "Failed" };
ph.textContent = s.action ? ({ switch: "Switching", stop: "Stopping", start: "Starting", restart: "Restarting" }[s.action.kind]) : labels[s.phase] || s.phase;
ph.className = "pill " + (s.action ? "loading" : s.phase);
$("uptime").textContent = s.phase === "ready" && s.uptime ? "up " + fmt.dur(s.uptime) : "";
const prof = s.models.find((p) => p.name === s.active);
$("cur-name").textContent = s.phase === "stopped" ? "Nothing loaded" : (s.active || "—");
$("cur-repo").textContent = prof ? `${prof.repo} · ${prof.format}` : "";
$("hwline").textContent = [s.hardware, s.budget_gib ? `${s.budget_gib} GiB usable` : "", s.backend === "mlx" ? "MLX" : "vLLM"].filter(Boolean).join(" · ");
const ll = $("loadline");
if (s.phase === "loading" || s.phase === "failed") {
ll.style.display = "block";
if (s.phase === "loading" && prof && !prof.downloaded) $("load-title").dataset.dl = "1"; else delete $("load-title").dataset.dl;
$("load-title").textContent = s.phase === "failed" ? "Failed —" : ($("load-title").dataset.dl ? `Downloading ${prof.weights_gib} GiB, then loading —` : "Loading —");
$("load-text").textContent = s.last_log || (s.phase === "failed" ? "see server log below" : "starting…");
ll.style.background = s.phase === "failed" ? "var(--bad-weak)" : "";
} else ll.style.display = "none";
$("btn-stop").disabled = s.phase === "stopped" || !!s.action;
$("btn-restart").disabled = s.phase === "stopped" || !!s.action;
$("btn-start").disabled = !(s.phase === "stopped" || s.phase === "failed") || !!s.action;
const pr = $("profiles");
const want = JSON.stringify([s.models, s.active, busy, s.phase]);
if (pr._sig !== want) {
pr._sig = want;
pr.innerHTML = "";
for (const p of s.models) {
const isActive = p.name === s.active && s.phase !== "stopped";
const row = document.createElement("div");
row.className = "prof" + (isActive ? " active" : "");
row.innerHTML = `<div class="info"><div class="pn"></div><div class="pm"></div></div>`;
row.querySelector(".pn").textContent = p.name;
row.querySelector(".pm").textContent = `${p.format} · ${p.weights_gib} GiB · ~${fmt.ctx(p.est_context)}`;
row.querySelector(".pm").title = p.repo;
if (!p.downloaded) {
const dl = document.createElement("div"); dl.className = "dl"; dl.textContent = "Not downloaded yet";
row.querySelector(".info").appendChild(dl);
}
if (isActive) {
const tag = document.createElement("span"); tag.className = "tag";
tag.textContent = s.phase === "ready" && !s.action ? "Active" : "Loading…";
row.appendChild(tag);
} else {
const b = document.createElement("button"); b.textContent = p.downloaded ? "Load" : "Download & load"; b.disabled = busy;
b.onclick = () => switchTo(p);
row.appendChild(b);
}
pr.appendChild(row);
}
const ex = $("excluded");
ex.innerHTML = "";
if (s.excluded && s.excluded.length) {
ex.append("Too big for this hardware: ");
s.excluded.forEach((e, i) => {
const b = document.createElement("b"); b.textContent = e.name; b.title = e.reason;
ex.append(i ? ", " : "", b, ` (≥${e.smallest_gib} GiB)`);
});
}
}
const m = s.metrics || {}, g = s.gpu || {};
const live = s.phase === "ready";
setV("t-gen", live ? fmt.n(m.gen_tps, m.gen_tps < 10 ? 1 : 0) : "—", "tok/s");
$("t-gen-s").textContent = live && m.gen_total != null ? fmt.big(m.gen_total) + " generated" : "";
setV("t-prompt", live ? fmt.n(m.prompt_tps, 0) : "—", "tok/s");
$("t-prompt-s").textContent = live && m.prompt_total != null ? fmt.big(m.prompt_total) + " processed" : "";
$("t-req").innerHTML = live ? `${fmt.n(m.running)}<small>running</small>` : "—";
$("t-req-s").textContent = live ? `${fmt.n(m.waiting)} waiting` + (m.preemptions ? ` · ${fmt.n(m.preemptions)} preempted` : "") : "";
setV("t-kv", live ? fmt.n(m.kv_pct, 1) : "—", "%");
$("b-kv").style.width = (live && m.kv_pct != null ? m.kv_pct : 0) + "%";
setV("t-util", fmt.pct(g.util), "");
$("t-util-s").textContent = g.temp != null ? `${Math.round(g.temp)}°C · ${Math.round(g.power)} / ${Math.round(g.power_limit)} W` : "";
$("t-mem").innerHTML = g.mem_used != null ? `${(g.mem_used / 1024).toFixed(1)}<small>/ ${(g.mem_total / 1024).toFixed(0)} GiB</small>` : "—";
$("b-mem").style.width = (g.mem_total ? g.mem_used / g.mem_total * 100 : 0) + "%";
$("t-spec").textContent = live && m.spec_accept != null ? fmt.pct(m.spec_accept * 100) : "—";
$("t-prefix").textContent = live && m.prefix_hit != null ? fmt.pct(m.prefix_hit * 100) : "—";
const h = s.history || [];
chartTimes = h.map((p) => p.t);
chart("c-gen", h.map((p) => p.gen), "var(--c1)", null, (v) => fmt.n(v, 0) + " tok/s");
chart("c-util", h.map((p) => p.util), "var(--c2)", 100, (v) => fmt.pct(v));
chart("c-kv", h.map((p) => p.kv), "var(--c3)", null, (v) => fmt.n(v, 1) + "%");
// Fixed scales so the shape means something: 0–100 °C, and 0 to the board power limit.
chart("c-temp", h.map((p) => p.temp), "var(--c4)", 100, (v) => Math.round(v) + " °C");
$("c-temp-max").textContent = g.temp == null ? "not reported on this hardware" : "0–100 °C";
const plim = g.power_limit || 600;
$("c-power-max").textContent = g.power == null ? "not reported on this hardware" : `0–${Math.round(plim)} W`;
chart("c-power", h.map((p) => p.power), "var(--c5)", plim, (v) => Math.round(v) + " W");
}
const CW = 300, CH = 90, CN = 300; // chart viewBox width/height, max samples
let chartTimes = [];
function chart(id, vals, color, fixedMax, f) {
const svg = $(id), W = CW, H = CH, N = CN;
const pts = vals.slice(-N);
const times = chartTimes.slice(-N);
const last = [...pts].reverse().find((v) => v != null);
$(id + "-v").textContent = last != null ? f(last) : "";
const max = fixedMax || Math.max(1, ...pts.filter((v) => v != null)) * 1.15;
const x = (i) => W - (pts.length - 1 - i) * (W / (N - 1));
const y = (v) => H - 2 - (v / max) * (H - 4);
let d = "", area = "", segStart = null;
pts.forEach((v, i) => {
if (v == null) { if (segStart != null) { area += `L${x(i - 1)},${H}Z`; segStart = null; } return; }
if (segStart == null) { d += `M${x(i)},${y(v)}`; area += `M${x(i)},${H}L${x(i)},${y(v)}`; segStart = i; }
else { d += `L${x(i)},${y(v)}`; area += `L${x(i)},${y(v)}`; }
});
if (segStart != null) area += `L${x(pts.length - 1)},${H}Z`;
svg.innerHTML =
`<line x1="0" x2="${W}" y1="${H - 1}" y2="${H - 1}" stroke="var(--border)" />` +
`<path d="${area}" fill="${color}" fill-opacity="0.12" />` +
`<path d="${d}" fill="none" stroke="${color}" stroke-width="1.75" vector-effect="non-scaling-stroke" stroke-linejoin="round" />`;
svg._data = { pts, times, color, f, x, y };
drawHover(svg);
}
// ---- hover crosshair ----
// The hover position is kept in viewBox units so it survives the 2s redraws:
// the cursor stays put and the tooltip follows whatever sample is now under it.
function attachHover(svg) {
const plot = document.createElement("div");
plot.className = "plot";
svg.parentNode.insertBefore(plot, svg);
plot.appendChild(svg);
svg._tip = Object.assign(document.createElement("div"), { className: "tip" });
svg._dot = Object.assign(document.createElement("div"), { className: "dot" });
plot.append(svg._tip, svg._dot);
const move = (e) => {
const r = svg.getBoundingClientRect();
svg._hoverVX = (e.clientX - r.left) / r.width * CW;
drawHover(svg);
};
svg.addEventListener("pointermove", move);
svg.addEventListener("pointerdown", move);
svg.addEventListener("pointerleave", () => { svg._hoverVX = null; drawHover(svg); });
}
function timeLabel(t) {
const now = state && state.time ? state.time : Date.now() / 1000;
const clock = new Date(t * 1000).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit", second: "2-digit" });
const ago = now - t;
return `${clock} · ${ago < 3 ? "now" : fmt.dur(ago) + " ago"}`;
}
function drawHover(svg) {
const d = svg._data, tip = svg._tip, dot = svg._dot;
if (!tip) return;
const old = svg.querySelector(".guide");
if (old) old.remove();
const hide = () => { tip.style.display = "none"; dot.style.display = "none"; };
if (!d || svg._hoverVX == null || !d.pts.length) return hide();
// Samples are right-aligned: the newest sits at x = CW, one step per sample to the left.
const step = CW / (CN - 1);
let i = Math.round(d.pts.length - 1 - (CW - svg._hoverVX) / step);
if (i < 0) return hide();
i = Math.min(i, d.pts.length - 1);
// Snap to the nearest real sample if the cursor is over a gap (e.g. while a model loads).
if (d.pts[i] == null) {
let j = -1;
for (let k = 1; k <= 3 && j < 0; k++) {
if (d.pts[i - k] != null) j = i - k; else if (d.pts[i + k] != null) j = i + k;
}
if (j < 0) return hide();
i = j;
}
const v = d.pts[i], vx = d.x(i), vy = d.y(v);
svg.insertAdjacentHTML("beforeend",
`<line class="guide" x1="${vx}" x2="${vx}" y1="0" y2="${CH}" stroke="var(--faint)" stroke-dasharray="3 3" vector-effect="non-scaling-stroke" />`);
const r = svg.getBoundingClientRect();
const px = vx / CW * r.width, py = vy / CH * r.height;
Object.assign(dot.style, { display: "block", left: px + "px", top: py + "px", background: d.color });
tip.innerHTML = "";
tip.append(d.f(v), Object.assign(document.createElement("small"), { textContent: timeLabel(d.times[i]) }));
tip.style.display = "block";
const tw = tip.offsetWidth;
tip.style.left = Math.max(0, Math.min(r.width - tw, px - tw / 2)) + "px";
const above = py - tip.offsetHeight - 10;
tip.style.top = (above >= -24 ? above : py + 12) + "px";
}
document.querySelectorAll(".chart svg").forEach(attachHover);
async function switchTo(p) {
if (state && state.phase === "ready" && state.metrics && state.metrics.running > 0 &&
!confirm(`${state.metrics.running} request(s) are running on ${state.active}. Switch anyway?`)) return;
if (!p.downloaded && !confirm(`${p.name} isn't downloaded yet. Download ${p.weights_gib} GiB now and load it?`)) return;
try { await api("/api/switch", { method: "POST", body: JSON.stringify({ model: p.name }) }); toast(p.downloaded ? `Loading ${p.name}…` : `Downloading ${p.name}, then loading…`); poll(); }
catch (e) { toast("Switch failed: " + e.message); }
}
async function ctl(kind, confirmMsg) {
if (confirmMsg && !confirm(confirmMsg)) return;
try { await api("/api/" + kind, { method: "POST" }); poll(); } catch (e) { toast(kind + " failed: " + e.message); }
}
$("btn-stop").onclick = () => ctl("stop", "Stop the model server? This frees GPU memory; clients won't work until you start it again.");
$("btn-start").onclick = () => ctl("start");
$("btn-restart").onclick = () => ctl("restart", "Restart the model server? It takes a few minutes to come back.");
async function loadLogs() {
try { const r = await api("/api/logs"); const pre = $("log-text");
const atBottom = pre.scrollHeight - pre.scrollTop - pre.clientHeight < 30;
pre.textContent = r.lines.join("\n") || "(empty)";
if (atBottom) pre.scrollTop = pre.scrollHeight;
} catch (e) {}
}
$("logs").addEventListener("toggle", () => {
clearInterval(logTimer);
if ($("logs").open) { loadLogs(); logTimer = setInterval(loadLogs, 4000); }
});
let pollTimer = null;
async function poll() {
clearTimeout(pollTimer);
if (!KEY) { showAuth(); return; }
try { render(await api("/api/status")); }
catch (e) { if (e.message !== "unauthorized") { $("phase").textContent = "Dashboard unreachable"; $("phase").className = "pill failed"; } }
pollTimer = setTimeout(poll, 2000);
}
poll();
</script>
</body>
</html>

279
llmhost/web/server.py Normal file
View file

@ -0,0 +1,279 @@
"""Dashboard: status, metrics and model switching. Stdlib only.
Serves index.html and a JSON API on cfg["web_port"]. /api/* routes need the API key.
"""
import hmac
import json
import re
import socket
import threading
import time
import urllib.request
from collections import deque
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from .. import hfcache, hw, paths, service
HERE = Path(__file__).resolve().parent
SAMPLE_SECONDS = 2
HISTORY_POINTS = 300 # 10 minutes
# The sampler's own polling shows up in vLLM's access log every 2s; hide it from the log view.
OWN_POLL_RE = re.compile(r'127\.0\.0\.1:\d+ - "GET /(health|metrics|v1/models|llmhost/metrics) ')
PROGRESS_RE = re.compile(r"\d+(\.\d+)?(it/s|s/it)\]")
METRIC_RE = re.compile(r"^(vllm:[a-z_]+)(\{[^}]*\})?\s+([0-9.eE+-]+|NaN)$")
def http_get(url, key=None, timeout=2):
req = urllib.request.Request(url)
if key:
req.add_header("Authorization", f"Bearer {key}")
try:
with urllib.request.urlopen(req, timeout=timeout) as r:
return r.status, r.read().decode()
except Exception:
return None, ""
def parse_vllm_metrics(text):
vals = {}
for line in text.splitlines():
m = METRIC_RE.match(line)
if not m:
continue
name, labels, v = m.group(1), m.group(2) or "", m.group(3)
if name.endswith(("_created", "_bucket")) or "position=" in labels or "reason=" in labels or "by_source" in name:
continue
if name == "vllm:engine_sleep_state":
continue
try:
vals[name] = vals.get(name, 0.0) + float(v)
except ValueError:
pass
return {
"running": vals.get("vllm:num_requests_running"),
"waiting": vals.get("vllm:num_requests_waiting"),
"kv": vals.get("vllm:kv_cache_usage_perc"),
"gen_total": vals.get("vllm:generation_tokens_total"),
"prompt_total": vals.get("vllm:prompt_tokens_total"),
"prefix_hits": vals.get("vllm:prefix_cache_hits_total"),
"prefix_queries": vals.get("vllm:prefix_cache_queries_total"),
"spec_accepted": vals.get("vllm:spec_decode_num_accepted_tokens_total"),
"spec_drafted": vals.get("vllm:spec_decode_num_draft_tokens_total"),
"preemptions": vals.get("vllm:num_preemptions_total"),
}
class Sampler:
def __init__(self, cfg, key):
self.cfg = cfg
self.key = key
self.lock = threading.Lock()
self.history = deque(maxlen=HISTORY_POINTS)
self.prev = None
self.state = {}
self.action = None
self._dl_cache = (0, {})
def reload_cfg(self):
self.cfg = paths.load_config() or self.cfg
def downloaded(self):
t, cache = self._dl_cache
if time.time() - t > 30:
cache = {m["repo"]: hfcache.is_downloaded(m["repo"]) for m in self.cfg.get("models", [])}
self._dl_cache = (time.time(), cache)
return cache
def loop(self):
while True:
try:
self.sample()
except Exception as e:
with self.lock:
self.state["sampler_error"] = repr(e)
time.sleep(SAMPLE_SECONDS)
def sample(self):
self.reload_cfg()
cfg = self.cfg
now = time.time()
base = f"http://127.0.0.1:{cfg['api_port']}"
svc_state, uptime = service.state("model")
health, _ = http_get(base + "/health")
served, metrics = None, {}
if health == 200:
st, body = http_get(base + "/v1/models", self.key)
if st == 200:
try:
served = [m["id"] for m in json.loads(body)["data"]]
except (ValueError, KeyError):
pass
if cfg["backend"] == "vllm":
st, body = http_get(base + "/metrics")
metrics = parse_vllm_metrics(body) if st == 200 else {}
else:
st, body = http_get(base + "/llmhost/metrics")
try:
metrics = json.loads(body) if st == 200 else {}
except ValueError:
metrics = {}
active = cfg.get("active")
if svc_state in ("inactive", "failed"):
phase = "failed" if svc_state == "failed" else "stopped"
elif health == 200 and served and active in served:
phase = "ready"
else:
phase = "loading"
gen_rate = prompt_rate = None
if metrics.get("gen_total") is not None and self.prev:
pt, pm = self.prev
dt = now - pt
if dt > 0 and pm.get("gen_total") is not None:
gen_rate = max(metrics["gen_total"] - pm["gen_total"], 0) / dt
prompt_rate = max((metrics.get("prompt_total") or 0) - (pm.get("prompt_total") or 0), 0) / dt
self.prev = (now, metrics) if metrics else None
gpu = hw.live_stats(cfg["kind"])
kv = metrics.get("kv")
point = {
"t": now, "gen": gen_rate, "prompt": prompt_rate,
"kv": kv * 100 if kv is not None else None,
"util": gpu["util"] if gpu else None,
"temp": gpu["temp"] if gpu else None,
"power": gpu["power"] if gpu else None,
}
def ratio(a, b):
return metrics[a] / metrics[b] if metrics.get(b) else None
last_log = None
if phase in ("loading", "failed"):
lines = [l for l in service.logs("model", 20) if l.strip() and not OWN_POLL_RE.search(l)]
last_log = lines[-1][-240:] if lines else None
dl = self.downloaded()
models = [{**m, "downloaded": dl.get(m["repo"], False)} for m in cfg.get("models", [])]
with self.lock:
self.history.append(point)
if self.action and phase in ("ready", "stopped", "failed") and now - self.action["t"] > 6:
self.action = None
self.state = {
"time": now, "phase": phase, "service": svc_state, "uptime": uptime,
"host": socket.gethostname(), "backend": cfg["backend"], "kind": cfg["kind"],
"hardware": cfg.get("hardware_name"), "budget_gib": cfg.get("budget_gib"),
"active": active, "served_models": served, "models": models,
"excluded": cfg.get("excluded", []), "gpu": gpu, "last_log": last_log,
"action": self.action,
"metrics": {
"running": metrics.get("running"), "waiting": metrics.get("waiting"),
"kv_pct": point["kv"], "gen_tps": gen_rate, "prompt_tps": prompt_rate,
"gen_total": metrics.get("gen_total"), "prompt_total": metrics.get("prompt_total"),
"prefix_hit": ratio("prefix_hits", "prefix_queries"),
"spec_accept": ratio("spec_accepted", "spec_drafted"),
"preemptions": metrics.get("preemptions"),
},
}
def snapshot(self):
with self.lock:
s = dict(self.state)
s["history"] = list(self.history)
return s
def control(self, kind, model=None):
if kind == "switch":
cfg = paths.load_config()
cfg["active"] = model
paths.save_config(cfg)
self.cfg = cfg
fn = service.restart
else:
fn = {"stop": service.stop, "start": service.start, "restart": service.restart}[kind]
with self.lock:
self.action = {"kind": kind, "model": model, "t": time.time()}
self.history.clear()
self.prev = None
threading.Thread(target=fn, args=("model",), daemon=True).start()
def make_handler(sampler, key):
class Handler(BaseHTTPRequestHandler):
server_version = "llm-host"
def log_message(self, fmt, *args):
pass
def send_json(self, code, obj):
body = json.dumps(obj).encode()
self.send_response(code)
self.send_header("Content-Type", "application/json")
self.send_header("Cache-Control", "no-store")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def authed(self):
h = self.headers.get("Authorization", "")
tok = h[7:] if h.startswith("Bearer ") else ""
if hmac.compare_digest(tok.encode(), key.encode()):
return True
self.send_json(401, {"error": "unauthorized"})
return False
def do_GET(self):
path = self.path.split("?", 1)[0]
if path in ("/", "/index.html"):
body = (HERE / "index.html").read_bytes()
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Cache-Control", "no-store")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
elif path == "/api/status":
if self.authed():
self.send_json(200, sampler.snapshot())
elif path == "/api/logs":
if self.authed():
lines = [l for l in service.logs("model", 1500)
if not PROGRESS_RE.search(l) and not OWN_POLL_RE.search(l)]
self.send_json(200, {"lines": lines[-80:]})
else:
self.send_json(404, {"error": "not found"})
def do_POST(self):
path = self.path.split("?", 1)[0]
if not self.authed():
return
try:
n = int(self.headers.get("Content-Length") or 0)
data = json.loads(self.rfile.read(n) or b"{}") if n else {}
except ValueError:
return self.send_json(400, {"error": "bad json"})
if path == "/api/switch":
name = str(data.get("model", ""))
if name not in {m["name"] for m in sampler.cfg.get("models", [])}:
return self.send_json(400, {"error": f"unknown model {name!r}"})
sampler.control("switch", name)
return self.send_json(202, {"ok": True, "model": name})
if path in ("/api/stop", "/api/start", "/api/restart"):
sampler.control(path.rsplit("/", 1)[1])
return self.send_json(202, {"ok": True})
self.send_json(404, {"error": "not found"})
return Handler
def serve():
cfg = paths.load_config()
if not cfg:
raise SystemExit("not set up; run `llmhost setup`")
key = paths.api_key()
sampler = Sampler(cfg, key)
threading.Thread(target=sampler.loop, daemon=True).start()
srv = ThreadingHTTPServer(("0.0.0.0", cfg["web_port"]), make_handler(sampler, key))
print(f"llm-host dashboard on :{cfg['web_port']}", flush=True)
srv.serve_forever()

47
tools/refresh_catalog.py Executable file
View file

@ -0,0 +1,47 @@
#!/usr/bin/env python3
"""Refresh weight sizes in llmhost/catalog.json from the Hugging Face API.
python3 tools/refresh_catalog.py # report differences
python3 tools/refresh_catalog.py --write # update the file
"""
import json
import sys
import urllib.request
from pathlib import Path
CATALOG = Path(__file__).resolve().parent.parent / "llmhost/catalog.json"
def weights_gb(repo):
with urllib.request.urlopen(f"https://huggingface.co/api/models/{repo}?blobs=true", timeout=30) as r:
d = json.load(r)
total = sum((s.get("size") or 0) for s in d.get("siblings", [])
if s["rfilename"].endswith(".safetensors") and "/" not in s["rfilename"])
return round(total / 1e9, 1)
def main():
write = "--write" in sys.argv
text = CATALOG.read_text()
cat = json.loads(text)
changed = 0
for m in cat["models"]:
for fmt, v in m["variants"].items():
try:
gb = weights_gb(v["repo"])
except Exception as e:
print(f"!! {v['repo']}: {e}")
continue
if abs(gb - v["gb"]) >= 0.1:
print(f"{m['name']:18} {fmt:9} {v['gb']:>7} -> {gb:>7} GB {v['repo']}")
old = f'"repo": "{v["repo"]}", "gb": {v["gb"]}'
text = text.replace(old, f'"repo": "{v["repo"]}", "gb": {gb}')
changed += 1
if write and changed:
json.loads(text)
CATALOG.write_text(text)
print(f"{changed} size(s) {'updated' if write else 'differ'}")
if __name__ == "__main__":
main()