Skip to content

Kyojin: open-source engine that runs 100 GB-class open models (GLM-5.3, Qwen3.8, DeepSeek V4.1) on one desktop machine. AMD Strix Halo, NVIDIA RTX and Apple Mac. OpenAI API, built on ExLlamaV3.

Health hand-off: pass the listening socket to the real server so no connection is refused; add source and loading message to /health; GLM gets its own /health

YanissAmz78dc3610b262
diff --git a/tools/glm/SERVE.md b/tools/glm/SERVE.md
index 8c71e39..b9d67da 100644
--- a/tools/glm/SERVE.md
+++ b/tools/glm/SERVE.md
@@ -60,7 +60,7 @@ python tools/glm/mtp_eh_sidecar.py <official GLM-5.3 checkpoint dir> <model fold
## Endpoints
### `GET /health`
-`200 {"status":"ok"}` when ready; load progress before that (see Start-up progress below).
+`200 {"status":"ok","source":"kyojin"}` when ready; load progress before that (see Start-up progress below).
### `GET /v1/models`
One entry: `{"id": "<model-id>", "object": "model", "created": 0, "owned_by": "local"}`.
@@ -116,14 +116,16 @@ parse, otherwise kept as strings.
## Start-up progress on `/health`
-The port answers from the first second, while the model is still loading. `GET /health` returns `200 {"status":"ok"}`
+The port answers from the first second, while the model is still loading. `GET /health` returns `200 {"status":"ok","source":"kyojin"}`
(plus the fields listed above) when the server is ready, and while it loads:
```json
-503 {"status": "loading", "progress": 0.31, "stage": "target weights", "stage_index": 1, "stage_count": 4,
+503 {"status": "loading", "source": "kyojin", "message": "Target weights, 40 % (stage 1 of 4)", "progress": 0.31, "stage": "target weights", "stage_index": 1, "stage_count": 4,
"stage_progress": 0.4, "elapsed_s": 52.1, "eta_s": null, "progress_basis": "stages"}
```
+Every `/health` reply carries `"source": "kyojin"` (a hint for parsers). While `status` is `loading`, `message` is one plain line for a UI, built from the other fields: stage, percent, "stage x of y", and "about N s left" when an ETA exists.
+
Stages here: target weights, drafter weights, warm-up, dense GEMM tuning (the last two can be switched off by `EXL3_SERVE_WARMUP=0` and `EXL3_SERVE_DTUNE_PRIME_S=0`). `stage_progress` is the share of modules loaded (or kernel keys tuned) and is `null` when a
stage cannot count its work. `progress` counts finished stages plus that share, with equal weights
(`progress_basis: "stages"`); once one start has completed, its stage durations are kept in
diff --git a/tools/glm/serve.py b/tools/glm/serve.py
index 83f1de3..018d0f5 100644
--- a/tools/glm/serve.py
+++ b/tools/glm/serve.py
@@ -465,6 +465,9 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
app = web.Application(client_max_size=16 * 1024**2)
app.update(engine=engine, model_id=model_id, template=template, queue=queue)
+ async def health(_: web.Request) -> web.Response:
+ return web.json_response({"status": "ok", "source": "kyojin", "model": model_id})
+
async def models(_: web.Request) -> web.Response:
return web.json_response({"object": "list", "data": [
{"id": model_id, "object": "model", "created": 0, "owned_by": "local"}]})
@@ -764,6 +767,7 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
if getattr(engine, "slot_store", None) is not None:
app.router.add_get("/slots", slots)
app.router.add_post("/slots/{id}", slot_action)
+ app.router.add_get("/health", health)
app.router.add_get("/v1/models", models)
app.router.add_post("/v1/chat/completions", completions)
app.router.add_post("/apply-template", apply_template)
@@ -836,8 +840,11 @@ def main() -> None:
startup_health.abort(f"{type(exc).__name__}: {exc}")
raise
app = create_app(engine, args.model_id, template)
- startup_health.finish() # free the early listener's port, then bind
- web.run_app(app, host=args.host, port=args.port)
+ sock = startup_health.finish() # the early listener's open socket: no refused connection
+ if sock is not None:
+ web.run_app(app, sock=sock)
+ else:
+ web.run_app(app, host=args.host, port=args.port)
if __name__ == "__main__":
diff --git a/tools/mimo/SERVE.md b/tools/mimo/SERVE.md
index 3c11ee0..17bf38d 100644
--- a/tools/mimo/SERVE.md
+++ b/tools/mimo/SERVE.md
@@ -46,14 +46,16 @@ top-level config does not carry `max_position_embeddings` — the GLM fix.
## Start-up progress on `/health`
-The port answers from the first second, while the model is still loading. `GET /health` returns `200 {"status":"ok"}`
+The port answers from the first second, while the model is still loading. `GET /health` returns `200 {"status":"ok","source":"kyojin"}`
(plus the fields listed above) when the server is ready, and while it loads:
```json
-503 {"status": "loading", "progress": 0.31, "stage": "target weights", "stage_index": 1, "stage_count": 3,
+503 {"status": "loading", "source": "kyojin", "message": "Target weights, 40 % (stage 1 of 4)", "progress": 0.31, "stage": "target weights", "stage_index": 1, "stage_count": 3,
"stage_progress": 0.4, "elapsed_s": 52.1, "eta_s": null, "progress_basis": "stages"}
```
+Every `/health` reply carries `"source": "kyojin"` (a hint for parsers). While `status` is `loading`, `message` is one plain line for a UI, built from the other fields: stage, percent, "stage x of y", and "about N s left" when an ETA exists.
+
Stages here: drafter weights, target weights, engine setup (no drafter stage with `--no-dflash`). `stage_progress` is the share of modules loaded (or kernel keys tuned) and is `null` when a
stage cannot count its work. `progress` counts finished stages plus that share, with equal weights
(`progress_basis: "stages"`); once one start has completed, its stage durations are kept in
diff --git a/tools/mimo/serve.py b/tools/mimo/serve.py
index c189aff..f2f3503 100644
--- a/tools/mimo/serve.py
+++ b/tools/mimo/serve.py
@@ -375,7 +375,7 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
gate = engine.gate_stats()
except Exception: # noqa: BLE001
gate = None
- return web.json_response({"status": "ok", "model": model_id,
+ return web.json_response({"status": "ok", "source": "kyojin", "model": model_id,
"generator": getattr(engine, "generator", None) is not None,
"spec_gate": gate})
@@ -776,8 +776,11 @@ def main() -> None:
f"spec_gate={engine.spec_gate_on} ctx={ctx} "
f"max_position={config_max_position(engine.config)}", flush=True)
app = create_app(engine, args.model_id, template)
- startup_health.finish() # free the early listener's port, then bind
- web.run_app(app, host=args.host, port=args.port)
+ sock = startup_health.finish() # the early listener's open socket: no refused connection
+ if sock is not None:
+ web.run_app(app, sock=sock)
+ else:
+ web.run_app(app, host=args.host, port=args.port)
if __name__ == "__main__":
diff --git a/tools/qwen/SERVE.md b/tools/qwen/SERVE.md
index d6da2f0..a14a3dc 100644
--- a/tools/qwen/SERVE.md
+++ b/tools/qwen/SERVE.md
@@ -84,14 +84,16 @@ environment wins. The engine modules read several of these when they are importe
## Start-up progress on `/health`
-The port answers from the first second, while the model is still loading. `GET /health` returns `200 {"status":"ok"}`
+The port answers from the first second, while the model is still loading. `GET /health` returns `200 {"status":"ok","source":"kyojin"}`
(plus the fields listed above) when the server is ready, and while it loads:
```json
-503 {"status": "loading", "progress": 0.31, "stage": "target weights", "stage_index": 1, "stage_count": 5,
+503 {"status": "loading", "source": "kyojin", "message": "Target weights, 40 % (stage 1 of 4)", "progress": 0.31, "stage": "target weights", "stage_index": 1, "stage_count": 5,
"stage_progress": 0.4, "elapsed_s": 52.1, "eta_s": null, "progress_basis": "stages"}
```
+Every `/health` reply carries `"source": "kyojin"` (a hint for parsers). While `status` is `loading`, `message` is one plain line for a UI, built from the other fields: stage, percent, "stage x of y", and "about N s left" when an ETA exists.
+
Stages here: target weights, drafter weights, vision tower, engine setup, warm-up (the vision stage is absent with `--no-vision`, the drafter with `--draft-policy off`). `stage_progress` is the share of modules loaded (or kernel keys tuned) and is `null` when a
stage cannot count its work. `progress` counts finished stages plus that share, with equal weights
(`progress_basis: "stages"`); once one start has completed, its stage durations are kept in
diff --git a/tools/qwen/serve.py b/tools/qwen/serve.py
index b31c4c1..5ad2b68 100644
--- a/tools/qwen/serve.py
+++ b/tools/qwen/serve.py
@@ -1035,7 +1035,7 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, An
"max_context": getattr(engine, "ctx", None)}]})
async def health(_: web.Request) -> web.Response:
- return web.json_response({"status": "ok", "model": model_id, "vision": bool(engine.supports_vision),
+ return web.json_response({"status": "ok", "source": "kyojin", "model": model_id, "vision": bool(engine.supports_vision),
**(engine.spec_stats() if hasattr(engine, "spec_stats") else {})})
async def worker() -> None:
@@ -1573,8 +1573,9 @@ def main() -> None:
async def serve() -> None:
runner = web.AppRunner(app)
await runner.setup()
- startup_health.finish() # free the early listener's port, then bind
- await web.TCPSite(runner, args.host, args.port).start()
+ sock = startup_health.finish() # the early listener's open socket: no refused connection
+ site = web.SockSite(runner, sock) if sock is not None else web.TCPSite(runner, args.host, args.port)
+ await site.start()
print(f"qserve: READY on http://{args.host}:{args.port} model={args.model_id} ctx={args.ctx} "
f"speculative={engine.spec_on} vision={engine.supports_vision} (start-up {time.time() - t0:.0f} s)",
flush=True)
diff --git a/tools/startup_health.py b/tools/startup_health.py
index f195679..c8112d8 100644
--- a/tools/startup_health.py
+++ b/tools/startup_health.py
@@ -4,11 +4,13 @@ The servers open their HTTP port only after the model is loaded, which can take
8-20 minutes on a first start). This module opens a small stdlib listener on the same host and port before the load,
answers every request with 503, and answers GET /health with the real load progress:
- 200 {"status": "ok"} ready (the server's own /health takes over)
- 503 {"status": "loading", "progress": 0.31, "stage": "target weights", "stage_index": 1, "stage_count": 4,
+ 200 {"status": "ok", "source": "kyojin"} ready (the server's own /health takes over)
+ 503 {"status": "loading", "source": "kyojin", "message": "Target weights, 40 % (stage 1 of 4)", "progress": 0.31, "stage": "target weights", "stage_index": 1, "stage_count": 4,
"stage_progress": 0.4, "elapsed_s": 52.1, "eta_s": null, "progress_basis": "stages"}
- 500 {"status": "error", "message": "..."}
+ 500 {"status": "error", "source": "kyojin", "message": "..."}
+Every reply carries `"source": "kyojin"` (a hint for parsers); while loading, `message` is one plain line for a UI
+built from the other fields (stage name, percent, stage x of y, about N s left when an ETA exists).
Honest values only: `stage_progress` is null when the stage cannot count its work; `progress` counts finished stages
plus the reported fraction of the current one (equal weights, or the durations of the previous start when it is
recorded: progress_basis "history"); `eta_s` is null unless a previous start recorded the stage durations
@@ -21,6 +23,7 @@ from __future__ import annotations
import json
import os
+import socket
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
@@ -34,6 +37,16 @@ def history_dir() -> Path:
return Path(os.environ.get("KYOJIN_HEALTH_DIR") or "~/.cache/kyojin").expanduser()
+def _loading_message(stage: str, index: int, count: int, frac, progress: float, eta) -> str:
+ """One plain line for a UI, built only from the fields of the same reply."""
+ what = stage[0].upper() + stage[1:]
+ pct = f"{round((frac if frac is not None else progress) * 100)} %"
+ text = f"{what}, {pct} (stage {index} of {count})" if frac is not None else f"{what} (stage {index} of {count}), {pct} overall"
+ if eta is not None:
+ text += f", about {round(eta)} s left"
+ return text
+
+
class StartupTracker:
"""Thread-safe record of the start-up stages. Stage indices are 1-based."""
@@ -105,9 +118,9 @@ class StartupTracker:
now = self.clock()
elapsed = round(now - self.t0, 1)
if self.state == "ready":
- return 200, {"status": "ok"}
+ return 200, {"status": "ok", "source": "kyojin"}
if self.state == "error":
- return 500, {"status": "error", "message": self.message, "elapsed_s": elapsed}
+ return 500, {"status": "error", "source": "kyojin", "message": self.message, "elapsed_s": elapsed}
n, cur, frac = len(self.stages), self.current, self.fraction
stage_elapsed = now - self.stage_t0
exp = self.expected
@@ -124,7 +137,10 @@ class StartupTracker:
eta = sum(exp[s] for s in self.stages[cur + 1:]) + left if left >= 0 else None
else:
progress, basis, eta = (cur + (frac or 0.0)) / n, "stages", None
- return 503, {"status": "loading", "progress": round(min(progress, 0.999), 3),
+ progress = round(min(progress, 0.999), 3)
+ return 503, {"status": "loading", "source": "kyojin",
+ "message": _loading_message(self.stages[cur], cur + 1, n, frac, progress, eta),
+ "progress": progress,
"stage": self.stages[cur], "stage_index": cur + 1, "stage_count": n,
"stage_progress": None if frac is None else round(frac, 3),
"elapsed_s": elapsed, "eta_s": None if eta is None else round(eta, 1),
@@ -136,11 +152,21 @@ class StartupTracker:
self.server = _EarlyServer(self, host, port)
def release_port(self) -> None:
- """Close the early listener; call right before the real server binds the same port."""
+ """Close the early listener (tests and the failure path). The servers use `handoff_socket` instead."""
if self.server is not None:
self.server.close()
self.server = None
+ def handoff_socket(self) -> socket.socket | None:
+ """Stop the early accept loop and give the still-listening socket to the real server.
+ The port never closes, so no connection is refused: clients that connect during the hand-off wait in the
+ listen backlog until the real server accepts them."""
+ if self.server is None:
+ return None
+ sock = self.server.detach()
+ self.server = None
+ return sock
+
class _EarlyServer:
def __init__(self, tracker: StartupTracker, host: str, port: int):
@@ -168,15 +194,24 @@ class _EarlyServer:
class Server(ThreadingHTTPServer):
daemon_threads = True
allow_reuse_address = True
+ request_queue_size = 128 # clients arriving during the hand-off wait in this backlog
self.httpd = Server((host, port), Handler)
self.port = self.httpd.server_address[1]
# A fork-without-exec child would keep the listening socket open after close() and block the real bind.
sock = self.httpd.socket
- os.register_at_fork(after_in_child=lambda: sock.close())
+ self._owned = True
+ os.register_at_fork(after_in_child=lambda: sock.close() if self._owned else None)
self.thread = threading.Thread(target=self.httpd.serve_forever, daemon=True, name="startup-health")
self.thread.start()
+ def detach(self) -> socket.socket:
+ """Stop answering but keep the listening socket open and return it (the caller now owns it)."""
+ self._owned = False
+ self.httpd.shutdown()
+ self.thread.join(timeout=5)
+ return self.httpd.socket
+
def close(self) -> None:
self.httpd.shutdown()
self.httpd.server_close()
@@ -221,11 +256,14 @@ def load_callback(stages: list[str] | None = None):
return cb
-def finish() -> None:
- """Models loaded and the real server about to bind: free the port, then mark ready."""
- if ACTIVE is not None:
- ACTIVE.release_port()
- ACTIVE.ready()
+def finish() -> socket.socket | None:
+ """Models loaded: stop the early answers, mark ready, and return the listening socket for the real server
+ (aiohttp `SockSite` / `run_app(sock=...)`). None without an early listener: the server then binds host/port."""
+ if ACTIVE is None:
+ return None
+ sock = ACTIVE.handoff_socket()
+ ACTIVE.ready()
+ return sock
def abort(message: str, grace_s: float = 3.0) -> None:
diff --git a/tools/test_startup_health.py b/tools/test_startup_health.py
index de86637..6941b56 100644
--- a/tools/test_startup_health.py
+++ b/tools/test_startup_health.py
@@ -11,6 +11,7 @@ import socket
import sys
import tempfile
import threading
+import time
import unittest
import urllib.error
import urllib.request
@@ -92,7 +93,7 @@ class SnapshotTest(unittest.TestCase):
def test_ready_error(self):
t = tracker(["a"])
t.ready()
- self.assertEqual(t.snapshot(), (200, {"status": "ok"}))
+ self.assertEqual(t.snapshot(), (200, {"status": "ok", "source": "kyojin"}))
t = tracker(["a"])
t.fail("boom")
code, body = t.snapshot()
@@ -201,6 +202,36 @@ class LoadCallbackTest(unittest.TestCase):
sh.abort("x")
+class SourceMessageTest(unittest.TestCase):
+ def test_source_in_every_state_and_loading_message(self):
+ c = Clock()
+ t = tracker(["target weights", "warm-up"], clock=c)
+ t.begin("target weights")
+ t.progress(2, 5)
+ code, body = t.snapshot()
+ self.assertEqual((code, body["source"]), (503, "kyojin"))
+ self.assertEqual(body["message"], "Target weights, 40 % (stage 1 of 2)")
+ t.begin("warm-up") # no fraction: overall percent, no ETA
+ self.assertEqual(t.snapshot()[1]["message"], "Warm-up (stage 2 of 2), 50 % overall")
+ t.fail("boom")
+ self.assertEqual(t.snapshot()[1]["source"], "kyojin")
+ t2 = tracker(["a"])
+ t2.ready()
+ self.assertEqual(t2.snapshot(), (200, {"status": "ok", "source": "kyojin"}))
+
+ def test_message_has_eta_when_known(self):
+ self.assertEqual(sh._loading_message("target weights", 3, 5, 0.42, 0.5, 35.4),
+ "Target weights, 42 % (stage 3 of 5), about 35 s left")
+
+ def test_servers_own_health_carries_source(self):
+ for name in ("qwen", "glm", "mimo"):
+ src = (TOOLS / name / "serve.py").read_text()
+ i = src.index("async def health")
+ self.assertIn('"source": "kyojin"', src[i:i + 500], name)
+ if name == "glm":
+ self.assertIn('add_get("/health", health)', src)
+
+
class ListenerTest(unittest.TestCase):
def test_health_and_other_paths_while_loading_then_handoff(self):
c = Clock()
@@ -257,6 +288,86 @@ class ListenerTest(unittest.TestCase):
self.assertEqual(result["r"][0], 200)
self.assertEqual(result["r"][1]["model"], "m")
+ def _hammer(self, port, stop, refused, ok):
+ while not stop.is_set():
+ try:
+ socket.create_connection(("127.0.0.1", port), timeout=2).close()
+ ok.append(1)
+ except OSError as exc:
+ refused.append(exc)
+
+ def _handoff_under_load(self, handoff):
+ """Hammer the port with connections while `handoff(t, port, runner)` swaps the listener for aiohttp."""
+ from aiohttp import web
+ t = tracker(["weights"])
+ t.serve("127.0.0.1", 0)
+ port = t.server.port
+ stop, refused, ok = threading.Event(), [], []
+ threads = [threading.Thread(target=self._hammer, args=(port, stop, refused, ok), daemon=True) for _ in range(4)]
+ for th in threads:
+ th.start()
+ time.sleep(0.2)
+ result = {}
+
+ async def run():
+ app = web.Application()
+
+ async def health(_):
+ return web.json_response({"status": "ok"})
+ app.router.add_get("/health", health)
+ runner = web.AppRunner(app)
+ await runner.setup()
+ await handoff(t, port, runner)
+ await asyncio.sleep(0.3)
+ result["r"] = await asyncio.get_running_loop().run_in_executor(None, get, f"http://127.0.0.1:{port}/health")
+ stop.set() # stop hammering before the server closes
+ await asyncio.get_running_loop().run_in_executor(None, lambda: [th.join() for th in threads])
+ await runner.cleanup()
+ try:
+ asyncio.run(run())
+ finally:
+ stop.set()
+ for th in threads:
+ th.join()
+ return refused, ok, result["r"]
+
+ def test_handoff_refuses_no_connection(self):
+ from aiohttp import web
+
+ async def handoff(t, port, runner):
+ sock = t.handoff_socket() # what startup_health.finish() does
+ t.ready()
+ await web.SockSite(runner, sock).start()
+ refused, ok, r = self._handoff_under_load(handoff)
+ self.assertEqual(refused, [])
+ self.assertGreater(len(ok), 50)
+ self.assertEqual(r[0], 200)
+
+ def test_close_then_bind_does_refuse_connections(self):
+ """Control: the old hand-off (close the listener, then bind) is caught by the hammer."""
+ from aiohttp import web
+
+ async def handoff(t, port, runner):
+ t.release_port()
+ t.ready()
+ await asyncio.sleep(1.5) # longer than a client's SYN retry
+ await web.TCPSite(runner, "127.0.0.1", port).start()
+ refused, ok, r = self._handoff_under_load(handoff)
+ self.assertGreater(len(refused), 0)
+
+ def test_finish_returns_the_live_socket_and_none_without_listener(self):
+ sh.ACTIVE = None
+ self.assertIsNone(sh.finish())
+ sh.start("x", ["a"], "127.0.0.1", 0)
+ port = sh.ACTIVE.server.port
+ sock = sh.finish()
+ try:
+ self.assertEqual(sock.getsockname()[1], port)
+ socket.create_connection(("127.0.0.1", port), timeout=1).close() # still listening
+ finally:
+ sock.close()
+ sh.ACTIVE = None
+
def test_start_fails_fast_when_the_port_is_taken(self):
s = socket.socket()
s.bind(("127.0.0.1", 0))