From 944eda06ccef779e70e11cd7bccba007ae14ed6f Mon Sep 17 00:00:00 2001 From: Neil Bantoc Date: Tue, 3 Nov 2026 01:28:09 -0800 Subject: [PATCH] Dashboard: KV cache on MLX, a completed-request table, honest GPU charts Three gaps, all of them things the dashboard drew but never filled. KV cache was never reported on MLX: /llmhost/metrics had no "kv" key at all, so the tile and chart sat empty. mlx_lm has no endpoint for it, but it logs "Prompt Cache: N sequences, X GB" (decimal GB, n_bytes/1e9) and that stream already passes through _pump_output, so pick it out there and report a fraction of --prompt-cache-bytes -- the same shape vLLM's kv already has, so the sampler needs no backend special-casing. Peak is kept alongside the current value. GPU temperature and power are root-only on macOS (powermetrics), so hw.live_stats has always returned None for them on Apple. Two permanently blank charts is worse than none: hide them and say why when the hardware doesn't report them. Add a completed-request table above the server log: when each request finished, its duration, time to first token, prompt and generated tokens, the rate for each phase, and peak KV during the run. Rates are split at the first token -- prompt tokens over TTFT, generated tokens over what's left -- since a single rate over the whole duration blurs prefill into generation. The proxy keeps the last 50 runs; peak KV is joined in by the sampler, which is the only side that samples KV on a timer. Also: close the upstream connection explicitly when a client hangs up mid-answer rather than leaving it to GC, log that in one line, and collapse mlx_lm's resulting BrokenPipeError traceback in the log view. Any other traceback is left verbatim. Co-Authored-By: Claude Opus 5 (1M context) --- llmhost/backends/mlx.py | 85 +++++++++++++++++++++++++--- llmhost/web/index.html | 119 +++++++++++++++++++++++++++++++++++++--- llmhost/web/server.py | 88 ++++++++++++++++++++++++++++- 3 files changed, 273 insertions(+), 19 deletions(-) diff --git a/llmhost/backends/mlx.py b/llmhost/backends/mlx.py index 070ed83..df35b25 100644 --- a/llmhost/backends/mlx.py +++ b/llmhost/backends/mlx.py @@ -12,16 +12,20 @@ import hmac import http.client import json import os +import re import shutil import signal import subprocess import sys import threading import time +from collections import deque from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from .. import paths +RECENT_RUNS = 50 # completed requests kept for the dashboard's summary + VENV = paths.DATA / "venv-mlx" PY = VENV / "bin/python" @@ -45,10 +49,16 @@ NOISE = (b'"GET /health HTTP', b"- INFO - HTTP Request: ", b"sending unauthentic FATAL = b"generation thread died" -def _pump_output(stream, on_fatal=None): +# mlx_lm logs the prompt cache's size periodically; it has no endpoint for it, so this +# line is the only way to see KV usage. Its "GB" is n_bytes/1e9 -- decimal, not GiB. +CACHE_RE = re.compile(rb"Prompt Cache: (\d+) sequences, ([\d.]+) GB") + + +def _pump_output(stream, on_fatal=None, stats=None): """Copy the child's output to ours, dropping noise. Splits on \r too so download progress bars still update instead of being held back until a newline. Calls on_fatal - when mlx_lm.server reports its generator died (it keeps running but can't answer).""" + when mlx_lm.server reports its generator died (it keeps running but can't answer). + Picks the prompt-cache size out of the stream on the way past.""" buf = b"" out = sys.stdout.buffer while True: @@ -67,6 +77,10 @@ def _pump_output(stream, on_fatal=None): if on_fatal and FATAL in seg: on_fatal() on_fatal = None + if stats is not None: + m = CACHE_RE.search(seg) + if m: + stats.set_kv(int(m.group(1)), float(m.group(2)) * 1e9) if buf: out.write(buf) out.flush() @@ -101,12 +115,30 @@ class Stats: self.ttft_sum = 0.0 # seconds from request received to first generated token, self.ttft_count = 0 # streamed requests only (non-streamed ones arrive all at once) self.ready = False # set once the model has actually answered (see _readiness_probe) + self.kv_bytes = None # prompt cache size, from mlx_lm's own log line + self.kv_seqs = None + self.kv_peak = None + self.kv_budget = None # --prompt-cache-bytes, so usage can be a fraction + self.recent = deque(maxlen=RECENT_RUNS) + + def set_kv(self, seqs, nbytes): + with self.lock: + self.kv_seqs, self.kv_bytes = seqs, nbytes + self.kv_peak = nbytes if self.kv_peak is None else max(self.kv_peak, nbytes) + + def add_run(self, run): + with self.lock: + self.recent.append(run) def snapshot(self): with self.lock: + kv = (self.kv_bytes / self.kv_budget) if (self.kv_bytes is not None and self.kv_budget) else None return {"running": self.running, "gen_total": self.gen_total, "prompt_total": self.prompt_total, "requests_total": self.requests_total, - "ttft_sum": self.ttft_sum, "ttft_count": self.ttft_count} + "ttft_sum": self.ttft_sum, "ttft_count": self.ttft_count, + "kv": kv, "kv_bytes": self.kv_bytes, "kv_seqs": self.kv_seqs, + "kv_peak_bytes": self.kv_peak, "kv_budget_bytes": self.kv_budget, + "recent": list(self.recent)} def _uncached(usage): @@ -183,6 +215,9 @@ def make_handler(inner_port, served_name, context, key, stats, aliases=()): if not self._authed(): return self._t0 = time.monotonic() + self._wall0 = time.time() + self._gen = 0 # tokens generated for THIS request + self._ttft = None n = int(self.headers.get("Content-Length") or 0) raw = self.rfile.read(n) if n else b"" strip_usage = False @@ -205,14 +240,29 @@ def make_handler(inner_port, served_name, context, key, stats, aliases=()): pass self._forward("POST", raw, strip_usage) + def _record_run(self, aborted): + """One finished request, for the dashboard's run summary. Peak KV during the run + is left to the dashboard: it samples KV on a timer, so it can take the max over + this run's window, which is more than the cache size happens to be at the end.""" + t0 = getattr(self, "_t0", None) + if t0 is None: + return + stats.add_run({"start": self._wall0, "end": time.time(), + "dur": time.monotonic() - t0, "gen": self._gen, + "prompt": getattr(self, "_pp", 0) or 0, + "ttft": self._ttft, "aborted": aborted}) + def _forward(self, method, raw, strip_usage=False): counted = self.path.startswith("/v1/") # health checks aren't requests + is_run = counted and method == "POST" + aborted = False + conn = None if counted: with stats.lock: stats.running += 1 stats.requests_total += 1 try: - conn = http.client.HTTPConnection("127.0.0.1", inner_port, timeout=3600) + conn = http.client.HTTPConnection("127.0.0.1", inner_port, timeout=3600) # noqa: F841 (closed in finally) headers = {"Content-Type": self.headers.get("Content-Type", "application/json")} if raw is not None: headers["Content-Length"] = str(len(raw)) @@ -251,20 +301,34 @@ def make_handler(inner_port, served_name, context, key, stats, aliases=()): self.wfile.write(buf) self.wfile.flush() else: + self._pp = 0 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 {} + self._gen = int(u.get("completion_tokens") or 0) + self._pp = _uncached(u) with stats.lock: - stats.gen_total += int(u.get("completion_tokens") or 0) - stats.prompt_total += _uncached(u) + stats.gen_total += self._gen + stats.prompt_total += self._pp except (ValueError, AttributeError): pass except (BrokenPipeError, ConnectionResetError): - pass + # The client gave up mid-answer (opencode cancelling a stream, say). Drop the + # upstream connection now rather than at GC time, and say so in one line: + # mlx_lm logs its own BrokenPipeError traceback when its writes stop landing. + aborted = True + sys.stderr.write("proxy: client disconnected; aborted the upstream request\n") finally: + if conn is not None: + try: + conn.close() + except Exception: + pass + if is_run: + self._record_run(aborted) if counted: with stats.lock: stats.running -= 1 @@ -303,10 +367,12 @@ def make_handler(inner_port, served_name, context, key, stats, aliases=()): 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 + self._gen += 1 first_token = True if first_token and not self._first and getattr(self, "_t0", None) is not None: self._first = True - stats.ttft_sum += time.monotonic() - self._t0 + self._ttft = time.monotonic() - self._t0 + stats.ttft_sum += self._ttft stats.ttft_count += 1 return bool(u) and not d.get("choices") return Proxy @@ -352,7 +418,8 @@ def run_server(cfg, entry, choice, args): print("llm-host: mlx_lm.server's generator crashed (often: out of GPU memory); restarting it", flush=True) child.terminate() - threading.Thread(target=_pump_output, args=(child.stdout, generator_died), daemon=True).start() + stats.kv_budget = int(choice["prompt_cache_gib"] * 2**30) if choice.get("prompt_cache_gib") else None + threading.Thread(target=_pump_output, args=(child.stdout, generator_died, stats), daemon=True).start() threading.Thread(target=_readiness_probe, args=(inner, stats), daemon=True).start() def stop(*_): diff --git a/llmhost/web/index.html b/llmhost/web/index.html index 70f5bf5..3f56396 100644 --- a/llmhost/web/index.html +++ b/llmhost/web/index.html @@ -116,6 +116,20 @@ button.danger { color: var(--bad); } } .chart .axis { display: flex; justify-content: space-between; font-size: 11px; color: var(--faint); margin-top: 4px; } +.runs { margin-top: 14px; } +.runs .head { display: flex; align-items: baseline; justify-content: space-between; gap: 10px; margin-bottom: 10px; } +.runs .head h2 { margin: 0; font-size: 12px; text-transform: uppercase; letter-spacing: .06em; color: var(--muted); font-weight: 600; } +.runs .head .sub { color: var(--muted); font-size: 12px; } +.runs .scroll { overflow-x: auto; } +.runs table { width: 100%; border-collapse: collapse; font-size: 12.5px; font-variant-numeric: tabular-nums; } +.runs th, .runs td { padding: 5px 10px 5px 0; text-align: right; white-space: nowrap; } +.runs th:first-child, .runs td:first-child { text-align: left; padding-left: 0; } +.runs th { color: var(--muted); font-weight: 600; border-bottom: 1px solid var(--border); font-size: 11.5px; } +.runs tbody tr + tr td { border-top: 1px solid color-mix(in srgb, var(--border) 55%, transparent); } +.runs td.none { color: var(--muted); } +.runs tr.aborted td:first-child::after { content: " cancelled"; color: var(--bad); font-size: 11px; } +.runs tfoot td { border-top: 1px solid var(--border); font-weight: 600; } +.runs .empty { color: var(--muted); font-size: 13px; padding: 6px 0 2px; } 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: "▸ "; } @@ -188,12 +202,32 @@ pre {
Time to first token
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
+
GPU temperature °C
10 min ago0–100 °Cnow
+
GPU power W
10 min agonow
+
+
+
+

Completed requests

+ +
+
+ + + + + + + + +
FinishedDurationTTFTPromptPrompt tok/sGeneratedGen tok/sPeak KV
+
+ +
+
Server log
…
@@ -339,6 +373,10 @@ function render(s) { $("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) + "%"; + if (m.kv_bytes != null && m.kv_budget_bytes) { + $("t-kv").title = `${(m.kv_bytes / 1e9).toFixed(2)} GB of ${(m.kv_budget_bytes / 1e9).toFixed(0)} GB` + + (m.kv_seqs != null ? ` · ${m.kv_seqs} sequences` : ""); + } 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)}/ ${(g.mem_total / 1024).toFixed(0)} GiB` : "—"; @@ -354,11 +392,76 @@ function render(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"); + // Apple Silicon reports neither through any API that works without root (powermetrics + // needs sudo), so hide the panels instead of drawing two charts that can never fill. + const hasTP = g.temp != null || g.power != null || h.some((p) => p.temp != null || p.power != null); + $("p-temp").hidden = !hasTP; + $("p-power").hidden = !hasTP; + $("p-nogpu").hidden = hasTP; + $("gpu-charts").classList.toggle("four", false); + if (!hasTP) { + $("nogpu-why").textContent = s.kind === "apple" + ? "macOS only exposes GPU temperature and power to root (powermetrics), so they aren't charted here." + : "not reported by this hardware"; + } else { + chart("c-temp", h.map((p) => p.temp), "var(--c4)", 100, (v) => Math.round(v) + " °C"); + $("c-temp-max").textContent = "0–100 °C"; + const plim = g.power_limit || 600; + $("c-power-max").textContent = `0–${Math.round(plim)} W`; + chart("c-power", h.map((p) => p.power), "var(--c5)", plim, (v) => Math.round(v) + " W"); + } + renderRuns(s); +} + +function renderRuns(s) { + const runs = s.runs || [], body = $("runs-body"), foot = $("runs-foot"); + $("runs-empty").hidden = runs.length > 0; + $("runs").hidden = s.backend !== "mlx" && runs.length === 0; + body.textContent = ""; + foot.textContent = ""; + if (!runs.length) { + $("runs-sub").textContent = s.backend === "mlx" ? "" : "per-request timings are only collected on MLX"; + return; + } + const clock = (t) => new Date(t * 1000).toLocaleTimeString(undefined, { hour12: false }); + const cell = (tr, text, cls) => { + const td = document.createElement("td"); + td.textContent = text; + if (cls) td.className = cls; + tr.append(td); + return td; + }; + const dash = (v, f) => (v == null ? ["—", "none"] : [f(v), ""]); + for (const r of runs) { + const tr = document.createElement("tr"); + if (r.aborted) tr.className = "aborted"; + cell(tr, clock(r.t)); + cell(tr, ...dash(r.dur, fmt.secs)); + cell(tr, ...dash(r.ttft, fmt.secs)); + cell(tr, ...dash(r.prompt, (v) => fmt.big(v))); + cell(tr, ...dash(r.prompt_tps, (v) => fmt.n(v, 0))); + cell(tr, ...dash(r.gen, (v) => fmt.big(v))); + cell(tr, ...dash(r.gen_tps, (v) => fmt.n(v, 1))); + cell(tr, ...dash(r.kv_peak_pct, (v) => fmt.n(v, 1) + "%")); + body.append(tr); + } + // Averages over the runs shown, so the row means the same thing as the table above it. + const avg = (k) => { + const xs = runs.map((r) => r[k]).filter((v) => v != null); + return xs.length ? xs.reduce((a, b) => a + b, 0) / xs.length : null; + }; + const peak = Math.max(...runs.map((r) => r.kv_peak_pct ?? 0)); + const tr = document.createElement("tr"); + cell(tr, `${runs.length} shown`); + cell(tr, ...dash(avg("dur"), fmt.secs)); + cell(tr, ...dash(avg("ttft"), fmt.secs)); + cell(tr, ...dash(avg("prompt"), (v) => fmt.big(v))); + cell(tr, ...dash(avg("prompt_tps"), (v) => fmt.n(v, 0))); + cell(tr, ...dash(avg("gen"), (v) => fmt.big(v))); + cell(tr, ...dash(avg("gen_tps"), (v) => fmt.n(v, 1))); + cell(tr, ...dash(peak > 0 ? peak : null, (v) => fmt.n(v, 1) + "%")); + foot.append(tr); + $("runs-sub").textContent = "newest first · averages below · tok/s split at first token"; } const CW = 300, CH = 90, CN = 300; // chart viewBox width/height, max samples diff --git a/llmhost/web/server.py b/llmhost/web/server.py index 605463d..993cab4 100644 --- a/llmhost/web/server.py +++ b/llmhost/web/server.py @@ -18,11 +18,56 @@ from .. import hfcache, hw, opencode, paths, service HERE = Path(__file__).resolve().parent SAMPLE_SECONDS = 2 HISTORY_POINTS = 300 # 10 minutes +RUNS_SHOWN = 20 # completed requests in the run summary # 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) ' r'|- INFO - HTTP Request: ') PROGRESS_RE = re.compile(r"\d+(\.\d+)?(it/s|s/it)\]") -METRIC_RE = re.compile(r"^(vllm:[a-z_]+)(\{[^}]*\})?\s+([0-9.eE+-]+|NaN)$") +# A client that hangs up mid-answer leaves mlx_lm writing to a closed socket, and its +# ThreadingHTTPServer prints a full traceback for it. That's expected (the proxy logs the +# disconnect in one line), so collapse the block instead of letting it bury the log. +DASHES_RE = re.compile(r"^-{20,}\s*$") +EXC_HEAD_RE = re.compile(r"^Exception occurred during processing of request") +DISCONNECT_RE = re.compile(r"^(BrokenPipeError|ConnectionResetError)\b") +MAX_TRACE_LINES = 80 + + +def collapse_disconnects(lines): + """Replace each mlx_lm traceback that ends in a broken pipe with one line. Any other + traceback is left exactly as it is -- those are worth reading in full. + + socketserver brackets each one with a row of dashes, which is what delimits a block + here; a block that never closes (the log was truncated, or is still being written) + is emitted unchanged.""" + out, block = [], None + + def flush(decide): + nonlocal block + if block is None: + return + if decide and any(DISCONNECT_RE.match(l.split(" - ")[-1].lstrip()) for l in block): + out.append(f" [client disconnected mid-answer; {len(block)} lines of traceback hidden]") + else: + out.extend(block) + block = None + + for l in lines: + bare = l.rstrip() + if block is None: + if DASHES_RE.match(bare) or EXC_HEAD_RE.match(bare): + block = [l] + else: + out.append(l) + continue + if DASHES_RE.match(bare): + block.append(l) + flush(True) + continue + block.append(l) + if len(block) > MAX_TRACE_LINES: + flush(False) + flush(False) + return out def http_get(url, key=None, timeout=2): @@ -78,6 +123,8 @@ class Sampler: self.action = None self._dl_cache = (0, {}) self.last_ttft = None # (time, seconds) of the latest sample with new first tokens + self.runs = deque(maxlen=RUNS_SHOWN) + self._seen_runs = set() def reload_cfg(self): self.cfg = paths.load_config() or self.cfg @@ -160,6 +207,15 @@ class Sampler: def ratio(a, b): return metrics[a] / metrics[b] if metrics.get(b) else None + def run_rates(r): + """Split a run into its two phases: time to first token covers the prefill, the + rest is generation. Rates over the whole duration would blur the two together.""" + dur, ttft = r.get("dur") or 0, r.get("ttft") + prompt_tps = (r["prompt"] / ttft) if (ttft and r.get("prompt")) else None + gen_window = dur - ttft if (ttft is not None and dur > ttft) else dur + gen_tps = (r["gen"] / gen_window) if (gen_window and r.get("gen")) else None + return gen_tps, prompt_tps + 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)] @@ -170,6 +226,28 @@ class Sampler: with self.lock: self.history.append(point) + # Peak KV per run is taken from the sampled history over the run's own window; + # the proxy can't do it, since it only learns KV when mlx_lm happens to log it. + for r in metrics.get("recent") or []: + key = (r.get("start"), r.get("end")) + if key in self._seen_runs or r.get("start") is None: + continue + self._seen_runs.add(key) + window = [q["kv"] for q in self.history + if q["kv"] is not None and r["start"] <= q["t"] <= r["end"]] + gen_tps, prompt_tps = run_rates(r) + self.runs.append({ + "t": r["end"], "dur": r.get("dur"), "gen": r.get("gen"), + "prompt": r.get("prompt"), "ttft": r.get("ttft"), + "gen_tps": gen_tps, "prompt_tps": prompt_tps, + "kv_peak_pct": max(window) if window else point["kv"], + "aborted": bool(r.get("aborted")), + }) + if len(self._seen_runs) > 4 * RUNS_SHOWN: + # The proxy only ever re-offers its own last RECENT_RUNS, so forgetting the + # oldest keys can't resurrect a run we already have. + self._seen_runs = {(r["t"], r["t"]) for r in self.runs} | { + (q.get("start"), q.get("end")) for q in (metrics.get("recent") or [])} if self.action and phase in ("ready", "stopped", "failed") and now - self.action["t"] > 6: self.action = None self.state = { @@ -190,7 +268,13 @@ class Sampler: "ttft_last_t": self.last_ttft[0] if self.last_ttft else None, "ttft_avg": ratio("ttft_sum", "ttft_count"), "ttft_count": metrics.get("ttft_count"), + "kv_bytes": metrics.get("kv_bytes"), + "kv_seqs": metrics.get("kv_seqs"), + "kv_budget_bytes": metrics.get("kv_budget_bytes"), + "kv_peak_pct": (metrics["kv_peak_bytes"] / metrics["kv_budget_bytes"] * 100) + if metrics.get("kv_peak_bytes") and metrics.get("kv_budget_bytes") else None, }, + "runs": list(self.runs)[::-1], } def snapshot(self): @@ -257,7 +341,7 @@ def make_handler(sampler, key): 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:]}) + self.send_json(200, {"lines": collapse_disconnects(lines)[-80:]}) else: self.send_json(404, {"error": "not found"})