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: llama.cpp-compatible Prometheus /metrics via a shared collector in tools/serve_metrics.py
Alex Nobert0c73c4ee4394
diff --git a/tools/glm/SERVE.md b/tools/glm/SERVE.mdindex 1ab7b42..ebb8ae6 100644--- a/tools/glm/SERVE.md+++ b/tools/glm/SERVE.md@@ -62,6 +62,13 @@ python tools/glm/mtp_eh_sidecar.py <official GLM-5.3 checkpoint dir> <model fold### `GET /v1/models`One entry: `{"id": "<model-id>", "object": "model", "created": 0, "owned_by": "local"}`.+### `GET /metrics`+Prometheus text (llama.cpp `llamacpp:*` names) for scraping. Counters accumulate when a+request completes; `requests_processing`, `requests_deferred` and `kv_cache_usage_ratio`+are read live. `spec_decode_num_drafts_total` is derived from the accepted+rejected draft+token counts divided by `--num-draft` (exact except for a final MTP window truncated by+`max_tokens`).+### `POST /v1/chat/completions`Honored:diff --git a/tools/glm/serve.py b/tools/glm/serve.pyindex b5eef72..66c2640 100644--- a/tools/glm/serve.py+++ b/tools/glm/serve.py@@ -19,6 +19,9 @@ import aiohttpfrom aiohttp import webfrom jinja2.sandbox import ImmutableSandboxedEnvironment+sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) # tools/ for the shared serve_metrics+from serve_metrics import Metrics+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@@ -450,18 +453,37 @@ def prime_dense_tune(budget_s: float = 600.0) -> tuple[int, float]:return done, time.perf_counter() - t0-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)."""+def create_app(engine: Any, model_id: str, template: str, num_draft: int = 0) -> web.Application:+ """Build the HTTP layer around a resident engine (also accepts a fake engine in tests).++ num_draft: MTP draft tokens per verification round (args.num_draft); used only to derive+ llamacpp:spec_decode_num_drafts_total from the accepted+rejected draft token counts.+ """queue: asyncio.Queue[tuple[dict[str, Any], asyncio.Queue]] = asyncio.Queue()lock = asyncio.Lock() # serializes generation with slot save/restore+ processing = 0 # admitted requests; closure, app config is immutable after startupapp = web.Application(client_max_size=16 * 1024**2)- app.update(engine=engine, model_id=model_id, template=template, queue=queue)+ app.update(engine=engine, model_id=model_id, template=template, queue=queue, metrics=Metrics())++ def observe(st: dict[str, Any], prompt_tokens: int) -> None:+ # The MTP window is a fixed num_draft tokens, so rounds = proposed / num_draft+ # (exact except for a final window truncated by max_new_tokens).+ accepted = int(st.get("accepted_draft_tokens", 0))+ rejected = int(st.get("rejected_draft_tokens", 0))+ proposed = accepted + rejected+ app["metrics"].observe(+ prompt_tokens=prompt_tokens, cached=int(st.get("cached_tokens", 0)),+ predicted=int(st.get("new_tokens", 0)),+ prefill_s=float(st.get("time_prefill") or 0.0), generate_s=float(st.get("time_generate") or 0.0),+ drafts=proposed // max(num_draft, 1) if proposed else 0,+ draft_tokens=proposed, accepted=accepted)async def models(_: web.Request) -> web.Response:return web.json_response({"object": "list", "data": [{"id": model_id, "object": "model", "created": 0, "owned_by": "local"}]})async def worker() -> None:+ nonlocal processingwhile True:body, out = await queue.get()cancel = body.get("_cancel")@@ -470,6 +492,7 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:queue.task_done()continuestore = getattr(engine, "slot_store", None)+ processing += 1 # admitted: counted from the dequeue, incl. lock and slot restoretry:async with lock:if store is not None:@@ -484,6 +507,7 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:except Exception as exc:out.put_nowait(exc)finally:+ processing -= 1if store is not None:store.busy = Falsequeue.task_done()@@ -617,6 +641,7 @@ 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:@@ -636,7 +661,6 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:await response.write_eof()except ConnectionError:pass- return responsetry:raw = "".join([d async for d in deltas()])@@ -651,6 +675,7 @@ 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}],@@ -720,6 +745,7 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:raisetext, stopped = stop_text(text, job["_stop"])st = getattr(engine, "last_stats", None) or {}+ observe(st, int(st.get("prompt_tokens", 0)))return web.json_response({"id": f"cmpl-{uuid.uuid4().hex}", "object": "completion", "created": int(time.time()),"model": model_id, "content": text,@@ -753,10 +779,25 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:return web.json_response({"error": {"code": 400, "message": f"{type(exc).__name__}: {exc}", "type": "invalid_request_error"}},status=400)+ async def metrics_view(_: web.Request) -> web.Response:+ # used_tokens = pages referenced by active jobs: in-flight tokens, retained cache excluded.+ # get_cache_stats is memoized on the page tables; the except covers fake engines and a+ # page-table mutation in the worker thread mid-walk.+ gen = getattr(engine, "generator", None) or getattr(engine, "greedy_generator", None)+ try:+ cs = gen.get_cache_stats()+ kv = cs["used_tokens"] / cs["max_tokens"] if cs.get("max_tokens") else 0.0+ except Exception: # noqa: BLE001+ kv = 0.0+ return web.Response(body=app["metrics"].render(+ processing=processing, deferred=queue.qsize(), kv_ratio=kv),+ headers={"Content-Type": "text/plain; version=0.0.4; charset=utf-8"})+if getattr(engine, "slot_store", None) is not None:app.router.add_get("/slots", slots)app.router.add_post("/slots/{id}", slot_action)app.router.add_get("/v1/models", models)+ app.router.add_get("/metrics", metrics_view)app.router.add_post("/v1/chat/completions", completions)app.router.add_post("/apply-template", apply_template)app.router.add_post("/completion", completion)@@ -818,7 +859,8 @@ def main() -> None:from rss_probe import installinstall(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)+ web.run_app(create_app(engine, args.model_id, template, num_draft=args.num_draft),+ host=args.host, port=args.port)if __name__ == "__main__":diff --git a/tools/glm/test_serve.py b/tools/glm/test_serve.pyindex effda68..8aea51a 100644--- a/tools/glm/test_serve.py+++ b/tools/glm/test_serve.py@@ -22,6 +22,9 @@ class FakeEngine:async def generate(self, prompt: str, **kwargs):self.prompts.append(prompt)+ self.last_stats = {"cached_tokens": 8, "new_tokens": 4, "prompt_tokens": 20,+ "time_prefill": 0.5, "time_generate": 1.0,+ "accepted_draft_tokens": 6, "rejected_draft_tokens": 6}for i in range(0, len(self.output), 3): # small chunks cut tags in halfyield self.output[i:i + 3]@@ -30,6 +33,11 @@ def run(coro):return asyncio.run(coro)+def metrics_samples(text: str) -> dict:+ return {line.split()[0]: float(line.split()[1]) for line in text.splitlines()+ if line and not line.startswith("#")}++class ServeTests(unittest.TestCase):template = "{% for m in messages %}<|im_start|>{{ m.role }}: {{ m.content }}<|im_end|>{% endfor %}{% if tools %}TOOLS={{ tools|length }}{% endif %}"@@ -314,6 +322,41 @@ class ServeTests(unittest.TestCase):run(check())+ def test_metrics_endpoint(self):+ from aiohttp.test_utils import TestClient, TestServer+ engine = FakeEngine('hello there')+ app = serve.create_app(engine, "m", self.template, num_draft=2)++ async def check():+ client = TestClient(TestServer(app))+ await client.start_server()+ await client.post("/v1/chat/completions", json={+ "model": "m", "messages": [{"role": "user", "content": "one two three four"}]})+ resp = await client.get("/metrics")+ text = await resp.text()+ await client.close()+ return resp, text++ resp, text = run(check())+ self.assertEqual(resp.status, 200)+ self.assertTrue(resp.headers["Content-Type"].startswith("text/plain"))+ import serve_metrics+ for name, mtype, _ in serve_metrics.METRICS:+ self.assertIn(f"# HELP {name} ", text)+ self.assertIn(f"# TYPE {name} {mtype}", text)+ v = metrics_samples(text)+ st = engine.last_stats+ prompt_tokens = engine.count_tokens(engine.prompts[-1])+ serve_metrics.assert_reported(+ v, self, prompt_tokens=prompt_tokens, cached=st["cached_tokens"],+ predicted=st["new_tokens"], prefill_s=st["time_prefill"], generate_s=st["time_generate"],+ drafts=(st["accepted_draft_tokens"] + st["rejected_draft_tokens"]) // 2,+ draft_tokens=st["accepted_draft_tokens"] + st["rejected_draft_tokens"],+ accepted=st["accepted_draft_tokens"])+ self.assertEqual(v["llamacpp:requests_processing"], 0)+ self.assertEqual(v["llamacpp:requests_deferred"], 0)+ self.assertEqual(v["llamacpp:kv_cache_usage_ratio"], 0) # fake engine: no get_cache_stats+if __name__ == "__main__":unittest.main()diff --git a/tools/mimo/SERVE.md b/tools/mimo/SERVE.mdindex 42509e3..cd4f208 100644--- a/tools/mimo/SERVE.md+++ b/tools/mimo/SERVE.md@@ -43,6 +43,11 @@ top-level config does not carry `max_position_embeddings` — the GLM fix.- `GET /health` — `{"status","model","generator","spec_gate"}`; with the gate on, `spec_gate`carries the live counters `n_spec n_plain n_off n_shadow n_probe_fail t_plain t_spectok_round`. Useful while tuning.+- `GET /metrics` — Prometheus text (llama.cpp `llamacpp:*` names) for scraping. Counters+ accumulate when a request completes; `requests_processing`, `requests_deferred` and+ `kv_cache_usage_ratio` are read live. `spec_decode_num_drafts_total` counts the engine's+ decode steps (one verification round each while speculating), an upper bound when+ `--spec-gate` falls back to plain.## SpecGate across mixed requests — decisiondiff --git a/tools/mimo/serve.py b/tools/mimo/serve.pyindex 9d8e729..c97f2ea 100644--- a/tools/mimo/serve.py+++ b/tools/mimo/serve.py@@ -18,6 +18,7 @@ import asyncioimport jsonimport osimport re+import sysimport timeimport uuidfrom collections.abc import AsyncIterator@@ -28,6 +29,9 @@ import aiohttpfrom aiohttp import webfrom jinja2.sandbox import ImmutableSandboxedEnvironment+sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) # tools/ for the shared serve_metrics+from serve_metrics import Metrics+DEFAULT_MODEL = os.path.expanduser("~/models/mimo26-exl3")DEFAULT_MODEL_ID = "MiMo-2.6-EXL3"DEFAULT_CTX = 4096@@ -314,12 +318,14 @@ class ResidentEngine:stop_conditions=list(self.config.eos_token_id_list) + stop)self.generator.enqueue(job)loop = asyncio.get_running_loop()+ self.last_rounds = 0try:while self.generator.num_remaining_jobs():if cancel is not None and cancel.is_set():self.generator.cancel(job)returnbatch = await loop.run_in_executor(None, lambda: list(self.generator.iterate()))+ self.last_rounds += 1 # with a drafter resident, one step is one verification roundfor event in batch:if event.get("error"):raise RuntimeError(str(event["error"]))@@ -354,8 +360,23 @@ 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()lock = asyncio.Lock() # serializes generation with slot save/restore+ processing = 0 # admitted requests; closure, app config is immutable after startupapp = web.Application(client_max_size=16 * 1024**2)- app.update(engine=engine, model_id=model_id, template=template, queue=queue)+ app.update(engine=engine, model_id=model_id, template=template, queue=queue, metrics=Metrics())++ def observe(st: dict[str, Any], prompt_tokens: int) -> None:+ accepted = int(st.get("accepted_draft_tokens", 0))+ rejected = int(st.get("rejected_draft_tokens", 0))+ proposed = accepted + rejected+ # Dynamic (confidence-truncated) drafts make rounds non-derivable from token counts;+ # the engine counted its decode steps per request in generate(), one round each while+ # speculating. Gate fallbacks (plain steps) make this an upper bound when --spec-gate is on.+ app["metrics"].observe(+ prompt_tokens=prompt_tokens, cached=int(st.get("cached_tokens", 0)),+ predicted=int(st.get("new_tokens", 0)),+ prefill_s=float(st.get("time_prefill") or 0.0), generate_s=float(st.get("time_generate") or 0.0),+ drafts=int(getattr(engine, "last_rounds", 0)) if proposed else 0,+ draft_tokens=proposed, accepted=accepted)async def models(_: web.Request) -> web.Response:return web.json_response({"object": "list", "data": [@@ -372,6 +393,7 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:"spec_gate": gate})async def worker() -> None:+ nonlocal processingwhile True:body, out = await queue.get()cancel = body.get("_cancel")@@ -380,6 +402,7 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:queue.task_done()continuestore = getattr(engine, "slot_store", None)+ processing += 1 # admitted: counted from the dequeue, incl. lock and slot restoretry:async with lock:if store is not None:@@ -396,6 +419,7 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:except Exception as exc: # noqa: BLE001out.put_nowait(exc)finally:+ processing -= 1if store is not None:store.busy = Falsequeue.task_done()@@ -535,6 +559,7 @@ 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:@@ -569,6 +594,7 @@ 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}],@@ -638,6 +664,7 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:raisetext, stopped = stop_text(text, job["_stop"])st = getattr(engine, "last_stats", None) or {}+ observe(st, int(st.get("prompt_tokens", 0)))return web.json_response({"id": f"cmpl-{uuid.uuid4().hex}", "object": "completion", "created": int(time.time()),"model": model_id, "content": text,@@ -671,11 +698,26 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:return web.json_response({"error": {"code": 400, "message": f"{type(exc).__name__}: {exc}", "type": "invalid_request_error"}},status=400)+ async def metrics_view(_: web.Request) -> web.Response:+ # used_tokens = pages referenced by active jobs: in-flight tokens, retained cache excluded.+ # get_cache_stats is memoized on the page tables; the except covers fake engines and a+ # page-table mutation in the worker thread mid-walk.+ gen = getattr(engine, "generator", None) or getattr(engine, "greedy_generator", None)+ try:+ cs = gen.get_cache_stats()+ kv = cs["used_tokens"] / cs["max_tokens"] if cs.get("max_tokens") else 0.0+ except Exception: # noqa: BLE001+ kv = 0.0+ return web.Response(body=app["metrics"].render(+ processing=processing, deferred=queue.qsize(), kv_ratio=kv),+ headers={"Content-Type": "text/plain; version=0.0.4; charset=utf-8"})+if getattr(engine, "slot_store", None) is not None:app.router.add_get("/slots", slots)app.router.add_post("/slots/{id}", slot_action)app.router.add_get("/v1/models", models)app.router.add_get("/health", health)+ app.router.add_get("/metrics", metrics_view)app.router.add_post("/v1/chat/completions", completions)app.router.add_post("/apply-template", apply_template)app.router.add_post("/completion", completion)diff --git a/tools/mimo/test_serve.py b/tools/mimo/test_serve.pyindex 1a5f633..cb198cd 100644--- a/tools/mimo/test_serve.py+++ b/tools/mimo/test_serve.py@@ -32,6 +32,10 @@ class FakeEngine:self.prompts.append(prompt)if kwargs.get("reset_gate"):self.reset_gate()+ self.last_stats = {"cached_tokens": 8, "new_tokens": 4, "prompt_tokens": 20,+ "time_prefill": 0.5, "time_generate": 1.0,+ "accepted_draft_tokens": 6, "rejected_draft_tokens": 6}+ self.last_rounds = 5for i in range(0, len(self.output), 3): # small chunks cut tags in halfyield self.output[i:i + 3]@@ -40,6 +44,11 @@ def run(coro):return asyncio.run(coro)+def metrics_samples(text: str) -> dict:+ return {line.split()[0]: float(line.split()[1]) for line in text.splitlines()+ if line and not line.startswith("#")}++TEMPLATE = ("{% for m in messages %}<|im_start|>{{ m.role }}\n{{ m.content }}<|im_end|>""{% endfor %}{% if tools %}TOOLS={{ tools|length }}{% endif %}""{% if add_generation_prompt %}<|im_start|>assistant\n{% endif %}")@@ -404,6 +413,41 @@ class ServeTests(unittest.TestCase):run(check())+ def test_metrics_endpoint(self):+ from aiohttp.test_utils import TestClient, TestServer+ import serve_metrics+ engine = FakeEngine('hello there')+ app = serve.create_app(engine, "m", TEMPLATE)++ async def check():+ client = TestClient(TestServer(app))+ await client.start_server()+ await client.post("/v1/chat/completions", json={+ "model": "m", "messages": [{"role": "user", "content": "one two three four"}]})+ resp = await client.get("/metrics")+ text = await resp.text()+ await client.close()+ return resp, text++ resp, text = run(check())+ self.assertEqual(resp.status, 200)+ self.assertTrue(resp.headers["Content-Type"].startswith("text/plain"))+ for name, mtype, _ in serve_metrics.METRICS:+ self.assertIn(f"# HELP {name} ", text)+ self.assertIn(f"# TYPE {name} {mtype}", text)+ v = metrics_samples(text)+ st = engine.last_stats+ prompt_tokens = engine.count_tokens(engine.prompts[-1])+ serve_metrics.assert_reported(+ v, self, prompt_tokens=prompt_tokens, cached=st["cached_tokens"],+ predicted=st["new_tokens"], prefill_s=st["time_prefill"], generate_s=st["time_generate"],+ drafts=engine.last_rounds,+ draft_tokens=st["accepted_draft_tokens"] + st["rejected_draft_tokens"],+ accepted=st["accepted_draft_tokens"])+ self.assertEqual(v["llamacpp:requests_processing"], 0)+ self.assertEqual(v["llamacpp:requests_deferred"], 0)+ self.assertEqual(v["llamacpp:kv_cache_usage_ratio"], 0) # fake engine: no get_cache_stats+if __name__ == "__main__":unittest.main()diff --git a/tools/serve_metrics.py b/tools/serve_metrics.pynew file mode 100644index 0000000..abbe04e--- /dev/null+++ b/tools/serve_metrics.py@@ -0,0 +1,103 @@+#!/usr/bin/env python3+"""Shared Prometheus /metrics collector for the kyojin servers (llama.cpp metric names).++Counters accumulate when a request completes (the HTTP layer observes the engine's eos stats);+the gauges requests_processing, requests_deferred and kv_cache_usage_ratio are read live at scrape.+All mutation happens on the server's event loop, so no locking is needed.+"""+from __future__ import annotations++# (name, type, help) in the order the /metrics body renders them.+METRICS = [+ ("llamacpp:prompt_tokens_cached_total", "counter", "Total prompt tokens reused from cache"),+ ("llamacpp:prompt_seconds_total", "counter", "Prompt process time"),+ ("llamacpp:tokens_predicted_total", "counter", "Total tokens generated"),+ ("llamacpp:tokens_predicted_seconds_total", "counter", "Predict process time"),+ ("llamacpp:n_tokens_max", "counter", "Largest observed n_tokens."),+ ("llamacpp:spec_decode_num_drafts_total", "counter", "Total speculative verification rounds"),+ ("llamacpp:spec_decode_num_draft_tokens_total", "counter", "Total draft tokens proposed"),+ ("llamacpp:spec_decode_num_accepted_tokens_total", "counter", "Total draft tokens accepted"),+ ("llamacpp:prompt_tokens_seconds", "gauge", "Prompt processing speed in tokens per second"),+ ("llamacpp:predicted_tokens_seconds", "gauge", "Generation speed in tokens per second"),+ ("llamacpp:requests_processing", "gauge", "Number of admitted requests, including cache preparation"),+ ("llamacpp:requests_deferred", "gauge", "Number of requests waiting for a session"),+ ("llamacpp:kv_cache_usage_ratio", "gauge",+ "In-flight prompt and generated tokens over sessions times context; excludes retained cache"),+]+++def fmt(v: float) -> str:+ return str(int(v)) if float(v).is_integer() else f"{v:.6f}"+++class Metrics:+ """Counters plus the last request's speeds, observed from the engine's eos event."""++ def __init__(self) -> None:+ self.prompt_cached_total = 0.0+ self.prompt_seconds_total = 0.0+ self.tokens_predicted_total = 0.0+ self.predicted_seconds_total = 0.0+ self.n_tokens_max = 0.0+ self.drafts_total = 0.0+ self.draft_tokens_total = 0.0+ self.accepted_tokens_total = 0.0+ self.prompt_tokens_seconds = 0.0+ self.predicted_tokens_seconds = 0.0++ def observe(self, *, prompt_tokens: int, cached: int, predicted: int,+ prefill_s: float, generate_s: float,+ drafts: int = 0, draft_tokens: int = 0, accepted: int = 0) -> None:+ self.prompt_cached_total += cached+ self.prompt_seconds_total += prefill_s+ self.tokens_predicted_total += predicted+ self.predicted_seconds_total += generate_s+ self.n_tokens_max = max(self.n_tokens_max, prompt_tokens + predicted)+ self.drafts_total += drafts+ self.draft_tokens_total += draft_tokens+ self.accepted_tokens_total += accepted+ if prefill_s:+ self.prompt_tokens_seconds = (prompt_tokens - cached) / prefill_s+ if generate_s:+ self.predicted_tokens_seconds = predicted / generate_s++ def render(self, *, processing: int, deferred: int, kv_ratio: float) -> bytes:+ values = {+ "llamacpp:prompt_tokens_cached_total": self.prompt_cached_total,+ "llamacpp:prompt_seconds_total": self.prompt_seconds_total,+ "llamacpp:tokens_predicted_total": self.tokens_predicted_total,+ "llamacpp:tokens_predicted_seconds_total": self.predicted_seconds_total,+ "llamacpp:n_tokens_max": self.n_tokens_max,+ "llamacpp:spec_decode_num_drafts_total": self.drafts_total,+ "llamacpp:spec_decode_num_draft_tokens_total": self.draft_tokens_total,+ "llamacpp:spec_decode_num_accepted_tokens_total": self.accepted_tokens_total,+ "llamacpp:prompt_tokens_seconds": self.prompt_tokens_seconds,+ "llamacpp:predicted_tokens_seconds": self.predicted_tokens_seconds,+ "llamacpp:requests_processing": processing,+ "llamacpp:requests_deferred": deferred,+ "llamacpp:kv_cache_usage_ratio": kv_ratio,+ }+ out = []+ for name, mtype, help_text in METRICS:+ out.append(f"# HELP {name} {help_text}\n# TYPE {name} {mtype}\n{name} {fmt(values[name])}\n")+ return "".join(out).encode()+++def assert_reported(samples: dict, test, *, prompt_tokens: int, cached: int, predicted: int,+ prefill_s: float, generate_s: float, drafts: int, draft_tokens: int,+ accepted: int) -> None:+ """unittest helper: rendered /metrics samples must match one observed request."""+ expected = {+ "llamacpp:prompt_tokens_cached_total": cached,+ "llamacpp:prompt_seconds_total": prefill_s,+ "llamacpp:tokens_predicted_total": predicted,+ "llamacpp:tokens_predicted_seconds_total": generate_s,+ "llamacpp:n_tokens_max": prompt_tokens + predicted,+ "llamacpp:spec_decode_num_drafts_total": drafts,+ "llamacpp:spec_decode_num_draft_tokens_total": draft_tokens,+ "llamacpp:spec_decode_num_accepted_tokens_total": accepted,+ "llamacpp:prompt_tokens_seconds": (prompt_tokens - cached) / prefill_s if prefill_s else 0,+ "llamacpp:predicted_tokens_seconds": predicted / generate_s if generate_s else 0,+ }+ for name, value in expected.items():+ test.assertAlmostEqual(samples[name], value, places=6, msg=name)