- 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
162 lines
7.4 KiB
Python
162 lines
7.4 KiB
Python
"""Pick a build of each catalog model that fits the hardware, and turn it into backend flags.
|
|
|
|
Fit rule: weights + overhead + KV cache for MIN_CONTEXT tokens must fit in the GPU budget.
|
|
KV cost per token comes from the catalog (measured on a real card); overhead covers
|
|
activations, CUDA graphs and the MTP head, and was ~3-4 GiB for every model we measured.
|
|
"""
|
|
import json
|
|
|
|
GB = 1e9 / 2**30 # decimal GB -> GiB
|
|
MIN_CONTEXT = 32768 # tokens of context a coding agent needs to be useful
|
|
UTILS = (0.90, 0.95) # vLLM gpu-memory-utilization; try the safer one first
|
|
|
|
# Order to try builds in, per preference. bf16 only wins over fp8 under "quality":
|
|
# fp8 is near-lossless and about twice as fast on dense models.
|
|
ORDERS = {
|
|
"nvidia": {
|
|
"balanced": ["fp8", "bf16", "nvfp4", "awq"],
|
|
"quality": ["bf16", "fp8", "nvfp4", "awq"],
|
|
"speed": ["nvfp4", "fp8", "awq", "bf16"],
|
|
},
|
|
"apple": {
|
|
"balanced": ["mlx-6bit", "mlx-4bit"],
|
|
"quality": ["mlx-8bit", "mlx-6bit", "mlx-4bit"],
|
|
"speed": ["mlx-4bit", "mlx-6bit"],
|
|
},
|
|
}
|
|
# Minimum CUDA compute capability per format (FP8 runs on Ampere via Marlin kernels).
|
|
MIN_CC = {"fp8": 8.0, "bf16": 8.0, "nvfp4": 10.0, "awq": 7.5}
|
|
BACKEND = {"nvidia": "vllm", "apple": "mlx"}
|
|
|
|
|
|
def _tp_size(n):
|
|
tp = 1
|
|
while tp * 2 <= n:
|
|
tp *= 2
|
|
return tp
|
|
|
|
|
|
def _overhead_gib(weights_gib, tp):
|
|
return 3.0 * tp + 0.02 * weights_gib
|
|
|
|
|
|
def plan(hw, catalog, prefer="balanced"):
|
|
"""Returns {"backend", "tp", "budget_gib", "models": [...fitting], "excluded": [...]}."""
|
|
kind = hw.get("kind")
|
|
if kind not in ORDERS:
|
|
return {"backend": None, "models": [], "excluded": [], "reason": "; ".join(hw.get("notes", [])) or "unsupported hardware"}
|
|
gpus = hw["gpus"]
|
|
if kind == "nvidia":
|
|
tp = _tp_size(len(gpus))
|
|
per_gpu = min(g["vram_gib"] for g in gpus[:tp])
|
|
cc = min(g["compute_cap"] for g in gpus[:tp])
|
|
total = per_gpu * tp
|
|
else:
|
|
tp, cc, total = 1, None, gpus[0]["vram_gib"]
|
|
|
|
fitting, excluded = [], []
|
|
for m in catalog["models"]:
|
|
choice, why_not = None, []
|
|
for fmt in ORDERS[kind][prefer]:
|
|
v = m["variants"].get(fmt)
|
|
if not v:
|
|
continue
|
|
if kind == "nvidia" and cc < MIN_CC[fmt]:
|
|
why_not.append(f"{fmt} needs compute capability {MIN_CC[fmt]}")
|
|
continue
|
|
w = v["gb"] * GB
|
|
# MLX keeps the KV cache in fp16: about twice the fp8 cost vLLM pays.
|
|
kv_kib = m["kv_kib_per_token"] * (2 if kind == "apple" else 1)
|
|
for util in (UTILS if kind == "nvidia" else (1.0,)):
|
|
free = total * util - w - _overhead_gib(w, tp)
|
|
ctx = int(free * 2**20 / kv_kib) if free > 0 else 0
|
|
if ctx >= MIN_CONTEXT:
|
|
est = min(ctx, m["context"])
|
|
choice = {"format": fmt, "repo": v["repo"], "weights_gib": round(w, 1),
|
|
"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
|
|
if choice:
|
|
break
|
|
why_not.append(f"{fmt} ({w:.0f} GiB) leaves too little memory")
|
|
if choice:
|
|
fitting.append({"name": m["name"], "title": m["title"], "about": m.get("about", ""),
|
|
"context": m["context"], "reasoning": m.get("reasoning", False), **choice})
|
|
else:
|
|
usable = set(ORDERS[kind]["quality"]) | set(ORDERS[kind]["speed"])
|
|
if kind == "nvidia":
|
|
usable = {f for f in usable if cc >= MIN_CC[f]}
|
|
sizes = [v["gb"] * GB for f, v in m["variants"].items() if f in usable]
|
|
if sizes:
|
|
smallest = min(sizes)
|
|
kv_kib = m["kv_kib_per_token"] * (2 if kind == "apple" else 1)
|
|
need = smallest + _overhead_gib(smallest, tp) + MIN_CONTEXT * kv_kib / 2**20
|
|
usable_gib = total * (max(UTILS) if kind == "nvidia" else 1.0)
|
|
reason = f"needs ~{need:.1f} GiB of GPU memory; {usable_gib:.1f} GiB usable here"
|
|
else:
|
|
smallest, reason = 0, "no build this GPU can run"
|
|
excluded.append({"name": m["name"], "title": m["title"], "reason": reason,
|
|
"smallest_gib": round(smallest, 1)})
|
|
return {"backend": BACKEND[kind], "kind": kind, "tp": tp, "budget_gib": round(total, 1),
|
|
"prefer": prefer, "models": fitting, "excluded": excluded}
|
|
|
|
|
|
def catalog_entry(catalog, name):
|
|
for m in catalog["models"]:
|
|
if m["name"] == name:
|
|
return m
|
|
raise KeyError(name)
|
|
|
|
|
|
# ---------- backend command lines ----------
|
|
|
|
def vllm_args(entry, choice, port, tp):
|
|
"""Arguments after `vllm serve`."""
|
|
v = entry.get("vllm", {})
|
|
args = [choice["repo"], "--served-model-name", entry["name"],
|
|
"--host", "0.0.0.0", "--port", str(port),
|
|
"--max-model-len", "-1", # let vLLM fit the context to free memory (capped at native)
|
|
"--gpu-memory-utilization", f"{choice['util']:.2f}",
|
|
"--enable-prefix-caching"]
|
|
if tp > 1:
|
|
args += ["--tensor-parallel-size", str(tp)]
|
|
if entry.get("hybrid"):
|
|
# Hybrid (Mamba-style) layers need one state slot per sequence; vLLM's default of
|
|
# 1024 concurrent sequences doesn't fit. A personal server never needs that many.
|
|
args += ["--max-num-seqs", "32"]
|
|
if v.get("kv_cache_dtype"):
|
|
args += ["--kv-cache-dtype", v["kv_cache_dtype"]]
|
|
if v.get("trust_remote_code"):
|
|
args += ["--trust-remote-code"]
|
|
if v.get("tool_parser"):
|
|
args += ["--enable-auto-tool-choice", "--tool-call-parser", v["tool_parser"]]
|
|
if v.get("reasoning_parser"):
|
|
args += ["--reasoning-parser", v["reasoning_parser"]]
|
|
if choice.get("mtp") and v.get("mtp_tokens"):
|
|
args += ["--speculative-config", json.dumps({"method": "mtp", "num_speculative_tokens": v["mtp_tokens"]})]
|
|
args += v.get("extra_args", [])
|
|
return args
|
|
|
|
|
|
def mlx_args(entry, choice, port):
|
|
"""Arguments for `mlx_lm.server` (bound to localhost; the auth proxy faces the network)."""
|
|
x = entry.get("mlx", {})
|
|
args = ["--model", choice["repo"], "--host", "127.0.0.1", "--port", str(port),
|
|
"--max-tokens", "32768"] # mlx_lm defaults to 512, which truncates coding answers
|
|
if x.get("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", [])
|
|
return args
|