llm-host/llmhost/backends/mlx.py
neil a250812d42 MLX: count prompt tokens while prefill runs, not when the request ends
The proxy only added a request's prompt tokens from the final usage chunk, so a
long prefill showed as a flat prompt rate and then one spike (prompt size over a
2 s sample), and requests the client abandoned mid-prefill were never counted.
mlx_lm.server already streams ": keepalive <done>/<total>" after each prefill
step; count those as they pass through, and top up from the usage chunk. Also
leave out prompt-cache hits (cached_tokens), which take no processing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QaE1hpvyZTJixEbUUMj9Ca
2026-11-02 13:50:10 -08:00

353 lines
15 KiB
Python

"""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),
- 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).
"""
import hmac
import http.client
import json
import os
import shutil
import signal
import subprocess
import sys
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from .. import paths
VENV = paths.DATA / "venv-mlx"
PY = VENV / "bin/python"
def install(hw, log=print):
u = shutil.which("uv") or str(paths.BIN_DIR / "uv")
if not PY.exists():
log(f"$ uv venv {VENV}")
subprocess.run([u, "venv", "--managed-python", "--python", "3.12", str(VENV)], check=True)
spec = os.environ.get("LLMHOST_MLX_SPEC", "mlx-lm")
log(f"$ uv pip install {spec}")
subprocess.run([u, "pip", "install", "--python", str(PY), spec, "huggingface_hub"], check=True)
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")
FATAL = b"generation thread died"
def _pump_output(stream, on_fatal=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)."""
buf = b""
out = sys.stdout.buffer
while True:
chunk = os.read(stream.fileno(), 65536)
if not chunk:
break
buf += chunk
while True:
i = min([x for x in (buf.find(b"\n"), buf.find(b"\r")) if x >= 0], default=-1)
if i < 0:
break
seg, buf = buf[:i + 1], buf[i + 1:]
if not any(n in seg for n in NOISE):
out.write(seg)
out.flush()
if on_fatal and FATAL in seg:
on_fatal()
on_fatal = None
if buf:
out.write(buf)
out.flush()
def _readiness_probe(inner_port, stats):
"""Send a 1-token request; it only completes once the model is downloaded and loaded."""
body = json.dumps({"model": "default_model", "max_tokens": 1,
"messages": [{"role": "user", "content": "hi"}]})
while not stats.ready:
try:
conn = http.client.HTTPConnection("127.0.0.1", inner_port, timeout=6 * 3600)
conn.request("POST", "/v1/chat/completions", body=body, headers={"Content-Type": "application/json"})
r = conn.getresponse()
r.read()
if r.status == 200:
stats.ready = True
print("llm-host: model loaded and answering", flush=True)
return
except OSError:
pass
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)
def snapshot(self):
with self.lock:
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}
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):
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 do_POST(self):
if not self._authed():
return
self._t0 = time.monotonic()
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):
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 _forward(self, method, raw, strip_usage=False):
counted = self.path.startswith("/v1/") # health checks aren't requests
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)
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:
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 {}
with stats.lock:
stats.gen_total += int(u.get("completion_tokens") or 0)
stats.prompt_total += _uncached(u)
except (ValueError, AttributeError):
pass
except (BrokenPipeError, ConnectionResetError):
pass
finally:
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
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
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."""
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()
try:
srv = ThreadingHTTPServer(("0.0.0.0", port),
make_handler(inner, entry["name"], choice.get("est_context", entry["context"]),
paths.api_key(), stats))
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)
exe = str(VENV / "bin/mlx_lm.server")
child = subprocess.Popen([exe, *args], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
def generator_died():
# Every request fails from here on, so exit and let the service manager restart us.
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()
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)