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/web/__init__.py
Normal file
0
llmhost/web/__init__.py
Normal file
486
llmhost/web/index.html
Normal file
486
llmhost/web/index.html
Normal 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
279
llmhost/web/server.py
Normal 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()
|
||||
Loading…
Add table
Add a link
Reference in a new issue