One model is loaded at a time under one setting, and that setting belongs next to the model it applies to -- the same reason the client can't switch models. So the proxy now takes a client's reasoning settings off the request before applying the dashboard's: a top-level reasoning_effort, and enable_thinking or reasoning_effort inside chat_template_kwargs. Other template kwargs, which llm-host has no opinion about, still pass through. This reverses the precedence the proxy had (a client's own kwargs won, mirroring mlx_lm's own rule), which was the wrong model for a single-model server: clients offer a generic menu -- opencode's low/medium/high -- and a level the template doesn't define makes it raise, so every request failed with nothing on the user's screen to explain it. - opencode: the provider block disables all three of opencode's effort levels instead of curating them. A chooser there would be a menu that does nothing. - Deletes the nearest-effort mapping (EFFORT_SCALE, nearest_effort, plan.effort_levels, the effort_levels= parameter through both backends): it existed only to rescue a client-supplied level, and none survives now. - plan.REASONING_KEYS names the knobs this server drives, with a test asserting it stays exactly equal to what reasoning_kwargs can emit -- so a new template knob can't be added without also taking it away from clients. - Two strings that still described a menu of models, from before the block held a single entry. Verified against the live MLX server: with the dashboard on xhigh, five request shapes (nothing, enable_thinking: false, effort low top-level, effort low in kwargs, and the off-scale "turbo" that used to 404) all answer identically, and the reply tracks the dashboard alone as it moves off / low / xhigh. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
120 lines
4.7 KiB
Python
120 lines
4.7 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, 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 http.client
|
|
import json
|
|
import os
|
|
import re
|
|
import shutil
|
|
import subprocess
|
|
import sys
|
|
import threading
|
|
import time
|
|
|
|
from .. import hfcache, paths
|
|
from . import proxy
|
|
|
|
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 {}
|
|
|
|
|
|
# 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"
|
|
|
|
|
|
# mlx_lm logs the prompt cache's size periodically; it has no endpoint for it, so this
|
|
# line is the only way to see KV usage. Its "GB" is n_bytes/1e9 -- decimal, not GiB.
|
|
CACHE_RE = re.compile(rb"Prompt Cache: (\d+) sequences, ([\d.]+) GB")
|
|
|
|
|
|
def _pump_output(stream, on_fatal=None, stats=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).
|
|
Picks the prompt-cache size out of the stream on the way past."""
|
|
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 stats is not None:
|
|
m = CACHE_RE.search(seg)
|
|
if m:
|
|
stats.set_kv(int(m.group(1)), float(m.group(2)) * 1e9)
|
|
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)
|
|
|
|
|
|
def run_server(cfg, entry, choice, args):
|
|
"""Start the proxy on api_port, then mlx_lm.server as a child on api_port+1."""
|
|
port = cfg["api_port"]
|
|
inner = port + 1
|
|
stats = proxy.Stats()
|
|
controls = hfcache.template_controls(choice["repo"])
|
|
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)))
|
|
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)
|
|
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()
|
|
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()
|
|
proxy.supervise(srv, child, "mlx_lm.server", port, inner)
|