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++

Linux/WSL: engine errors end the engine and reach the client

Niko12216c06571710e0
diff --git a/serve/server.py b/serve/server.py
index b00872663..b35d1fb4d 100644
--- a/serve/server.py
+++ b/serve/server.py
@@ -662,6 +662,10 @@ class Service:
f"{' Its log: ' + self.engine.log_path if getattr(self.engine, 'log_path', None) else ''}",
flush=True)
raise
+ except 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
finally:
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
@@ -1049,6 +1053,9 @@ def make_handler(svc: Service):
except EngineDied as e: # mid-stream: say so, then end the stream properly
err = {"error": {"type": "server_error", "message": f"{e}; the next request restarts it"}}
self.wfile.write(b"data: " + json.dumps(err).encode() + b"\n\ndata: [DONE]\n\n")
+ except ValueError as e: # the engine's ERR after the stream started: the
+ err = {"error": {"type": "server_error", "message": str(e)}} # headers are sent, so no 400 now
+ self.wfile.write(b"data: " + json.dumps(err).encode() + b"\n\ndata: [DONE]\n\n")
def _anthropic(self, req):
req = svc.with_shared(req, "anthropic")
@@ -1076,6 +1083,9 @@ def make_handler(svc: Service):
except EngineDied as e: # mid-stream: Anthropic's error event
err = {"type": "error", "error": {"type": "api_error", "message": f"{e}; the next request restarts it"}}
self.wfile.write(b"event: error\ndata: " + json.dumps(err).encode() + b"\n\n")
+ except ValueError as e: # the engine's ERR after the stream started
+ err = {"type": "error", "error": {"type": "api_error", "message": str(e)}}
+ self.wfile.write(b"event: error\ndata: " + json.dumps(err).encode() + b"\n\n")
return Handler
diff --git a/serve/test_server.py b/serve/test_server.py
index 2ce796cac..c088abbcf 100644
--- a/serve/test_server.py
+++ b/serve/test_server.py
@@ -221,6 +221,34 @@ class EngineDeath(unittest.TestCase):
httpd.shutdown()
httpd.server_close()
+ def test_engine_err_mid_stream(self):
+ """The engine's ERR line after the stream started reaches the client as an error event (it used to be a
+ 400 written into the open stream, which clients read as an empty answer)."""
+ class ErrEngine(MockEngine):
+ def generate(self, ids, max_new, sampling, cancel, embeddings=None):
+ yield None # a prompt-progress heartbeat: the stream has started
+ raise ValueError("verify: layer 31 never rang (an illegal memory access was encountered)")
+
+ tok = ByteTokenizer()
+ svc = Service(ErrEngine(tok, ANSWER, max_context=CTX), tok, ChatTemplate(ROOT / "serve/chat_template.jinja"))
+ httpd = serve(svc, port=0)
+ base = f"http://127.0.0.1:{httpd.server_address[1]}"
+ try:
+ for path, body in [("/v1/chat/completions", {"model": "m", "stream": True, "max_tokens": 20,
+ "messages": [{"role": "user", "content": "hi"}]}),
+ ("/v1/messages", {"model": "m", "stream": True, "max_tokens": 20,
+ "messages": [{"role": "user", "content": "hi"}]})]:
+ req = urllib.request.Request(base + path, data=json.dumps(body).encode(),
+ headers={"Content-Type": "application/json"})
+ with urllib.request.urlopen(req, timeout=30) as r:
+ text = r.read().decode()
+ self.assertIn("illegal memory access", text, path)
+ self.assertNotIn("HTTP/1", text, path)
+ self.assertEqual(svc.metrics()["requests"][0]["finish"], "error")
+ finally:
+ httpd.shutdown()
+ httpd.server_close()
+
class SharedSettings(unittest.TestCase):
"""The web app's "Use for other apps too": POST /settings makes its Chat settings every client's defaults."""
diff --git a/setup.py b/setup.py
index 2a9d15687..96fce32de 100644
--- a/setup.py
+++ b/setup.py
@@ -662,14 +662,27 @@ def engine_version(exe: Path) -> tuple:
return tuple(int(x) for x in str(meta.get("version", "0")).split(".")[:3] if x.isdigit())
+def is_wsl() -> bool:
+ return sys.platform.startswith("linux") and "microsoft" in platform.uname().release.lower()
+
+
def upgrade_config(cfg_path: Path, cfg: dict) -> dict:
"""Configs written before v0.1.13 read prompts in fixed 2048-token chunks; the engine now picks the chunk
- itself (`--prefill auto`: up to 8192, as the free VRAM allows - about 2x faster on long prompts)."""
+ itself (`--prefill auto`: up to 8192, as the free VRAM allows - about 2x faster on long prompts). Under WSL,
+ KV streaming is dropped: its RAM copy must be pinned, and the driver pins only about 1 GB there."""
a = cfg.get("args", [])
+ changed = False
if "--prefill" in a and a[a.index("--prefill") + 1] == "2048" and engine_version(cfg["exe"]) >= (0, 1, 13):
a[a.index("--prefill") + 1] = "auto"
- cfg_path.write_text(json.dumps(cfg, indent=1), encoding="utf-8")
+ changed = True
ok("prompt reading: the engine now picks its chunk size (--prefill auto)")
+ if is_wsl() and "--kv-resident" in a:
+ i = a.index("--kv-resident")
+ del a[i:i + 2]
+ changed = True
+ ok("WSL: KV streaming off (the driver pins only about 1 GB of RAM); the KV cache stays in VRAM")
+ if changed:
+ cfg_path.write_text(json.dumps(cfg, indent=1), encoding="utf-8")
return cfg
@@ -976,7 +989,10 @@ def main() -> int:
# per layer) stays in VRAM; the VRAM it frees holds more experts (+6% at 128K, +23% at 262K with Q2_0). It
# costs ~13.7 KB of RAM per context token with 8-bit KV (1.7 GB at 128K), 7.5 KB with 4-bit, so only when it fits.
kv_ram_gb = ctx * (13 * (576 if kv == "q4_0" else 1056)) / 1e9 # 12 QSA layers + the draft layer
- if ctx >= 65536 and ram >= MODELS[model]["ram_gb"] + kv_ram_gb + 1:
+ # the RAM copy must be pinned, and under WSL the NVIDIA driver pins only about 1 GB in all
+ if is_wsl() and ctx >= 65536:
+ ok("WSL: KV streaming off (the driver pins only about 1 GB of RAM); the KV cache stays in VRAM")
+ elif ctx >= 65536 and ram >= MODELS[model]["ram_gb"] + kv_ram_gb + 1:
args += ["--kv-resident", "32768"]
ok(f"KV streaming on: the context's KV cache lives in RAM ({kv_ram_gb:.1f} GB), more experts fit in VRAM")
if vision != "none":
diff --git a/src/core/layer.cpp b/src/core/layer.cpp
index b40b9169d..8147ae8fd 100644
--- a/src/core/layer.cpp
+++ b/src/core/layer.cpp
@@ -610,8 +610,11 @@ uint64_t qsa_state_init(const ModelGeometry& g, int64_t max_cells, void* base, Q
uint8_t* d = nullptr;
if (cudaHostAlloc((void**) &h, bytes, cudaHostAllocMapped | cudaHostAllocPortable) != cudaSuccess ||
cudaHostGetDevicePointer((void**) &d, h, 0) != cudaSuccess) {
+ // under WSL the NVIDIA driver pins only ~1 GiB in all, which is less than 128K of 8-bit KV needs
if (p.mode == 1) std::fprintf(stderr, "strata: KV streaming: cannot pin %.2f GiB of RAM for a layer's KV copy "
- "(lower the context, or run without --kv-resident)\n", (double) bytes / 1073741824.0);
+ "(%.2f GiB pinned so far) - lower the context, or run without --kv-resident (under "
+ "WSL the driver pins only about 1 GiB in all)\n", (double) bytes / 1073741824.0,
+ (double) g_kv_host_bytes / 1073741824.0);
return 0;
}
g_kv_host_bytes += bytes;
diff --git a/src/core/session.cpp b/src/core/session.cpp
index 7578ad32e..d18a5ec38 100644
--- a/src/core/session.cpp
+++ b/src/core/session.cpp
@@ -88,9 +88,12 @@ uint64_t session_init(const ModelGeometry& g, int64_t max_cells, int64_t k, void
s.qsa_buf_arena = take(qsa_buffers_bytes(g, max_cells));
uint8_t* qp = (uint8_t*) s.qsa_state_arena;
+ // a layer whose pinned RAM could not be had (KV streaming's host copy) is half-built: going on would have the
+ // attention read null host pointers at the first request ("illegal memory access"), so the session fails here
for (int64_t i = 0; i < g.n_qsa_layers(); ++i)
- qsa_state_init(g, max_cells, qp + (i == 0 ? 0 : first + (uint64_t) (i - 1) * rest), s.qsa_states[i],
- i == 0 ? nullptr : &s.qsa_states[0]);
+ if (qsa_state_init(g, max_cells, qp + (i == 0 ? 0 : first + (uint64_t) (i - 1) * rest), s.qsa_states[i],
+ i == 0 ? nullptr : &s.qsa_states[0]) == 0)
+ return 0;
qsa_buffers_init(g, max_cells, s.qsa_buf_arena, s.qsa_bufs);
s.moe_arena = take(moe_buffers_bytes(g, k));
diff --git a/src/program/generate.cpp b/src/program/generate.cpp
index d1b349f0b..be66c9247 100644
--- a/src/program/generate.cpp
+++ b/src/program/generate.cpp
@@ -53,6 +53,10 @@
#if defined(_WIN32)
#include <windows.h>
#include <psapi.h>
+#include <io.h>
+#else
+#include <unistd.h>
+#include <cerrno>
#endif
#include <cuda_runtime.h>
@@ -2445,8 +2449,35 @@ int main(int argc, char** argv) {
std::deque<std::string> in_lines;
bool in_eof = false;
std::thread([&] {
- std::string l;
- while (std::getline(std::cin, l)) {
+ // read(2) on the descriptor, not std::cin: glibc's exit() flushes every stdio stream and waits for
+ // stdin's lock, which getline holds while it waits for input - an engine ending on an error (every
+ // std::exit) would hang in exit() on Linux, and the server would wait for it forever
+ std::string l, buf;
+ char chunk[4096];
+ auto getline_fd = [&](std::string& out) -> bool {
+ for (;;) {
+ const size_t nlpos = buf.find('\n');
+ if (nlpos != std::string::npos) {
+ out.assign(buf, 0, nlpos);
+ buf.erase(0, nlpos + 1);
+ return true;
+ }
+#if defined(_WIN32)
+ const int n = _read(0, chunk, (unsigned) sizeof chunk);
+#else
+ const ssize_t n = ::read(0, chunk, sizeof chunk);
+ if (n < 0 && errno == EINTR) continue;
+#endif
+ if (n <= 0) {
+ if (buf.empty()) return false;
+ out.swap(buf);
+ buf.clear();
+ return true;
+ }
+ buf.append(chunk, (size_t) n);
+ }
+ };
+ while (getline_fd(l)) {
if (!l.empty() && l.back() == '\r') l.pop_back();
if (l == "STOP") { stop_req.store(true); continue; }
std::lock_guard<std::mutex> lk(in_mu);