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

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