"""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"], SERVED_ALIAS, "--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 # A second name the API answers to, besides the model's own. opencode (and any client # with a saved default) points at this instead of a specific model, so the choice keeps # working after `llmhost switch` -- only one model is loaded at a time, so naming one in # a client config only ever goes stale. vLLM takes it as a second --served-model-name and # still reports the real slug, being the first; the MLX proxy accepts it as an alias. SERVED_ALIAS = "default" # ---- reasoning effort ------------------------------------------------------------- # Not a backend flag: it's a chat-template kwarg, read per request. "default" means send # nothing and let the template decide; "off" suppresses thinking; anything else is an # effort level the template defines. Levels come from the catalog (they're model-specific # and a wrong one makes the template raise), gated by what the template really reads. OFF = "off" DEFAULT = "default" def reasoning_options(entry, choice, controls): """The settings a model can be given, as (value, label) pairs, most effort first.""" if not entry.get("reasoning"): return [] opts = [(DEFAULT, "Model default")] levels = (entry.get("effort") or {}).get("levels") or [] if controls.get("effort") and levels: pretty = {"xhigh": "Extra high", "high": "High", "medium": "Medium", "low": "Low"} opts += [(l, pretty.get(l, l.title())) for l in reversed(levels)] if controls.get("thinking"): opts.append((OFF, "Thinking off")) return opts if len(opts) > 1 else [] def reasoning_kwargs(value, entry, controls): """chat_template_kwargs for a setting, or {} for "default"/anything unsupported.""" if not value or value == DEFAULT or not entry.get("reasoning"): return {} if value == OFF: return {"enable_thinking": False} if controls.get("thinking") else {} levels = (entry.get("effort") or {}).get("levels") or [] if controls.get("effort") and value in levels: return {"reasoning_effort": value} return {}