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: end an engine that lost step with the server instead of waiting forever (#481)
Niko1221a9e9eb2ae189
diff --git a/docs/DETAILS.md b/docs/DETAILS.mdindex 0e4d0f21d..e30c2954f 100644--- a/docs/DETAILS.md+++ b/docs/DETAILS.md@@ -816,6 +816,7 @@ the document, +0.4% on the chat. Details: `bench/results/2026-09-27-esp/`.| Pictures are slow (10-30 s) | The encoder runs on the CPU: run setup again with `--vision gpu` (needs ~1.4 GB of VRAM). || A request never finishes: "reading the prompt", GPU "100%" at low power | The GPU ran out of VRAM (engines before 0.1.9 could end with ~30 MiB free at large contexts). Run `START-HERE.bat` once to get engine 0.1.9 or newer; the log then says `... MiB of VRAM free with everything loaded` (a few hundred) and names the `--vram-reserve-mib` to add if it is low. || Generation stops mid-answer, GPU "100%", one CPU core busy | Fixed in engine 0.1.12 (issue #29, a race in the CPU expert pool on big-VRAM cards). Since then a request that stops moving ends with an error instead of hanging (after 2 minutes; 1 minute from 0.1.13): the log says `no progress for ... s ... (issue #29)` with where it stopped, and the next request starts the engine again. If you see that line, please open an issue with it. Engine 0.1.13 adds a stall report under it (what every expert-pool thread and the GPU handshake were doing, memory and page faults) and, on Windows, a `strata-stall-<pid>.dmp` file with every thread's stack: attach both. (`STRATA_WATCHDOG_S` sets the time in seconds; 0 turns it off.) Engine 0.1.14 fixes the stall those reports found (issue #31: with the IQ packs the host could wait forever inside the NVIDIA driver while copying experts in a verify window; the experts are now copied by a GPU kernel, `--pcie-mode dma` restores the old way). |+| `the engine said nothing for ... s during the request` or `... did not finish the request after it was stopped (STOP)` | Issue #481: the engine and the server lost step (the engine waits for its next command, the server for the request's end; GPU at 0 %, nothing in the log). The server ends the engine after 300 s without a line from it during a request (while a prompt is read: each chunk may take three times the previous one's time, the first one up to its tokens at 50 tok/s more), the request ends with an error and the next request starts the engine again. `"engine_silence_s": 600` in `strata-<model>.json` sets the time (0 = wait forever, as before). If you see it, please add the end of the engine log to #481. || `out of memory: cudaFuncSetAttribute` in the log (IQ3_XXS, long prompt) | Fixed in engine 0.1.15: CUDA loaded a kernel's code when it was first needed, and mid-prompt there was no VRAM left for it. Run `START-HERE.bat` (Windows) or `./setup.sh` (Linux) once to update. || Anything else | The engine log is `strata-<model>.log` in this folder. |diff --git a/serve/server.py b/serve/server.pyindex 5e36519e7..542ce8f40 100644--- a/serve/server.py+++ b/serve/server.py@@ -66,6 +66,16 @@ CTX_SLACK = 8 # `strata --serve` rejects prompt + max_new + 8 > co# token (the Monitor showed five-digit numbers) and then undershoots for the first second of every answer.RATE_WINDOW_S = 2.0RATE_MIN_SPAN_S = 0.25 # younger than this there is no rate yet: the mean so far, with the span floored here+# #481: a running request whose engine prints nothing (no T, PP or any other line) for this long has lost step with the+# server (the engine's main thread waits, untimed, for its next command): the engine is ended and the request fails;+# the next request starts it again. The config's "engine_silence_s" sets it (0: wait forever, as before).+ENGINE_SILENCE_S = 300.0+# ... except while a prompt is read: a PP line comes once per chunk (up to 32768 tokens with --prefill auto, issue+# #282), and the slowest PCs read ~100 tok/s, so a first chunk can take minutes before the first line. Until the first+# PP the wait adds the chunk's tokens at PP_FLOOR_TOK_S; after one, a chunk may take PP_SLACK x the last one's time.+PP_CHUNK_MAX = 32768+PP_FLOOR_TOK_S = 50.0+PP_SLACK = 3.0# ------------------------------------------------------------------------------------------------ engines@@ -113,6 +123,12 @@ class ModelBusy(RuntimeError):"""Explicit model controls must not interrupt active or queued requests."""+class EngineSilent(EngineDied):+ """#481: the engine said nothing for too long during a request (or never acknowledged a STOP): the two sides lost+ step - the engine waiting for its next command, the server for this request's end - and the server ended it. An+ EngineDied, so the request ends with an error and the next one starts the engine again."""++class EngineStuck(RuntimeError):"""The engine process did not end after QUIT, terminate and kill: the server keeps it (and says so) rather thanreporting its GPU and RAM as given back."""@@ -240,6 +256,8 @@ class StrataEngine:(`temperature=F top_p=F top_k=N seed=N`, the engine's own spelling). An absent temperature keeps theengine's default, which is greedy; `temperature=0` means the same thing, so it is not forwarded."""+ silence_s = ENGINE_SILENCE_S # #481: main() sets the config's engine_silence_s (survives restart())+ silent_note = None # #481: why the server ended a silent engine (death_note says it)def __init__(self, exe: str, args: list[str], cwd: str | None = None, log: str | None = None,env: dict | None = None, lazy: bool = False):@@ -255,7 +273,8 @@ class StrataEngine:self.info = {} # INFO key=value facts (engine 0.1.8+): kv, expert slots, ... (Monitor tab)self.prefill_tok_s_mean = Noneself.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.silent_note = None+ try: # a ready-made engine's BUILD.json says its versionself.info["version"] = json.loads((Path(exe).parent / "BUILD.json").read_text()).get("version")except (OSError, ValueError):self.info["version"] = None@@ -310,6 +329,8 @@ class StrataEngine:def death_note(self) -> str:"""Why the engine most likely ended, from the end of its log: its own watchdog (issue #29), else RAM."""+ if getattr(self, "silent_note", None): # #481: the server ended it, not the OS or the engine itself+ return self.silent_notetail = ""try:with open(self.log_path, "rb") as f:@@ -440,19 +461,34 @@ class StrataEngine:except OSError: # the pipe is gone: the engine died (not the client)raise EngineDied(f"the engine stopped unexpectedly (exit code {self.exit_code()})") from Nonedone = False+ # #481: how long the engine may stay silent from here. Until the first line: the request's first prompt+ # chunk at the slowest prompt reading on top of silence_s; a PP line resets it to its own chunk's time.+ silence = float(self.silence_s or 0)+ allow = silence + min(len(ids), PP_CHUNK_MAX) / PP_FLOOR_TOK_S if silence > 0 else 0.0+ heard, read_to = time.monotonic(), 0try:while True:+ wait = 10.0+ if allow > 0:+ wait = min(wait, allow - (time.monotonic() - heard))+ if wait <= 0:+ done = True # no STOP and no drain: nothing is listening+ raise self._silent(f"the engine said nothing for {time.monotonic() - heard:.0f} s during "+ "the request")try:- line = self.lines.get(timeout=10)+ line = self.lines.get(timeout=wait)except queue.Empty:if cancel.is_set():return- yield None+ if wait >= 10.0:+ yield None # the 10 s heartbeat (the deadline's short waits are not)continueif line is None:done = Trueraise EngineDied(f"the engine stopped unexpectedly (exit code {self.exit_code()})")+ heard = time.monotonic() # any line is output: T, PP, RESUME, INFO ...if line.startswith("T "):+ allow = silenceif cancel.is_set():returnyield int(line[2:])@@ -461,9 +497,18 @@ class StrataEngine:if len(f) >= 3 and f[1].isdigit() and f[2].isdigit():self.progress = (int(f[1]), int(f[2])) # prompt progress, one per chunk: also a heartbeat (theself.prefill_tok_s_mean = float(f[4]) if len(f) >= 5 else None+ rate, chunk = self.prefill_tok_s_mean or 0.0, int(f[1]) - read_to+ read_to = int(f[1])+ if silence > 0 and rate > 0 and chunk > 0: # #481: the next chunk, as long as this one+ allow = max(silence, PP_SLACK * chunk / rate)if cancel.is_set(): # lines reset the 10 s wait, so without this a long promptreturn # would send no keep-alives at all)yield None+ elif line.startswith("RESUME "): # the reused tokens: the first chunk starts after them+ try:+ read_to = int(line.split()[1])+ except (IndexError, ValueError):+ passelif line.startswith("DONE"):self._parse_done(line)done = True@@ -479,13 +524,41 @@ class StrataEngine:self.proc.stdin.flush()except OSError:pass+ # #481: never an untimed wait here - it holds the request FIFO, and an engine that lost step never+ # answers. An engine that honours STOP gets the current allowance in all (a STOP during a prompt+ # chunk is seen after it); an older one runs on to max_new, so each line only has to come in time.+ heard = time.monotonic()while True:- line = self.lines.get()+ left = allow - (time.monotonic() - heard) if allow > 0 else None+ try:+ if left is not None and left <= 0:+ raise queue.Empty+ line = self.lines.get(timeout=left)+ except queue.Empty:+ raise self._silent("the engine did not finish the request after it was stopped (STOP) "+ f"within {allow:.0f} s") from Noneif line is None or line.startswith("ERR"):breakif line.startswith("DONE"):self._parse_done(line)break+ if not self.can_stop:+ heard = time.monotonic()++ def _silent(self, what: str) -> EngineSilent:+ """#481: end an engine that lost step with the server (its main thread waits for a command the server never+ sends), so the next request starts it again: killed now, its GPU and RAM go back with the process."""+ self.silent_note = ("The engine and the server lost step (issue #481; a very slow PC can raise "+ "\"engine_silence_s\" in the config, 0 = wait forever). If it happens again, please add "+ "the end of the engine log to github.com/Niko1221/Strata/issues/481.")+ self.ended = True # not alive from now: the next request restarts it+ proc = self.proc+ try:+ proc.kill()+ proc.wait(timeout=20) # restart() -> close() handles one that is still exiting+ except (OSError, AttributeError, subprocess.TimeoutExpired):+ pass+ return EngineSilent(f"{what}; the server ended the engine")def close(self):"""End the engine process: QUIT first (the engine frees its memory itself - unpinning tens of GB can take@@ -653,6 +726,17 @@ def gpu_list(cfg: dict) -> list[int]:return [int(str(x).strip()) for x in items if str(x).strip() != ""]+def engine_silence_s(cfg: dict) -> float:+ """#481: the config's "engine_silence_s" - seconds an engine may print nothing during a request before the server+ ends it (default ENGINE_SILENCE_S; 0 = wait forever). ValueError for anything but a number >= 0."""+ v = cfg.get("engine_silence_s")+ if v is None:+ return ENGINE_SILENCE_S+ if isinstance(v, bool) or not isinstance(v, (int, float)) or v < 0:+ raise ValueError(f'"engine_silence_s" must be a number of seconds >= 0 (0 = no limit), not {v!r}')+ return float(v)++def engine_args(cfg: dict) -> list[str]:"""The engine's arguments: the config's, and with several GPUs the layer split across them ("layer_split" in theconfig: "auto" by default, or the first layer of each later GPU's share, e.g. "18" or "16,32")."""@@ -949,6 +1033,13 @@ class Service:self.engine.restart()print("[strata] the engine is running again", flush=True)+ def _say_died(self, e: Exception) -> None:+ """The server window's line for an engine that died (or was ended, #481) in the middle of a request."""+ note = self.engine.death_note() if hasattr(self.engine, "death_note") else ""+ log = getattr(self.engine, "log_path", None)+ print(f"[strata] {e}. {note} The next request starts the engine again."+ f"{' Its log: ' + log if log else ''}", flush=True)+def load(self):"""POST /load and every generation request: start the engine now if it is unloaded (raises GpuBusy)."""# a request is on its way: the idle thread must not unload between this and the request's own start@@ -1319,7 +1410,7 @@ class Service:while True:gen = self.engine.generate(prompt, max_new - n, sampling, cancel, embeddings=emb) if emb \else self.engine.generate(prompt, max_new - n, sampling, cancel)- seg, wrap = [], False # this pass's tokens; the budget is reached+ seg, wrap, leaving = [], False, False # this pass's tokens; the budget is reached; closedtry:for t in gen:if t is None: # heartbeat while the engine is quiet@@ -1349,19 +1440,25 @@ class Service:breakexcept EngineDied as e:finish = "error"- note = self.engine.death_note() if hasattr(self.engine, "death_note") else ""- log = getattr(self.engine, "log_path", None)- print(f"[strata] {e}. {note} The next request starts the engine again."- f"{' Its log: ' + log if log else ''}", flush=True)+ self._say_died(e)raiseexcept ValueError as e: # the engine's ERR line (it may have ended after it)finish = "error"print(f"[strata] the engine reported an error: {e}", flush=True)raise+ except GeneratorExit: # the client went away: an engine that never acknowledges+ leaving = True # the STOP below is ended, but no error replaces this+ raisefinally:- gen.close() # STOP+drain to THIS request's DONE while still holding the- # fifo, so a stop-token break can't leave the shared engine- # queue mid-drain for the next request to read as its own DONE+ try:+ gen.close() # STOP+drain to THIS request's DONE while still holding the+ # fifo, so a stop-token break can't leave the shared engine+ # queue mid-drain for the next request to read as its own DONE+ except EngineSilent as e: # #481: the STOP was never acknowledged: the engine is ended+ finish = "error"+ self._say_died(e)+ if not leaving and not cancel.is_set():+ raiseif not wrap or cancel.is_set():break# #123: the thinking reached reasoning_budget_tokens. Close it the way the model would (a@@ -2577,7 +2674,12 @@ def main() -> int:# 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"]))+ try:+ silence = engine_silence_s(cfg) # #481: checked before the (minutes-long) start+ except ValueError as e:+ raise SystemExit(f"[strata] config {e}")engine = StrataEngine(exe, engine_args(cfg), cwd=cfg.get("cwd"), log=cfg.get("log"), env=env, lazy=lazy)+ engine.silence_s = silence # an attribute of its own: restart() keeps itwarn_tight_ram(engine.info.get("arena_mib"))else:engine, vision, sampling_defaults = MockEngine(tok, a.script or [diff --git a/serve/test_server.py b/serve/test_server.pyindex d746693dc..2099ba9af 100644--- a/serve/test_server.py+++ b/serve/test_server.py@@ -2043,5 +2043,163 @@ class AmdTelemetry(unittest.TestCase):self.assertEqual(svc.free_vram_mib(), 26 << 10)+class SilentEngine(unittest.TestCase):+ """#481: an engine that prints nothing for engine_silence_s during a request (or never acknowledges a STOP) has+ lost step with the server: it is ended and the request fails with EngineDied, instead of waiting forever."""++ def bare(self, silence, can_stop=False):+ import io+ import queue+ engine = StrataEngine.__new__(StrataEngine)+ engine.proc = mock.Mock()+ engine.proc.stdin = io.StringIO()+ engine.proc.poll.return_value = None+ engine.lines, engine.can_stop, engine.max_context = queue.Queue(), can_stop, 4096+ engine.silence_s, engine.log_path = silence, None+ return engine++ def later(self, engine, delay, *lines):+ def put():+ time.sleep(delay)+ for x in lines:+ engine.lines.put(x)+ threading.Thread(target=put, daemon=True).start()++ def test_silence_mid_answer_ends_the_engine(self):+ from serve.server import EngineSilent+ engine = self.bare(0.3)+ engine.lines.put("T 5")+ gen = engine.generate([1], 10, {}, threading.Event())+ self.assertEqual(next(gen), 5)+ t0 = time.monotonic()+ with self.assertRaises(EngineSilent) as cm:+ next(gen)+ self.assertIsInstance(cm.exception, EngineDied) # every EngineDied path handles it+ self.assertLess(time.monotonic() - t0, 5)+ engine.proc.kill.assert_called_once()+ self.assertFalse(engine.alive()) # the next request restarts it+ self.assertIn("#481", engine.death_note())+ self.assertNotIn("STOP", engine.proc.stdin.getvalue()) # nothing is listening: no STOP, no drain++ def test_prompt_chunks_set_the_wait(self):+ # a PP line every second, at 100 tok/s: far over a 0.3 s silence, but each chunk is on time for its size+ engine = self.bare(0.3)+ engine.lines.put("RESUME 0")+ engine.lines.put("PP 100 300 1000 100.0")+ self.later(engine, 1.0, "PP 200 300 2000 100.0", "T 7", "DONE 1 300 2000 1 length")+ self.assertEqual(list(engine.generate([1], 10, {}, threading.Event())), [None, None, 7])+ engine.proc.kill.assert_not_called()++ def test_a_long_first_chunk_is_allowed(self):+ # 100 prompt tokens at the slowest prompt reading (50 tok/s): 2 s on top of the silence before the first PP+ engine = self.bare(0.3)+ self.later(engine, 1.0, "PP 100 100 1000 100.0", "DONE 0 100 1000 0 length")+ self.assertEqual(list(engine.generate([1] * 100, 10, {}, threading.Event())), [None])+ engine.proc.kill.assert_not_called()++ def test_a_stop_never_acknowledged(self):+ from serve.server import EngineSilent+ engine = self.bare(0.3, can_stop=True)+ engine.lines.put("T 5")+ gen = engine.generate([1], 10, {}, threading.Event())+ self.assertEqual(next(gen), 5)+ with self.assertRaises(EngineSilent):+ gen.close() # the consumer stopped: STOP, then the drain+ self.assertIn("STOP", engine.proc.stdin.getvalue())+ engine.proc.kill.assert_called_once()+ self.assertFalse(engine.alive())++ def test_zero_waits_as_before(self):+ engine = self.bare(0)+ self.later(engine, 0.5, "T 5", "DONE 1 1 1 1 length")+ self.assertEqual(list(engine.generate([1], 10, {}, threading.Event())), [5])++ def test_config(self):+ from serve.server import ENGINE_SILENCE_S, engine_silence_s+ self.assertEqual(engine_silence_s({}), ENGINE_SILENCE_S)+ self.assertEqual(engine_silence_s({"engine_silence_s": 0}), 0.0)+ self.assertEqual(engine_silence_s({"engine_silence_s": 900}), 900.0)+ for bad in (-1, "300", True):+ with self.assertRaises(ValueError):+ engine_silence_s({"engine_silence_s": bad})+++FAKE_LOST_STEP = '''import pathlib, sys, time+mark = pathlib.Path(sys.argv[sys.argv.index("--mark") + 1])+mode = sys.argv[sys.argv.index("--mode") + 1]+print("READY 4096 stop", flush=True)+for line in sys.stdin:+ if line.startswith("QUIT"):+ break+ if line.startswith("GEN"):+ if not mark.exists(): # the first engine loses step (#481): it never says DONE+ mark.touch()+ print("T 104", flush=True)+ if mode == "stop":+ print("T 257", flush=True) # <|im_end|>: the server STOPs and drains, and the engine is silent+ time.sleep(3600)+ print("T 111", flush=True)+ print("T 107", flush=True)+ print("DONE 2 5 1.0 1.0 length", flush=True)+'''+++class LostStep(unittest.TestCase):+ """#481 over HTTP, with a real process: the request with the silent engine ends with an error, and the next one+ starts the engine again and is answered (the server used to wait forever, holding the request FIFO)."""++ def run_mode(self, mode, stream):+ import serve.server as server+ with tempfile.TemporaryDirectory() as d:+ script, mark = Path(d) / "fake_strata.py", Path(d) / "lost"+ script.write_text(FAKE_LOST_STEP, encoding="utf-8")+ real = server.subprocess.Popen+ with mock.patch.object(server.subprocess, "Popen",+ lambda cmd, **kw: real([sys.executable, str(script), *cmd[1:]], **kw)):+ eng = StrataEngine("strata", ["--mark", str(mark), "--mode", mode])+ eng.silence_s = 0.5+ tok = ByteTokenizer()+ svc = Service(eng, tok, ChatTemplate(ROOT / "serve/chat_template.jinja"))+ httpd = serve(svc, port=0)+ base = f"http://127.0.0.1:{httpd.server_address[1]}"+ body = {"model": "m", "max_tokens": 2, "reasoning_effort": "none", "stream": stream,+ "messages": [{"role": "user", "content": "hi"}]}+ try:+ first = eng.proc+ req = urllib.request.Request(base + "/v1/chat/completions", data=json.dumps(body).encode(),+ headers={"Content-Type": "application/json"})+ try:+ with urllib.request.urlopen(req, timeout=60) as r:+ text = r.read().decode()+ except urllib.error.HTTPError as e:+ self.assertEqual(e.code, 503)+ text = e.read().decode()+ self.assertIn("the next request restarts it", text)+ self.assertIsNotNone(first.poll(), "the silent engine still runs")+ self.assertEqual(svc.history[-1]["finish"], "error")+ with urllib.request.urlopen(req, timeout=60) as r:+ text = r.read().decode()+ self.assertIsNot(eng.proc, first)+ if stream:+ answer = "".join(json.loads(x[6:])["choices"][0]["delta"].get("content") or ""+ for x in text.splitlines() if x.startswith("data: {") and "choices" in x)+ else:+ answer = json.loads(text)["choices"][0]["message"]["content"]+ self.assertEqual(answer, "ok")+ finally:+ httpd.shutdown()+ httpd.server_close()+ eng.unload()++ def test_silent_mid_answer(self):+ self.run_mode("silent", stream=False)++ def test_silent_mid_stream(self):+ self.run_mode("silent", stream=True)++ def test_stop_never_acknowledged(self):+ self.run_mode("stop", stream=False)++if __name__ == "__main__":unittest.main()