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.
Python amdapple-siliconcudadeepseekexl3exllamav3glminferencellmllm-inferencelocal-llmnvidiaopenai-apiquantizationqwenrocmstrix-halo
Servers: JSON 404/405, history per start kind, per-stage ETA, clear start-up errors
YanissAmza99e9b04a33a
diff --git a/tools/glm/SERVE.md b/tools/glm/SERVE.mdindex 5a05b6b..5e4c91b 100644--- a/tools/glm/SERVE.md+++ b/tools/glm/SERVE.md@@ -128,7 +128,7 @@ The port answers from the first second, while the model is still loading. `GET /```json503 {"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"}+ "stage_progress": 0.4, "elapsed_s": 52.1, "eta_s": null, "stage_eta_s": 78.0, "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.@@ -137,9 +137,9 @@ Stages here: target weights, drafter weights, warm-up, dense GEMM tuning (the lastage 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`~/.cache/kyojin/startup-glm.json` (`KYOJIN_HEALTH_DIR` changes the folder) and later starts weigh the stages by-them (`"history"`) and report `eta_s`. Without a history `eta_s` is `null`: no estimate is made up. A failed load-answers `500 {"status":"error","message":...}` for a few seconds before the process exits. Every other path answers-`503 {"error":{"message":"Loading model",...}}` during the load, like llama.cpp. Nothing changes after READY, and+them (`"history"`) and report `eta_s`. Without a history `eta_s` is `null`: no estimate is made up. `stage_eta_s` is this run's own estimate for the current stage alone (from the share loaded so far); it is `null` until 2 % of the stage is done, and is there with or without a history. GLM keeps two histories (`startup-glm-tuned.json`, `startup-glm-untuned.json`) so a start with the dense GEMM tuning already cached is never timed with the slow first start. A failed load+answers `500 {"status":"error","message":...}` for a few seconds before the process exits. The real API endpoints answer+`503 {"error":{"message":"Loading model",...}}` during the load, like llama.cpp; an unknown path answers `404` and a wrong method `405`, in the same JSON error shape (also after READY). Nothing changes after READY, andthe `READY` line is the same. The helper is `tools/startup_health.py`, shared by the three servers.llama-swap polls `checkEndpoint` (default `/health`, HTTP 200 = ready) until `healthCheckTimeout` runs out, so give itdiff --git a/tools/glm/serve.py b/tools/glm/serve.pyindex 0c3d47c..cbb0d1c 100644--- a/tools/glm/serve.py+++ b/tools/glm/serve.py@@ -229,7 +229,7 @@ def reply_room(engine: Any, prompt_tokens: int) -> int | None:return Noneroom = ctx - prompt_tokens - 1 - getattr(engine, "num_draft", 0)if room < 1:- raise web.HTTPBadRequest(reason=f"prompt is {prompt_tokens} tokens, the server context is {ctx}")+ raise web.HTTPBadRequest(reason=f"context length exceeded: prompt is {prompt_tokens} tokens, the server context is {ctx}")return room@@ -460,12 +460,16 @@ def prime_dense_tune(budget_s: float = 600.0) -> tuple[int, float]:return done, time.perf_counter() - t0+# Every route of create_app(), for the early /health listener (404 / 405 while loading); a test keeps it in step.+ROUTES = {"/health": ("GET",), "/v1/models": ("GET",), "/metrics": ("GET",), "/slots": ("GET",), "/v1/chat/completions": ("POST",), "/apply-template": ("POST",), "/completion": ("POST",), "/slots/{id}": ("POST",)}++def create_app(engine: Any, model_id: str, template: str) -> web.Application:"""Build the HTTP layer around a resident engine (also accepts a fake engine in tests)."""queue: asyncio.Queue[tuple[dict[str, Any], asyncio.Queue, dict[str, Any]]] = asyncio.Queue()lock = asyncio.Lock() # serializes generation with slot save/restoreprocessing = 0 # admitted requests; closure, app config is immutable after startup- app = web.Application(client_max_size=16 * 1024**2)+ app = web.Application(client_max_size=16 * 1024**2, middlewares=[startup_health.json_errors_middleware()])app.update(engine=engine, model_id=model_id, template=template, queue=queue, metrics=Metrics())def observe(st: dict[str, Any], prompt_tokens: int) -> None:@@ -847,7 +851,10 @@ def main() -> None:warm = os.environ.get("EXL3_SERVE_WARMUP", "1") != "0"tune = warm and float(os.environ.get("EXL3_SERVE_DTUNE_PRIME_S", "600")) > 0stages = ["target weights", "drafter weights"] + (["warm-up"] if warm else []) + (["dense GEMM tuning"] if tune else [])- startup_health.start("glm", stages, args.host, args.port)+ startup_health.check_model_dir("serve", args.model, ("config.json",) if args.chat_template else ("config.json", "chat_template.jinja"))+ # A start with the dense GEMM tuning already cached is much shorter than the first one: keep their timings apart.+ startup_health.start("glm", stages, args.host, args.port, routes=ROUTES,+ variant="tuned" if tune and dense_tune_path().exists() else "untuned")try:engine = ResidentEngine(args.model, max_history=args.max_history or args.num_draft, max_ctx=args.max_ctx, num_draft=args.num_draft)template = Path(args.chat_template or Path(args.model) / "chat_template.jinja").expanduser().read_text(encoding="utf-8")diff --git a/tools/glm/test_serve.py b/tools/glm/test_serve.pyindex cdc3e7e..309119f 100644--- a/tools/glm/test_serve.py+++ b/tools/glm/test_serve.py@@ -46,6 +46,50 @@ def metrics_samples(text: str) -> dict:class ServeTests(unittest.TestCase):template = "{% for m in messages %}<|im_start|>{{ m.role }}: {{ m.content }}<|im_end|>{% endfor %}{% if tools %}TOOLS={{ tools|length }}{% endif %}"+++ def test_prompt_longer_than_the_context_is_a_clear_400(self):+ from aiohttp.test_utils import TestClient, TestServer++ class Small(FakeEngine):+ ctx = 256++ async def check():+ client = TestClient(TestServer(serve.create_app(Small("x"), "m", self.template)))+ await client.start_server()+ out = []+ for stream in (False, True):+ r = await client.post("/v1/chat/completions", json={+ "model": "m", "stream": stream, "messages": [{"role": "user", "content": "word " * 400}]})+ out.append((r.status, await r.json()))+ await client.close()+ return out++ for status, body in run(check()):+ self.assertEqual(status, 400)+ self.assertEqual(body["error"]["type"], "invalid_request_error")+ self.assertIn("context length exceeded: prompt is", body["error"]["message"])+ self.assertIn("the server context is 256", body["error"]["message"])++ def test_unknown_path_and_wrong_method_answer_404_405_in_json(self):+ from aiohttp.test_utils import TestClient, TestServer++ async def check():+ client = TestClient(TestServer(serve.create_app(FakeEngine("x"), "m", self.template)))+ await client.start_server()+ out = []+ for method, path in (("GET", "/nope"), ("POST", "/nope"), ("POST", "/health"), ("GET", "/v1/chat/completions")):+ r = await client.request(method, path)+ out.append((r.status, r.headers["Content-Type"], await r.json()))+ await client.close()+ return out++ for (status, ctype, body), want in zip(run(check()), (404, 404, 405, 405)):+ self.assertEqual(status, want)+ self.assertTrue(ctype.startswith("application/json"))+ self.assertEqual((body["error"]["code"], body["error"]["type"]), (want, "invalid_request_error"))+ self.assertTrue(body["error"]["message"])+def test_eh_sidecar_source_order(self):import os, tempfilefrom unittest import mockdiff --git a/tools/mimo/SERVE.md b/tools/mimo/SERVE.mdindex f9c2316..e36e137 100644--- a/tools/mimo/SERVE.md+++ b/tools/mimo/SERVE.md@@ -57,7 +57,7 @@ The port answers from the first second, while the model is still loading. `GET /```json503 {"status": "loading", "source": "kyojin", "message": "Target weights, 40 % (stage 1 of 3)", "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"}+ "stage_progress": 0.4, "elapsed_s": 52.1, "eta_s": null, "stage_eta_s": 78.0, "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.@@ -66,9 +66,9 @@ Stages here: drafter weights, target weights, engine setup (no drafter stage witstage 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`~/.cache/kyojin/startup-mimo.json` (`KYOJIN_HEALTH_DIR` changes the folder) and later starts weigh the stages by-them (`"history"`) and report `eta_s`. Without a history `eta_s` is `null`: no estimate is made up. A failed load-answers `500 {"status":"error","message":...}` for a few seconds before the process exits. Every other path answers-`503 {"error":{"message":"Loading model",...}}` during the load, like llama.cpp. Nothing changes after READY, and+them (`"history"`) and report `eta_s`. Without a history `eta_s` is `null`: no estimate is made up. `stage_eta_s` is this run's own estimate for the current stage alone (from the share loaded so far); it is `null` until 2 % of the stage is done, and is there with or without a history. A failed load+answers `500 {"status":"error","message":...}` for a few seconds before the process exits. The real API endpoints answer+`503 {"error":{"message":"Loading model",...}}` during the load, like llama.cpp; an unknown path answers `404` and a wrong method `405`, in the same JSON error shape (also after READY). Nothing changes after READY, andthe `READY` line is the same. The helper is `tools/startup_health.py`, shared by the three servers.llama-swap polls `checkEndpoint` (default `/health`, HTTP 200 = ready) until `healthCheckTimeout` runs out, so give itdiff --git a/tools/mimo/serve.py b/tools/mimo/serve.pyindex b014699..494ec24 100644--- a/tools/mimo/serve.py+++ b/tools/mimo/serve.py@@ -209,7 +209,7 @@ def reply_room(engine: Any, prompt_tokens: int) -> int | None:return Noneroom = ctx // 256 * 256 - prompt_tokens - 1 - getattr(engine, "num_draft", 0) # page table = ctx // 256 pages of 256 tokensif room < 1:- raise web.HTTPBadRequest(reason=f"prompt is {prompt_tokens} tokens, the server context is {ctx}")+ raise web.HTTPBadRequest(reason=f"context length exceeded: prompt is {prompt_tokens} tokens, the server context is {ctx}")return room@@ -362,12 +362,16 @@ class ResidentEngine:# ---------------------------------------------------------------------------- HTTP+# Every route of create_app(), for the early /health listener (404 / 405 while loading); a test keeps it in step.+ROUTES = {"/health": ("GET",), "/v1/models": ("GET",), "/metrics": ("GET",), "/slots": ("GET",), "/v1/chat/completions": ("POST",), "/apply-template": ("POST",), "/completion": ("POST",), "/slots/{id}": ("POST",)}++def create_app(engine: Any, model_id: str, template: str) -> web.Application:"""Build the HTTP layer around a resident engine (also accepts a fake engine in tests)."""queue: asyncio.Queue[tuple[dict[str, Any], asyncio.Queue, dict[str, Any]]] = asyncio.Queue()lock = asyncio.Lock() # serializes generation with slot save/restoreprocessing = 0 # admitted requests; closure, app config is immutable after startup- app = web.Application(client_max_size=16 * 1024**2)+ app = web.Application(client_max_size=16 * 1024**2, middlewares=[startup_health.json_errors_middleware()])app.update(engine=engine, model_id=model_id, template=template, queue=queue, metrics=Metrics())def observe(st: dict[str, Any], prompt_tokens: int) -> None:@@ -800,7 +804,8 @@ def main() -> None:"decoding without speculation", flush=True)stages = (["drafter weights"] if drafter else []) + ["target weights", "engine setup"]- startup_health.start("mimo", stages, args.host, args.port)+ startup_health.check_model_dir("msrv", args.model)+ startup_health.start("mimo", stages, args.host, args.port, routes=ROUTES)# --ctx 0 = the model's own max context, with the nested text_config handled like the GLM fix.try:probe = Config.from_directory(args.model)diff --git a/tools/mimo/test_serve.py b/tools/mimo/test_serve.pyindex 966bf62..1c5ae43 100644--- a/tools/mimo/test_serve.py+++ b/tools/mimo/test_serve.py@@ -56,6 +56,50 @@ TEMPLATE = ("{% for m in messages %}<|im_start|>{{ m.role }}\n{{ m.content }}<|iclass ServeTests(unittest.TestCase):+++ def test_prompt_longer_than_the_context_is_a_clear_400(self):+ from aiohttp.test_utils import TestClient, TestServer++ class Small(FakeEngine):+ ctx = 256++ async def check():+ client = TestClient(TestServer(serve.create_app(Small("x"), "m", TEMPLATE)))+ await client.start_server()+ out = []+ for stream in (False, True):+ r = await client.post("/v1/chat/completions", json={+ "model": "m", "stream": stream, "messages": [{"role": "user", "content": "word " * 400}]})+ out.append((r.status, await r.json()))+ await client.close()+ return out++ for status, body in run(check()):+ self.assertEqual(status, 400)+ self.assertEqual(body["error"]["type"], "invalid_request_error")+ self.assertIn("context length exceeded: prompt is", body["error"]["message"])+ self.assertIn("the server context is 256", body["error"]["message"])++ def test_unknown_path_and_wrong_method_answer_404_405_in_json(self):+ from aiohttp.test_utils import TestClient, TestServer++ async def check():+ client = TestClient(TestServer(serve.create_app(FakeEngine("x"), "m", TEMPLATE)))+ await client.start_server()+ out = []+ for method, path in (("GET", "/nope"), ("POST", "/nope"), ("POST", "/health"), ("GET", "/v1/chat/completions")):+ r = await client.request(method, path)+ out.append((r.status, r.headers["Content-Type"], await r.json()))+ await client.close()+ return out++ for (status, ctype, body), want in zip(run(check()), (404, 404, 405, 405)):+ self.assertEqual(status, want)+ self.assertTrue(ctype.startswith("application/json"))+ self.assertEqual((body["error"]["code"], body["error"]["type"]), (want, "invalid_request_error"))+ self.assertTrue(body["error"]["message"])+def test_reply_budget_is_clamped_to_the_context_room(self):from aiohttp.test_utils import TestClient, TestServerdiff --git a/tools/qwen/SERVE.md b/tools/qwen/SERVE.mdindex 4736b44..691dee6 100644--- a/tools/qwen/SERVE.md+++ b/tools/qwen/SERVE.md@@ -91,7 +91,7 @@ The port answers from the first second, while the model is still loading. `GET /```json503 {"status": "loading", "source": "kyojin", "message": "Target weights, 40 % (stage 1 of 5)", "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"}+ "stage_progress": 0.4, "elapsed_s": 52.1, "eta_s": null, "stage_eta_s": 78.0, "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.@@ -100,9 +100,9 @@ Stages here: target weights, drafter weights, vision tower, engine setup, warm-ustage 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`~/.cache/kyojin/startup-qwen.json` (`KYOJIN_HEALTH_DIR` changes the folder) and later starts weigh the stages by-them (`"history"`) and report `eta_s`. Without a history `eta_s` is `null`: no estimate is made up. A failed load-answers `500 {"status":"error","message":...}` for a few seconds before the process exits. Every other path answers-`503 {"error":{"message":"Loading model",...}}` during the load, like llama.cpp. Nothing changes after READY, and+them (`"history"`) and report `eta_s`. Without a history `eta_s` is `null`: no estimate is made up. `stage_eta_s` is this run's own estimate for the current stage alone (from the share loaded so far); it is `null` until 2 % of the stage is done, and is there with or without a history. A failed load+answers `500 {"status":"error","message":...}` for a few seconds before the process exits. The real API endpoints answer+`503 {"error":{"message":"Loading model",...}}` during the load, like llama.cpp; an unknown path answers `404` and a wrong method `405`, in the same JSON error shape (also after READY). Nothing changes after READY, andthe `READY` line is the same. The helper is `tools/startup_health.py`, shared by the three servers.llama-swap polls `checkEndpoint` (default `/health`, HTTP 200 = ready) until `healthCheckTimeout` runs out, so give itdiff --git a/tools/qwen/serve.py b/tools/qwen/serve.pyindex 360f1ae..9e39218 100644--- a/tools/qwen/serve.py+++ b/tools/qwen/serve.py@@ -1160,6 +1160,10 @@ def format_logprobs(entries: list, token_ids: list[int], token_str, chat: bool)"top_logprobs_ids": [None if e is None else [[int(a), b] for a, b in e[1]] for e in entries]}+# Every route of create_app(), for the early /health listener (404 / 405 while loading); a test keeps it in step.+ROUTES = {"/health": ("GET",), "/v1/models": ("GET",), "/slots": ("GET",), "/v1/chat/completions": ("POST",), "/apply-template": ("POST",), "/completion": ("POST",), "/v1/completions": ("POST",), "/slots/{id}": ("POST",)}++def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, Any] | None = None,default_max_tokens: int = 32768) -> web.Application:"""HTTP layer around a resident engine (also accepts a fake engine in tests)."""@@ -1169,7 +1173,7 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, Angate = asyncio.Semaphore(sessions) # one permit per running request; slot actions take them all (drain)lock = asyncio.Lock() # serializes the slot actionsrunning = 0- app = web.Application(client_max_size=64 * 1024**2)+ app = web.Application(client_max_size=64 * 1024**2, middlewares=[startup_health.json_errors_middleware()])app.update(engine=engine, model_id=model_id, template=template, defaults=defaults)def err(status: int, message: str) -> web.Response:@@ -1751,7 +1755,8 @@ def main() -> None:# /health answers 503 with the load progress from here until READY (stdlib listener on the same port).stages = ["target weights"] + (["drafter weights"] if args.draft_policy != "off" else []) \+ (["vision tower"] if not args.no_vision else []) + ["engine setup", "warm-up"]- startup_health.start("qwen", stages, args.host, args.port)+ startup_health.check_model_dir("qserve", args.model)+ startup_health.start("qwen", stages, args.host, args.port, routes=ROUTES)try:engine, template, defaults, model_dir, t0 = load_all(args)except BaseException as exc: # noqa: BLE001diff --git a/tools/qwen/test_serve.py b/tools/qwen/test_serve.pyindex 198bcca..0381d1e 100644--- a/tools/qwen/test_serve.py+++ b/tools/qwen/test_serve.py@@ -695,6 +695,26 @@ class ReplyRoomTests(unittest.TestCase):class MiscTests(unittest.TestCase):++ def test_unknown_path_and_wrong_method_answer_404_405_in_json(self):+ from aiohttp.test_utils import TestClient, TestServer++ async def check():+ client = TestClient(TestServer(serve.create_app(FakeEngine("x"), "m", THINK_TEMPLATE, serve.load_defaults("/x"))))+ await client.start_server()+ out = []+ for method, path in (("GET", "/nope"), ("POST", "/nope"), ("POST", "/health"), ("GET", "/v1/chat/completions")):+ r = await client.request(method, path)+ out.append((r.status, r.headers["Content-Type"], await r.json()))+ await client.close()+ return out++ for (status, ctype, body), want in zip(run(check()), (404, 404, 405, 405)):+ self.assertEqual(status, want)+ self.assertTrue(ctype.startswith("application/json"))+ self.assertEqual((body["error"]["code"], body["error"]["type"]), (want, "invalid_request_error"))+ self.assertTrue(body["error"]["message"])+def test_sse_framing_and_stop_text(self):self.assertEqual(serve.sse({"a": 1}), b'data: {"a":1}\n\n')self.assertEqual(serve.stop_text("hello STOP x", ["STOP"]), ("hello ", "STOP"))diff --git a/tools/startup_health.py b/tools/startup_health.pyindex a3a072a..3c143ba 100644--- a/tools/startup_health.py+++ b/tools/startup_health.py@@ -6,7 +6,7 @@ answers every request with 503, and answers GET /health with the real load progr200 {"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"}+ "stage_progress": 0.4, "elapsed_s": 52.1, "eta_s": null, "stage_eta_s": 78.0, "progress_basis": "stages"}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@@ -33,28 +33,73 @@ LOADING_BODY = {"error": {"message": "Loading model", "type": "unavailable_errorACTIVE: "StartupTracker | None" = None+def error_body(code: int, message: str) -> dict:+ """The JSON error shape of the servers (OpenAI style)."""+ return {"error": {"message": message, "type": "invalid_request_error", "code": code}}+++def route_methods(routes: dict[str, tuple[str, ...]], path: str) -> tuple[str, ...] | None:+ """Allowed methods for `path` in a route table (`{x}` matches one segment), or None when the path is unknown."""+ parts = path.rstrip("/").split("/")+ for pattern, methods in routes.items():+ pp = pattern.rstrip("/").split("/")+ if len(pp) == len(parts) and all(a == b or (a.startswith("{") and a.endswith("}") and b) for a, b in zip(pp, parts)):+ return methods+ return None+++def json_errors_middleware():+ """aiohttp middleware: 404, 405 and the other HTTP errors raised by the router answer in the JSON error shape+ (aiohttp's own reply is plain text). Imported lazily: the rest of this module needs no aiohttp."""+ from aiohttp import web++ @web.middleware+ async def middleware(request, handler):+ try:+ return await handler(request)+ except web.HTTPException as exc:+ if exc.status < 400:+ raise+ if exc.status == 404:+ message = f"not found: {request.method} {request.path}"+ elif exc.status == 405:+ message = f"method {request.method} not allowed on {request.path} (allowed: {', '.join(a.strip() for a in exc.headers.get('Allow', '').split(','))})"+ else:+ # aiohttp's default body is "<status>: <reason>"; the JSON message is the reason alone+ message = exc.reason if exc.text in (None, "", f"{exc.status}: {exc.reason}") else exc.text+ headers = {"Allow": exc.headers["Allow"]} if "Allow" in exc.headers else None+ return web.json_response(error_body(exc.status, message), status=exc.status, headers=headers)+ return middleware++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:+def _loading_message(stage: str, index: int, count: int, frac, progress: float, eta, stage_eta=None) -> 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"+ elif stage_eta is not None:+ text += f", about {round(stage_eta)} s left in this stage"return textclass StartupTracker:"""Thread-safe record of the start-up stages. Stage indices are 1-based."""- def __init__(self, name: str, stages: list[str], clock=time.monotonic, history: Path | None = None):+ def __init__(self, name: str, stages: list[str], clock=time.monotonic, history: Path | None = None,+ variant: str | None = None):if not stages:raise ValueError("at least one stage")self.name, self.stages, self.clock = name, list(stages), clock- self.history_path = (history if history is not None else history_dir() / f"startup-{name}.json")+ # `variant` keeps the durations of different kinds of start apart (e.g. cached kernel tuning or not), so a+ # fast start is never timed with the history of a slow one.+ suffix = f"-{variant}" if variant else ""+ self.history_path = (history if history is not None else history_dir() / f"startup-{name}{suffix}.json")self.lock = threading.Lock()self.t0 = clock()self.state = "loading"@@ -65,6 +110,7 @@ class StartupTracker:self.durations: dict[str, float] = {}self.expected = self._load_history()self.server: _EarlyServer | None = None+ self.routes: dict[str, tuple[str, ...]] | None = Nonedef _load_history(self) -> dict[str, float] | None:try:@@ -137,13 +183,16 @@ class StartupTracker:eta = sum(exp[s] for s in self.stages[cur + 1:]) + left if left >= 0 else Noneelse:progress, basis, eta = (cur + (frac or 0.0)) / n, "stages", None+ # Pace of this run in the current stage: an estimate for that stage alone, whatever the history says.+ stage_eta = stage_elapsed * (1 - frac) / frac if frac is not None and frac >= 0.02 and stage_elapsed > 0 else Noneprogress = round(min(progress, 0.999), 3)return 503, {"status": "loading", "source": "kyojin",- "message": _loading_message(self.stages[cur], cur + 1, n, frac, progress, eta),+ "message": _loading_message(self.stages[cur], cur + 1, n, frac, progress, eta, stage_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),+ "stage_eta_s": None if stage_eta is None else round(stage_eta, 1),"progress_basis": basis}# ---- early listener@@ -172,13 +221,24 @@ class _EarlyServer:def __init__(self, tracker: StartupTracker, host: str, port: int):class Handler(BaseHTTPRequestHandler):def _reply(self):- if self.path.split("?", 1)[0].rstrip("/") == "/health":+ path = self.path.split("?", 1)[0]+ routes = getattr(tracker, "routes", None)+ allowed = route_methods(routes, path) if routes is not None else None+ extra = None+ if path.rstrip("/") == "/health" and self.command in ("GET", "HEAD"):code, body = tracker.snapshot()+ elif allowed is None and routes is not None:+ code, body = 404, error_body(404, f"not found: {self.command} {path}")+ elif allowed is not None and self.command not in allowed and not (self.command == "HEAD" and "GET" in allowed):+ code, body = 405, error_body(405, f"method {self.command} not allowed on {path} (allowed: {', '.join(allowed)})")+ extra = ("Allow", ", ".join(allowed))else:code, body = 503, LOADING_BODYdata = json.dumps(body).encode()try:self.send_response(code)+ if extra:+ self.send_header(*extra)self.send_header("Content-Type", "application/json")self.send_header("Content-Length", str(len(data)))self.send_header("Retry-After", "5")@@ -223,11 +283,30 @@ class _EarlyServer:# ---- module-level helpers used by the servers (no-ops without an active tracker)-def start(name: str, stages: list[str], host: str, port: int) -> StartupTracker:- """Create the tracker and open the early listener. Fails at once when the port is taken."""+def check_model_dir(name: str, model_dir, needed: tuple[str, ...] = ("config.json", "chat_template.jinja")) -> None:+ """Exit with one plain line (no traceback) when the pack folder is missing or lacks a file every start needs."""+ d = Path(model_dir).expanduser()+ if not d.is_dir():+ raise SystemExit(f"{name}: model folder not found: {d} (point --model at the downloaded pack folder)")+ missing = [f for f in needed if not (d / f).is_file()]+ if missing:+ raise SystemExit(f"{name}: {d} is not a complete pack, missing: {', '.join(missing)} (download it again)")+++def start(name: str, stages: list[str], host: str, port: int, variant: str | None = None,+ routes: dict[str, tuple[str, ...]] | None = None) -> StartupTracker:+ """Create the tracker and open the early listener. Fails at once when the port is taken.+ `routes` maps each path of the server (`{x}` is a wildcard segment) to its allowed methods: while loading, a path+ outside it answers 404 and a wrong method 405 (JSON), the real endpoints answer 503."""global ACTIVE- ACTIVE = StartupTracker(name, stages)- ACTIVE.serve(host, port)+ ACTIVE = StartupTracker(name, stages, variant=variant)+ ACTIVE.routes = routes+ try:+ ACTIVE.serve(host, port)+ except OSError as exc:+ ACTIVE = None+ raise SystemExit(f"{name}: cannot listen on {host}:{port}: {exc.strerror or exc} "+ "(another server on this port? choose another --port)") from Nonereturn ACTIVEdiff --git a/tools/test_startup_health.py b/tools/test_startup_health.pyindex b5819e4..c77aebb 100644--- a/tools/test_startup_health.py+++ b/tools/test_startup_health.py@@ -7,6 +7,7 @@ from __future__ import annotationsimport astimport asyncioimport json+import reimport socketimport sysimport tempfile@@ -165,6 +166,49 @@ class HistoryTest(unittest.TestCase):self.path.write_text("{nope")self.assertEqual(tracker(["a"], history=self.path).snapshot()[1]["progress_basis"], "stages")+ def test_variants_keep_their_histories_apart(self):+ # a cold start (slow stage) must not time a later warm start, and the other way round+ base = Path(self.dir.name)+ old = sh.history_dir+ sh.history_dir = lambda: base+ try:+ for variant, dur in (("untuned", {"a": 5, "b": 600}), ("tuned", {"a": 5, "b": 20})):+ c = Clock()+ t = sh.StartupTracker("g", ["a", "b"], clock=c, variant=variant)+ for stage in ("a", "b"):+ t.begin(stage)+ c.t += dur[stage]+ t.ready()+ self.assertEqual(json.loads((base / "startup-g-untuned.json").read_text())["b"], 600.0)+ self.assertEqual(json.loads((base / "startup-g-tuned.json").read_text())["b"], 20.0)+ t = sh.StartupTracker("g", ["a", "b"], clock=Clock(), variant="tuned")+ self.assertEqual(t.snapshot()[1]["eta_s"], 25.0) # 5 + 20, not 605+ t = sh.StartupTracker("g", ["a", "b"], clock=Clock(), variant="other")+ self.assertEqual(t.snapshot()[1]["progress_basis"], "stages") # no history for it: no made-up eta+ finally:+ sh.history_dir = old++ def test_stage_eta_from_own_pace_without_history(self):+ c = Clock()+ t = tracker(["a", "b"], clock=c)+ body = t.snapshot()[1]+ self.assertIn("stage_eta_s", body)+ self.assertIsNone(body["stage_eta_s"])+ c.t += 30+ t.progress(1, 4) # 30 s for a quarter: 90 s left in this stage+ body = t.snapshot()[1]+ self.assertEqual((body["eta_s"], body["stage_eta_s"], body["progress_basis"]), (None, 90.0, "stages"))+ self.assertIn("about 90 s left in this stage", body["message"])++ def test_stage_eta_is_there_with_history_too(self):+ self.run_start(["a", "b"], {"a": 600, "b": 10})+ c = Clock()+ t = tracker(["a", "b"], history=self.path, clock=c)+ c.t += 10+ t.progress(50, 100)+ body = t.snapshot()[1]+ self.assertEqual((body["eta_s"], body["stage_eta_s"]), (20.0, 10.0))+class LoadCallbackTest(unittest.TestCase):def setUp(self):@@ -373,8 +417,12 @@ class ListenerTest(unittest.TestCase):s.bind(("127.0.0.1", 0))s.listen(1)try:- with self.assertRaises(OSError):+ with self.assertRaises(SystemExit) as cm: # one plain line, no tracebacksh.start("t", ["a"], "127.0.0.1", s.getsockname()[1])+ msg = str(cm.exception)+ self.assertIn("cannot listen on 127.0.0.1:", msg)+ self.assertIn("choose another --port", msg)+ self.assertIsNone(sh.ACTIVE)finally:s.close()sh.ACTIVE = None@@ -391,6 +439,94 @@ class ListenerTest(unittest.TestCase):self.assertEqual(codes, [503] * 8)+class RouteErrorTest(unittest.TestCase):+ ROUTES = {"/health": ("GET",), "/v1/models": ("GET",), "/v1/chat/completions": ("POST",), "/slots/{id}": ("POST",)}++ def test_early_listener_answers_404_and_405_in_json_and_keeps_503_for_real_endpoints(self):+ t = tracker(["weights"])+ t.routes = self.ROUTES+ t.serve("127.0.0.1", 0)+ base = f"http://127.0.0.1:{t.server.port}"+ try:+ code, body, headers = get(base + "/nope")+ self.assertEqual((code, body["error"]["code"], body["error"]["type"]), (404, 404, "invalid_request_error"))+ self.assertIn("/nope", body["error"]["message"])+ self.assertEqual(headers["Content-Type"], "application/json")+ code, body, _ = get(base + "/v1/chat/completions") # GET on a POST route+ self.assertEqual((code, body["error"]["code"]), (405, 405))+ self.assertEqual(_["Allow"], "POST")+ req = urllib.request.Request(base + "/health", data=b"{}", method="POST")+ with self.assertRaises(urllib.error.HTTPError) as cm:+ urllib.request.urlopen(req, timeout=5)+ self.assertEqual(cm.exception.code, 405)+ self.assertEqual(get(base + "/v1/models")[0], 503) # a real endpoint: still "loading"+ self.assertEqual(get(base + "/health")[0], 503)+ self.assertEqual(get(base + "/slots/3")[0], 405) # wildcard segment matched, wrong method+ self.assertEqual(get(base + "/slots")[0], 404)+ finally:+ t.release_port()++ def test_route_methods_matching(self):+ self.assertEqual(sh.route_methods(self.ROUTES, "/slots/7"), ("POST",))+ self.assertEqual(sh.route_methods(self.ROUTES, "/v1/models/"), ("GET",))+ self.assertIsNone(sh.route_methods(self.ROUTES, "/slots/"))+ self.assertIsNone(sh.route_methods(self.ROUTES, "/x/y/z"))++ def test_middleware_gives_json_404_405_and_leaves_handler_answers_alone(self):+ from aiohttp import web+ from aiohttp.test_utils import TestClient, TestServer++ async def ok(_):+ return web.json_response({"ok": 1})++ async def teapot(_):+ return web.json_response({"error": {"message": "mine"}}, status=418)++ async def go():+ app = web.Application(middlewares=[sh.json_errors_middleware()])+ app.router.add_get("/ok", ok)+ app.router.add_post("/tea", teapot)+ client = TestClient(TestServer(app))+ await client.start_server()+ out = {}+ for key, method, path in (("404", "GET", "/nope"), ("405", "POST", "/ok"), ("ok", "GET", "/ok"), ("418", "POST", "/tea")):+ r = await client.request(method, path)+ out[key] = (r.status, r.headers["Content-Type"], await r.json(), r.headers.get("Allow"))+ await client.close()+ return out+ out = asyncio.run(go())+ self.assertEqual(out["404"][0], 404)+ self.assertTrue(out["404"][1].startswith("application/json"))+ self.assertEqual(out["404"][2]["error"], {"message": "not found: GET /nope", "type": "invalid_request_error", "code": 404})+ self.assertEqual(out["405"][0], 405)+ self.assertEqual(out["405"][3], "GET,HEAD")+ self.assertIn("(allowed: GET, HEAD)", out["405"][2]["error"]["message"])+ self.assertIn("method POST not allowed on /ok", out["405"][2]["error"]["message"])+ self.assertEqual(out["ok"][2], {"ok": 1})+ self.assertEqual((out["418"][0], out["418"][2]["error"]["message"]), (418, "mine"))+++class ModelDirTest(unittest.TestCase):+ def test_missing_folder_and_missing_files_give_one_plain_line(self):+ with tempfile.TemporaryDirectory() as d:+ with self.assertRaises(SystemExit) as cm:+ sh.check_model_dir("qserve", Path(d) / "nope")+ self.assertIn("model folder not found", str(cm.exception))+ self.assertIn("--model", str(cm.exception))+ (Path(d) / "config.json").write_text("{}")+ with self.assertRaises(SystemExit) as cm:+ sh.check_model_dir("qserve", d)+ self.assertIn("missing: chat_template.jinja", str(cm.exception))+ sh.check_model_dir("qserve", d, ("config.json",)) # needed list is the caller's+ (Path(d) / "chat_template.jinja").write_text("x")+ sh.check_model_dir("qserve", d)++ def test_servers_check_the_pack_before_the_port_opens(self):+ for name in ("qwen", "glm", "mimo"):+ src = (TOOLS / name / "serve.py").read_text()+ self.assertLess(src.index("startup_health.check_model_dir("), src.index("startup_health.start("), name)++class QuietDisconnectTest(unittest.TestCase):def test_client_that_hangs_up_leaves_no_traceback(self):import contextlib@@ -495,6 +631,19 @@ class WiringTest(unittest.TestCase):self.assertLess(src.index("draft_model.load("), src.index(" model.load("))self.assertIn('["drafter weights"] if drafter_path else []) + ["target weights"]', (TOOLS / "mimo" / "serve.py").read_text())+ def test_servers_pass_routes_and_json_middleware_and_routes_match_the_app(self):+ for name in self.EXPECT:+ src = (TOOLS / name / "serve.py").read_text()+ self.assertIn("routes=ROUTES", src, name)+ self.assertIn("middlewares=[startup_health.json_errors_middleware()]", src, name)+ registered = set(re.findall(r'router\.add_(?:get|post)\("([^"]+)"', src))+ declared = set(re.search(r"^ROUTES = (\{.*\})$", src, re.M).group(1).replace("(", "[").replace(")", "]") and+ json.loads(re.search(r"^ROUTES = (\{.*\})$", src, re.M).group(1).replace("(", "[").replace(")", "]").replace(",]", "]")))+ self.assertEqual(registered, declared, name)++ def test_glm_keeps_tuned_and_untuned_history_apart(self):+ self.assertIn('variant="tuned" if tune and dense_tune_path().exists() else "untuned"', (TOOLS / "glm" / "serve.py").read_text())+def test_default_ready_line_unchanged(self):self.assertIn("qserve: READY on http://", (TOOLS / "qwen" / "serve.py").read_text())