Initial llm-host: hardware-aware local LLM server with dashboard
Detects the GPU (NVIDIA on Linux, Apple Silicon on macOS), picks the catalog models and builds that fit, installs vLLM or MLX without sudo, and runs the model server plus a web dashboard as user services. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01QaE1hpvyZTJixEbUUMj9Ca
This commit is contained in:
commit
5b9586ac80
19 changed files with 2458 additions and 0 deletions
147
llmhost/plan.py
Normal file
147
llmhost/plan.py
Normal file
|
|
@ -0,0 +1,147 @@
|
|||
"""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:
|
||||
choice = {"format": fmt, "repo": v["repo"], "weights_gib": round(w, 1),
|
||||
"util": util, "est_context": min(ctx, m["context"]), "mtp": bool(v.get("mtp"))}
|
||||
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"]
|
||||
args += x.get("extra_args", [])
|
||||
return args
|
||||
Loading…
Add table
Add a link
Reference in a new issue