diff --git a/llmhost/backends/mlx.py b/llmhost/backends/mlx.py index df35b25..8f96c5c 100644 --- a/llmhost/backends/mlx.py +++ b/llmhost/backends/mlx.py @@ -22,10 +22,25 @@ import time from collections import deque from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer -from .. import paths +from .. import hfcache, paths, plan RECENT_RUNS = 50 # completed requests kept for the dashboard's summary +_cfg_cache = {"mtime": None, "cfg": {}} + + +def live_cfg(): + """config.json, re-read when it changes. The reasoning setting is edited from the + dashboard while this process runs, and it must take effect without a restart -- + a restart would unload the model, which is the whole thing we're avoiding.""" + try: + mtime = paths.CONFIG_FILE.stat().st_mtime + except OSError: + return _cfg_cache["cfg"] + if mtime != _cfg_cache["mtime"]: + _cfg_cache["mtime"], _cfg_cache["cfg"] = mtime, paths.load_config() + return _cfg_cache["cfg"] + VENV = paths.DATA / "venv-mlx" PY = VENV / "bin/python" @@ -148,7 +163,7 @@ def _uncached(usage): return max(n - int(cached), 0) -def make_handler(inner_port, served_name, context, key, stats, aliases=()): +def make_handler(inner_port, served_name, context, key, stats, aliases=(), reasoning=None): # Names a client may call the loaded model: its llm-host name and its repo id. accepted = {served_name.lower(), *(a.lower() for a in aliases if a)} @@ -226,6 +241,17 @@ def make_handler(inner_port, served_name, context, key, stats, aliases=()): if isinstance(body, dict): if self.path.startswith("/v1/") and not self._model_ok(body): return + # Server-side reasoning default. Only chat completions go through a + # chat template, and a key the client set itself always wins -- the + # same precedence mlx_lm applies to its own --chat-template-kwargs. + if reasoning and "chat/completions" in self.path: + kw = reasoning() + if kw: + mine = dict(kw) + theirs = body.get("chat_template_kwargs") + if isinstance(theirs, dict): + mine.update(theirs) + body["chat_template_kwargs"] = mine # Force the preloaded model: mlx_lm would otherwise try to load a # model matching the name it's given. body["model"] = "default_model" @@ -401,10 +427,19 @@ def run_server(cfg, entry, choice, args): inner = port + 1 # Claim the public port first: if it's taken, fail before starting (and orphaning) a child. stats = Stats() + # The template is fixed for this process, so read its knobs once; the chosen level is + # read per request, since the dashboard can change it while we run. + controls = hfcache.template_controls(choice["repo"]) + + def reasoning(): + value = (live_cfg().get("reasoning") or {}).get(entry["name"]) + return plan.reasoning_kwargs(value, entry, controls) + try: srv = ThreadingHTTPServer(("0.0.0.0", port), make_handler(inner, entry["name"], choice.get("est_context", entry["context"]), - paths.api_key(), stats, aliases=(choice.get("repo"),))) + paths.api_key(), stats, aliases=(choice.get("repo"),), + reasoning=reasoning)) except OSError as e: print(f"llm-host: can't listen on port {port} ({e.strerror}). Another program is using it; " f"pick a free port with: llmhost setup --api-port ", flush=True) diff --git a/llmhost/catalog.json b/llmhost/catalog.json index 71ad868..98cd58e 100644 --- a/llmhost/catalog.json +++ b/llmhost/catalog.json @@ -9,16 +9,52 @@ "context": 262144, "hybrid": true, "reasoning": true, - "vllm": {"tool_parser": "qwen3_coder", "reasoning_parser": "qwen3", "kv_cache_dtype": "fp8", "mtp_tokens": 3}, + "vllm": { + "tool_parser": "qwen3_coder", + "reasoning_parser": "qwen3", + "kv_cache_dtype": "fp8", + "mtp_tokens": 3 + }, "mlx": {}, "variants": { - "fp8": {"repo": "Qwen/Qwen3.8-27B-FP8", "gb": 30.9, "mtp": true}, - "bf16": {"repo": "Qwen/Qwen3.8-27B", "gb": 55.6, "mtp": true}, - "nvfp4": {"repo": "nvidia/Qwen3.8-27B-NVFP4", "gb": 21.9}, - "awq": {"repo": "cyankiwi/Qwen3.8-27B-AWQ-INT4", "gb": 21.0}, - "mlx-8bit": {"repo": "lmstudio-community/Qwen3.8-27B-MLX-8bit", "gb": 29.5}, - "mlx-6bit": {"repo": "lmstudio-community/Qwen3.8-27B-MLX-6bit", "gb": 22.8}, - "mlx-4bit": {"repo": "lmstudio-community/Qwen3.8-27B-MLX-4bit", "gb": 16.1} + "fp8": { + "repo": "Qwen/Qwen3.8-27B-FP8", + "gb": 30.9, + "mtp": true + }, + "bf16": { + "repo": "Qwen/Qwen3.8-27B", + "gb": 55.6, + "mtp": true + }, + "nvfp4": { + "repo": "nvidia/Qwen3.8-27B-NVFP4", + "gb": 21.9 + }, + "awq": { + "repo": "cyankiwi/Qwen3.8-27B-AWQ-INT4", + "gb": 21.0 + }, + "mlx-8bit": { + "repo": "lmstudio-community/Qwen3.8-27B-MLX-8bit", + "gb": 29.5 + }, + "mlx-6bit": { + "repo": "lmstudio-community/Qwen3.8-27B-MLX-6bit", + "gb": 22.8 + }, + "mlx-4bit": { + "repo": "lmstudio-community/Qwen3.8-27B-MLX-4bit", + "gb": 16.1 + } + }, + "effort": { + "levels": [ + "low", + "medium", + "xhigh" + ], + "default": "xhigh" } }, { @@ -29,16 +65,44 @@ "context": 262144, "hybrid": true, "reasoning": true, - "vllm": {"tool_parser": "qwen3_xml", "reasoning_parser": "qwen3", "kv_cache_dtype": "fp8", "trust_remote_code": true}, - "mlx": {"trust_remote_code": true}, + "vllm": { + "tool_parser": "qwen3_xml", + "reasoning_parser": "qwen3", + "kv_cache_dtype": "fp8", + "trust_remote_code": true + }, + "mlx": { + "trust_remote_code": true + }, "variants": { - "fp8": {"repo": "ornith-ai/Ornith-1.5-35B-A3B-FP8", "gb": 39.4}, - "bf16": {"repo": "ornith-ai/Ornith-1.5-35B-A3B", "gb": 71.9}, - "nvfp4": {"repo": "ornith-ai/Ornith-1.5-35B-A3B-NVFP4", "gb": 23.4}, - "awq": {"repo": "cyankiwi/Ornith-1.5-35B-A3B-AWQ-INT4", "gb": 26.1}, - "mlx-8bit": {"repo": "ornith-ai/Ornith-1.5-35B-A3B-MLX-8bit", "gb": 36.8}, - "mlx-6bit": {"repo": "ornith-ai/Ornith-1.5-35B-A3B-MLX-6bit", "gb": 28.2}, - "mlx-4bit": {"repo": "ornith-ai/Ornith-1.5-35B-A3B-MLX-4bit", "gb": 19.5} + "fp8": { + "repo": "ornith-ai/Ornith-1.5-35B-A3B-FP8", + "gb": 39.4 + }, + "bf16": { + "repo": "ornith-ai/Ornith-1.5-35B-A3B", + "gb": 71.9 + }, + "nvfp4": { + "repo": "ornith-ai/Ornith-1.5-35B-A3B-NVFP4", + "gb": 23.4 + }, + "awq": { + "repo": "cyankiwi/Ornith-1.5-35B-A3B-AWQ-INT4", + "gb": 26.1 + }, + "mlx-8bit": { + "repo": "ornith-ai/Ornith-1.5-35B-A3B-MLX-8bit", + "gb": 36.8 + }, + "mlx-6bit": { + "repo": "ornith-ai/Ornith-1.5-35B-A3B-MLX-6bit", + "gb": 28.2 + }, + "mlx-4bit": { + "repo": "ornith-ai/Ornith-1.5-35B-A3B-MLX-4bit", + "gb": 19.5 + } } }, { @@ -49,15 +113,36 @@ "context": 262144, "hybrid": false, "reasoning": false, - "vllm": {"tool_parser": "qwen3_coder", "kv_cache_dtype": "fp8"}, + "vllm": { + "tool_parser": "qwen3_coder", + "kv_cache_dtype": "fp8" + }, "mlx": {}, "variants": { - "fp8": {"repo": "Qwen/Qwen3-Coder-30B-A3B-Instruct-FP8", "gb": 31.2}, - "bf16": {"repo": "Qwen/Qwen3-Coder-30B-A3B-Instruct", "gb": 61.1}, - "awq": {"repo": "cyankiwi/Qwen3-Coder-30B-A3B-Instruct-AWQ-4bit", "gb": 18.1}, - "mlx-8bit": {"repo": "lmstudio-community/Qwen3-Coder-30B-A3B-Instruct-MLX-8bit", "gb": 32.4}, - "mlx-6bit": {"repo": "lmstudio-community/Qwen3-Coder-30B-A3B-Instruct-MLX-6bit", "gb": 24.8}, - "mlx-4bit": {"repo": "lmstudio-community/Qwen3-Coder-30B-A3B-Instruct-MLX-4bit", "gb": 17.2} + "fp8": { + "repo": "Qwen/Qwen3-Coder-30B-A3B-Instruct-FP8", + "gb": 31.2 + }, + "bf16": { + "repo": "Qwen/Qwen3-Coder-30B-A3B-Instruct", + "gb": 61.1 + }, + "awq": { + "repo": "cyankiwi/Qwen3-Coder-30B-A3B-Instruct-AWQ-4bit", + "gb": 18.1 + }, + "mlx-8bit": { + "repo": "lmstudio-community/Qwen3-Coder-30B-A3B-Instruct-MLX-8bit", + "gb": 32.4 + }, + "mlx-6bit": { + "repo": "lmstudio-community/Qwen3-Coder-30B-A3B-Instruct-MLX-6bit", + "gb": 24.8 + }, + "mlx-4bit": { + "repo": "lmstudio-community/Qwen3-Coder-30B-A3B-Instruct-MLX-4bit", + "gb": 17.2 + } } }, { @@ -68,15 +153,40 @@ "context": 262144, "hybrid": true, "reasoning": true, - "vllm": {"tool_parser": "qwen3_xml", "reasoning_parser": "qwen3", "kv_cache_dtype": "fp8", "trust_remote_code": true}, - "mlx": {"trust_remote_code": true}, + "vllm": { + "tool_parser": "qwen3_xml", + "reasoning_parser": "qwen3", + "kv_cache_dtype": "fp8", + "trust_remote_code": true + }, + "mlx": { + "trust_remote_code": true + }, "variants": { - "fp8": {"repo": "ornith-ai/Ornith-1.5-122B-FP8", "gb": 132.9}, - "bf16": {"repo": "ornith-ai/Ornith-1.5-122B", "gb": 250.2}, - "nvfp4": {"repo": "ornith-ai/Ornith-1.5-122B-NVFP4", "gb": 77.6}, - "awq": {"repo": "cyankiwi/Ornith-1.5-122B-AWQ-INT4", "gb": 85.3}, - "mlx-8bit": {"repo": "ornith-ai/Ornith-1.5-122B-MLX-8bit", "gb": 130.6}, - "mlx-4bit": {"repo": "ornith-ai/Ornith-1.5-122B-MLX-4bit", "gb": 69.6} + "fp8": { + "repo": "ornith-ai/Ornith-1.5-122B-FP8", + "gb": 132.9 + }, + "bf16": { + "repo": "ornith-ai/Ornith-1.5-122B", + "gb": 250.2 + }, + "nvfp4": { + "repo": "ornith-ai/Ornith-1.5-122B-NVFP4", + "gb": 77.6 + }, + "awq": { + "repo": "cyankiwi/Ornith-1.5-122B-AWQ-INT4", + "gb": 85.3 + }, + "mlx-8bit": { + "repo": "ornith-ai/Ornith-1.5-122B-MLX-8bit", + "gb": 130.6 + }, + "mlx-4bit": { + "repo": "ornith-ai/Ornith-1.5-122B-MLX-4bit", + "gb": 69.6 + } } }, { @@ -87,15 +197,40 @@ "context": 262144, "hybrid": true, "reasoning": true, - "vllm": {"tool_parser": "qwen3_xml", "reasoning_parser": "qwen3", "kv_cache_dtype": "fp8", "trust_remote_code": true}, - "mlx": {"trust_remote_code": true}, + "vllm": { + "tool_parser": "qwen3_xml", + "reasoning_parser": "qwen3", + "kv_cache_dtype": "fp8", + "trust_remote_code": true + }, + "mlx": { + "trust_remote_code": true + }, "variants": { - "bf16": {"repo": "ornith-ai/Ornith-1.5-9B", "gb": 19.3}, - "nvfp4": {"repo": "ornith-ai/Ornith-1.5-9B-NVFP4", "gb": 8.8}, - "awq": {"repo": "cyankiwi/Ornith-1.5-9B-AWQ-INT4", "gb": 9.0}, - "mlx-8bit": {"repo": "ornith-ai/Ornith-1.5-9B-MLX-8bit", "gb": 9.5}, - "mlx-6bit": {"repo": "ornith-ai/Ornith-1.5-9B-MLX-6bit", "gb": 7.3}, - "mlx-4bit": {"repo": "ornith-ai/Ornith-1.5-9B-MLX-4bit", "gb": 5.0} + "bf16": { + "repo": "ornith-ai/Ornith-1.5-9B", + "gb": 19.3 + }, + "nvfp4": { + "repo": "ornith-ai/Ornith-1.5-9B-NVFP4", + "gb": 8.8 + }, + "awq": { + "repo": "cyankiwi/Ornith-1.5-9B-AWQ-INT4", + "gb": 9.0 + }, + "mlx-8bit": { + "repo": "ornith-ai/Ornith-1.5-9B-MLX-8bit", + "gb": 9.5 + }, + "mlx-6bit": { + "repo": "ornith-ai/Ornith-1.5-9B-MLX-6bit", + "gb": 7.3 + }, + "mlx-4bit": { + "repo": "ornith-ai/Ornith-1.5-9B-MLX-4bit", + "gb": 5.0 + } } } ] diff --git a/llmhost/hfcache.py b/llmhost/hfcache.py index bb92895..b6be77a 100644 --- a/llmhost/hfcache.py +++ b/llmhost/hfcache.py @@ -59,3 +59,36 @@ def download_gib(repo): except OSError: pass return total / 2**30 + + +def chat_template(repo): + """The model's chat template, or "" if it isn't on disk. Newer repos ship it as + chat_template.jinja; older ones keep it inside tokenizer_config.json.""" + snaps = repo_dir(repo) / "snapshots" + if not snaps.is_dir(): + return "" + for snap in snaps.iterdir(): + f = snap / "chat_template.jinja" + if f.exists(): + try: + return f.read_text() + except OSError: + pass + cfg = snap / "tokenizer_config.json" + if cfg.exists(): + try: + t = json.loads(cfg.read_text()).get("chat_template") + except (OSError, ValueError): + continue + if isinstance(t, str) and t: + return t + return "" + + +def template_controls(repo): + """Which reasoning knobs this model's template actually reads. Checked against the + template rather than trusted from the catalog, because passing a kwarg the template + doesn't expect is silently ignored, and an effort level it doesn't know makes it + raise -- so the dashboard must only ever offer what is really there.""" + t = chat_template(repo) + return {"thinking": "enable_thinking" in t, "effort": "reasoning_effort" in t} diff --git a/llmhost/plan.py b/llmhost/plan.py index d0e948e..6e633a6 100644 --- a/llmhost/plan.py +++ b/llmhost/plan.py @@ -160,3 +160,39 @@ def mlx_args(entry, choice, port): args += ["--prompt-concurrency", "1", "--decode-concurrency", "4"] args += x.get("extra_args", []) return args + + +# ---- 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 {} diff --git a/llmhost/web/index.html b/llmhost/web/index.html index 3f56396..52dab6e 100644 --- a/llmhost/web/index.html +++ b/llmhost/web/index.html @@ -63,6 +63,15 @@ h1 span { color: var(--muted); font-weight: 500; } } .loadline b { color: var(--warn); font-family: system-ui, sans-serif; margin-right: 6px; } .btns { display: flex; gap: 8px; margin-top: 14px; flex-wrap: wrap; } +.effort { margin-top: 14px; padding-top: 14px; border-top: 1px solid var(--border); } +.effort .k { font-size: 11.5px; text-transform: uppercase; letter-spacing: .06em; color: var(--muted); font-weight: 600; } +.effort .row { display: flex; gap: 8px; align-items: center; margin-top: 8px; flex-wrap: wrap; } +.effort select { + background: var(--bg); color: var(--text); border: 1px solid var(--border); border-radius: 8px; + padding: 6px 10px; font: inherit; font-size: 13px; min-width: 150px; +} +.effort select:disabled { color: var(--muted); } +.effort .s { color: var(--muted); font-size: 12px; margin-top: 7px; line-height: 1.45; } button { font: inherit; font-size: 13px; font-weight: 550; padding: 7px 13px; border-radius: 8px; cursor: pointer; border: 1px solid var(--border); background: var(--panel-2); color: var(--text); @@ -171,6 +180,15 @@ pre {
Loading
+ +
@@ -411,8 +429,58 @@ function render(s) { chart("c-power", h.map((p) => p.power), "var(--c5)", plim, (v) => Math.round(v) + " W"); } renderRuns(s); + renderEffort(s); } +let effortBusy = false; + +function renderEffort(s) { + const r = s.reasoning || {}, box = $("effort"), sel = $("effort-sel"); + const opts = r.options || []; + // Hidden rather than disabled when there is nothing to choose: on vLLM there's no proxy + // to inject the kwarg, and a model whose template has no switches has nothing to offer. + box.hidden = !opts.length && !r.why; + if (!opts.length) { + sel.innerHTML = ""; + sel.disabled = true; + $("effort-state").textContent = ""; + $("effort-note").textContent = r.why || ""; + return; + } + if (effortBusy) return; + const want = opts.map((o) => o.value).join("|"); + if (sel.dataset.sig !== want) { + sel.dataset.sig = want; + sel.innerHTML = ""; + for (const o of opts) { + const el = document.createElement("option"); + el.value = o.value; + el.textContent = o.label; + sel.append(el); + } + } + sel.value = r.value || "default"; + sel.disabled = s.phase !== "ready"; + $("effort-state").textContent = s.phase === "ready" ? "" : "available once the model is ready"; + $("effort-note").textContent = "Applies to requests that don't set their own; takes effect " + + "on the next request, with no reload."; +} + +$("effort-sel").onchange = async (e) => { + const value = e.target.value; + effortBusy = true; + try { + await api("/api/reasoning", { method: "POST", body: JSON.stringify({ value }) }); + const opt = e.target.selectedOptions[0]; + toast(`Reasoning: ${opt ? opt.textContent : value}`); + } catch (err) { + toast("Couldn't change reasoning"); + } finally { + effortBusy = false; + poll(); + } +}; + function renderRuns(s) { const runs = s.runs || [], body = $("runs-body"), foot = $("runs-foot"); $("runs-empty").hidden = runs.length > 0; diff --git a/llmhost/web/server.py b/llmhost/web/server.py index 993cab4..72724b3 100644 --- a/llmhost/web/server.py +++ b/llmhost/web/server.py @@ -13,7 +13,7 @@ from collections import deque from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path -from .. import hfcache, hw, opencode, paths, service +from .. import hfcache, hw, opencode, paths, plan, service HERE = Path(__file__).resolve().parent SAMPLE_SECONDS = 2 @@ -223,6 +223,7 @@ class Sampler: dl = self.downloaded() models = [{**m, "downloaded": dl.get(m["repo"], False)} for m in cfg.get("models", [])] + reasoning = self.reasoning_state(cfg, active) with self.lock: self.history.append(point) @@ -256,6 +257,7 @@ class Sampler: "hardware": cfg.get("hardware_name"), "budget_gib": cfg.get("budget_gib"), "active": active, "served_models": served, "models": models, "excluded": cfg.get("excluded", []), "gpu": gpu, "last_log": last_log, + "reasoning": reasoning, "action": self.action, "metrics": { "running": metrics.get("running"), "waiting": metrics.get("waiting"), @@ -277,6 +279,42 @@ class Sampler: "runs": list(self.runs)[::-1], } + def reasoning_state(self, cfg, active): + """What the active model can be told about reasoning, and what it's set to. + Only MLX: on vLLM llm-host has no proxy in front, so nothing here could inject + the kwarg into a client's request.""" + choice = next((m for m in cfg.get("models", []) if m["name"] == active), None) + if not choice or cfg.get("backend") != "mlx": + return {"options": [], "value": plan.DEFAULT, "why": "" if choice else None} + entry = next((m for m in paths.load_catalog()["models"] if m["name"] == active), None) + if not entry: + return {"options": [], "value": plan.DEFAULT, "why": None} + if not hfcache.repo_dir(choice["repo"]).exists(): + return {"options": [], "value": plan.DEFAULT, + "why": "the model isn't downloaded yet, so its chat template can't be read"} + controls = hfcache.template_controls(choice["repo"]) + opts = plan.reasoning_options(entry, choice, controls) + value = (cfg.get("reasoning") or {}).get(active) or plan.DEFAULT + if value not in [v for v, _ in opts]: + value = plan.DEFAULT + why = "" if opts else "this model's chat template exposes no reasoning controls" + return {"options": [{"value": v, "label": l} for v, l in opts], "value": value, "why": why} + + def set_reasoning(self, value): + """Takes effect on the next request -- no restart, so the model stays loaded.""" + cfg = paths.load_config() + active = cfg.get("active") + allowed = [o["value"] for o in self.reasoning_state(cfg, active)["options"]] + if value not in allowed: + return False, allowed + cfg.setdefault("reasoning", {})[active] = value + paths.save_config(cfg) + self.cfg = cfg + with self.lock: + if self.state.get("reasoning"): + self.state["reasoning"]["value"] = value + return True, allowed + def snapshot(self): with self.lock: s = dict(self.state) @@ -360,6 +398,12 @@ def make_handler(sampler, key): return self.send_json(400, {"error": f"unknown model {name!r}"}) sampler.control("switch", name) return self.send_json(202, {"ok": True, "model": name}) + if path == "/api/reasoning": + ok, allowed = sampler.set_reasoning(str(data.get("value", ""))) + if not ok: + return self.send_json(400, {"error": "unsupported value for this model", + "allowed": allowed}) + return self.send_json(200, {"ok": True, "value": data.get("value")}) if path in ("/api/stop", "/api/start", "/api/restart"): sampler.control(path.rsplit("/", 1)[1]) return self.send_json(202, {"ok": True})