MLX: cap KV caches and recover from crashes; add llmhost watch
- mlx_lm.server kept up to 10 conversations' KV caches with no byte limit and prefilled 8 prompts at once, which ran a 16 GB Mac out of GPU memory. The plan now gives the live request half the free memory (at least 32k tokens), caps --prompt-cache-bytes to the rest, and on small machines prefills one prompt at a time. - When its generation thread dies, mlx_lm.server keeps running but fails every request. The proxy now restarts it. - llmhost watch: one live line with download progress (bytes, speed, time left), then loading, until the model answers. Setup and switch point at it instead of llmhost logs -f. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01QaE1hpvyZTJixEbUUMj9Ca
This commit is contained in:
parent
0b2cdcf513
commit
8611d92cf4
5 changed files with 131 additions and 6 deletions
|
|
@ -46,6 +46,7 @@ PYTHONPATH=. python3 -P -m llmhost plan --simulate apple:64 # a 64 GB Mac
|
||||||
| `llmhost models` | models that fit this machine (`*` = active) |
|
| `llmhost models` | models that fit this machine (`*` = active) |
|
||||||
| `llmhost switch <model>` | serve a different model (downloads it first if needed) |
|
| `llmhost switch <model>` | serve a different model (downloads it first if needed) |
|
||||||
| `llmhost download <model>` | download ahead of time |
|
| `llmhost download <model>` | download ahead of time |
|
||||||
|
| `llmhost watch` | download and loading progress, until the model is ready |
|
||||||
| `llmhost logs -f` | follow the model server log |
|
| `llmhost logs -f` | follow the model server log |
|
||||||
| `llmhost start` / `stop` / `restart` | control the model server (stop frees the GPU) |
|
| `llmhost start` / `stop` / `restart` | control the model server (stop frees the GPU) |
|
||||||
| `llmhost key` | print the API key |
|
| `llmhost key` | print the API key |
|
||||||
|
|
|
||||||
|
|
@ -41,9 +41,13 @@ QUIET_PATHS = {"/health", "/v1/models", "/llmhost/metrics"}
|
||||||
NOISE = (b'"GET /health HTTP', b"- INFO - HTTP Request: ", b"sending unauthenticated requests to the HF Hub")
|
NOISE = (b'"GET /health HTTP', b"- INFO - HTTP Request: ", b"sending unauthenticated requests to the HF Hub")
|
||||||
|
|
||||||
|
|
||||||
def _pump_output(stream):
|
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
|
"""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."""
|
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""
|
buf = b""
|
||||||
out = sys.stdout.buffer
|
out = sys.stdout.buffer
|
||||||
while True:
|
while True:
|
||||||
|
|
@ -59,6 +63,9 @@ def _pump_output(stream):
|
||||||
if not any(n in seg for n in NOISE):
|
if not any(n in seg for n in NOISE):
|
||||||
out.write(seg)
|
out.write(seg)
|
||||||
out.flush()
|
out.flush()
|
||||||
|
if on_fatal and FATAL in seg:
|
||||||
|
on_fatal()
|
||||||
|
on_fatal = None
|
||||||
if buf:
|
if buf:
|
||||||
out.write(buf)
|
out.write(buf)
|
||||||
out.flush()
|
out.flush()
|
||||||
|
|
@ -278,7 +285,12 @@ def run_server(cfg, entry, choice, args):
|
||||||
|
|
||||||
exe = str(VENV / "bin/mlx_lm.server")
|
exe = str(VENV / "bin/mlx_lm.server")
|
||||||
child = subprocess.Popen([exe, *args], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
|
child = subprocess.Popen([exe, *args], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
|
||||||
threading.Thread(target=_pump_output, args=(child.stdout,), daemon=True).start()
|
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()
|
threading.Thread(target=_readiness_probe, args=(inner, stats), daemon=True).start()
|
||||||
|
|
||||||
def stop(*_):
|
def stop(*_):
|
||||||
|
|
|
||||||
|
|
@ -186,7 +186,7 @@ Done.
|
||||||
API: http://{host}:{cfg['api_port']}/v1 (OpenAI-compatible)
|
API: http://{host}:{cfg['api_port']}/v1 (OpenAI-compatible)
|
||||||
Dashboard: http://{host}:{cfg['web_port']}
|
Dashboard: http://{host}:{cfg['web_port']}
|
||||||
API key: {paths.KEY_FILE} (show it with: llmhost key)
|
API key: {paths.KEY_FILE} (show it with: llmhost key)
|
||||||
Model: {active} — {"not started yet; run: llmhost start" if a.no_start else ("loading" if hfcache.is_downloaded(first["repo"]) else "downloading, then loading") + "; watch with: llmhost logs -f"}""")
|
Model: {active} — {"not started yet; run: llmhost start" if a.no_start else ("loading" if hfcache.is_downloaded(first["repo"]) else "downloading, then loading") + "; watch progress with: llmhost watch"}""")
|
||||||
if not a.no_opencode:
|
if not a.no_opencode:
|
||||||
setup_opencode(cfg, ask=sys.stdin.isatty() and not a.yes, install_ok=a.opencode)
|
setup_opencode(cfg, ask=sys.stdin.isatty() and not a.yes, install_ok=a.opencode)
|
||||||
say(f"\nOther machines: run `llmhost opencode-config` here for their opencode setup.")
|
say(f"\nOther machines: run `llmhost opencode-config` here for their opencode setup.")
|
||||||
|
|
@ -342,7 +342,7 @@ def cmd_switch(a):
|
||||||
cfg["active"] = a.model
|
cfg["active"] = a.model
|
||||||
paths.save_config(cfg)
|
paths.save_config(cfg)
|
||||||
service.restart("model")
|
service.restart("model")
|
||||||
say(f"Switched to {a.model}. Watch it load with: llmhost logs -f")
|
say(f"Switched to {a.model}. Watch it load with: llmhost watch")
|
||||||
|
|
||||||
|
|
||||||
def cmd_ctl(a):
|
def cmd_ctl(a):
|
||||||
|
|
@ -361,6 +361,87 @@ def cmd_logs(a):
|
||||||
say(line)
|
say(line)
|
||||||
|
|
||||||
|
|
||||||
|
def _served_models(cfg, key):
|
||||||
|
try:
|
||||||
|
if urllib.request.urlopen(f"http://127.0.0.1:{cfg['api_port']}/health", timeout=2).status != 200:
|
||||||
|
return []
|
||||||
|
req = urllib.request.Request(f"http://127.0.0.1:{cfg['api_port']}/v1/models",
|
||||||
|
headers={"Authorization": f"Bearer {key}"})
|
||||||
|
return [m["id"] for m in json.load(urllib.request.urlopen(req, timeout=3))["data"]]
|
||||||
|
except Exception:
|
||||||
|
return []
|
||||||
|
|
||||||
|
|
||||||
|
def _fmt_secs(t):
|
||||||
|
t = int(t)
|
||||||
|
return f"{t // 3600}h{t % 3600 // 60:02d}m" if t >= 3600 else (f"{t // 60}m{t % 60:02d}s" if t >= 60 else f"{t}s")
|
||||||
|
|
||||||
|
|
||||||
|
def cmd_watch(a):
|
||||||
|
"""One live status line: download progress, then loading, until the model answers."""
|
||||||
|
cfg = _service_check()
|
||||||
|
key = paths.api_key()
|
||||||
|
name = cfg["active"]
|
||||||
|
m = next(x for x in cfg["models"] if x["name"] == name)
|
||||||
|
tty = sys.stdout.isatty()
|
||||||
|
start = time.time()
|
||||||
|
samples = [] # (time, GiB) over the last ~10 s, for the download rate
|
||||||
|
down_since = None # when the service was first seen stopped (it may just be restarting)
|
||||||
|
last_plain = (None, 0)
|
||||||
|
i = 0
|
||||||
|
|
||||||
|
def show(text, key_phase):
|
||||||
|
nonlocal last_plain
|
||||||
|
if tty:
|
||||||
|
sys.stdout.write("\r\033[K" + text)
|
||||||
|
sys.stdout.flush()
|
||||||
|
elif key_phase != last_plain[0] or time.time() - last_plain[1] >= 15:
|
||||||
|
print(text, flush=True)
|
||||||
|
last_plain = (key_phase, time.time())
|
||||||
|
|
||||||
|
def done(text, rc):
|
||||||
|
if tty:
|
||||||
|
sys.stdout.write("\r\033[K")
|
||||||
|
print(text, flush=True)
|
||||||
|
raise SystemExit(rc)
|
||||||
|
|
||||||
|
try:
|
||||||
|
while True:
|
||||||
|
now = time.time()
|
||||||
|
if name in _served_models(cfg, key):
|
||||||
|
done(f"\u2713 {name} is ready: http://{default_host()}:{cfg['api_port']}/v1 "
|
||||||
|
f"({_fmt_secs(now - start)})", 0)
|
||||||
|
st, _ = service.state("model")
|
||||||
|
if st in ("inactive", "failed"):
|
||||||
|
down_since = down_since or now
|
||||||
|
if now - down_since > 20:
|
||||||
|
lines = [l for l in service.logs("model", 400) if l.strip()][-15:]
|
||||||
|
done(f"The model server is {'not running' if st == 'inactive' else 'failing'}. "
|
||||||
|
f"Last log lines:\n " + "\n ".join(lines) +
|
||||||
|
"\nFull log: llmhost logs" + ("" if st == "failed" else " Start it: llmhost start"), 1)
|
||||||
|
else:
|
||||||
|
down_since = None
|
||||||
|
frame = Spinner.FRAMES[i % len(Spinner.FRAMES)] if tty else "-"
|
||||||
|
i += 1
|
||||||
|
total = m.get("weights_gib") or 0
|
||||||
|
if total and not hfcache.is_downloaded(m["repo"]):
|
||||||
|
got = hfcache.download_gib(m["repo"])
|
||||||
|
samples = [x for x in samples if now - x[0] <= 10] + [(now, got)]
|
||||||
|
rate = (got - samples[0][1]) / (now - samples[0][0]) if now > samples[0][0] else 0
|
||||||
|
frac = min(got / total, 0.999)
|
||||||
|
bar = "\u2588" * int(frac * 24) + "\u2591" * (24 - int(frac * 24))
|
||||||
|
extra = ""
|
||||||
|
if rate > 0.001:
|
||||||
|
extra = f" \u00b7 {rate * 1024 * 2**20 / 1e6:.0f} MB/s \u00b7 ~{_fmt_secs((total - got) / rate)} left"
|
||||||
|
show(f"{frame} Downloading {name} {bar} {got:.1f} / {total:.1f} GiB ({frac:.0%}){extra}",
|
||||||
|
"download")
|
||||||
|
else:
|
||||||
|
show(f"{frame} Loading {name} ({_fmt_secs(now - start)})", "load")
|
||||||
|
time.sleep(1)
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
done("Stopped watching (the model server keeps going).", 130)
|
||||||
|
|
||||||
|
|
||||||
def cmd_key(a):
|
def cmd_key(a):
|
||||||
say(paths.api_key())
|
say(paths.api_key())
|
||||||
|
|
||||||
|
|
@ -531,6 +612,8 @@ def main(argv=None):
|
||||||
s.add_argument("-n", type=int, default=100)
|
s.add_argument("-n", type=int, default=100)
|
||||||
s.add_argument("--web", action="store_true", help="dashboard logs instead")
|
s.add_argument("--web", action="store_true", help="dashboard logs instead")
|
||||||
s.set_defaults(fn=cmd_logs)
|
s.set_defaults(fn=cmd_logs)
|
||||||
|
sub.add_parser("watch", help="show download and loading progress until the model is ready"
|
||||||
|
).set_defaults(fn=cmd_watch)
|
||||||
sub.add_parser("key", help="print the API key").set_defaults(fn=cmd_key)
|
sub.add_parser("key", help="print the API key").set_defaults(fn=cmd_key)
|
||||||
s = sub.add_parser("download", help="download a model ahead of time")
|
s = sub.add_parser("download", help="download a model ahead of time")
|
||||||
s.add_argument("model")
|
s.add_argument("model")
|
||||||
|
|
|
||||||
|
|
@ -45,3 +45,17 @@ def disk_gib(repo):
|
||||||
except OSError:
|
except OSError:
|
||||||
pass
|
pass
|
||||||
return total / 2**30
|
return total / 2**30
|
||||||
|
|
||||||
|
|
||||||
|
def download_gib(repo):
|
||||||
|
"""Bytes downloaded so far, in GiB: finished files plus ones still being written
|
||||||
|
(huggingface_hub writes those as blobs/*.incomplete inside the repo's own folder)."""
|
||||||
|
total = disk_gib(repo) * 2**30
|
||||||
|
blobs = repo_dir(repo) / "blobs"
|
||||||
|
if blobs.is_dir():
|
||||||
|
for f in blobs.glob("*.incomplete"):
|
||||||
|
try:
|
||||||
|
total += f.stat().st_size
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
return total / 2**30
|
||||||
|
|
|
||||||
|
|
@ -71,8 +71,17 @@ def plan(hw, catalog, prefer="balanced"):
|
||||||
free = total * util - w - _overhead_gib(w, tp)
|
free = total * util - w - _overhead_gib(w, tp)
|
||||||
ctx = int(free * 2**20 / kv_kib) if free > 0 else 0
|
ctx = int(free * 2**20 / kv_kib) if free > 0 else 0
|
||||||
if ctx >= MIN_CONTEXT:
|
if ctx >= MIN_CONTEXT:
|
||||||
|
est = min(ctx, m["context"])
|
||||||
choice = {"format": fmt, "repo": v["repo"], "weights_gib": round(w, 1),
|
choice = {"format": fmt, "repo": v["repo"], "weights_gib": round(w, 1),
|
||||||
"util": util, "est_context": min(ctx, m["context"]), "mtp": bool(v.get("mtp"))}
|
"util": util, "est_context": est, "mtp": bool(v.get("mtp"))}
|
||||||
|
if kind == "apple":
|
||||||
|
# mlx_lm.server also keeps finished conversations' KV caches for reuse.
|
||||||
|
# Give the live request half the free memory (at least MIN_CONTEXT) and
|
||||||
|
# cap the reuse cache to the rest, so the two can't exhaust GPU memory.
|
||||||
|
est = min(max(MIN_CONTEXT, ctx // 2), m["context"])
|
||||||
|
cache = free - est * kv_kib / 2**20
|
||||||
|
choice.update(est_context=est, free_gib=round(free, 2),
|
||||||
|
prompt_cache_gib=round(max(cache, 0.25), 2))
|
||||||
break
|
break
|
||||||
if choice:
|
if choice:
|
||||||
break
|
break
|
||||||
|
|
@ -143,5 +152,11 @@ def mlx_args(entry, choice, port):
|
||||||
"--max-tokens", "32768"] # mlx_lm defaults to 512, which truncates coding answers
|
"--max-tokens", "32768"] # mlx_lm defaults to 512, which truncates coding answers
|
||||||
if x.get("trust_remote_code"):
|
if x.get("trust_remote_code"):
|
||||||
args += ["--trust-remote-code"]
|
args += ["--trust-remote-code"]
|
||||||
|
if choice.get("prompt_cache_gib"):
|
||||||
|
# Unset, mlx_lm keeps up to 10 conversations' caches with no byte limit (OOM on small Macs).
|
||||||
|
args += ["--prompt-cache-bytes", str(int(choice["prompt_cache_gib"] * 2**30))]
|
||||||
|
if choice.get("free_gib", 99) < 8:
|
||||||
|
# Little room beyond the weights: prefill one prompt at a time (default 8 in parallel).
|
||||||
|
args += ["--prompt-concurrency", "1", "--decode-concurrency", "4"]
|
||||||
args += x.get("extra_args", [])
|
args += x.get("extra_args", [])
|
||||||
return args
|
return args
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue