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

@ -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 {
<div class="panel chart"><div class="head"><span>Time to first token</span><b id="c-ttft-v"></b></div><svg id="c-ttft" 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="grid charts" id="gpu-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 class="panel chart" id="p-temp"><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" id="p-power"><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 class="panel chart" id="p-nogpu" hidden><div class="head"><span>GPU temperature &amp; power</span></div><div class="empty" id="nogpu-why">not available on this hardware</div></div>
</div>
<section class="panel runs" id="runs">
<div class="head">
<h2>Completed requests</h2>
<span class="sub" id="runs-sub"></span>
</div>
<div class="scroll">
<table>
<thead><tr>
<th>Finished</th><th>Duration</th><th>TTFT</th>
<th>Prompt</th><th>Prompt tok/s</th>
<th>Generated</th><th>Gen tok/s</th><th>Peak KV</th>
</tr></thead>
<tbody id="runs-body"></tbody>
<tfoot id="runs-foot"></tfoot>
</table>
</div>
<div class="empty" id="runs-empty" hidden>No requests finished yet.</div>
</section>
<details class="panel logs" id="logs">
<summary>Server log</summary>
<pre id="log-text">…</pre>
@ -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)}<small>/ ${(g.mem_total / 1024).toFixed(0)} GiB</small>` : "—";
@ -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

View file

@ -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"})