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) <noreply@anthropic.com>
This commit is contained in:
Neil Bantoc 2026-11-03 01:28:09 -08:00
parent 2c0818ca2b
commit 944eda06cc
3 changed files with 273 additions and 19 deletions

View file

@ -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(*_):