commit 5b9586ac803420ec2e1183ff7bc93c11b96b40bc Author: neil Date: Mon Nov 2 03:51:06 2026 -0800 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 Claude-Session: https://claude.ai/code/session_01QaE1hpvyZTJixEbUUMj9Ca diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b908d4c --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +__pycache__/ +*.pyc +.DS_Store diff --git a/README.md b/README.md new file mode 100644 index 0000000..8fb313b --- /dev/null +++ b/README.md @@ -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 ` | serve a different model (downloads it first if needed) | +| `llmhost download ` | 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://.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. diff --git a/install.sh b/install.sh new file mode 100755 index 0000000..18102b1 --- /dev/null +++ b/install.sh @@ -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" < 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) diff --git a/llmhost/backends/vllm.py b/llmhost/backends/vllm.py new file mode 100644 index 0000000..5183c9c --- /dev/null +++ b/llmhost/backends/vllm.py @@ -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)) diff --git a/llmhost/catalog.json b/llmhost/catalog.json new file mode 100644 index 0000000..97160f2 --- /dev/null +++ b/llmhost/catalog.json @@ -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} + } + } + ] +} diff --git a/llmhost/cli.py b/llmhost/cli.py new file mode 100644 index 0000000..f741ee7 --- /dev/null +++ b/llmhost/cli.py @@ -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 ` 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: .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) diff --git a/llmhost/hfcache.py b/llmhost/hfcache.py new file mode 100644 index 0000000..d06ac0d --- /dev/null +++ b/llmhost/hfcache.py @@ -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 diff --git a/llmhost/hw.py b/llmhost/hw.py new file mode 100644 index 0000000..10bed13 --- /dev/null +++ b/llmhost/hw.py @@ -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 diff --git a/llmhost/paths.py b/llmhost/paths.py new file mode 100644 index 0000000..9c92785 --- /dev/null +++ b/llmhost/paths.py @@ -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 diff --git a/llmhost/plan.py b/llmhost/plan.py new file mode 100644 index 0000000..72ccc09 --- /dev/null +++ b/llmhost/plan.py @@ -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 diff --git a/llmhost/service.py b/llmhost/service.py new file mode 100644 index 0000000..be7e50e --- /dev/null +++ b/llmhost/service.py @@ -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-`. +""" +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""" + + + + Label{_label(name)} + ProgramArguments + {paths.SHIM}run-{name} + RunAtLoad + KeepAliveSuccessfulExit + ThrottleInterval10 + StandardOutPath{log} + StandardErrorPath{log} + EnvironmentVariablesPATH{path_env} + + +""") + + +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 diff --git a/llmhost/web/__init__.py b/llmhost/web/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/llmhost/web/index.html b/llmhost/web/index.html new file mode 100644 index 0000000..d7140f0 --- /dev/null +++ b/llmhost/web/index.html @@ -0,0 +1,486 @@ + + + + + +llm-host + + + +
+
+

llm-host

+ … + + + +
+ +
+
+

Serving

+
—
+
+
+
Loading
+
+ + + +
+
+
+

Models

+
+
+
+
+ +
+
Generation
—
+
Prompt processing
—
+
Requests
—
+
KV cache
—
+
GPU
—
+
VRAM
—
+
MTP acceptance
—
speculative tokens kept
+
Prefix cache hits
—
prompt tokens reused
+
+ +
+
Generation tok/s
10 min agonow
+
KV cache %
10 min agonow
+
+
+
GPU utilization %
10 min agonow
+
GPU temperature °C
10 min ago0–100 °Cnow
+
GPU power W
10 min agonow
+
+ +
+ Server log +
…
+
+
+ +
+
+

API key

+

Enter the API key from ~/.config/llm-host/api_key on the server (or run llmhost key). It's kept in this browser only.

+ +
+ +
+
+
+ + + + diff --git a/llmhost/web/server.py b/llmhost/web/server.py new file mode 100644 index 0000000..3706ec8 --- /dev/null +++ b/llmhost/web/server.py @@ -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() diff --git a/tools/refresh_catalog.py b/tools/refresh_catalog.py new file mode 100755 index 0000000..08c2db5 --- /dev/null +++ b/tools/refresh_catalog.py @@ -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()