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++
server: the image encoder unloads and loads with the engine; docs for sharing the GPU
bytethecookie376430c7db6a
diff --git a/docs/DETAILS.md b/docs/DETAILS.mdindex 1217072e4..be65b89e1 100644--- a/docs/DETAILS.md+++ b/docs/DETAILS.md@@ -296,6 +296,27 @@ Terminal chat: `.venv/bin/python chat.py`.---+## Sharing the GPU with other programs (optional)++By default the model stays loaded until you close Strata. On a PC that also games, renders or runs another model+server, three server options (all off by default; also as keys in `strata-<model>.json`) give the VRAM back:++| Option | Config key | What it does |+| --- | --- | --- |+| `--idle-unload 600` | `"idle_unload_s": 600` | unload the model after 600 s without requests; the next request loads it again |+| `--min-free-vram-mib 11000` | `"min_free_vram_mib": 11000` | load an unloaded model only when that much VRAM is free (it waits up to 15 s for memory being given back), else answer **503** "the GPU is in use by another program" instead of starting into what a game left |+| `--before-load "cmd"` | `"before_load": "cmd"` or `["cmd", "arg"]` | a command run before the model is loaded again, e.g. one that unloads another server's model |++`POST /unload` unloads it now (`409` while a request is running) and `POST /load` loads it ahead of a request;+`/health` says `"loaded"`, `/v1/models` lists it as `unloaded` (like llama.cpp's router), `/props` sets+`is_sleeping` and the Monitor shows the state. Unloading ends the engine process - and the image encoder, when images+are on; it is started again first, as at a start - so their VRAM and RAM go straight back. The model files stay in+the OS file cache, so loading again takes seconds while that RAM is not needed elsewhere. Measured on an RTX 5060 Ti+16 GB with Q2_0 in the low-RAM mode: unloading takes ~0.3 s, and a request to an unloaded model answered after+4.6 s (text) or 14.7 s (a picture, image encoder on the CPU).++---+## Using itThe server listens on `http://127.0.0.1:8080` (change with `--port` in setup, or edit the run script).diff --git a/serve/server.py b/serve/server.pyindex 4f7b8b6e4..dadea7a8d 100644--- a/serve/server.py+++ b/serve/server.py@@ -418,14 +418,37 @@ class Vision:if cfg.get("max_tokens"):args += ["--max-tokens", str(cfg["max_tokens"])]self.dir = Path(tempfile.mkdtemp(prefix="strata-vision-"))+ self.spawn = (args, log, env) # to start it again after an unload+ self.stopped = False+ self._start()+ self.lock = threading.Lock()+ self.cache: dict[str, tuple[Path, int]] = {}++ def _start(self):+ args, log, env = self.spawnself.proc = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=log or subprocess.DEVNULL,text=True, encoding="utf-8", bufsize=1, env=env)contain(self.proc)line = self.proc.stdout.readline()if not line.startswith("READY"):raise RuntimeError("the vision encoder did not start: " + line.strip())- self.lock = threading.Lock()- self.cache: dict[str, tuple[Path, int]] = {}+ self.stopped = False++ def alive(self) -> bool:+ return not self.stopped and self.proc.poll() is None++ def unload(self):+ """Stop the encoder process (its VRAM or RAM goes back); the encoded images stay cached on disk."""+ self.close()+ self.stopped = True++ def restart(self):+ """Start the encoder again after an unload (or if it died); the cache of encoded images is kept."""+ try:+ self.proc.kill()+ except OSError:+ pass+ self._start()@staticmethoddef load(source: str) -> bytes:@@ -618,6 +641,9 @@ class Service:def loaded(self) -> bool:return not hasattr(self.engine, "alive") or self.engine.alive()+ def _vision_down(self) -> bool:+ return self.vision is not None and hasattr(self.vision, "alive") and not self.vision.alive()+def free_vram_mib(self) -> int | None:"""Free VRAM on the engine's (first) GPU, from NVML; None when it can't be read (then nothing is refused)."""try:@@ -635,7 +661,7 @@ class Service:def ensure_loaded(self):"""Start the engine if it is not running (unloaded, or it died - issue #27), after the before_load hook andthe free-VRAM check. The caller holds self.fifo."""- if self.loaded():+ if self.loaded() and not self._vision_down():returnif self.before_load:cmd = self.before_load@@ -653,6 +679,11 @@ class Service:if free is not None and free < self.min_free_vram_mib:raise GpuBusy(f"the GPU is in use by another program: {free} MiB of VRAM free, the model needs "f"{self.min_free_vram_mib} (min_free_vram_mib) - it stays unloaded until that is free")+ if self._vision_down(): # first, as at a start: a GPU encoder takes its VRAM before+ print("[strata] starting the vision encoder again ...", flush=True) # the engine sizes its cache+ self.vision.restart()+ if self.loaded():+ returnif getattr(self.engine, "unloaded", False):print("[strata] loading the model again (it was unloaded) ...", flush=True)else:@@ -664,7 +695,7 @@ class Service:def load(self):"""POST /load and every generation request: start the engine now if it is unloaded (raises GpuBusy)."""- if self.loaded():+ if self.loaded() and not self._vision_down():returnwith self.fifo:self.ensure_loaded()@@ -685,6 +716,8 @@ class Service:if idle_for is not None and time.time() - (self.last_request_at or self.started_at) < idle_for:return "busy"self.engine.unload()+ if self.vision is not None and hasattr(self.vision, "unload"):+ self.vision.unload()print(f"[strata] model unloaded{f' after {idle_for:.0f} s idle' if idle_for else ''}; ""the next request loads it again", flush=True)return "unloaded"diff --git a/serve/test_server.py b/serve/test_server.pyindex 5d1baadab..b4fad2265 100644--- a/serve/test_server.py+++ b/serve/test_server.py@@ -1041,6 +1041,31 @@ class SharingTheGpu(unittest.TestCase):self.assertEqual(self.chat()[0], 200)self.assertTrue(mark.exists())+ def test_vision_encoder_unloads_and_starts_first(self):+ order = []++ class FakeVision:+ running = True++ def alive(self):+ return self.running++ def unload(self):+ self.running = False++ def restart(self):+ order.append("vision")+ self.running = True++ engine_restart = self.engine.restart+ self.engine.restart = lambda: (order.append("engine"), engine_restart())+ self.svc.vision = FakeVision()+ self.assertEqual(self.svc.unload(), "unloaded")+ self.assertFalse(self.svc.vision.alive())+ self.assertEqual(self.chat()[0], 200)+ self.assertEqual(order, ["vision", "engine"]) # the encoder first, as at a start+ self.assertTrue(self.svc.vision.alive())+def test_off_by_default(self):self.assertEqual((self.svc.idle_unload_s, self.svc.min_free_vram_mib, self.svc.before_load), (0, 0, None))self.assertEqual(self.req("/health")[1]["loaded"], True)