diff --git a/llmhost/backends/mlx.py b/llmhost/backends/mlx.py index cf99ff6..cf4565b 100644 --- a/llmhost/backends/mlx.py +++ b/llmhost/backends/mlx.py @@ -36,6 +36,53 @@ 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") + + +def _pump_output(stream): + """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.""" + 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 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() @@ -43,6 +90,7 @@ class Stats: self.gen_total = 0 self.prompt_total = 0 self.requests_total = 0 + self.ready = False # set once the model has actually answered (see _readiness_probe) def snapshot(self): with self.lock: @@ -55,6 +103,9 @@ def make_handler(inner_port, served_name, context, key, stats): 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): @@ -75,6 +126,10 @@ def make_handler(inner_port, served_name, context, key, stats): 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"): @@ -208,7 +263,9 @@ def run_server(cfg, entry, choice, args): _kill_stale_servers(inner) exe = str(VENV / "bin/mlx_lm.server") - child = subprocess.Popen([exe, *args]) + child = subprocess.Popen([exe, *args], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) + threading.Thread(target=_pump_output, args=(child.stdout,), daemon=True).start() + threading.Thread(target=_readiness_probe, args=(inner, stats), daemon=True).start() def stop(*_): child.terminate() diff --git a/llmhost/web/server.py b/llmhost/web/server.py index 3706ec8..76ff3a3 100644 --- a/llmhost/web/server.py +++ b/llmhost/web/server.py @@ -19,7 +19,8 @@ HERE = Path(__file__).resolve().parent SAMPLE_SECONDS = 2 HISTORY_POINTS = 300 # 10 minutes # The sampler's own polling shows up in vLLM's access log every 2s; hide it from the log view. -OWN_POLL_RE = re.compile(r'127\.0\.0\.1:\d+ - "GET /(health|metrics|v1/models|llmhost/metrics) ') +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)$")