Proxy in front of vLLM too; dashboard reset/clear; opencode effort variants

- Move the MLX proxy into backends/proxy.py and run it on both backends:
  public port 1134 is the proxy, the model server listens on 127.0.0.1:1135.
  On vLLM this brings the reasoning chooser, the "default" alias and the
  per-request table. Effort levels the model lacks map to the nearest it has
  (high -> xhigh on qwen3.8); vLLM's own key is sent upstream; streamed runs
  are counted from the usage chunk (MTP packs several tokens per chunk).
- Dashboard: restore METRIC_RE (vLLM page stuck on "loading"); Statistics
  header with Reset, Requests header with Clear; drop the TTFT chart; rename
  token columns; Peak KV shows "-" when no samples cover a run.
- opencode: config snippet's model points at <provider>/default, and
  reasoning models get variants built from the levels the template accepts.
- README: proxy on both platforms; NVIDIA checklist split into verified / open.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
neil 2026-11-03 13:03:52 -08:00
parent 1121c3f908
commit 8879db44a0
12 changed files with 886 additions and 493 deletions

View file

@ -49,6 +49,10 @@ h1 span { color: var(--muted); font-weight: 500; }
.meta { color: var(--muted); font-size: 12.5px; }
.grid { display: grid; gap: 14px; }
.section-head { display: flex; align-items: center; gap: 10px; margin: 26px 0 -2px; }
.section-head h2 { margin: 0; font-size: 12px; text-transform: uppercase; letter-spacing: .06em; color: var(--muted); font-weight: 600; }
.section-head .sub { color: var(--muted); font-size: 12px; }
button.small { font-size: 12px; padding: 4px 10px; }
.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; }
@ -105,9 +109,7 @@ button.danger { color: var(--bad); }
.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.four { grid-template-columns: repeat(4, minmax(0, 1fr)); }
@media (max-width: 1100px) { .charts.four { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
@media (max-width: 820px) { .charts, .charts.four { grid-template-columns: minmax(0, 1fr); } }
@media (max-width: 820px) { .charts { 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; }
@ -126,9 +128,6 @@ 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; }
@ -202,6 +201,13 @@ pre {
</section>
</div>
<div class="section-head">
<h2>Statistics</h2>
<span class="sub" id="stats-since"></span>
<span class="spacer"></span>
<button id="btn-stats-reset" class="small" title="Empty the charts and count totals and averages from now">Reset</button>
</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>
@ -214,10 +220,9 @@ pre {
<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 four">
<div class="grid charts">
<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>Prompt processing tok/s</span><b id="c-prompt-v"></b></div><svg id="c-prompt" 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>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" id="gpu-charts">
@ -227,17 +232,20 @@ pre {
<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>
<div class="section-head">
<h2>Requests</h2>
<span class="sub" id="runs-sub"></span>
<span class="spacer"></span>
<button id="btn-runs-clear" class="small" title="Empty this table">Clear</button>
</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>
<th>Prompt tok</th><th>Prompt tok/s</th>
<th>Generated tok</th><th>Gen tok/s</th><th>Peak KV</th>
</tr></thead>
<tbody id="runs-body"></tbody>
<tfoot id="runs-foot"></tfoot>
@ -377,6 +385,8 @@ function render(s) {
const m = s.metrics || {}, g = s.gpu || {};
const live = s.phase === "ready";
$("stats-since").textContent = s.stats_since
? "since " + new Date(s.stats_since * 1000).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }) : "";
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");
@ -406,7 +416,6 @@ function render(s) {
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-prompt", h.map((p) => p.prompt), "var(--c6)", null, (v) => fmt.n(v, 0) + " tok/s");
chart("c-ttft", h.map((p) => p.ttft), "var(--c7)", null, (v) => fmt.secs(v));
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.
@ -416,7 +425,6 @@ function render(s) {
$("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."
@ -437,8 +445,8 @@ let effortBusy = false;
function renderEffort(s) {
const r = s.reasoning || {}, box = $("effort"), sel = $("effort-sel");
const opts = r.options || [];
// Hidden rather than disabled when there is nothing to choose: on vLLM there's no proxy
// to inject the kwarg, and a model whose template has no switches has nothing to offer.
// Hidden rather than disabled when there is nothing to choose: a model whose template
// has no switches has nothing to offer.
box.hidden = !opts.length && !r.why;
if (!opts.length) {
sel.innerHTML = "";
@ -483,12 +491,12 @@ $("effort-sel").onchange = async (e) => {
function renderRuns(s) {
const runs = s.runs || [], body = $("runs-body"), foot = $("runs-foot");
$("btn-runs-clear").disabled = !runs.length;
$("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";
$("runs-sub").textContent = "";
return;
}
const clock = (t) => new Date(t * 1000).toLocaleTimeString(undefined, { hour12: false });
@ -647,6 +655,12 @@ async function ctl(kind, confirmMsg) {
}
$("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-stats-reset").onclick = async () => {
try { await api("/api/stats/reset", { method: "POST" }); poll(); } catch (e) { toast("Reset failed: " + e.message); }
};
$("btn-runs-clear").onclick = async () => {
try { await api("/api/runs/clear", { method: "POST" }); poll(); } catch (e) { toast("Clear failed: " + e.message); }
};
$("btn-restart").onclick = () => ctl("restart", "Restart the model server? It takes a few minutes to come back.");
async function loadLogs() {

View file

@ -23,6 +23,7 @@ RUNS_SHOWN = 20 # completed requests in the run summary
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.
@ -81,6 +82,18 @@ def http_get(url, key=None, timeout=2):
return None, ""
def run_kv_peak(history, run, now, current):
"""Peak KV % over a finished run's window, from the sampled history. A run shorter
than the sampling interval has no samples, so the reading just after it ended stands
in -- but only while that's fresh: a run picked up later (after a dashboard restart,
say) has nothing to go on, and today's idle reading would claim a peak of 0%."""
window = [q["kv"] for q in history
if q["kv"] is not None and run["start"] <= q["t"] <= run["end"]]
if window:
return max(window)
return current if now - run["end"] <= 2 * SAMPLE_SECONDS else None
def parse_vllm_metrics(text):
vals = {}
for line in text.splitlines():
@ -123,6 +136,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.baseline = None # counter values at the last stats reset (see reset_stats)
self.stats_since = None
self.runs = deque(maxlen=RUNS_SHOWN)
self._seen_runs = set()
@ -160,15 +175,19 @@ class Sampler:
served = [m["id"] for m in json.loads(body)["data"]]
except (ValueError, KeyError):
pass
# The proxy records each request on either backend; on vLLM the engine's own
# /metrics (on the inner port) has the aggregates, KV usage included.
st, body = http_get(base + "/llmhost/metrics")
try:
proxied = json.loads(body) if st == 200 else {}
except ValueError:
proxied = {}
if cfg["backend"] == "vllm":
st, body = http_get(base + "/metrics")
st, body = http_get(f"http://127.0.0.1:{cfg['api_port'] + 1}/metrics")
metrics = parse_vllm_metrics(body) if st == 200 else {}
metrics["recent"] = proxied.get("recent") or []
else:
st, body = http_get(base + "/llmhost/metrics")
try:
metrics = json.loads(body) if st == 200 else {}
except ValueError:
metrics = {}
metrics = proxied
active = cfg.get("active")
if svc_state in ("inactive", "failed"):
@ -193,6 +212,7 @@ class Sampler:
if ttft is not None:
self.last_ttft = (now, ttft)
self.prev = (now, metrics) if metrics else None
shown = self.since_reset(metrics)
gpu = hw.live_stats(cfg["kind"])
kv = metrics.get("kv")
@ -205,7 +225,7 @@ class Sampler:
}
def ratio(a, b):
return metrics[a] / metrics[b] if metrics.get(b) else None
return shown[a] / shown[b] if shown.get(b) else None
def run_rates(r):
"""Split a run into its two phases: time to first token covers the prefill, the
@ -228,20 +248,18 @@ 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.
# the proxy can't do it, since it never sees KV usage (mlx_lm only logs it now and then).
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"],
"kv_peak_pct": run_kv_peak(self.history, r, now, point["kv"]),
"aborted": bool(r.get("aborted")),
})
if len(self._seen_runs) > 4 * RUNS_SHOWN:
@ -260,32 +278,76 @@ class Sampler:
"reasoning": reasoning,
"action": self.action,
"metrics": {
"running": metrics.get("running"), "waiting": metrics.get("waiting"),
"running": shown.get("running"), "waiting": shown.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"),
"gen_total": shown.get("gen_total"), "prompt_total": shown.get("prompt_total"),
"prefix_hit": ratio("prefix_hits", "prefix_queries"),
"spec_accept": ratio("spec_accepted", "spec_drafted"),
"preemptions": metrics.get("preemptions"),
"preemptions": shown.get("preemptions"),
"ttft_last": self.last_ttft[1] if self.last_ttft else None,
"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,
"ttft_count": shown.get("ttft_count"),
"kv_bytes": shown.get("kv_bytes"),
"kv_seqs": shown.get("kv_seqs"),
"kv_budget_bytes": shown.get("kv_budget_bytes"),
"kv_peak_pct": self.kv_peak_pct(shown),
},
"runs": list(self.runs)[::-1],
"stats_since": self.stats_since,
}
# Counters that run from the model server's start; a stats reset rebases these.
COUNTERS = ("gen_total", "prompt_total", "requests_total", "prefix_hits", "prefix_queries",
"spec_accepted", "spec_drafted", "preemptions", "ttft_sum", "ttft_count")
def since_reset(self, metrics):
"""metrics with the counters taken from the last reset rather than the server's
start. Rates are unaffected: they come from differences between samples."""
base = self.baseline
if not base:
return metrics
if any(metrics.get(k) is not None and base.get(k) is not None and metrics[k] < base[k]
for k in self.COUNTERS):
# The model server restarted since the reset, so its counters already start
# after it. (What came between the reset and the restart is lost.)
self.baseline = base = {}
out = dict(metrics)
for k in self.COUNTERS:
if out.get(k) is not None:
out[k] = out[k] - (base.get(k) or 0)
return out
def kv_peak_pct(self, shown):
"""Peak KV since the model started (MLX reports it); since a reset, the highest
sampled value instead -- the server's own peak can't be rebased."""
if self.stats_since is not None:
vals = [p["kv"] for p in self.history if p["kv"] is not None]
return max(vals) if vals else None
if shown.get("kv_peak_bytes") and shown.get("kv_budget_bytes"):
return shown["kv_peak_bytes"] / shown["kv_budget_bytes"] * 100
return None
def reset_stats(self):
"""Start the Statistics section over: empty the charts, count from now."""
with self.lock:
latest = self.prev[1] if self.prev else {}
self.baseline = {k: latest.get(k) for k in self.COUNTERS}
self.stats_since = time.time()
self.history.clear()
self.last_ttft = None
def clear_runs(self):
"""Empty the Requests table. Runs already seen stay seen, so they don't come back."""
with self.lock:
self.runs.clear()
def reasoning_state(self, cfg, active):
"""What the active model can be told about reasoning, and what it's set to.
Only MLX: on vLLM llm-host has no proxy in front, so nothing here could inject
the kwarg into a client's request."""
"""What the active model can be told about reasoning, and what it's set to. The
proxy in front of either backend applies it to each chat request."""
choice = next((m for m in cfg.get("models", []) if m["name"] == active), None)
if not choice or cfg.get("backend") != "mlx":
return {"options": [], "value": plan.DEFAULT, "why": "" if choice else None}
if not choice:
return {"options": [], "value": plan.DEFAULT, "why": None}
entry = next((m for m in paths.load_catalog()["models"] if m["name"] == active), None)
if not entry:
return {"options": [], "value": plan.DEFAULT, "why": None}
@ -404,6 +466,12 @@ def make_handler(sampler, key):
return self.send_json(400, {"error": "unsupported value for this model",
"allowed": allowed})
return self.send_json(200, {"ok": True, "value": data.get("value")})
if path == "/api/stats/reset":
sampler.reset_stats()
return self.send_json(200, {"ok": True})
if path == "/api/runs/clear":
sampler.clear_runs()
return self.send_json(200, {"ok": True})
if path in ("/api/stop", "/api/start", "/api/restart"):
sampler.control(path.rsplit("/", 1)[1])
return self.send_json(202, {"ok": True})