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: add lazy startup and reliable Windows model cleanup
Ricardo Ambrogi7f3a09189526
diff --git a/docs/DETAILS.md b/docs/DETAILS.mdindex 2454069f2..3619c9d75 100644--- a/docs/DETAILS.md+++ b/docs/DETAILS.md@@ -778,3 +778,20 @@ Strata itself: [MIT](../LICENSE). The model files are not part of it; their lice`serve/web/fonts/OFL.txt`). Its Monitor tab started from @code-martin's dashboard idea (PR #22).- The experimental speed projection's vector (`data/experimental-speed-projection/`): Qwen Community License 1.0,made from the model's activations (see its README).++### Start the text API without occupying the GPU++`serve/server.py --engine strata --config strata-<model>.json --lazy` (or `"lazy_load": true` in that+config) starts the lightweight HTTP API without spawning the native engine. The first generation request+loads it through the existing reload path, including `before_load` and `min_free_vram_mib`. Eager startup+remains the default. This option is text-only: a vision configuration with lazy startup is rejected explicitly.++`POST /v1/load` and `/v1/unload` are JSON control aliases for integrations, accepting `{}` or+`{"model":"<configured model>"}` and returning model status. They require the configured API key,+`application/json`, and no foreign browser Origin. They return **409** while a request is active or queued,+and **404** for an unknown model. Existing `/load` and `/unload` behavior is preserved. `/api/health` aliases+`/health`; `/v1/status` exposes `loaded` and `auto_load`. The unloaded model remains discoverable.++Unloading and shutdown close the native engine's stdin after sending `QUIT`, allowing Windows' detached+stdin reader to see EOF. Cleanup waits for process exit before releasing handles; if forced shutdown still+times out, the server keeps ownership and reports an error rather than claiming the model was unloaded.diff --git a/serve/server.py b/serve/server.pyindex 5c5fbd10a..32ef06487 100644--- a/serve/server.py+++ b/serve/server.py@@ -100,6 +100,10 @@ class EngineDied(RuntimeError):"""The engine process ended in the middle of a request (issue #27: on Linux, the out-of-memory killer)."""+class ModelBusy(RuntimeError):+ """Explicit model controls must not interrupt active or queued requests."""++class GpuBusy(RuntimeError):"""The model is unloaded and the GPU has less free VRAM than min_free_vram_mib: something else (a game, anothermodel server) is using it, so the engine is not started into the little that is left."""@@ -197,11 +201,26 @@ class StrataEngine:"""def __init__(self, exe: str, args: list[str], cwd: str | None = None, log: str | None = None,- env: dict | None = None):+ env: dict | None = None, lazy: bool = False):self.spawn = (exe, list(args), cwd, log, env) # to start it again after it died (issue #27)paths = {k: v for k, v in zip(args, args[1:]) if k in ("--native", "--pack")}self.model_path = paths.get("--native") or paths.get("--pack", "pack/full")self.log_path = log+ self.proc, self.pump, self.log = None, None, None+ self.ended, self.unloaded = True, True+ self.max_context = int(args[args.index("--max-context") + 1]) if "--max-context" in args else 4096+ self.can_stop = False # the engine honours a STOP line mid-request (READY <ctx> stop)+ self.last = {}+ self.info = {} # INFO key=value facts (engine 0.1.8+): kv, expert slots, ... (Monitor tab)+ self.prefill_tok_s_mean = None+ self.progress = None # (read, total) prompt tokens while a prompt is read, from PP lines+ try: # a ready-made engine's BUILD.json says its version+ self.info["version"] = json.loads((Path(exe).parent / "BUILD.json").read_text()).get("version")+ except (OSError, ValueError):+ self.info["version"] = None+ if lazy:+ return+ self.ended, self.unloaded = False, Falseself.log = open(log, "a", encoding="utf-8") if log else subprocess.DEVNULLloading = threading.Event() # set once READY: the narrator below stopsif log:@@ -215,16 +234,6 @@ class StrataEngine:stderr=self.log, text=True, encoding="utf-8", bufsize=1, env=env)contain(self.proc) # ends with the server, however it ends (Windows)self.max_context = 0- self.unloaded = False # stopped on purpose (idle unload, POST /unload), not crashed- self.can_stop = False # the engine honours a STOP line mid-request (READY <ctx> stop)- self.last = {}- self.info = {} # INFO key=value facts (engine 0.1.8+): kv, expert slots, ... (Monitor tab)- self.prefill_tok_s_mean = None- self.progress = None # (read, total) prompt tokens while a prompt is read, from PP lines- try: # a ready-made engine's BUILD.json says its version- self.info["version"] = json.loads((Path(exe).parent / "BUILD.json").read_text()).get("version")- except (OSError, ValueError):- self.info["version"] = Nonefor line in self.proc.stdout:if line.startswith("INFO "):for kv in line.split()[1:]:@@ -244,7 +253,8 @@ class StrataEngine:self.info["version"] = str(self.info["engine"])# the engine's stdout on a thread, so a request can wait with a timeout (heartbeats, cancel checks)self.lines: queue.Queue = queue.Queue()- threading.Thread(target=self._pump, daemon=True).start()+ self.pump = threading.Thread(target=self._pump, daemon=True)+ self.pump.start()def _pump(self):for line in self.proc.stdout:@@ -276,39 +286,24 @@ class StrataEngine:"smaller model (Q2_0 / IQ2_XS).")def alive(self) -> bool:- return not getattr(self, "ended", False) and self.proc.poll() is None+ return self.proc is not None and not getattr(self, "ended", False) and self.proc.poll() is Nonedef exit_code(self):+ if self.proc is None:+ return Nonetry:return self.proc.wait(timeout=5)except subprocess.TimeoutExpired:return Nonedef unload(self):- """Stop the engine process so its VRAM and RAM go back to the system (idle unload, POST /unload); the next- request starts it again with restart(). Only between requests: the caller holds the service's fifo."""- try:- try: # QUIT first, as close() does: the engine frees its memory- self.proc.stdin.write("QUIT\n")- self.proc.stdin.flush()- self.proc.wait(timeout=20)- except (OSError, ValueError, subprocess.TimeoutExpired):- self.proc.terminate()- self.proc.wait(timeout=20)- except subprocess.TimeoutExpired:- self.proc.kill()- self.proc.wait(timeout=20)- except OSError:- pass- self.ended = True+ """Release GPU/RAM between requests, retaining the spawn config for automatic reloading."""+ self.close()self.unloaded = Truedef restart(self):"""Start the engine again (the same command) after it died; the new process has its own line queue."""- try:- self.proc.kill()- except OSError:- pass+ self.close()info = dict(self.info)self.ended = Falseself.__init__(*self.spawn)@@ -442,12 +437,31 @@ class StrataEngine:breakdef close(self):+ if self.proc is None:+ returntry:- self.proc.stdin.write("QUIT\n")- self.proc.stdin.flush()- self.proc.wait(timeout=10)- except Exception:+ if self.proc.poll() is None:+ self.proc.stdin.write("QUIT\n")+ self.proc.stdin.flush()+ self.proc.stdin.close() # Windows' detached stdin reader must see EOF before shutdown+ self.proc.wait(timeout=10)+ except (OSError, ValueError, subprocess.TimeoutExpired):self.proc.kill()+ try:+ self.proc.wait(timeout=5)+ except subprocess.TimeoutExpired:+ raise RuntimeError("Strata is still releasing GPU/RAM; retry unloading after it exits") from None+ finally:+ if self.proc.poll() is not None:+ if self.pump is not None:+ self.pump.join(timeout=2)+ self.proc.stdin.close()+ self.proc.stdout.close()+ if self.log not in (None, subprocess.DEVNULL):+ self.log.close()+ self.proc = None+ self.ended = True+ self.progress, self.last = None, {}class Vision:@@ -937,6 +951,7 @@ class Service:images = self.vision is not Nonereturn {"service": "strata", "model": self.model,+ "loaded": self.loaded(), "auto_load": hasattr(self.engine, "restart"),"engine": (getattr(self.engine, "info", {}) or {}).get("version"),"started": int(self.started_at), "uptime_s": int(time.time() - self.started_at),"cache_max_tokens": ctx,@@ -1633,10 +1648,10 @@ def make_handler(svc: Service):self.send_header("Content-Length", str(len(body)))self.end_headers()self.wfile.write(body)- elif path == "/health":+ elif path in ("/health", "/api/health"):self._json(200, {"status": "ok", "max_context": svc.engine.max_context, "model": svc.model,"images": svc.vision is not None, "api_key": bool(svc.api_key),- "loaded": svc.loaded()})+ "loaded": svc.loaded(), "service": "strata"})elif path == "/status":if not self._authorized(): # #212: it shows the end of the last answerreturn@@ -1698,6 +1713,32 @@ def make_handler(svc: Service):returntry:req = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))) or b"{}")+ if not isinstance(req, dict):+ raise ValueError("send a JSON object")+ if path in ("/v1/load", "/v1/unload"):+ if not self._own_page("the model can be loaded or unloaded"):+ return+ if req.get("model") not in (None, svc.model):+ self._json(404, {"error": {"message": "model not found"}})+ return+ if path == "/v1/unload":+ result = svc.unload()+ if result == "busy":+ raise ModelBusy("a request is running or queued")+ else:+ if not svc.fifo.acquire(blocking=False):+ raise ModelBusy("a request is running or queued")+ try:+ with svc.status_lock:+ if svc.status.get("busy") or svc.status.get("queued"):+ raise ModelBusy("a request is running or queued")+ svc.ensure_loaded()+ svc.last_request_at = time.time()+ finally:+ svc.fifo.release()+ result = "loaded"+ self._json(200, {"status": result, **svc.v1_status()})+ returnif path in ("/v1/chat/completions", "/v1/messages"):svc.load() # unloaded: load first (or 503 while the GPU is busy)if path == "/v1/chat/completions":@@ -1710,10 +1751,14 @@ def make_handler(svc: Service):self._json(404, {"error": {"message": "not found"}})except ValueError as e:self._json(400, {"error": {"type": "invalid_request_error", "message": str(e)}})+ except ModelBusy as e:+ self._json(409, {"error": {"type": "model_busy", "message": str(e)}})except GpuBusy as e:self._json(503, {"error": {"type": "server_error", "message": str(e)}})except EngineDied as e: # before the answer started (not streamed)self._json(503, {"error": {"type": "server_error", "message": f"{e}; the next request restarts it"}})+ except RuntimeError as e:+ self._json(503, {"error": {"type": "server_error", "message": str(e)}})def _props(self):model = parse_qs(urlsplit(self.path).query).get("model", [svc.model])[0]@@ -1731,7 +1776,7 @@ def make_handler(svc: Service):params["n_predict"] = svc.shared.get("max_tokens", -1)props = {"default_generation_settings": {"n_ctx": svc.engine.max_context, "params": params},"total_slots": 1, "model_alias": svc.model, "chat_template": svc.template.source,- "modalities": {"vision": svc.vision is not None}, "models_autoload": False,+ "modalities": {"vision": svc.vision is not None}, "models_autoload": hasattr(svc.engine, "restart"),"is_sleeping": not svc.loaded()}if getattr(svc.engine, "model_path", None):props["model_path"] = svc.engine.model_path@@ -2064,6 +2109,7 @@ def main() -> int:ap.add_argument("--mcp-config", help="a JSON file with MCP servers in Claude Desktop's format ({\"mcpServers\": ""{...}}); the web app's chat can use their tools (also \"mcp_servers\" in ""the config)")+ ap.add_argument("--lazy", action="store_true", help="start the text-only API unloaded; load on first request")ap.add_argument("--idle-unload", type=float, default=None, metavar="SECONDS",help="unload the model after this many seconds without requests, so other programs (games, other ""model servers) can use the VRAM; the next request loads it again (also \"idle_unload_s\" "@@ -2108,6 +2154,9 @@ def main() -> int:if sampling_defaults:pretty = ", ".join(f"{k}={v}" for k, v in sampling_defaults.items())print(f"[strata] sampling defaults from the config: {pretty}", flush=True)+ lazy = a.lazy or cfg.get("lazy_load") is True+ if lazy and cfg.get("vision"):+ ap.error("lazy loading is text-only; disable vision in the config")if cfg.get("vision"):print("loading the vision encoder ...", flush=True)# relative paths are the config's cwd's, as for the engine below@@ -2115,13 +2164,14 @@ def main() -> int:if k in ("exe", "mmproj", "model") and isinstance(v, str) and not os.path.isabs(v) else v)for k, v in cfg["vision"].items()}vision = Vision(vcfg, log=open(cfg["log"], "a", encoding="utf-8") if cfg.get("log") else None, env=env)- print("loading the model (the first start takes a minute or two) ...", flush=True)+ print("model unloaded; the first request loads it ..." if lazy else+ "loading the model (the first start takes a minute or two) ...", flush=True)if len(gpu_list(cfg)) > 1:print(f"[strata] layer split across GPUs {gpu_list(cfg)} ({cfg.get('layer_split') or 'auto'})", flush=True)# a relative "exe" is the config's cwd's: Windows' CreateProcess resolves "engine/strata.exe" against nothing# it is told about (WinError 2), so it is made absolute hereexe = cfg["exe"] if os.path.isabs(cfg["exe"]) else os.path.abspath(os.path.join(cfg.get("cwd") or ".", cfg["exe"]))- engine = StrataEngine(exe, engine_args(cfg), cwd=cfg.get("cwd"), log=cfg.get("log"), env=env)+ engine = StrataEngine(exe, engine_args(cfg), cwd=cfg.get("cwd"), log=cfg.get("log"), env=env, lazy=lazy)warn_tight_ram(engine.info.get("arena_mib"))else:engine, vision, sampling_defaults = MockEngine(tok, a.script or [diff --git a/serve/test_lifecycle.py b/serve/test_lifecycle.pynew file mode 100644index 000000000..6e54fd8fa--- /dev/null+++ b/serve/test_lifecycle.py@@ -0,0 +1,147 @@+"""Model discovery, on-demand loading and safe unloading over the actual HTTP API."""+import json+import io+import subprocess+import time+import unittest+import urllib.error+import urllib.request+from pathlib import Path+from unittest import mock++from serve.frontend import ChatTemplate+from serve.server import ByteTokenizer, MockEngine, Service, StrataEngine, serve+++class ResidentEngine(StrataEngine):+ def __init__(self, tok):+ self.reply = MockEngine(tok, "Hello.", max_context=4096)+ self.max_context, self.info, self.last = 4096, {}, {}+ self.loaded, self.starts, self.closes = False, 0, 0+ self.unloaded = True+ self.progress = None++ def alive(self):+ return self.loaded++ def exit_code(self):+ return None++ def restart(self):+ self.loaded = True+ self.starts += 1+ self.unloaded = False++ def close(self):+ self.loaded = False+ self.closes += 1++ def unload(self):+ self.close()+ self.unloaded = True++ def generate(self, *args, **kwargs):+ yield from self.reply.generate(*args, **kwargs)+++class Lifecycle(unittest.TestCase):+ def test_close_sends_eof_before_waiting_for_windows_reader(self):+ engine = StrataEngine("missing-executable", [], lazy=True)+ proc = mock.Mock()+ proc.stdin, proc.stdout = io.StringIO(), io.StringIO()+ proc.poll.side_effect = [None, 0]+ proc.wait.side_effect = lambda **kwargs: self.assertTrue(proc.stdin.closed)+ engine.proc = proc+ engine.close()+ self.assertIsNone(engine.proc)+ proc.kill.assert_not_called()++ def test_close_does_not_forget_a_process_still_exiting(self):+ engine = StrataEngine("missing-executable", [], lazy=True)+ proc = mock.Mock()+ proc.stdin, proc.stdout = io.StringIO(), io.StringIO()+ proc.poll.return_value = None+ proc.wait.side_effect = subprocess.TimeoutExpired("engine", 2)+ engine.proc = proc+ with self.assertRaisesRegex(RuntimeError, "still releasing"):+ engine.close()+ self.assertIs(engine.proc, proc)+ proc.kill.assert_called_once()++ def test_native_lazy_constructor_does_not_start_a_process(self):+ engine = StrataEngine("missing-executable", ["--max-context", "16384"], lazy=True)+ self.assertFalse(engine.alive())+ self.assertEqual(engine.max_context, 16384)+ self.assertIsNone(engine.exit_code())+ engine.close()++ def setUp(self):+ tok = ByteTokenizer()+ self.engine = ResidentEngine(tok)+ self.svc = Service(self.engine, tok, ChatTemplate(Path(__file__).parent / "chat_template.jinja"))+ self.httpd = serve(self.svc, port=0)+ self.base = f"http://127.0.0.1:{self.httpd.server_address[1]}"++ def tearDown(self):+ self.httpd.shutdown()+ self.httpd.server_close()++ def request(self, path, body=None, headers=None):+ req = urllib.request.Request(self.base + path, data=json.dumps(body).encode() if body is not None else None,+ headers={"Content-Type": "application/json", **(headers or {})})+ try:+ response = urllib.request.urlopen(req, timeout=10)+ except urllib.error.HTTPError as error:+ response = error+ with response:+ data = response.read().decode()+ return response.status, data if "event-stream" in response.headers.get("Content-Type", "") else json.loads(data)++ def test_discover_chat_unload_and_stream_reload(self):+ self.assertEqual(self.request("/api/health")[1]["service"], "strata")+ self.assertFalse(self.request("/v1/status")[1]["loaded"])+ self.assertEqual(self.request("/v1/models")[1]["data"][0]["status"]["value"], "unloaded")+ self.assertTrue(self.request("/props")[1]["models_autoload"])+ self.assertEqual(self.engine.starts, 0)+ chat = {"messages": [{"role": "user", "content": "Hello"}], "max_tokens": 32, "reasoning_effort": "none"}+ for _ in range(2):+ code, answer = self.request("/v1/chat/completions", chat)+ self.assertEqual(code, 200)+ self.assertEqual(answer["choices"][0]["message"]["content"], "Hello.")+ self.assertEqual(self.engine.starts, 1)+ self.assertFalse(self.request("/v1/unload", {})[1]["loaded"])+ code, stream = self.request("/v1/chat/completions", {**chat, "stream": True})+ self.assertEqual(code, 200)+ self.assertIn("data: [DONE]", stream)+ self.assertEqual(self.engine.starts, 2)++ def test_busy_auth_and_foreign_origin_cannot_unload(self):+ self.engine.loaded = True+ with self.svc.fifo:+ self.assertEqual(self.request("/v1/unload", {})[0], 409)+ self.svc.api_key = "local-secret"+ self.assertEqual(self.request("/v1/unload", {})[0], 401)+ self.assertEqual(self.request("/v1/unload", {}, {"Authorization": "Bearer local-secret",+ "Origin": "https://other.example"})[0], 403)+ self.assertEqual(self.engine.closes, 0)+ self.assertTrue(self.engine.loaded)+ self.assertEqual(self.request("/v1/unload", {}, {"Authorization": "Bearer local-secret"})[0], 200)++ def test_explicit_load_and_model_matching(self):+ self.assertEqual(self.request("/v1/load", {"model": "other-model"})[0], 404)+ self.assertEqual(self.engine.starts, 0)+ before = time.time()+ code, status = self.request("/v1/load", {"model": self.svc.model})+ self.assertEqual(code, 200)+ self.assertTrue(status["loaded"])+ self.assertEqual(self.engine.starts, 1)+ self.assertGreaterEqual(self.svc.last_request_at, before)+ self.svc.status["queued"] = 1+ self.assertEqual(self.request("/v1/load", {})[0], 409)+ self.assertEqual(self.request("/v1/unload", {})[0], 409)+ self.assertEqual(self.engine.closes, 0)+ self.assertEqual(self.request("/v1/load", {}, {"Content-Type": "text/plain"})[0], 415)+++if __name__ == "__main__":+ unittest.main()