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.

Add GET /health with load progress to the Qwen, GLM and MiMo servers

YanissAmzff9a8606fdb9
diff --git a/exllamav3/model/model.py b/exllamav3/model/model.py
index 7b6e2b3..3399b0f 100644
--- a/exllamav3/model/model.py
+++ b/exllamav3/model/model.py
@@ -381,7 +381,7 @@ class Model(Model_TPMixin, Model_LSMixin):
"Cannot specify reserve_per_device or use_per_device when loading to single device."
assert not tensor_p, \
"Cannot use tensor_p when loading to single device."
- self._load_single(progressbar, device, self.config, self.modules, verbose)
+ self._load_single(progressbar, device, self.config, self.modules, verbose, callback)
self.output_device = self.modules[-1].device
# Use/reserve
diff --git a/exllamav3/model/model_ls.py b/exllamav3/model/model_ls.py
index 2a897d9..163fb42 100644
--- a/exllamav3/model/model_ls.py
+++ b/exllamav3/model/model_ls.py
@@ -33,11 +33,13 @@ class Model_LSMixin(ABC):
device: torch.device,
config: Config,
modules: list,
- verbose: bool
+ verbose: bool,
+ callback = None
):
pin = config.infer_params.vision_pinned and getattr(self, "component", "text") == "vision"
with ProgressBar(f"Loading" if progressbar else None, len(modules)) as progress:
for idx, module in enumerate(modules):
+ if callback: callback(idx, len(modules))
defer = module.can_defer_load()
if defer:
# Pinned modules leave the arena alone: their slab slices would keep whole
diff --git a/tools/glm/SERVE.md b/tools/glm/SERVE.md
index 1ab7b42..8c71e39 100644
--- a/tools/glm/SERVE.md
+++ b/tools/glm/SERVE.md
@@ -59,6 +59,9 @@ 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).
+
### `GET /v1/models`
One entry: `{"id": "<model-id>", "object": "model", "created": 0, "owned_by": "local"}`.
@@ -111,6 +114,37 @@ simply absent. GLM tool calls are emitted by the model as `<\u200btool_call>name
deliberate so plain prose never triggers the parser; arg values are JSON-parsed when they
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"}`
+(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,
+ "stage_progress": 0.4, "elapsed_s": 52.1, "eta_s": null, "progress_basis": "stages"}
+```
+
+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
+`~/.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
+the `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 it
+room for a first start:
+
+```yaml
+healthCheckTimeout: 1800 # seconds; a first start tunes kernels
+models:
+ "glm":
+ proxy: http://127.0.0.1:${PORT}
+ checkEndpoint: /health
+ cmd: python tools/glm/serve.py --port ${PORT}
+```
+
## Known limits
- **One model, one flight.** The `asyncio.Queue` worker serializes every request; a
@@ -142,7 +176,7 @@ parse, otherwise kept as strings.
## Tests
```bash
-python -m pytest -q tools/glm/test_serve.py
+python -m pytest -q tools/glm/test_serve.py tools/test_startup_health.py
```
Model-free: a `FakeEngine` emits deterministic GLM XML in 3-character chunks so tags are
diff --git a/tools/glm/serve.py b/tools/glm/serve.py
index 6d0b1d0..ca0918a 100644
--- a/tools/glm/serve.py
+++ b/tools/glm/serve.py
@@ -19,6 +19,9 @@ import aiohttp
from aiohttp import web
from jinja2.sandbox import ImmutableSandboxedEnvironment
+sys.path.append(str(Path(__file__).resolve().parent.parent))
+import startup_health # noqa: E402 (GET /health with load progress while the model loads)
+
DEFAULT_MODEL = "~/models/glm53-exl3-td205"
EH_SIDECAR_DEFAULT = "~/models/glm53-mtp-eh-proj-bf16.safetensors"
# Name inside the model folder. Not *.safetensors, so the weight loader never indexes it as model weights
@@ -258,11 +261,13 @@ class ResidentEngine:
self.ctx = ctx
self.cache = Cache(self.model, max_num_tokens=ctx + 4096,
max_history=max_history)
- self.model.load(device="cuda:0", progressbar=False)
+ startup_health.stage("target weights")
+ self.model.load(device="cuda:0", progressbar=False, callback=startup_health.load_callback())
self.draft_model = Model.from_config(self.config, component="mtp")
self.draft_cache = Cache(self.draft_model, max_num_tokens=ctx + 4096,
max_history=max_history)
- self.draft_model.load(device="cuda:0", progressbar=False)
+ startup_health.stage("drafter weights")
+ self.draft_model.load(device="cuda:0", progressbar=False, callback=startup_health.load_callback())
self.greedy_generator = Generator(
model=self.model, cache=self.cache, tokenizer=self.tokenizer,
draft_model=self.draft_model, draft_cache=self.draft_cache, num_draft_tokens=num_draft,
@@ -413,6 +418,7 @@ def prime_dense_tune(budget_s: float = 600.0) -> tuple[int, float]:
have.add((f[0], int(f[1]), int(f[2]), int(f[3]), int(f[4]), int(f[5])))
tag = f[0] # the last line carries the running library's tag (the C++ side appends)
# Keys the C++ tuner already holds cost nothing to skip: no buffers, no GEMM.
+ startup_health.stage("dense GEMM tuning")
todo = [(n, k, ldn, f32, mc) for n, k, ldn, f32 in sorted(shapes) for mc in sorted(classes)
if (tag, n, k, mc, ldn, f32) not in have]
print(f"serve: dense GEMM prime: {len(todo)} of {len(shapes) * len(classes)} keys missing", flush=True)
@@ -445,6 +451,7 @@ def prime_dense_tune(budget_s: float = 600.0) -> tuple[int, float]:
c = c_buf[:mc * w * dt.itemsize].view(dt).view(mc, w)
ext.hgemm_recon(a, b, c if ldn else c[:, :n])
done += 1
+ startup_health.progress(done, len(todo))
torch.cuda.synchronize()
del a_buf, b_buf, c_buf
torch.cuda.empty_cache()
@@ -791,35 +798,46 @@ def main() -> None:
os.environ.setdefault(key, value)
os.environ.setdefault("EXL3_MOE_UNION_V2", "1")
apply_eh_sidecar_default(args.model)
- 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")
- print(mem_line("loaded"), flush=True)
- # Warm-up before the slot store is attached, so the warm-up prompt never shows in /slots.
- # EXL3_SERVE_WARMUP=0 skips it.
- if os.environ.get("EXL3_SERVE_WARMUP", "1") != "0":
- print(f"serve: warm-up {warmup(engine, template):.1f} s", flush=True)
- print(mem_line("warm"), flush=True)
- if os.environ.get("EXL3_SERVE_EMPTY_CACHE", "1") == "1": # lever (a): drop the allocator's inactive slack
- import torch
- torch.cuda.empty_cache()
- print(mem_line("emptied"), flush=True)
- if os.environ.get("EXL3_SERVE_MEMDIAG") == "1":
- mem_diag("warm")
- # EXL3_SERVE_DTUNE_PRIME_S: time budget for pre-tuning dense GEMM classes (0 = skip)
- budget = float(os.environ.get("EXL3_SERVE_DTUNE_PRIME_S", "600"))
- if budget > 0:
- keys, secs = prime_dense_tune(budget)
- print(f"serve: dense GEMM prime {keys} keys {secs:.1f} s", flush=True)
- print(mem_line("primed"), flush=True)
- from exllamav3.generator.slot_store import SlotStore
- engine.slot_store = SlotStore(engine.greedy_generator, [engine.cache, engine.draft_cache],
- args.slot_save_path, args.model_id)
- if os.environ.get("EXL3_SERVE_RSS_LOG"): # rssleak1: per-request host-RSS accounting, off by default
- sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
- from rss_probe import install
- install(engine)
- print(f"serve: rss probe -> {os.environ['EXL3_SERVE_RSS_LOG']}", flush=True)
- web.run_app(create_app(engine, args.model_id, template), host=args.host, port=args.port)
+ warm = os.environ.get("EXL3_SERVE_WARMUP", "1") != "0"
+ tune = warm and float(os.environ.get("EXL3_SERVE_DTUNE_PRIME_S", "600")) > 0
+ stages = ["target weights", "drafter weights"] + (["warm-up"] if warm else []) + (["dense GEMM tuning"] if tune else [])
+ startup_health.start("glm", stages, args.host, args.port)
+ 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")
+ print(mem_line("loaded"), flush=True)
+ # Warm-up before the slot store is attached, so the warm-up prompt never shows in /slots.
+ # EXL3_SERVE_WARMUP=0 skips it.
+ if os.environ.get("EXL3_SERVE_WARMUP", "1") != "0":
+ startup_health.stage("warm-up")
+ print(f"serve: warm-up {warmup(engine, template):.1f} s", flush=True)
+ print(mem_line("warm"), flush=True)
+ if os.environ.get("EXL3_SERVE_EMPTY_CACHE", "1") == "1": # lever (a): drop the allocator's inactive slack
+ import torch
+ torch.cuda.empty_cache()
+ print(mem_line("emptied"), flush=True)
+ if os.environ.get("EXL3_SERVE_MEMDIAG") == "1":
+ mem_diag("warm")
+ # EXL3_SERVE_DTUNE_PRIME_S: time budget for pre-tuning dense GEMM classes (0 = skip)
+ budget = float(os.environ.get("EXL3_SERVE_DTUNE_PRIME_S", "600"))
+ if budget > 0:
+ keys, secs = prime_dense_tune(budget)
+ print(f"serve: dense GEMM prime {keys} keys {secs:.1f} s", flush=True)
+ print(mem_line("primed"), flush=True)
+ from exllamav3.generator.slot_store import SlotStore
+ engine.slot_store = SlotStore(engine.greedy_generator, [engine.cache, engine.draft_cache],
+ args.slot_save_path, args.model_id)
+ if os.environ.get("EXL3_SERVE_RSS_LOG"): # rssleak1: per-request host-RSS accounting, off by default
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+ from rss_probe import install
+ install(engine)
+ print(f"serve: rss probe -> {os.environ['EXL3_SERVE_RSS_LOG']}", flush=True)
+ except BaseException as exc: # noqa: BLE001
+ 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)
if __name__ == "__main__":
diff --git a/tools/mimo/SERVE.md b/tools/mimo/SERVE.md
index 42509e3..3c11ee0 100644
--- a/tools/mimo/SERVE.md
+++ b/tools/mimo/SERVE.md
@@ -44,6 +44,37 @@ top-level config does not carry `max_position_embeddings` — the GLM fix.
carries the live counters `n_spec n_plain n_off n_shadow n_probe_fail t_plain t_spec
tok_round`. Useful while tuning.
+## Start-up progress on `/health`
+
+The port answers from the first second, while the model is still loading. `GET /health` returns `200 {"status":"ok"}`
+(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,
+ "stage_progress": 0.4, "elapsed_s": 52.1, "eta_s": null, "progress_basis": "stages"}
+```
+
+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
+`~/.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
+the `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 it
+room for a first start:
+
+```yaml
+healthCheckTimeout: 600 # seconds; a first start tunes kernels
+models:
+ "mimo":
+ proxy: http://127.0.0.1:${PORT}
+ checkEndpoint: /health
+ cmd: python tools/mimo/serve.py --port ${PORT}
+```
+
## SpecGate across mixed requests — decision
**Kept, not reset per request** (the default). The gate holds no prompt content: only smoothed
@@ -60,6 +91,7 @@ it is a debugging switch, not the default.
## Tests
python tools/mimo/test_serve.py # no GPU
+ python tools/test_startup_health.py # /health load progress, no GPU
python tools/mimo/test_toolcalls.py # tool-call parser, no GPU
No `exllamav3` import and no model: the tests drive the HTTP layer against a fake engine and cover
diff --git a/tools/mimo/serve.py b/tools/mimo/serve.py
index 5604219..c189aff 100644
--- a/tools/mimo/serve.py
+++ b/tools/mimo/serve.py
@@ -18,6 +18,7 @@ import asyncio
import json
import os
import re
+import sys
import time
import uuid
from collections.abc import AsyncIterator
@@ -28,6 +29,9 @@ import aiohttp
from aiohttp import web
from jinja2.sandbox import ImmutableSandboxedEnvironment
+sys.path.append(str(Path(__file__).resolve().parent.parent))
+import startup_health # noqa: E402 (GET /health with load progress while the model loads)
+
DEFAULT_MODEL = os.path.expanduser("~/models/mimo26-exl3")
DEFAULT_MODEL_ID = "MiMo-2.6-EXL3"
DEFAULT_CTX = 4096
@@ -258,8 +262,12 @@ class ResidentEngine:
model_init.add_args(parser, cache=True, add_draft_model_args=True)
args = parser.parse_args(argv)
+ # model_init.init loads the drafter first, then the target, through one call: a drop of the module counter
+ # moves /health to the next stage.
+ weight_stages = (["drafter weights"] if drafter_path else []) + ["target weights"]
(self.model, self.config, self.cache, self.tokenizer, self.draft_model,
- self.draft_config, self.draft_cache) = model_init.init(args)
+ self.draft_config, self.draft_cache) = model_init.init(args, callback=startup_health.load_callback(weight_stages))
+ startup_health.stage("engine setup")
self.ndt = ndt if drafter_path else 1
self.drafter_path = drafter_path
self.generator = Generator(
@@ -748,20 +756,28 @@ def main() -> None:
print(f"msrv: no drafter found ({explicit or 'looked in <model>/drafter and <model>-drafter'}); "
"decoding without speculation", flush=True)
+ stages = (["drafter weights"] if drafter else []) + ["target weights", "engine setup"]
+ startup_health.start("mimo", stages, args.host, args.port)
# --ctx 0 = the model's own max context, with the nested text_config handled like the GLM fix.
- probe = Config.from_directory(args.model)
- ctx = args.ctx or min(config_max_position(probe), 131072)
- engine = ResidentEngine(args.model, drafter, ndt=args.ndt, spec_gate=args.spec_gate, ctx=ctx,
- reset_gate_per_request=args.spec_gate_reset_per_request,
- dynamic_draft=args.dynamic_draft, draft_confidence=args.draft_confidence)
- from exllamav3.generator.slot_store import SlotStore
- engine.slot_store = SlotStore(engine.generator, [c for c in (engine.cache, engine.draft_cache) if c is not None],
- args.slot_save_path, args.model_id)
- template = (Path(args.model) / "chat_template.jinja").read_text(encoding="utf-8")
+ try:
+ probe = Config.from_directory(args.model)
+ ctx = args.ctx or min(config_max_position(probe), 131072)
+ engine = ResidentEngine(args.model, drafter, ndt=args.ndt, spec_gate=args.spec_gate, ctx=ctx,
+ reset_gate_per_request=args.spec_gate_reset_per_request,
+ dynamic_draft=args.dynamic_draft, draft_confidence=args.draft_confidence)
+ from exllamav3.generator.slot_store import SlotStore
+ engine.slot_store = SlotStore(engine.generator, [c for c in (engine.cache, engine.draft_cache) if c is not None],
+ args.slot_save_path, args.model_id)
+ template = (Path(args.model) / "chat_template.jinja").read_text(encoding="utf-8")
+ except BaseException as exc: # noqa: BLE001
+ startup_health.abort(f"{type(exc).__name__}: {exc}")
+ raise
print(f"msrv: model={args.model} drafter={drafter} ndt={args.ndt} "
f"spec_gate={engine.spec_gate_on} ctx={ctx} "
f"max_position={config_max_position(engine.config)}", flush=True)
- web.run_app(create_app(engine, args.model_id, template), host=args.host, port=args.port)
+ 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)
if __name__ == "__main__":
diff --git a/tools/qwen/SERVE.md b/tools/qwen/SERVE.md
index 1f96ea7..d6da2f0 100644
--- a/tools/qwen/SERVE.md
+++ b/tools/qwen/SERVE.md
@@ -82,6 +82,37 @@ environment wins. The engine modules read several of these when they are importe
forgets the prompt cache first (cold run), `"return_token_ids": true` adds the generated ids. Switching
speculative mode or `cache_prompt: false` rebuilds the Generator and so drops the prompt cache.
+## Start-up progress on `/health`
+
+The port answers from the first second, while the model is still loading. `GET /health` returns `200 {"status":"ok"}`
+(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,
+ "stage_progress": 0.4, "elapsed_s": 52.1, "eta_s": null, "progress_basis": "stages"}
+```
+
+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
+`~/.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
+the `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 it
+room for a first start:
+
+```yaml
+healthCheckTimeout: 300 # seconds; a first start tunes kernels
+models:
+ "qwen":
+ proxy: http://127.0.0.1:${PORT}
+ checkEndpoint: /health
+ cmd: python tools/qwen/serve.py --port ${PORT}
+```
+
## Prompt cache between turns
The Generator keeps KV pages (256 tokens) and GDN recurrent checkpoints in RAM (4 GiB, about 111 MiB each). A follow-up
@@ -90,7 +121,7 @@ new text. `timings.prompt_n` shows how many tokens were prefilled. Requests are
## Tests
- python -m pytest tools/qwen/test_serve.py tools/qwen/test_guard.py # CPU, fake engine, no GPU (template test needs the pack)
+ python -m pytest tools/test_startup_health.py tools/qwen/test_serve.py tools/qwen/test_guard.py # CPU, fake engine, no GPU (template test needs the pack)
python tools/qwen/serve_check.py http://127.0.0.1:8000 out_dir # live server: chat, thinking, tools, stream, image,
# 3-turn cache, plain vs speculative, warm vs cold
diff --git a/tools/qwen/serve.py b/tools/qwen/serve.py
index 1446476..b31c4c1 100644
--- a/tools/qwen/serve.py
+++ b/tools/qwen/serve.py
@@ -36,6 +36,8 @@ from aiohttp import web
HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
+sys.path.append(str(HERE.parent))
+import startup_health # noqa: E402 (GET /health with load progress while the model loads)
def _load_mimo():
@@ -628,26 +630,30 @@ class QwenEngine:
if os.environ.get("EXL3_WARM_DENSE", "1") != "0":
from exllamav3.model.dense_warmup import seed_dense_tune
seed_dense_tune()
+ startup_health.stage("target weights")
with Heartbeat("loading target model"):
- self.model.load(max_chunk_size=max_chunk_size, progressbar=False)
+ self.model.load(max_chunk_size=max_chunk_size, progressbar=False, callback=startup_health.load_callback())
from exllamav3.modules.hyperconnections import GS_STATS
print("qserve: hc mixer sites by code source", dict(GS_STATS), flush=True)
self.draft_model = self.draft_cache = None
if draft_policy != "off":
self.draft_model = Model.from_config(self.config, component="mtp")
self.draft_cache = Cache(self.draft_model, max_num_tokens=ctx, max_history=3, **qkw)
+ startup_health.stage("drafter weights")
with Heartbeat("loading MTP drafter"):
- self.draft_model.load(progressbar=False)
+ self.draft_model.load(progressbar=False, callback=startup_health.load_callback())
self.vision = None
if vision:
try:
self.vision = Model.from_config(self.config, component="vision")
+ startup_health.stage("vision tower")
with Heartbeat("loading vision tower"):
- self.vision.load(progressbar=False)
+ self.vision.load(progressbar=False, callback=startup_health.load_callback())
except Exception as exc: # noqa: BLE001
self.vision = None
print(f"qserve: vision tower not loaded ({exc!r}); image input disabled", flush=True)
self.supports_vision = self.vision is not None
+ startup_health.stage("engine setup")
self._ngram_resident()
self.generator = self.uninstall = None
self.spec_on = self.draft_model is not None
@@ -1504,6 +1510,27 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, An
# ---------------------------------------------------------------------------- main
+def load_all(args: argparse.Namespace):
+ """Everything before the port opens: template, defaults, engine, slot store, warm-up."""
+ model_dir = str(Path(args.model).expanduser())
+ template = (Path(model_dir) / "chat_template.jinja").read_text(encoding="utf-8")
+ defaults = load_defaults(model_dir, args)
+ t0 = time.time()
+ print(f"qserve: starting, model={model_dir} ctx={args.ctx} draft_policy={args.draft_policy} "
+ f"defaults={ {k: v for k, v in defaults.items() if v is not None} }", flush=True)
+ engine = QwenEngine(model_dir, args.ctx, ndt=args.ndt, draft_policy=args.draft_policy, vision=not args.no_vision,
+ cache_bits=args.cache_bits)
+ env = {k: v for k, v in sorted(os.environ.items()) if k.startswith(("EXL3_", "MPW"))}
+ print(f"qserve: effective env {env}", flush=True)
+ from exllamav3.generator.slot_store import SlotStore
+ engine.slot_store = SlotStore(engine.generator, [c for c in (engine.cache, engine.draft_cache) if c is not None],
+ args.slot_save_path, args.model_id)
+ startup_health.stage("warm-up")
+ with Heartbeat("warm-up (first decode steps)"):
+ engine.warmup()
+ return engine, template, defaults, model_dir, t0
+
+
def main() -> None:
parser = argparse.ArgumentParser(allow_abbrev=False, description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
@@ -1532,26 +1559,21 @@ def main() -> None:
if args.no_uncensor:
os.environ["EXL3_ABLIT_RUNTIME"] = "off"
- model_dir = str(Path(args.model).expanduser())
- template = (Path(model_dir) / "chat_template.jinja").read_text(encoding="utf-8")
- defaults = load_defaults(model_dir, args)
- t0 = time.time()
- print(f"qserve: starting, model={model_dir} ctx={args.ctx} draft_policy={args.draft_policy} "
- f"defaults={ {k: v for k, v in defaults.items() if v is not None} }", flush=True)
- engine = QwenEngine(model_dir, args.ctx, ndt=args.ndt, draft_policy=args.draft_policy, vision=not args.no_vision,
- cache_bits=args.cache_bits)
- env = {k: v for k, v in sorted(os.environ.items()) if k.startswith(("EXL3_", "MPW"))}
- print(f"qserve: effective env {env}", flush=True)
- from exllamav3.generator.slot_store import SlotStore
- engine.slot_store = SlotStore(engine.generator, [c for c in (engine.cache, engine.draft_cache) if c is not None],
- args.slot_save_path, args.model_id)
- with Heartbeat("warm-up (first decode steps)"):
- engine.warmup()
+ # /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)
+ try:
+ engine, template, defaults, model_dir, t0 = load_all(args)
+ except BaseException as exc: # noqa: BLE001
+ startup_health.abort(f"{type(exc).__name__}: {exc}")
+ raise
app = create_app(engine, args.model_id, template, defaults, args.default_max_tokens)
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()
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)",
diff --git a/tools/startup_health.py b/tools/startup_health.py
new file mode 100644
index 0000000..97a7c49
--- /dev/null
+++ b/tools/startup_health.py
@@ -0,0 +1,232 @@
+"""Start-up progress for the Kyojin servers: GET /health answers while the model is still loading.
+
+The servers open their HTTP port only after the model is loaded, which can take minutes (GLM tunes kernels for
+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,
+ "stage_progress": 0.4, "elapsed_s": 52.1, "eta_s": null, "progress_basis": "stages"}
+ 500 {"status": "error", "message": "..."}
+
+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
+(then it adds the old durations of the stages to come, so a stage that is much faster the second time, e.g. cached
+kernel tuning, makes it an upper bound).
+Nothing here imports torch. The servers call `stage()`, `progress()` and `load_callback()`; all are no-ops when no
+tracker is active (tests, library use).
+"""
+from __future__ import annotations
+
+import json
+import os
+import threading
+import time
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from pathlib import Path
+
+LOADING_BODY = {"error": {"message": "Loading model", "type": "unavailable_error", "code": 503}}
+ACTIVE: "StartupTracker | None" = None
+
+
+def history_dir() -> Path:
+ return Path(os.environ.get("KYOJIN_HEALTH_DIR") or "~/.cache/kyojin").expanduser()
+
+
+class 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):
+ 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")
+ self.lock = threading.Lock()
+ self.t0 = clock()
+ self.state = "loading"
+ self.message = ""
+ self.current = 0
+ self.stage_t0 = self.t0
+ self.fraction: float | None = None
+ self.durations: dict[str, float] = {}
+ self.expected = self._load_history()
+ self.server: _EarlyServer | None = None
+
+ def _load_history(self) -> dict[str, float] | None:
+ try:
+ data = json.loads(Path(self.history_path).read_text())
+ exp = {s: float(data[s]) for s in self.stages}
+ except (OSError, ValueError, KeyError, TypeError):
+ return None
+ return exp if all(v > 0 for v in exp.values()) else None
+
+ # ---- updates (called by the loader)
+
+ def begin(self, stage: str) -> None:
+ """Enter `stage`. Earlier stages count as finished; a stage that is skipped is simply finished."""
+ with self.lock:
+ idx = self.stages.index(stage)
+ if idx <= self.current:
+ return # same stage again, or backwards: ignore
+ now = self.clock()
+ self.durations[self.stages[self.current]] = now - self.stage_t0
+ self.current, self.stage_t0, self.fraction = idx, now, None
+
+ def progress(self, done: float, total: float) -> None:
+ if total and total > 0:
+ with self.lock:
+ self.fraction = min(max(done / total, 0.0), 1.0)
+
+ def ready(self) -> None:
+ with self.lock:
+ now = self.clock()
+ self.durations[self.stages[self.current]] = now - self.stage_t0
+ self.state = "ready"
+ self._save_history()
+
+ def fail(self, message: str) -> None:
+ with self.lock:
+ self.state, self.message = "error", message
+
+ def _save_history(self) -> None:
+ if set(self.durations) != set(self.stages):
+ return # a run that skipped stages teaches nothing
+ try:
+ Path(self.history_path).parent.mkdir(parents=True, exist_ok=True)
+ Path(self.history_path).write_text(json.dumps({k: round(v, 3) for k, v in self.durations.items()}))
+ except OSError:
+ pass
+
+ # ---- reading
+
+ def snapshot(self) -> tuple[int, dict]:
+ with self.lock:
+ now = self.clock()
+ elapsed = round(now - self.t0, 1)
+ if self.state == "ready":
+ return 200, {"status": "ok"}
+ if self.state == "error":
+ return 500, {"status": "error", "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
+ if exp:
+ total = sum(exp.values())
+ done = sum(exp[s] for s in self.stages[:cur]) + exp[self.stages[cur]] * (frac or 0.0)
+ progress, basis = done / total, "history"
+ if frac is not None and frac >= 0.02: # this run's own pace beats the old duration
+ left = stage_elapsed * (1 - frac) / frac
+ elif frac is not None:
+ left = exp[self.stages[cur]]
+ else:
+ left = exp[self.stages[cur]] - stage_elapsed
+ 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),
+ "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),
+ "progress_basis": basis}
+
+ # ---- early listener
+
+ def serve(self, host: str, port: int) -> None:
+ 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."""
+ if self.server is not None:
+ self.server.close()
+ self.server = None
+
+
+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":
+ code, body = tracker.snapshot()
+ else:
+ code, body = 503, LOADING_BODY
+ data = json.dumps(body).encode()
+ self.send_response(code)
+ self.send_header("Content-Type", "application/json")
+ self.send_header("Content-Length", str(len(data)))
+ self.send_header("Retry-After", "5")
+ self.send_header("Connection", "close")
+ self.end_headers()
+ if self.command != "HEAD":
+ self.wfile.write(data)
+
+ do_GET = do_HEAD = do_POST = do_PUT = do_DELETE = _reply
+
+ def log_message(self, *args):
+ pass
+
+ class Server(ThreadingHTTPServer):
+ daemon_threads = True
+ allow_reuse_address = True
+
+ self.httpd = Server((host, port), Handler)
+ self.port = self.httpd.server_address[1]
+ self.thread = threading.Thread(target=self.httpd.serve_forever, daemon=True, name="startup-health")
+ self.thread.start()
+
+ def close(self) -> None:
+ self.httpd.shutdown()
+ self.httpd.server_close()
+ self.thread.join(timeout=5)
+
+
+# ---- 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."""
+ global ACTIVE
+ ACTIVE = StartupTracker(name, stages)
+ ACTIVE.serve(host, port)
+ return ACTIVE
+
+
+def stage(name: str) -> None:
+ if ACTIVE is not None and name in ACTIVE.stages:
+ ACTIVE.begin(name)
+
+
+def progress(done: float, total: float) -> None:
+ if ACTIVE is not None:
+ ACTIVE.progress(done, total)
+
+
+def load_callback(stages: list[str] | None = None):
+ """Callback for Model.load(callback=...), called as (modules_done, modules_total) before each module.
+ With `stages`, a drop of the counter means the next model started, and the next stage begins (several
+ models loaded through one call, e.g. drafter then target in model_init.init)."""
+ state = {"last": -1, "i": 0}
+
+ def cb(done: int, total: int) -> None:
+ if stages and done < state["last"]:
+ state["i"] = min(state["i"] + 1, len(stages) - 1)
+ state["last"] = done
+ if stages:
+ stage(stages[state["i"]])
+ progress(done, total)
+ if stages:
+ stage(stages[0])
+ 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 abort(message: str, grace_s: float = 3.0) -> None:
+ """Load failed: report it on /health for a moment before the process exits."""
+ if ACTIVE is not None:
+ ACTIVE.fail(message)
+ time.sleep(grace_s)
diff --git a/tools/test_startup_health.py b/tools/test_startup_health.py
new file mode 100644
index 0000000..458439f
--- /dev/null
+++ b/tools/test_startup_health.py
@@ -0,0 +1,332 @@
+"""CPU tests of tools/startup_health.py (GET /health with load progress) and of its wiring in the three servers.
+
+Run: cd tools && python3 -m unittest test_startup_health
+"""
+from __future__ import annotations
+
+import ast
+import asyncio
+import json
+import socket
+import sys
+import tempfile
+import threading
+import unittest
+import urllib.error
+import urllib.request
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).parent))
+import startup_health as sh # noqa: E402
+
+TOOLS = Path(__file__).parent
+
+
+class Clock:
+ def __init__(self):
+ self.t = 100.0
+
+ def __call__(self):
+ return self.t
+
+
+def tracker(stages, history=None, clock=None):
+ return sh.StartupTracker("t", stages, clock=clock or Clock(), history=history or Path("/nonexistent/none.json"))
+
+
+def get(url: str):
+ try:
+ with urllib.request.urlopen(url, timeout=5) as r:
+ return r.status, json.loads(r.read()), r.headers
+ except urllib.error.HTTPError as e:
+ return e.code, json.loads(e.read()), e.headers
+
+
+class SnapshotTest(unittest.TestCase):
+ def test_first_stage_at_zero(self):
+ t = tracker(["a", "b"])
+ code, body = t.snapshot()
+ self.assertEqual(code, 503)
+ self.assertEqual((body["status"], body["stage"], body["stage_index"], body["stage_count"]), ("loading", "a", 1, 2))
+ self.assertEqual(body["progress"], 0.0)
+ self.assertIsNone(body["stage_progress"])
+ self.assertIsNone(body["eta_s"])
+ self.assertEqual(body["progress_basis"], "stages")
+
+ def test_progress_counts_finished_stages_and_reported_fraction(self):
+ c = Clock()
+ t = tracker(["a", "b", "c", "d"], clock=c)
+ t.progress(1, 2)
+ self.assertEqual(t.snapshot()[1]["progress"], 0.125)
+ c.t += 30
+ t.begin("b")
+ body = t.snapshot()[1]
+ self.assertEqual((body["stage"], body["stage_index"], body["progress"], body["stage_progress"]), ("b", 2, 0.25, None))
+ self.assertEqual(body["elapsed_s"], 30.0)
+ t.progress(3, 4)
+ self.assertEqual(t.snapshot()[1]["progress"], 0.438) # (1 + 0.75) / 4, rounded
+
+ def test_unknown_stage_progress_stays_unknown_not_guessed(self):
+ c = Clock()
+ t = tracker(["a", "b"], clock=c)
+ c.t += 500 # a long stage with no counter
+ body = t.snapshot()[1]
+ self.assertEqual(body["progress"], 0.0)
+ self.assertIsNone(body["stage_progress"])
+ self.assertIsNone(body["eta_s"])
+
+ def test_never_reports_one_while_loading(self):
+ t = tracker(["a"])
+ t.progress(10, 10)
+ self.assertLess(t.snapshot()[1]["progress"], 1.0)
+
+ def test_stage_never_goes_backwards_and_repeat_keeps_fraction(self):
+ t = tracker(["a", "b"])
+ t.begin("b")
+ t.progress(1, 2)
+ t.begin("a")
+ t.begin("b")
+ body = t.snapshot()[1]
+ self.assertEqual((body["stage"], body["stage_progress"]), ("b", 0.5))
+
+ def test_ready_error(self):
+ t = tracker(["a"])
+ t.ready()
+ self.assertEqual(t.snapshot(), (200, {"status": "ok"}))
+ t = tracker(["a"])
+ t.fail("boom")
+ code, body = t.snapshot()
+ self.assertEqual((code, body["status"], body["message"]), (500, "error", "boom"))
+
+ def test_progress_ignores_zero_total(self):
+ t = tracker(["a"])
+ t.progress(0, 0)
+ self.assertIsNone(t.snapshot()[1]["stage_progress"])
+
+
+class HistoryTest(unittest.TestCase):
+ def setUp(self):
+ self.dir = tempfile.TemporaryDirectory()
+ self.path = Path(self.dir.name) / "h.json"
+
+ def tearDown(self):
+ self.dir.cleanup()
+
+ def run_start(self, stages, durations, skip=()):
+ c = Clock()
+ t = tracker(stages, history=self.path, clock=c)
+ for s in stages:
+ if s in skip:
+ continue
+ t.begin(s)
+ c.t += durations[s]
+ t.ready()
+
+ def test_history_saved_and_used_for_eta_and_weights(self):
+ self.run_start(["a", "b", "c"], {"a": 60, "b": 30, "c": 10})
+ self.assertEqual(json.loads(self.path.read_text()), {"a": 60.0, "b": 30.0, "c": 10.0})
+ c = Clock()
+ t = tracker(["a", "b", "c"], history=self.path, clock=c)
+ c.t += 20
+ body = t.snapshot()[1]
+ self.assertEqual(body["progress_basis"], "history")
+ self.assertEqual(body["progress"], 0.0) # no fraction reported: no guess
+ self.assertEqual(body["eta_s"], 80.0) # (60 - 20) + 30 + 10
+ t.progress(1, 2)
+ t.begin("b")
+ self.assertEqual(t.snapshot()[1]["progress"], 0.6) # 60 of 100 s done
+
+ def test_eta_uses_current_pace_when_fraction_known(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) # 10 s for half: 10 s left, not 590
+ self.assertEqual(t.snapshot()[1]["eta_s"], 20.0) # 10 + the next stage's 10
+
+ def test_overrun_stage_without_counter_has_no_eta(self):
+ self.run_start(["a", "b"], {"a": 10, "b": 10})
+ c = Clock()
+ t = tracker(["a", "b"], history=self.path, clock=c)
+ c.t += 50
+ self.assertIsNone(t.snapshot()[1]["eta_s"])
+
+ def test_run_that_skipped_a_stage_saves_nothing(self):
+ self.run_start(["a", "b"], {"a": 5, "b": 5}, skip=("b",))
+ self.assertFalse(self.path.exists())
+
+ def test_history_for_other_stage_list_is_ignored(self):
+ self.path.write_text(json.dumps({"a": 5, "z": 5}))
+ t = tracker(["a", "b"], history=self.path)
+ self.assertEqual(t.snapshot()[1]["progress_basis"], "stages")
+
+ def test_corrupt_history_is_ignored(self):
+ self.path.write_text("{nope")
+ self.assertEqual(tracker(["a"], history=self.path).snapshot()[1]["progress_basis"], "stages")
+
+
+class LoadCallbackTest(unittest.TestCase):
+ def setUp(self):
+ self.t = tracker(["drafter", "target", "setup"])
+ sh.ACTIVE = self.t
+
+ def tearDown(self):
+ sh.ACTIVE = None
+
+ def test_single_model_reports_module_fraction(self):
+ cb = sh.load_callback()
+ cb(0, 10)
+ cb(5, 10)
+ self.assertEqual(self.t.snapshot()[1]["stage_progress"], 0.5)
+
+ def test_two_models_one_call_roll_to_the_next_stage(self):
+ cb = sh.load_callback(["drafter", "target"])
+ for i in range(4):
+ cb(i, 4)
+ self.assertEqual(self.t.snapshot()[1]["stage"], "drafter")
+ cb(0, 40) # the counter dropped: the target started
+ body = self.t.snapshot()[1]
+ self.assertEqual((body["stage"], body["stage_progress"]), ("target", 0.0))
+ cb(20, 40)
+ self.assertEqual(self.t.snapshot()[1]["stage_progress"], 0.5)
+
+ def test_helpers_are_noops_without_tracker_or_for_unknown_stage(self):
+ sh.stage("nope") # unknown name: ignored
+ self.assertEqual(self.t.snapshot()[1]["stage"], "drafter")
+ sh.ACTIVE = None
+ sh.stage("target")
+ sh.progress(1, 2)
+ sh.load_callback()(1, 2)
+ sh.finish()
+ sh.abort("x")
+
+
+class ListenerTest(unittest.TestCase):
+ def test_health_and_other_paths_while_loading_then_handoff(self):
+ c = Clock()
+ t = tracker(["weights", "warm-up"], clock=c)
+ t.serve("127.0.0.1", 0)
+ port = t.server.port
+ try:
+ c.t += 12
+ t.progress(1, 4)
+ code, body, headers = get(f"http://127.0.0.1:{port}/health")
+ self.assertEqual(code, 503)
+ self.assertEqual((body["status"], body["stage"], body["stage_progress"], body["elapsed_s"]),
+ ("loading", "weights", 0.25, 12.0))
+ self.assertEqual(headers["Retry-After"], "5")
+ code, body, _ = get(f"http://127.0.0.1:{port}/v1/models") # llama.cpp style: 503 "Loading model"
+ self.assertEqual((code, body["error"]["message"]), (503, "Loading model"))
+ code, body, _ = get(f"http://127.0.0.1:{port}/health?x=1")
+ self.assertEqual(code, 503)
+ req = urllib.request.Request(f"http://127.0.0.1:{port}/v1/chat/completions", data=b"{}", method="POST")
+ with self.assertRaises(urllib.error.HTTPError) as cm:
+ urllib.request.urlopen(req, timeout=5)
+ self.assertEqual(cm.exception.code, 503)
+ t.fail("kernel build failed")
+ code, body, _ = get(f"http://127.0.0.1:{port}/health")
+ self.assertEqual((code, body["status"], body["message"]), (500, "error", "kernel build failed"))
+ finally:
+ t.release_port()
+ with self.assertRaises(OSError): # the port is closed after the handoff
+ socket.create_connection(("127.0.0.1", port), timeout=1)
+
+ def test_port_is_answering_before_the_load_and_real_server_binds_after(self):
+ """The early listener and an aiohttp TCPSite take the same port one after the other."""
+ from aiohttp import web
+ t = tracker(["weights"])
+ t.serve("127.0.0.1", 0)
+ port = t.server.port
+ self.assertEqual(get(f"http://127.0.0.1:{port}/health")[0], 503) # before any model code runs
+ result = {}
+
+ async def run():
+ app = web.Application()
+
+ async def health(_):
+ return web.json_response({"status": "ok", "model": "m"})
+ app.router.add_get("/health", health)
+ runner = web.AppRunner(app)
+ await runner.setup()
+ t.release_port()
+ t.ready()
+ await web.TCPSite(runner, "127.0.0.1", port).start()
+ result["r"] = await asyncio.get_running_loop().run_in_executor(None, get, f"http://127.0.0.1:{port}/health")
+ await runner.cleanup()
+ asyncio.run(run())
+ self.assertEqual(result["r"][0], 200)
+ self.assertEqual(result["r"][1]["model"], "m")
+
+ def test_start_fails_fast_when_the_port_is_taken(self):
+ s = socket.socket()
+ s.bind(("127.0.0.1", 0))
+ s.listen(1)
+ try:
+ with self.assertRaises(OSError):
+ sh.start("t", ["a"], "127.0.0.1", s.getsockname()[1])
+ finally:
+ s.close()
+ sh.ACTIVE = None
+
+ def test_concurrent_polls(self):
+ t = tracker(["a"])
+ t.serve("127.0.0.1", 0)
+ codes = []
+ threads = [threading.Thread(target=lambda: codes.append(get(f"http://127.0.0.1:{t.server.port}/health")[0]))
+ for _ in range(8)]
+ [x.start() for x in threads]
+ [x.join() for x in threads]
+ t.release_port()
+ self.assertEqual(codes, [503] * 8)
+
+
+class WiringTest(unittest.TestCase):
+ """The three servers call the same helper, in the right order, with stage names the lists declare."""
+
+ EXPECT = {
+ "qwen": {"target weights", "drafter weights", "vision tower", "engine setup", "warm-up"},
+ "glm": {"target weights", "drafter weights", "warm-up", "dense GEMM tuning"},
+ "mimo": {"target weights", "drafter weights", "engine setup"},
+ }
+
+ def calls(self, name):
+ src = (TOOLS / name / "serve.py").read_text()
+ tree = ast.parse(src)
+ out = []
+ for n in ast.walk(tree):
+ if isinstance(n, ast.Call) and isinstance(n.func, ast.Attribute) and isinstance(n.func.value, ast.Name) \
+ and n.func.value.id == "startup_health":
+ out.append((n.func.attr, n.lineno, [a.value for a in n.args if isinstance(a, ast.Constant)]))
+ return src, out
+
+ def test_each_server_starts_listener_and_releases_before_bind(self):
+ for name in self.EXPECT:
+ src, calls = self.calls(name)
+ attrs = {a for a, _, _ in calls}
+ self.assertTrue({"start", "stage", "finish", "abort", "load_callback"} <= attrs, name)
+ finish = min(l for a, l, _ in calls if a == "finish")
+ start = min(l for a, l, _ in calls if a == "start")
+ bind = src[: src.index("TCPSite(runner") if "TCPSite(runner" in src else src.index("web.run_app(app")].count("\n") + 1
+ self.assertLess(start, finish, name)
+ self.assertLess(finish, bind, name)
+
+ def test_stage_names_are_declared(self):
+ for name, expect in self.EXPECT.items():
+ _, calls = self.calls(name)
+ used = {args[0] for a, _, args in calls if a == "stage" and args}
+ self.assertTrue(used <= expect, (name, used - expect))
+ src = (TOOLS / name / "serve.py").read_text()
+ for stage in expect: # every declared stage is entered somewhere
+ self.assertIn(f'"{stage}"', src, (name, stage))
+
+ def test_mimo_loads_drafter_first_like_model_init(self):
+ src = (TOOLS.parent / "exllamav3" / "model_init.py").read_text()
+ 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_default_ready_line_unchanged(self):
+ self.assertIn("qserve: READY on http://", (TOOLS / "qwen" / "serve.py").read_text())
+
+
+if __name__ == "__main__":
+ unittest.main()