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.

Metrics: hand each request its own stats copy from the worker

Alex Nobert4a2cc4c78f62
diff --git a/tools/glm/serve.py b/tools/glm/serve.py
index 77ca88c..33cc4f3 100644
--- a/tools/glm/serve.py
+++ b/tools/glm/serve.py
@@ -455,7 +455,7 @@ def prime_dense_tune(budget_s: float = 600.0) -> tuple[int, float]:
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]] = asyncio.Queue()
+ queue: asyncio.Queue[tuple[dict[str, Any], asyncio.Queue, dict[str, Any]]] = asyncio.Queue()
lock = asyncio.Lock() # serializes generation with slot save/restore
processing = 0 # admitted requests; closure, app config is immutable after startup
app = web.Application(client_max_size=16 * 1024**2)
@@ -482,7 +482,7 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
async def worker() -> None:
nonlocal processing
while True:
- body, out = await queue.get()
+ body, out, request_stats = await queue.get()
cancel = body.get("_cancel")
if cancel is not None and cancel.is_set(): # the client left while the job was queued: no prefill, no decode
out.put_nowait(None)
@@ -500,6 +500,9 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
top_p=body.get("top_p", 1.0), stop=body.get("_stop", []),
cancel=body.get("_cancel")):
out.put_nowait(delta)
+ request_stats.update(getattr(engine, "last_stats", None) or {})
+ if request_stats:
+ observe(request_stats, body.get("_prompt_tokens") or int(request_stats.get("prompt_tokens", 0)))
out.put_nowait(None)
except Exception as exc:
out.put_nowait(exc)
@@ -552,6 +555,7 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
body["_stop"] = [stops] if isinstance(stops, str) else list(stops)
prompt = render_prompt(template, body["messages"], body.get("tools"), **template_kwargs(body))
prompt_tokens = engine.count_tokens(prompt)
+ body["_prompt_tokens"] = prompt_tokens
body["_room"] = reply_room(engine, prompt_tokens)
body["_prompt"] = prompt
for key in ("temperature", "top_p"):
@@ -570,8 +574,9 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
return base | {"choices": [{"index": 0, "delta": delta, "finish_reason": finish}]}
out: asyncio.Queue = asyncio.Queue()
+ request_stats: dict[str, Any] = {}
cancel = body["_cancel"] = asyncio.Event()
- await queue.put((body, out))
+ await queue.put((body, out, request_stats))
prefix = "<think>" if opens_thinking(prompt) else ""
def deltas() -> AsyncIterator[str]:
@@ -591,7 +596,7 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
def timings(raw: str) -> dict[str, Any]:
# llama.cpp names: the swap orchestrator reads cache_n as the verdict of a KV restore
- st = getattr(engine, "last_stats", None) or {}
+ st = request_stats
cache_n = int(st.get("cached_tokens", 0))
pre, gen = st.get("time_prefill") or 0.0, st.get("time_generate") or 0.0
n = int(st.get("new_tokens", 0))
@@ -638,7 +643,6 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
dict(call, index=n) for n, call in enumerate(message["tool_calls"])]})))
await response.write(sse(event({}, finish_for(message, text[len(prefix):])) |
{"usage": usage(text[len(prefix):]), "timings": timings(text)}))
- observe(getattr(engine, "last_stats", None) or {}, prompt_tokens)
await response.write(b"data: [DONE]\n\n")
await response.write_eof()
except ConnectionResetError:
@@ -672,7 +676,6 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
text, _ = stop_text(prefix + raw, body["_stop"])
message = parse_completion(text)
finish = finish_for(message, text[len(prefix):])
- observe(getattr(engine, "last_stats", None) or {}, prompt_tokens)
return web.json_response({
"id": request_id, "object": "chat.completion", "created": created, "model": model_id,
"choices": [{"index": 0, "message": message, "finish_reason": finish}],
@@ -726,8 +729,9 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
raise web.HTTPBadRequest(reason=str(exc)) from exc
out: asyncio.Queue = asyncio.Queue()
+ request_stats: dict[str, Any] = {}
cancel = job["_cancel"] = asyncio.Event()
- await queue.put((job, out))
+ await queue.put((job, out, request_stats))
text = ""
try:
async for item in drain(request, cancel, out):
@@ -741,8 +745,7 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
cancel.set()
raise
text, stopped = stop_text(text, job["_stop"])
- st = getattr(engine, "last_stats", None) or {}
- observe(st, int(st.get("prompt_tokens", 0)))
+ st = request_stats
return web.json_response({
"id": f"cmpl-{uuid.uuid4().hex}", "object": "completion", "created": int(time.time()),
"model": model_id, "content": text,
diff --git a/tools/glm/test_serve.py b/tools/glm/test_serve.py
index 24c15f2..83bee60 100644
--- a/tools/glm/test_serve.py
+++ b/tools/glm/test_serve.py
@@ -362,6 +362,52 @@ class ServeTests(unittest.TestCase):
self.assertEqual(v["llamacpp:requests_deferred"], 0)
self.assertEqual(v["llamacpp:kv_cache_usage_ratio"], 0) # fake engine: no get_cache_stats
+ def test_two_queued_requests_are_both_counted(self):
+ """Back-to-back requests each get their own timings handed over by the worker, so both are
+ counted in full even though engine.last_stats is a single shared attr reset per job."""
+ from aiohttp.test_utils import TestClient, TestServer
+
+ class QueuedEngine(FakeEngine):
+ def __init__(self):
+ super().__init__("")
+ self.calls = 0
+
+ async def generate(self, prompt, **kwargs):
+ self.prompts.append(prompt)
+ self.calls += 1
+ n = 3 * self.calls # distinct per request: 3 then 6
+ self.last_stats = {"cached_tokens": self.calls, "new_tokens": n,
+ "prompt_tokens": 20, "time_prefill": 0.5, "time_generate": 1.0,
+ "accepted_draft_tokens": 2, "rejected_draft_tokens": 2}
+ await asyncio.sleep(0) # let the second request sit queued behind this one
+ yield f"reply {self.calls}"
+
+ async def check():
+ engine = QueuedEngine()
+ client = TestClient(TestServer(serve.create_app(engine, "m", self.template)))
+ await client.start_server()
+ bodies = [
+ {"model": "m", "messages": [{"role": "user", "content": "one two three four"}]},
+ {"model": "m", "messages": [{"role": "user", "content": "five six seven eight nine"}]},
+ ]
+ responses = await asyncio.gather(*(client.post("/v1/chat/completions", json=b) for b in bodies))
+ for r in responses:
+ self.assertEqual(r.status, 200)
+ # each reply reports its own generation, not the shared attr's last value (which would be 6 for both)
+ payloads = await asyncio.gather(*(r.json() for r in responses))
+ predicted = sorted(p["timings"]["predicted_n"] for p in payloads)
+ self.assertEqual(predicted, [3, 6])
+ resp = await client.get("/metrics")
+ text = await resp.text()
+ await client.close()
+ return engine, text
+
+ engine, text = run(check())
+ v = metrics_samples(text)
+ # both generations counted in full: predicted = 3 + 6, not a prompt-only first request
+ self.assertEqual(v["llamacpp:tokens_predicted_total"], 9.0)
+ self.assertEqual(v["llamacpp:prompt_tokens_total"], float(sum(engine.count_tokens(p) for p in engine.prompts)))
+
if __name__ == "__main__":
unittest.main()
diff --git a/tools/mimo/serve.py b/tools/mimo/serve.py
index c3f7d84..8c65a64 100644
--- a/tools/mimo/serve.py
+++ b/tools/mimo/serve.py
@@ -357,7 +357,7 @@ class ResidentEngine:
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]] = asyncio.Queue()
+ queue: asyncio.Queue[tuple[dict[str, Any], asyncio.Queue, dict[str, Any]]] = asyncio.Queue()
lock = asyncio.Lock() # serializes generation with slot save/restore
processing = 0 # admitted requests; closure, app config is immutable after startup
app = web.Application(client_max_size=16 * 1024**2)
@@ -394,7 +394,7 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
async def worker() -> None:
nonlocal processing
while True:
- body, out = await queue.get()
+ body, out, request_stats = await queue.get()
cancel = body.get("_cancel")
if cancel is not None and cancel.is_set(): # the client left while the job was queued: no prefill, no decode
out.put_nowait(None)
@@ -414,6 +414,9 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
reset_gate=body.get("_reset_gate", False),
cancel=body.get("_cancel")):
out.put_nowait(delta)
+ request_stats.update(getattr(engine, "last_stats", None) or {})
+ if request_stats:
+ observe(request_stats, body.get("_prompt_tokens") or int(request_stats.get("prompt_tokens", 0)))
out.put_nowait(None)
except Exception as exc: # noqa: BLE001
out.put_nowait(exc)
@@ -467,6 +470,7 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
body["_reset_gate"] = bool(getattr(app["engine"], "reset_gate_per_request", False))
prompt = render_prompt(template, body["messages"], body.get("tools"))
prompt_tokens = engine.count_tokens(prompt)
+ body["_prompt_tokens"] = prompt_tokens
body["_room"] = reply_room(engine, prompt_tokens)
body["_prompt"] = prompt
for key in ("temperature", "top_p"): # absent or explicit null -> lane default
@@ -486,8 +490,9 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
return base | {"choices": [{"index": 0, "delta": delta, "finish_reason": finish}]}
out: asyncio.Queue = asyncio.Queue()
+ request_stats: dict[str, Any] = {}
cancel = body["_cancel"] = asyncio.Event()
- await queue.put((body, out))
+ await queue.put((body, out, request_stats))
# MiMo's generation prompt is "<|im_start|>assistant\n": no implicit <think> block.
def deltas() -> AsyncIterator[str]:
@@ -507,7 +512,7 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
def timings() -> dict[str, Any]:
# llama.cpp names: the swap orchestrator reads cache_n as the verdict of a KV restore
- st = getattr(engine, "last_stats", None) or {}
+ st = request_stats
cache_n = int(st.get("cached_tokens", 0))
pre, gen = st.get("time_prefill") or 0.0, st.get("time_generate") or 0.0
n = int(st.get("new_tokens", 0))
@@ -558,7 +563,6 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
dict(call, index=n) for n, call in enumerate(message["tool_calls"])]})))
await response.write(sse(event({}, finish_for(message, text)) |
{"usage": usage(text), "timings": timings()}))
- observe(getattr(engine, "last_stats", None) or {}, prompt_tokens)
await response.write(b"data: [DONE]\n\n")
await response.write_eof()
except ConnectionResetError:
@@ -593,7 +597,6 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
text, _ = stop_text(raw, body["_stop"])
message = parse_completion(text, body.get("tools"))
finish = finish_for(message, text)
- observe(getattr(engine, "last_stats", None) or {}, prompt_tokens)
return web.json_response({
"id": request_id, "object": "chat.completion", "created": created, "model": model_id,
"choices": [{"index": 0, "message": message, "finish_reason": finish}],
@@ -647,8 +650,9 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
raise web.HTTPBadRequest(reason=str(exc)) from exc
out: asyncio.Queue = asyncio.Queue()
+ request_stats: dict[str, Any] = {}
cancel = job["_cancel"] = asyncio.Event()
- await queue.put((job, out))
+ await queue.put((job, out, request_stats))
text = ""
try:
async for item in drain(request, cancel, out):
@@ -662,8 +666,7 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
cancel.set()
raise
text, stopped = stop_text(text, job["_stop"])
- st = getattr(engine, "last_stats", None) or {}
- observe(st, int(st.get("prompt_tokens", 0)))
+ st = request_stats
return web.json_response({
"id": f"cmpl-{uuid.uuid4().hex}", "object": "completion", "created": int(time.time()),
"model": model_id, "content": text,
diff --git a/tools/mimo/test_serve.py b/tools/mimo/test_serve.py
index cb198cd..92e71e3 100644
--- a/tools/mimo/test_serve.py
+++ b/tools/mimo/test_serve.py
@@ -448,6 +448,53 @@ class ServeTests(unittest.TestCase):
self.assertEqual(v["llamacpp:requests_deferred"], 0)
self.assertEqual(v["llamacpp:kv_cache_usage_ratio"], 0) # fake engine: no get_cache_stats
+ def test_two_queued_requests_are_both_counted(self):
+ """Back-to-back requests each get their own timings handed over by the worker, so both are
+ counted in full even though engine.last_stats is a single shared attr reset per job."""
+ from aiohttp.test_utils import TestClient, TestServer
+
+ class QueuedEngine(FakeEngine):
+ def __init__(self):
+ super().__init__("")
+ self.calls = 0
+
+ async def generate(self, prompt, **kwargs):
+ self.prompts.append(prompt)
+ self.calls += 1
+ n = 3 * self.calls # distinct per request: 3 then 6
+ self.last_stats = {"cached_tokens": self.calls, "new_tokens": n,
+ "prompt_tokens": 20, "time_prefill": 0.5, "time_generate": 1.0,
+ "accepted_draft_tokens": 2, "rejected_draft_tokens": 2}
+ self.last_rounds = self.calls
+ await asyncio.sleep(0) # let the second request sit queued behind this one
+ yield f"reply {self.calls}"
+
+ async def check():
+ engine = QueuedEngine()
+ client = TestClient(TestServer(serve.create_app(engine, "m", TEMPLATE)))
+ await client.start_server()
+ bodies = [
+ {"model": "m", "messages": [{"role": "user", "content": "one two three four"}]},
+ {"model": "m", "messages": [{"role": "user", "content": "five six seven eight nine"}]},
+ ]
+ responses = await asyncio.gather(*(client.post("/v1/chat/completions", json=b) for b in bodies))
+ for r in responses:
+ self.assertEqual(r.status, 200)
+ # each reply reports its own generation, not the shared attr's last value (which would be 6 for both)
+ payloads = await asyncio.gather(*(r.json() for r in responses))
+ predicted = sorted(p["timings"]["predicted_n"] for p in payloads)
+ self.assertEqual(predicted, [3, 6])
+ resp = await client.get("/metrics")
+ text = await resp.text()
+ await client.close()
+ return engine, text
+
+ engine, text = run(check())
+ v = metrics_samples(text)
+ # both generations counted in full: predicted = 3 + 6, not a prompt-only first request
+ self.assertEqual(v["llamacpp:tokens_predicted_total"], 9.0)
+ self.assertEqual(v["llamacpp:prompt_tokens_total"], float(sum(engine.count_tokens(p) for p in engine.prompts)))
+
if __name__ == "__main__":
unittest.main()