Skip to content

Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.

C++

serve: Intel Arc readings in the Monitor tab; a model menu for hosts that swap models

maxfridbe6f12431d5346
diff --git a/serve/server.py b/serve/server.py
index f51fc174b..4dbf76c06 100644
--- a/serve/server.py
+++ b/serve/server.py
@@ -562,6 +562,28 @@ class Detokenizer:
return delta
+def model_switcher(svc, mode: str = "") -> dict:
+ """The host's model swapper (config `model_switcher`, an RPC taking {"mode": m}): the models it serves on THIS
+ port, which one holds the card, whether one is loading. With `mode`, asks for that one first; this server is
+ then usually the one stopped, so the web app waits for /health to name the new model."""
+ url = getattr(svc, "switcher", None)
+ if not url:
+ return {"enabled": False}
+ try:
+ body = json.dumps({"mode": mode} if mode else {}).encode()
+ req = urllib.request.Request(url, body, {"Content-Type": "application/json"})
+ with urllib.request.urlopen(req, timeout=10) as r:
+ res = json.load(r)
+ st = res.get("result", res)
+ except (OSError, ValueError) as e:
+ return {"enabled": True, "error": f"the model switcher did not answer ({e})"}
+ port = f":{getattr(svc, 'port', '')}"
+ urls = st.get("urls") or {}
+ mine = {k: v for k, v in (st.get("choices") or {}).items() if not urls or str(urls.get(k, "")).endswith(port)}
+ return {"enabled": True, "mode": st.get("mode"), "up": st.get("up"), "starting": st.get("starting"),
+ "choices": mine, "model": svc.model}
+
+
class Service:
def __init__(self, engine: Engine, tokenizer, template: ChatTemplate, model_name: str = "qwen3.8-flash-next",
vision: Vision | None = None, sampling_defaults: dict | None = None,
@@ -1316,6 +1338,10 @@ def make_handler(svc: Service):
if self._authorized():
self._json(200, {"shared": bool(svc.shared), "defaults": svc.shared})
return
+ if path == "/switcher":
+ if self._authorized():
+ self._json(200, model_switcher(svc))
+ return
if path == "/mcp":
# the MCP servers, their state and tools (the web app's switch and Monitor card)
if self._authorized():
@@ -1376,6 +1402,10 @@ def make_handler(svc: Service):
if path == "/settings":
self._settings()
return
+ if path == "/switcher": # the web app's model menu: ask the host to swap models
+ req = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))) or b"{}")
+ self._json(200, model_switcher(svc, str(req.get("mode") or "")))
+ return
try:
req = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))) or b"{}")
if path in ("/v1/chat/completions", "/v1/messages"): # who asked: a later "disconnect" names its client
@@ -1780,6 +1810,10 @@ def main() -> int:
file=sys.stderr)
return 2
svc.api_key = a.api_key or cfg.get("api_key", "")
+ # A host that runs one model at a time and swaps them (a GPU shared with other work) can name the RPC that does
+ # the swap: the web app then offers the models served on this port. {"mode": m} switches, {} only reports.
+ svc.switcher = cfg.get("model_switcher") or None
+ svc.port = a.port
svc.gpu_index = (gpu_list(cfg) or [0])[0] # the Monitor reads the card the engine runs on (issue #51)
svc.gpu_indices = gpu_list(cfg) # ... or every card of a layer split (issue #112)
if a.config: # the Chat settings shared with other apps, from last time
diff --git a/serve/telemetry.py b/serve/telemetry.py
index 6cfd0e3be..640792cc2 100644
--- a/serve/telemetry.py
+++ b/serve/telemetry.py
@@ -2,7 +2,9 @@
A background thread samples once a second and keeps the last 60 readings of each series for the sparklines:
- GPU: NVIDIA's own NVML library (nvml.dll / libnvidia-ml.so.1, installed with every driver) through ctypes, so no
- pip package is needed: load, VRAM, temperature, power, PCIe link and throughput.
+ pip package is needed: load, VRAM, temperature, power, PCIe link and throughput. On an Intel Arc (xe driver) the
+ same readings come from a root sampler's /run/gpustat.json when one runs (load and VRAM need root: per-client
+ fdinfo), else from sysfs directly (temperature, power, PCIe link).
- CPU, RAM, disk: `psutil` when it is installed (setup installs it); without it the CPU and RAM readings fall back to
the OS (Windows GlobalMemoryStatusEx / GetSystemTimes, Linux /proc) and the disk rate is absent.
Anything that cannot be read is None; nothing here can stop the server.
@@ -103,6 +105,98 @@ class _Nvml:
return out
+# ------------------------------------------------------------------------------------------------ Intel Arc (xe)
+class _XeGpu:
+ """The Intel Arc readings in NVML's shape. Load and VRAM come from /run/gpustat.json (a root sampler: the only
+ VRAM accounting xe exposes is per-client fdinfo, readable by root only); temperature, power and the PCIe link are
+ read from sysfs too, so they show without the sampler."""
+ STAT = "/run/gpustat.json"
+
+ def __init__(self):
+ import glob
+ self.dev = None
+ for d in sorted(glob.glob("/sys/class/drm/card[0-9]*/device")):
+ try:
+ if open(f"{d}/vendor").read().strip() == "0x8086" and os.path.isdir(f"{d}/tile0"):
+ self.dev = os.path.realpath(d)
+ break
+ except OSError:
+ continue
+ self.hwmon = None
+ for n in glob.glob(f"{self.dev}/hwmon/hwmon*/name") if self.dev else []:
+ self.hwmon = os.path.dirname(n)
+ self._e = None # (t, card energy uJ) for power without the sampler
+
+ def ok(self):
+ return self.dev is not None and sys.platform.startswith("linux")
+
+ def name(self):
+ st = self._stat()
+ return (st or {}).get("name") or "Intel Arc GPU"
+
+ def _stat(self):
+ try:
+ import json
+ with open(self.STAT) as f:
+ st = json.load(f)
+ return st if time.time() - float(st.get("ts", 0)) < 15 else None
+ except (OSError, ValueError):
+ return None
+
+ def _rd(self, p):
+ try:
+ return open(p).read().strip()
+ except OSError:
+ return None
+
+ def _link(self):
+ """The link the card trained at: its own functions sit behind an internal x1 switch, so the first port up
+ the path wider than x1; the max is what card AND slot allow (the root port caps it)."""
+ gen = {"2.5": 1, "5.0": 2, "8.0": 3, "16.0": 4, "32.0": 5, "64.0": 6}
+ d, chain = self.dev, []
+ while d and d.startswith("/sys/devices/pci") and os.path.exists(f"{d}/current_link_speed"):
+ chain.append(d)
+ d = os.path.dirname(d)
+ for p in chain:
+ w = int(self._rd(f"{p}/current_link_width") or 0)
+ if w > 1:
+ g = lambda q, k: gen.get((self._rd(f"{q}/{k}_link_speed") or "").split(" ")[0])
+ card, slot = g(p, "max"), g(chain[-1], "max")
+ return g(p, "current"), min(x for x in (card, slot) if x) if (card or slot) else None, w
+ return None, None, None
+
+ def read(self):
+ out = {}
+ st = self._stat()
+ if st:
+ out["util"] = st.get("busy_pct")
+ if st.get("vram_used_mb") is not None:
+ out["mem_used"] = st["vram_used_mb"] * 2**20
+ out["mem_total"] = st.get("vram_total_mb", 0) * 2**20 or None
+ out["temp"] = st.get("temp_pkg")
+ out["power"] = st.get("power_w")
+ out["power_limit"] = st.get("power_cap_w")
+ out["vram_temp"] = st.get("temp_vram_max") or st.get("temp_vram")
+ if self.hwmon:
+ if out.get("temp") is None:
+ for lab in os.listdir(self.hwmon):
+ if lab.endswith("_label") and self._rd(f"{self.hwmon}/{lab}") == "pkg":
+ v = self._rd(f"{self.hwmon}/{lab[:-6]}_input")
+ out["temp"] = int(v) / 1000 if v else None
+ if out.get("power") is None:
+ e, t = self._rd(f"{self.hwmon}/energy1_input"), time.time()
+ if e and e.isdigit():
+ if self._e and t > self._e[0] and int(e) >= self._e[1]:
+ out["power"] = (int(e) - self._e[1]) / 1e6 / (t - self._e[0])
+ self._e = (t, int(e))
+ if out.get("power_limit") is None:
+ cap = self._rd(f"{self.hwmon}/power1_cap")
+ out["power_limit"] = int(cap) / 1e6 if cap and cap.isdigit() and int(cap) > 0 else None
+ out["pcie_gen"], out["pcie_gen_max"], out["pcie_width"] = self._link()
+ out["pcie_rx_mb"] = out["pcie_tx_mb"] = None # xe exposes no PCIe traffic counters
+ return out
+
+
# ------------------------------------------------------------------------------------------------ CPU / RAM
def _cpu_name():
if os.name == "nt":
@@ -181,6 +275,10 @@ class Telemetry:
idx = list(gpu_indices) if gpu_indices and len(gpu_indices) > 1 else [gpu_index]
self.gpus = [(i, _Nvml(i)) for i in idx]
self.gpus = [(i, g) for i, g in self.gpus if g.ok()] or self.gpus[:1]
+ if not self.gpus[0][1].ok(): # no NVIDIA card: an Intel Arc on the xe driver?
+ xe = _XeGpu()
+ if xe.ok():
+ self.gpus = [(0, xe)]
self.gpu = self.gpus[0][1]
try:
import psutil # noqa: F401
diff --git a/serve/web/app.css b/serve/web/app.css
index 4e8363d4a..77ff60beb 100644
--- a/serve/web/app.css
+++ b/serve/web/app.css
@@ -168,3 +168,10 @@ main { flex: 1; min-height: 0; display: flex; }
.facts { grid-template-columns: 1fr; gap: 2px; }
.facts dd { margin-bottom: var(--st-s-2); }
}
+/* the model menu (a host that swaps models: config model_switcher) */
+.model-switch{display:flex;align-items:center;gap:var(--st-s-2);font-size:var(--st-fs-sm);color:var(--st-ink-muted)}
+.model-switch[hidden]{display:none}
+.model-switch select{font:inherit;color:var(--st-ink);background:var(--st-surface-2);border:1px solid var(--st-line);
+ border-radius:var(--st-r-md);padding:4px 8px;max-width:340px}
+.model-switch select:focus{outline:2px solid var(--st-focus);outline-offset:1px}
+@media (max-width:640px){.model-switch__k{display:none}.model-switch select{max-width:150px}}
diff --git a/serve/web/app.js b/serve/web/app.js
index 6e8fa6b29..eb501612b 100644
--- a/serve/web/app.js
+++ b/serve/web/app.js
@@ -107,6 +107,55 @@ async function loadHealth() {
}
}
+// ------------------------------------------------------------------ the model menu
+// A host that swaps models on one GPU (config model_switcher): this page offers the ones served here. Switching
+// stops THIS server and starts the other on the same port, so the page waits for /health to name the new model.
+let switching = null;
+async function loadSwitcher() {
+ let sw;
+ try { sw = await (await fetch("switcher", {headers: headers()})).json(); } catch (e) { return; }
+ const keys = Object.keys(sw.choices || {});
+ if (!sw.enabled || sw.error || keys.length < 2) { $("model-switch").hidden = true; return; }
+ const sel = $("model-select");
+ sel.replaceChildren(...keys.map((k) => {
+ const o = document.createElement("option");
+ o.value = k;
+ o.textContent = sw.choices[k].replace(/ \(Strata SYCL engine\)$/, "");
+ o.selected = k === (sw.starting || sw.mode);
+ return o;
+ }));
+ sel.disabled = !!sw.starting || !!switching;
+ $("model-switch").hidden = false;
+ if (sw.starting && !switching) setPill("reading", `Loading ${sw.choices[sw.starting] || sw.starting}…`);
+}
+$("model-select").onchange = async () => {
+ const mode = $("model-select").value, name = $("model-select").selectedOptions[0].textContent;
+ if (!confirm(`Load ${name}? The current model is unloaded first; it takes about 2 minutes and stops any answer in progress.`)) {
+ loadSwitcher();
+ return;
+ }
+ switching = {mode, from: health.model, t0: Date.now()};
+ $("model-select").disabled = true;
+ setPill("reading", `Switching to ${name}… (about 2 minutes)`, true);
+ try {
+ await fetch("switcher", {method: "POST", headers: headers(true), body: JSON.stringify({mode})});
+ } catch (e) { /* this server may already be going down */ }
+ const wait = async () => {
+ try {
+ const h = await (await fetch("health", {cache: "no-store"})).json();
+ if (h.model && h.model !== switching.from) { location.reload(); return; }
+ } catch (e) { /* down while the models swap */ }
+ if (Date.now() - switching.t0 > 6 * 60 * 1000) {
+ setPill("error", `${name} did not come up in 6 minutes`, true);
+ switching = null;
+ return;
+ }
+ setPill("reading", `Switching to ${name}… ${Math.round((Date.now() - switching.t0) / 1000)} s`, true);
+ setTimeout(wait, 3000);
+ };
+ setTimeout(wait, 5000);
+};
+
// ------------------------------------------------------------------ Monitor
const METRICS = [
{key: "speed", label: "Speed", icon: "gauge", unit: "t/s", series: "tok_s"},
@@ -171,7 +220,8 @@ async function poll() {
setTimeout(poll, 1000);
}
-function setPill(state, text) {
+function setPill(state, text, force = false) {
+ if (switching && !force) return; // while the models swap, the menu owns the pill
$("pill").dataset.state = state === "error" ? "queued" : state;
$("pill-text").textContent = text;
}
@@ -975,6 +1025,7 @@ setBusy(false);
renderChat();
const startQuestion = new URLSearchParams(location.search).get("q"); // /?q=... starts a chat (a shortcut)
if (startQuestion) history.replaceState(null, "", location.pathname + location.hash);
-loadHealth().then(loadMcp).then(() => { if (startQuestion) { $("input").value = startQuestion; send(); } });
+loadHealth().then(loadSwitcher).then(loadMcp).then(() => { if (startQuestion) { $("input").value = startQuestion; send(); } });
showTab(location.hash.slice(1) || "chat");
poll();
+setInterval(() => { if (!switching) loadSwitcher(); }, 15000); // a switch started elsewhere shows here too
diff --git a/serve/web/index.html b/serve/web/index.html
index d858d2f08..c4ecf325b 100644
--- a/serve/web/index.html
+++ b/serve/web/index.html
@@ -19,6 +19,11 @@
<body>
<header class="st-header">
<span class="st-header__brand">Strata</span>
+ <!-- the model on the GPU, when the host swaps models (config model_switcher); hidden otherwise -->
+ <label class="model-switch" id="model-switch" hidden title="Which model is loaded. Only one fits on the GPU at a time: switching unloads this one and loads the other (about 2 minutes).">
+ <span class="model-switch__k">Model</span>
+ <select id="model-select" aria-label="Model on the GPU"></select>
+ </label>
<nav class="st-tabs" role="tablist" aria-label="Views">
<button class="st-tab" role="tab" id="tab-btn-chat" aria-controls="view-chat" aria-selected="true" data-tab="chat">
<svg class="st-icon st-icon--sm"><use href="web/sprite.svg#i-chat"/></svg>Chat</button>
diff --git a/setup.py b/setup.py
index 194f797e4..c0431365d 100644
--- a/setup.py
+++ b/setup.py
@@ -2311,6 +2311,9 @@ def main() -> int:
if old.get("sampling") and "sampling" not in cfg:
cfg["sampling"] = old["sampling"]
ok("kept the sampling defaults of the earlier config: " + ", ".join(f"{k}={v}" for k, v in old["sampling"].items()))
+ if old.get("model_switcher") and "model_switcher" not in cfg: # the web app's model menu (a host swapping models)
+ cfg["model_switcher"] = old["model_switcher"]
+ ok("kept the model switcher of the earlier config: " + old["model_switcher"])
except (OSError, ValueError):
pass
cal = None if backend in ("llama", "sycl") or hip else saved_calibration(cfg) # tools/calibrate.py is NVIDIA-only for now