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:
parent
1121c3f908
commit
8879db44a0
12 changed files with 886 additions and 493 deletions
|
|
@ -1,45 +1,22 @@
|
|||
"""MLX backend (Apple Silicon).
|
||||
|
||||
mlx_lm.server has no API-key support and loads whatever model a request names, so it
|
||||
listens on localhost only and this module runs a small proxy on the public port that:
|
||||
- checks the API key (like vLLM's --api-key),
|
||||
- rejects a request for a model that isn't the loaded one (404 model_not_found),
|
||||
then rewrites the request's "model" to the loaded one, and answers /v1/models with
|
||||
the served name, so clients see the same API as on vLLM,
|
||||
- counts in-flight requests and generated tokens for the dashboard (/llmhost/metrics).
|
||||
listens on localhost only, behind llm-host's proxy (backends/proxy.py) on the public port.
|
||||
This module adds what's particular to mlx_lm: a readiness probe (its /health is OK before
|
||||
the model has loaded), KV usage read from its log, and a restart when its generator dies.
|
||||
"""
|
||||
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 hfcache, paths, plan
|
||||
|
||||
RECENT_RUNS = 50 # completed requests kept for the dashboard's summary
|
||||
|
||||
_cfg_cache = {"mtime": None, "cfg": {}}
|
||||
|
||||
|
||||
def live_cfg():
|
||||
"""config.json, re-read when it changes. The reasoning setting is edited from the
|
||||
dashboard while this process runs, and it must take effect without a restart --
|
||||
a restart would unload the model, which is the whole thing we're avoiding."""
|
||||
try:
|
||||
mtime = paths.CONFIG_FILE.stat().st_mtime
|
||||
except OSError:
|
||||
return _cfg_cache["cfg"]
|
||||
if mtime != _cfg_cache["mtime"]:
|
||||
_cfg_cache["mtime"], _cfg_cache["cfg"] = mtime, paths.load_config()
|
||||
return _cfg_cache["cfg"]
|
||||
from . import proxy
|
||||
|
||||
VENV = paths.DATA / "venv-mlx"
|
||||
PY = VENV / "bin/python"
|
||||
|
|
@ -56,7 +33,6 @@ def install(hw, log=print):
|
|||
return {}
|
||||
|
||||
|
||||
QUIET_PATHS = {"/health", "/v1/models", "/llmhost/metrics"}
|
||||
# Lines from mlx_lm.server / huggingface_hub that add nothing to the log.
|
||||
NOISE = (b'"GET /health HTTP', b"- INFO - HTTP Request: ", b"sending unauthenticated requests to the HF Hub")
|
||||
|
||||
|
|
@ -120,334 +96,17 @@ def _readiness_probe(inner_port, stats):
|
|||
time.sleep(3)
|
||||
|
||||
|
||||
class Stats:
|
||||
def __init__(self):
|
||||
self.lock = threading.Lock()
|
||||
self.running = 0
|
||||
self.gen_total = 0
|
||||
self.prompt_total = 0
|
||||
self.requests_total = 0
|
||||
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,
|
||||
"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):
|
||||
"""Prompt tokens the server actually processed: cached prefix tokens cost nothing."""
|
||||
n = int(usage.get("prompt_tokens") or 0)
|
||||
cached = (usage.get("prompt_tokens_details") or {}).get("cached_tokens") or 0
|
||||
return max(n - int(cached), 0)
|
||||
|
||||
|
||||
def make_handler(inner_port, served_name, context, key, stats, aliases=(), reasoning=None):
|
||||
# Names a client may call the loaded model: its llm-host name, its repo id, and the
|
||||
# stable alias that means "whatever is loaded" (plan.SERVED_ALIAS).
|
||||
accepted = {served_name.lower(), plan.SERVED_ALIAS, *(a.lower() for a in aliases if a)}
|
||||
|
||||
class Proxy(BaseHTTPRequestHandler):
|
||||
protocol_version = "HTTP/1.1"
|
||||
|
||||
def log_message(self, fmt, *a):
|
||||
# The dashboard polls these every 2s from localhost; logging them buries real traffic.
|
||||
if self.client_address[0] in ("127.0.0.1", "::1") and self.path.split("?")[0] in QUIET_PATHS:
|
||||
return
|
||||
sys.stderr.write("proxy: %s - %s\n" % (self.address_string(), fmt % a))
|
||||
|
||||
def _json(self, code, obj):
|
||||
body = json.dumps(obj).encode()
|
||||
self.send_response(code)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def _authed(self):
|
||||
h = self.headers.get("Authorization", "")
|
||||
tok = h[7:] if h.startswith("Bearer ") else ""
|
||||
if hmac.compare_digest(tok.encode(), key.encode()):
|
||||
return True
|
||||
self._json(401, {"error": {"message": "invalid API key", "type": "auth"}})
|
||||
return False
|
||||
|
||||
def do_GET(self):
|
||||
if self.path == "/health":
|
||||
# mlx_lm's /health is OK as soon as its thread runs, even while the model is
|
||||
# still downloading. Report ready only after a real generation has succeeded.
|
||||
if not stats.ready:
|
||||
return self._json(503, {"status": "loading"})
|
||||
return self._forward("GET", None)
|
||||
if self.path == "/llmhost/metrics":
|
||||
if self.client_address[0] not in ("127.0.0.1", "::1"):
|
||||
return self._json(403, {"error": "local only"})
|
||||
return self._json(200, stats.snapshot())
|
||||
if not self._authed():
|
||||
return
|
||||
if self.path.startswith("/v1/models"):
|
||||
return self._json(200, {"object": "list", "data": [
|
||||
{"id": served_name, "object": "model", "owned_by": "llm-host", "max_model_len": context}]})
|
||||
self._forward("GET", None)
|
||||
|
||||
def _model_ok(self, body):
|
||||
"""One model is loaded at a time, and mlx_lm answers with whatever it has
|
||||
regardless of the name asked for -- so an unrecognised name would come back
|
||||
as another model's output wearing it. Refuse it instead."""
|
||||
want = body.get("model")
|
||||
if not isinstance(want, str) or not want.strip():
|
||||
return True # no preference stated: the loaded one it is
|
||||
if want.strip().lower() in accepted:
|
||||
return True
|
||||
self._json(404, {"error": {
|
||||
"message": f"model '{want}' is not loaded; this server is serving "
|
||||
f"'{served_name}'. Load it with `llmhost switch {want}` "
|
||||
f"(one model is loaded at a time), or ask for '{served_name}' "
|
||||
f"-- or for '{plan.SERVED_ALIAS}', which always means whatever "
|
||||
f"is loaded.",
|
||||
"type": "invalid_request_error", "code": "model_not_found", "param": "model"}})
|
||||
return False
|
||||
|
||||
def do_POST(self):
|
||||
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
|
||||
try:
|
||||
body = json.loads(raw or b"{}")
|
||||
if isinstance(body, dict):
|
||||
if self.path.startswith("/v1/") and not self._model_ok(body):
|
||||
return
|
||||
# Server-side reasoning default. Only chat completions go through a
|
||||
# chat template, and a key the client set itself always wins -- the
|
||||
# same precedence mlx_lm applies to its own --chat-template-kwargs.
|
||||
if reasoning and "chat/completions" in self.path:
|
||||
kw = reasoning()
|
||||
if kw:
|
||||
mine = dict(kw)
|
||||
theirs = body.get("chat_template_kwargs")
|
||||
if isinstance(theirs, dict):
|
||||
mine.update(theirs)
|
||||
body["chat_template_kwargs"] = mine
|
||||
# Force the preloaded model: mlx_lm would otherwise try to load a
|
||||
# model matching the name it's given.
|
||||
body["model"] = "default_model"
|
||||
# Ask for the final usage chunk so prompt tokens can be counted, and
|
||||
# hide it again from clients that didn't ask for it.
|
||||
opts = body.get("stream_options") or {}
|
||||
if body.get("stream") and not opts.get("include_usage"):
|
||||
body["stream_options"] = {**opts, "include_usage": True}
|
||||
strip_usage = True
|
||||
raw = json.dumps(body).encode()
|
||||
except ValueError:
|
||||
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) # 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))
|
||||
try:
|
||||
conn.request(method, self.path, body=raw, headers=headers)
|
||||
resp = conn.getresponse()
|
||||
except OSError:
|
||||
return self._json(503, {"error": {"message": "model server not ready", "type": "unavailable"}})
|
||||
self.send_response(resp.status)
|
||||
ctype = resp.getheader("Content-Type", "application/json")
|
||||
self.send_header("Content-Type", ctype)
|
||||
streaming = "text/event-stream" in ctype
|
||||
if streaming:
|
||||
self.send_header("Cache-Control", "no-cache")
|
||||
self.send_header("Connection", "close")
|
||||
self.end_headers()
|
||||
self.close_connection = True
|
||||
buf = b""
|
||||
self._first = False
|
||||
self._pp = 0 # prompt tokens of this request already counted
|
||||
while True:
|
||||
chunk = resp.read1(65536) if hasattr(resp, "read1") else resp.read(4096)
|
||||
if not chunk:
|
||||
break
|
||||
buf += chunk
|
||||
# Forward whole events (the server writes one per token anyway).
|
||||
while b"\n\n" in buf:
|
||||
event, buf = buf.split(b"\n\n", 1)
|
||||
if event.startswith(b": keepalive "):
|
||||
self._count_progress(event)
|
||||
usage_only = self._count_event(event)
|
||||
if not (strip_usage and usage_only):
|
||||
self.wfile.write(event + b"\n\n")
|
||||
self.wfile.flush()
|
||||
if buf:
|
||||
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 += self._gen
|
||||
stats.prompt_total += self._pp
|
||||
except (ValueError, AttributeError):
|
||||
pass
|
||||
except (BrokenPipeError, ConnectionResetError):
|
||||
# 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
|
||||
|
||||
def _count_progress(self, event):
|
||||
"""mlx_lm.server sends ': keepalive <done>/<total>' after each prefill step of a
|
||||
streamed request (counting only the part not found in its prompt cache). Count
|
||||
those as they arrive so the prompt rate shows prefill while it happens, not as
|
||||
one spike when the request ends (or never, if the client gives up first)."""
|
||||
try:
|
||||
done = int(event[12:].split(b"/")[0])
|
||||
except ValueError:
|
||||
return
|
||||
if done > self._pp:
|
||||
with stats.lock:
|
||||
stats.prompt_total += done - self._pp
|
||||
self._pp = done
|
||||
|
||||
def _count_event(self, event):
|
||||
"""Update token counts; returns True for a usage-only chunk (no choices)."""
|
||||
if not event.startswith(b"data: {"):
|
||||
return False
|
||||
try:
|
||||
d = json.loads(event[6:])
|
||||
except ValueError:
|
||||
return False
|
||||
u = d.get("usage")
|
||||
first_token = False
|
||||
with stats.lock:
|
||||
if u: # final usage chunk: top up whatever the progress events didn't cover
|
||||
rest = _uncached(u) - self._pp
|
||||
if rest > 0:
|
||||
stats.prompt_total += rest
|
||||
self._pp += rest
|
||||
for c in d.get("choices") or []:
|
||||
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
|
||||
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
|
||||
|
||||
|
||||
def _kill_stale_servers(inner_port):
|
||||
"""Stop mlx_lm.server processes left behind by an earlier crash of this service.
|
||||
Only processes running from our own venv are touched."""
|
||||
out = subprocess.run(["lsof", "-nP", f"-iTCP:{inner_port}", "-sTCP:LISTEN", "-t"],
|
||||
capture_output=True, text=True).stdout.split()
|
||||
for pid in out:
|
||||
cmd = subprocess.run(["ps", "-o", "command=", "-p", pid], capture_output=True, text=True).stdout
|
||||
if str(VENV) in cmd and "mlx_lm" in cmd:
|
||||
print(f"llm-host: stopping leftover mlx_lm.server (pid {pid}) on port {inner_port}", flush=True)
|
||||
try:
|
||||
os.kill(int(pid), signal.SIGTERM)
|
||||
except OSError:
|
||||
pass
|
||||
if out:
|
||||
time.sleep(2)
|
||||
|
||||
|
||||
def run_server(cfg, entry, choice, args):
|
||||
"""Start the auth proxy on api_port, then mlx_lm.server as a child on api_port+1."""
|
||||
"""Start the proxy on api_port, then mlx_lm.server as a child on api_port+1."""
|
||||
port = cfg["api_port"]
|
||||
inner = port + 1
|
||||
# Claim the public port first: if it's taken, fail before starting (and orphaning) a child.
|
||||
stats = Stats()
|
||||
# The template is fixed for this process, so read its knobs once; the chosen level is
|
||||
# read per request, since the dashboard can change it while we run.
|
||||
stats = proxy.Stats()
|
||||
controls = hfcache.template_controls(choice["repo"])
|
||||
|
||||
def reasoning():
|
||||
value = (live_cfg().get("reasoning") or {}).get(entry["name"])
|
||||
return plan.reasoning_kwargs(value, entry, controls)
|
||||
|
||||
try:
|
||||
srv = ThreadingHTTPServer(("0.0.0.0", port),
|
||||
make_handler(inner, entry["name"], choice.get("est_context", entry["context"]),
|
||||
paths.api_key(), stats, aliases=(choice.get("repo"),),
|
||||
reasoning=reasoning))
|
||||
except OSError as e:
|
||||
print(f"llm-host: can't listen on port {port} ({e.strerror}). Another program is using it; "
|
||||
f"pick a free port with: llmhost setup --api-port <port>", flush=True)
|
||||
sys.exit(1)
|
||||
_kill_stale_servers(inner)
|
||||
srv = proxy.listen(port, proxy.make_handler(
|
||||
inner, entry["name"], choice.get("est_context", entry["context"]), paths.api_key(), stats,
|
||||
aliases=(choice.get("repo"),), reasoning=proxy.reasoning_setting(entry, controls),
|
||||
effort_levels=plan.effort_levels(entry, controls)))
|
||||
proxy.kill_stale(inner, VENV, "mlx_lm")
|
||||
|
||||
exe = str(VENV / "bin/mlx_lm.server")
|
||||
child = subprocess.Popen([exe, *args], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
|
||||
|
|
@ -459,24 +118,4 @@ def run_server(cfg, entry, choice, args):
|
|||
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(*_):
|
||||
child.terminate()
|
||||
try:
|
||||
child.wait(timeout=20)
|
||||
except subprocess.TimeoutExpired:
|
||||
child.kill()
|
||||
os._exit(0)
|
||||
signal.signal(signal.SIGTERM, stop)
|
||||
signal.signal(signal.SIGINT, stop)
|
||||
|
||||
try:
|
||||
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
||||
print(f"llm-host: proxy on :{port} -> mlx_lm.server on 127.0.0.1:{inner}", flush=True)
|
||||
rc = child.wait()
|
||||
print(f"llm-host: mlx_lm.server exited with {rc}", flush=True)
|
||||
finally:
|
||||
if child.poll() is None:
|
||||
child.terminate()
|
||||
time.sleep(1)
|
||||
os._exit(rc or 1)
|
||||
proxy.supervise(srv, child, "mlx_lm.server", port, inner)
|
||||
|
|
|
|||
430
llmhost/backends/proxy.py
Normal file
430
llmhost/backends/proxy.py
Normal file
|
|
@ -0,0 +1,430 @@
|
|||
"""The proxy llm-host puts in front of every model server (vLLM and mlx_lm.server alike).
|
||||
|
||||
The model server listens on localhost (api_port + 1); this listens on the public api_port
|
||||
and, so that clients see the same API on either backend:
|
||||
- checks the API key,
|
||||
- rejects a request for a model that isn't the loaded one (404 model_not_found), and
|
||||
rewrites the request's "model" to the name the server knows it by; /v1/models answers
|
||||
with the served name,
|
||||
- applies the dashboard's reasoning setting to chat requests, and maps an effort level
|
||||
the model doesn't have (a client's generic "high", say) to the nearest one it does,
|
||||
- counts in-flight requests and tokens and records each finished request for the
|
||||
dashboard (/llmhost/metrics, localhost only).
|
||||
"""
|
||||
import hmac
|
||||
import http.client
|
||||
import json
|
||||
import os
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from collections import deque
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
|
||||
from .. import paths, plan
|
||||
|
||||
RECENT_RUNS = 50 # completed requests kept for the dashboard's summary
|
||||
QUIET_PATHS = {"/health", "/v1/models", "/llmhost/metrics"}
|
||||
|
||||
|
||||
class Stats:
|
||||
def __init__(self):
|
||||
self.lock = threading.Lock()
|
||||
self.running = 0
|
||||
self.gen_total = 0
|
||||
self.prompt_total = 0
|
||||
self.requests_total = 0
|
||||
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 # MLX: set once the model has answered; vLLM: from the start
|
||||
self.kv_bytes = None # MLX 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,
|
||||
"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):
|
||||
"""Prompt tokens the server actually processed: cached prefix tokens cost nothing."""
|
||||
n = int(usage.get("prompt_tokens") or 0)
|
||||
cached = (usage.get("prompt_tokens_details") or {}).get("cached_tokens") or 0
|
||||
return max(n - int(cached), 0)
|
||||
|
||||
|
||||
def make_handler(inner_port, served_name, context, key, stats, aliases=(), reasoning=None,
|
||||
upstream_model="default_model", upstream_key=None, effort_levels=()):
|
||||
"""upstream_model: what the inner server calls the loaded model ("default_model" makes
|
||||
mlx_lm use the preloaded one; vLLM wants its --served-model-name). upstream_key: sent
|
||||
on to an inner server that checks keys itself (vLLM). effort_levels: the levels this
|
||||
model's template accepts; an unknown one from a client is mapped to the nearest."""
|
||||
# Names a client may call the loaded model: its llm-host name, its repo id, and the
|
||||
# stable alias that means "whatever is loaded" (plan.SERVED_ALIAS).
|
||||
accepted = {served_name.lower(), plan.SERVED_ALIAS, *(a.lower() for a in aliases if a)}
|
||||
|
||||
class Proxy(BaseHTTPRequestHandler):
|
||||
protocol_version = "HTTP/1.1"
|
||||
|
||||
def log_message(self, fmt, *a):
|
||||
# The dashboard polls these every 2s from localhost; logging them buries real traffic.
|
||||
if self.client_address[0] in ("127.0.0.1", "::1") and self.path.split("?")[0] in QUIET_PATHS:
|
||||
return
|
||||
sys.stderr.write("proxy: %s - %s\n" % (self.address_string(), fmt % a))
|
||||
|
||||
def _json(self, code, obj):
|
||||
body = json.dumps(obj).encode()
|
||||
self.send_response(code)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def _authed(self):
|
||||
h = self.headers.get("Authorization", "")
|
||||
tok = h[7:] if h.startswith("Bearer ") else ""
|
||||
if hmac.compare_digest(tok.encode(), key.encode()):
|
||||
return True
|
||||
self._json(401, {"error": {"message": "invalid API key", "type": "auth"}})
|
||||
return False
|
||||
|
||||
def do_GET(self):
|
||||
if self.path == "/health":
|
||||
# mlx_lm's /health is OK as soon as its thread runs, even while the model is
|
||||
# still downloading. Report ready only after a real generation has succeeded.
|
||||
if not stats.ready:
|
||||
return self._json(503, {"status": "loading"})
|
||||
return self._forward("GET", None)
|
||||
if self.path == "/llmhost/metrics":
|
||||
if self.client_address[0] not in ("127.0.0.1", "::1"):
|
||||
return self._json(403, {"error": "local only"})
|
||||
return self._json(200, stats.snapshot())
|
||||
if not self._authed():
|
||||
return
|
||||
if self.path.startswith("/v1/models"):
|
||||
return self._json(200, {"object": "list", "data": [
|
||||
{"id": served_name, "object": "model", "owned_by": "llm-host", "max_model_len": context}]})
|
||||
self._forward("GET", None)
|
||||
|
||||
def _model_ok(self, body):
|
||||
"""One model is loaded at a time, and mlx_lm answers with whatever it has
|
||||
regardless of the name asked for -- so an unrecognised name would come back
|
||||
as another model's output wearing it. Refuse it instead."""
|
||||
want = body.get("model")
|
||||
if not isinstance(want, str) or not want.strip():
|
||||
return True # no preference stated: the loaded one it is
|
||||
if want.strip().lower() in accepted:
|
||||
return True
|
||||
self._json(404, {"error": {
|
||||
"message": f"model '{want}' is not loaded; this server is serving "
|
||||
f"'{served_name}'. Load it with `llmhost switch {want}` "
|
||||
f"(one model is loaded at a time), or ask for '{served_name}' "
|
||||
f"-- or for '{plan.SERVED_ALIAS}', which always means whatever "
|
||||
f"is loaded.",
|
||||
"type": "invalid_request_error", "code": "model_not_found", "param": "model"}})
|
||||
return False
|
||||
|
||||
def _fit_effort(self, holder, k):
|
||||
"""Map holder[k], a client's effort level, onto one this model accepts. Clients
|
||||
offer a generic menu (opencode: low/medium/high), and a level the template
|
||||
doesn't define makes it raise -- every request then fails until the user finds
|
||||
the setting. The nearest level is what they meant."""
|
||||
v = holder.get(k)
|
||||
if effort_levels and isinstance(v, str) and v not in effort_levels:
|
||||
fit = plan.nearest_effort(v, effort_levels)
|
||||
if fit:
|
||||
holder[k] = fit
|
||||
|
||||
def do_POST(self):
|
||||
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
|
||||
try:
|
||||
body = json.loads(raw or b"{}")
|
||||
if isinstance(body, dict):
|
||||
if self.path.startswith("/v1/") and not self._model_ok(body):
|
||||
return
|
||||
if "chat/completions" in self.path:
|
||||
theirs = body.get("chat_template_kwargs")
|
||||
# Server-side reasoning default. Only chat completions go through a
|
||||
# chat template, and a setting the client made itself always wins --
|
||||
# the same precedence mlx_lm applies to its own --chat-template-kwargs.
|
||||
kw = reasoning() if reasoning else {}
|
||||
if kw:
|
||||
mine = dict(kw)
|
||||
if "reasoning_effort" in body: # the OpenAI-style top-level field
|
||||
mine.pop("reasoning_effort", None)
|
||||
if isinstance(theirs, dict):
|
||||
mine.update(theirs)
|
||||
body["chat_template_kwargs"] = theirs = mine
|
||||
self._fit_effort(body, "reasoning_effort")
|
||||
if isinstance(theirs, dict):
|
||||
self._fit_effort(theirs, "reasoning_effort")
|
||||
# Name the loaded model the way the inner server knows it (mlx_lm would
|
||||
# otherwise try to load a model matching the name it's given).
|
||||
body["model"] = upstream_model
|
||||
# Ask for the final usage chunk so prompt tokens can be counted, and
|
||||
# hide it again from clients that didn't ask for it.
|
||||
opts = body.get("stream_options") or {}
|
||||
if body.get("stream") and not opts.get("include_usage"):
|
||||
body["stream_options"] = {**opts, "include_usage": True}
|
||||
strip_usage = True
|
||||
raw = json.dumps(body).encode()
|
||||
except ValueError:
|
||||
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) # noqa: F841 (closed in finally)
|
||||
headers = {"Content-Type": self.headers.get("Content-Type", "application/json")}
|
||||
if upstream_key:
|
||||
headers["Authorization"] = f"Bearer {upstream_key}"
|
||||
if raw is not None:
|
||||
headers["Content-Length"] = str(len(raw))
|
||||
try:
|
||||
conn.request(method, self.path, body=raw, headers=headers)
|
||||
resp = conn.getresponse()
|
||||
except OSError:
|
||||
return self._json(503, {"error": {"message": "model server not ready", "type": "unavailable"}})
|
||||
self.send_response(resp.status)
|
||||
ctype = resp.getheader("Content-Type", "application/json")
|
||||
self.send_header("Content-Type", ctype)
|
||||
streaming = "text/event-stream" in ctype
|
||||
if streaming:
|
||||
self.send_header("Cache-Control", "no-cache")
|
||||
self.send_header("Connection", "close")
|
||||
self.end_headers()
|
||||
self.close_connection = True
|
||||
buf = b""
|
||||
self._first = False
|
||||
self._pp = 0 # prompt tokens of this request already counted
|
||||
while True:
|
||||
chunk = resp.read1(65536) if hasattr(resp, "read1") else resp.read(4096)
|
||||
if not chunk:
|
||||
break
|
||||
buf += chunk
|
||||
# Forward whole events (the server writes one per token anyway).
|
||||
while b"\n\n" in buf:
|
||||
event, buf = buf.split(b"\n\n", 1)
|
||||
if event.startswith(b": keepalive "):
|
||||
self._count_progress(event)
|
||||
usage_only = self._count_event(event)
|
||||
if not (strip_usage and usage_only):
|
||||
self.wfile.write(event + b"\n\n")
|
||||
self.wfile.flush()
|
||||
if buf:
|
||||
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 += self._gen
|
||||
stats.prompt_total += self._pp
|
||||
except (ValueError, AttributeError):
|
||||
pass
|
||||
except (BrokenPipeError, ConnectionResetError):
|
||||
# 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
|
||||
|
||||
def _count_progress(self, event):
|
||||
"""mlx_lm.server sends ': keepalive <done>/<total>' after each prefill step of a
|
||||
streamed request (counting only the part not found in its prompt cache). Count
|
||||
those as they arrive so the prompt rate shows prefill while it happens, not as
|
||||
one spike when the request ends (or never, if the client gives up first)."""
|
||||
try:
|
||||
done = int(event[12:].split(b"/")[0])
|
||||
except ValueError:
|
||||
return
|
||||
if done > self._pp:
|
||||
with stats.lock:
|
||||
stats.prompt_total += done - self._pp
|
||||
self._pp = done
|
||||
|
||||
def _count_event(self, event):
|
||||
"""Update token counts; returns True for a usage-only chunk (no choices)."""
|
||||
if not event.startswith(b"data: {"):
|
||||
return False
|
||||
try:
|
||||
d = json.loads(event[6:])
|
||||
except ValueError:
|
||||
return False
|
||||
u = d.get("usage")
|
||||
first_token = False
|
||||
with stats.lock:
|
||||
if u: # final usage chunk: top up whatever the stream itself didn't cover
|
||||
rest = _uncached(u) - self._pp
|
||||
if rest > 0:
|
||||
stats.prompt_total += rest
|
||||
self._pp += rest
|
||||
# One chunk is usually one token, but not always (vLLM with speculative
|
||||
# decoding sends several at once), so the usage count is the truth.
|
||||
more = int(u.get("completion_tokens") or 0) - self._gen
|
||||
if more > 0:
|
||||
stats.gen_total += more
|
||||
self._gen += more
|
||||
for c in d.get("choices") or []:
|
||||
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
|
||||
self._gen += 1
|
||||
first_token = True
|
||||
if first_token and not self._first and getattr(self, "_t0", None) is not None:
|
||||
self._first = True
|
||||
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
|
||||
|
||||
|
||||
_cfg_cache = {"mtime": None, "cfg": {}}
|
||||
|
||||
|
||||
def live_cfg():
|
||||
"""config.json, re-read when it changes. The reasoning setting is edited from the
|
||||
dashboard while this process runs, and it must take effect without a restart --
|
||||
a restart would unload the model, which is the whole thing we're avoiding."""
|
||||
try:
|
||||
mtime = paths.CONFIG_FILE.stat().st_mtime
|
||||
except OSError:
|
||||
return _cfg_cache["cfg"]
|
||||
if mtime != _cfg_cache["mtime"]:
|
||||
_cfg_cache["mtime"], _cfg_cache["cfg"] = mtime, paths.load_config()
|
||||
return _cfg_cache["cfg"]
|
||||
|
||||
def reasoning_setting(entry, controls):
|
||||
"""The dashboard's reasoning setting as chat_template_kwargs, read per request: the
|
||||
dashboard changes it while the server runs, and a restart would unload the model.
|
||||
The template's knobs are fixed for the process, so they're read once by the caller."""
|
||||
def kwargs():
|
||||
value = (live_cfg().get("reasoning") or {}).get(entry["name"])
|
||||
return plan.reasoning_kwargs(value, entry, controls)
|
||||
return kwargs
|
||||
|
||||
|
||||
def kill_stale(inner_port, venv, marker):
|
||||
"""Stop model servers left behind on the inner port by an earlier crash of this
|
||||
service. Only processes running from our own venv are touched."""
|
||||
try:
|
||||
out = subprocess.run(["lsof", "-nP", f"-iTCP:{inner_port}", "-sTCP:LISTEN", "-t"],
|
||||
capture_output=True, text=True).stdout.split()
|
||||
except FileNotFoundError:
|
||||
return
|
||||
for pid in out:
|
||||
cmd = subprocess.run(["ps", "-o", "command=", "-p", pid], capture_output=True, text=True).stdout
|
||||
if str(venv) in cmd and marker in cmd:
|
||||
print(f"llm-host: stopping leftover {marker} (pid {pid}) on port {inner_port}", flush=True)
|
||||
try:
|
||||
os.kill(int(pid), signal.SIGTERM)
|
||||
except OSError:
|
||||
pass
|
||||
if out:
|
||||
time.sleep(2)
|
||||
|
||||
|
||||
class _Server(ThreadingHTTPServer):
|
||||
daemon_threads = True
|
||||
request_queue_size = 128 # the default of 5 is easy to exceed with parallel agent requests
|
||||
|
||||
|
||||
def listen(port, handler):
|
||||
"""Claim the public port before starting a child, so a clash fails before orphaning one."""
|
||||
try:
|
||||
return _Server(("0.0.0.0", port), handler)
|
||||
except OSError as e:
|
||||
print(f"llm-host: can't listen on port {port} ({e.strerror}). Another program is using it; "
|
||||
f"pick a free port with: llmhost setup --api-port <port>", flush=True)
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
def supervise(srv, child, name, port, inner, stop_timeout=20):
|
||||
"""Serve the proxy until the model server exits, then exit non-zero so the service
|
||||
manager restarts us. SIGTERM stops the child first."""
|
||||
def stop(*_):
|
||||
child.terminate()
|
||||
try:
|
||||
child.wait(timeout=stop_timeout)
|
||||
except subprocess.TimeoutExpired:
|
||||
child.kill()
|
||||
os._exit(0)
|
||||
signal.signal(signal.SIGTERM, stop)
|
||||
signal.signal(signal.SIGINT, stop)
|
||||
rc = 1
|
||||
try:
|
||||
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
||||
print(f"llm-host: proxy on :{port} -> {name} on 127.0.0.1:{inner}", flush=True)
|
||||
rc = child.wait()
|
||||
print(f"llm-host: {name} exited with {rc}", flush=True)
|
||||
finally:
|
||||
if child.poll() is None:
|
||||
child.terminate()
|
||||
time.sleep(1)
|
||||
os._exit(rc or 1)
|
||||
|
|
@ -160,7 +160,26 @@ def run_env(cfg, hw=None, include_key=True):
|
|||
return env
|
||||
|
||||
|
||||
def exec_server(cfg, args):
|
||||
"""Replace this process with `vllm serve` (so the service manager tracks vLLM directly)."""
|
||||
def run_server(cfg, entry, choice, args):
|
||||
"""Start the proxy on api_port, then `vllm serve` as a child on api_port+1 (args).
|
||||
vLLM keeps its own API key, so the inner port isn't open to anyone else on the box;
|
||||
the proxy checks the client's key and sends ours on."""
|
||||
from .. import hfcache, plan
|
||||
from . import proxy
|
||||
port = cfg["api_port"]
|
||||
inner = port + 1
|
||||
stats = proxy.Stats()
|
||||
stats.ready = True # vLLM's own /health is only OK once the model is loaded
|
||||
controls = hfcache.template_controls(choice["repo"])
|
||||
key = paths.api_key()
|
||||
srv = proxy.listen(port, proxy.make_handler(
|
||||
inner, entry["name"], choice.get("est_context", entry["context"]), key, stats,
|
||||
aliases=(choice.get("repo"),), reasoning=proxy.reasoning_setting(entry, controls),
|
||||
upstream_model=entry["name"], upstream_key=key,
|
||||
effort_levels=plan.effort_levels(entry, controls)))
|
||||
proxy.kill_stale(inner, VENV, "vllm")
|
||||
exe = str(VENV / "bin/vllm")
|
||||
os.execve(exe, [exe, "serve", *args], run_env(cfg))
|
||||
# vLLM's output goes straight to ours (the service log); nothing in it needs reading.
|
||||
child = subprocess.Popen([exe, "serve", *args], env=run_env(cfg))
|
||||
# vLLM shuts its engine processes down on SIGTERM; give that time before killing.
|
||||
proxy.supervise(srv, child, "vllm", port, inner, stop_timeout=45)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue