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:
commit
5b9586ac80
19 changed files with 2458 additions and 0 deletions
0
llmhost/backends/__init__.py
Normal file
0
llmhost/backends/__init__.py
Normal file
200
llmhost/backends/mlx.py
Normal file
200
llmhost/backends/mlx.py
Normal 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
155
llmhost/backends/vllm.py
Normal 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))
|
||||
Loading…
Add table
Add a link
Reference in a new issue