"""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, plan 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), 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) 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)