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
Qwen GET /metrics, and kyojin:* metrics in the shared collector (#227)
Alessandro Del Preted5fe8f674d49
diff --git a/tools/ds41/serve.py b/tools/ds41/serve.pyindex 102040f..b1273d0 100644--- a/tools/ds41/serve.py+++ b/tools/ds41/serve.py@@ -27,7 +27,7 @@ for _p in (str(HERE), str(HERE.parent)):sys.path.append(_p)import startup_health # noqa: E402 (GET /health with load progress while the model loads)import serve_compat # noqa: E402 (vLLM-style token-id prompts, cache_salt, /tokenize, usage details)-from serve_metrics import Metrics # noqa: E402 (symlink to the shared tools/strix_halo/serve_metrics.py)+from serve_metrics import Metrics, gpu_memory # noqa: E402 (symlink to the shared tools/strix_halo/serve_metrics.py)from serve_reqlog import Lifecycle, ReqLog, StreamWriter # noqa: E402 (one line per request event; off by default)from serve_ping import ServePing # noqa: E402 (SSE keep-alive comments; off by default)import ds41_chat # noqa: E402@@ -176,7 +176,8 @@ def create_app(engine: Any, model_id: str, defaults: Defaults | None = None) ->processing = 0running = 0app = web.Application(client_max_size=64 * 1024**2, middlewares=[startup_health.json_errors_middleware()])- app.update(engine=engine, model_id=model_id, defaults=defaults, queue=queue, metrics=Metrics())+ app.update(engine=engine, model_id=model_id, defaults=defaults, queue=queue,+ metrics=Metrics(server="ds41", model=model_id, sessions=sessions, context=getattr(engine, "ctx", None)))reqlog = ReqLog.from_env(server="ds41")app.update(reqlog=reqlog)@@ -241,7 +242,7 @@ def create_app(engine: Any, model_id: str, defaults: Defaults | None = None) ->except ValueError as exc:raise web.HTTPBadRequest(reason=str(exc)) from exc- def observe(st: dict[str, Any], prompt_tokens: int) -> None:+ def observe(st: dict[str, Any], prompt_tokens: int, queue_s: float = 0.0) -> None:_memlog(prompt_tokens, int(st.get("new_tokens", 0)))num_draft = int(getattr(getattr(engine, "greedy_generator", None), "num_draft_tokens", 0) or 0)accepted = int(st.get("accepted_draft_tokens", 0))@@ -252,7 +253,7 @@ def create_app(engine: Any, model_id: str, defaults: Defaults | None = None) ->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(st.get("draft_steps") or 0) or (proposed // num_draft if proposed and num_draft else 0),- draft_tokens=proposed, accepted=accepted)+ draft_tokens=proposed, accepted=accepted, queue_s=queue_s)async def health(_: web.Request) -> web.Response:return web.json_response({"status": "ok", "source": "kyojin", "model": model_id,@@ -345,12 +346,14 @@ def create_app(engine: Any, model_id: str, defaults: Defaults | None = None) ->if sessions == 1: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)))+ observe(request_stats, body.get("_prompt_tokens") or int(request_stats.get("prompt_tokens", 0)),+ started - (body.get("_queued_at") or started))lifecycle.job_done(rid, request_stats, started,prompt_tokens=int(request_stats.get("prompt_tokens") or body.get("_prompt_tokens") or 0))out.put_nowait(None)except Exception as exc: # noqa: BLE001lifecycle.job_error(rid, exc, started)+ app["metrics"].failed()out.put_nowait(exc)finally:processing -= 1@@ -821,8 +824,9 @@ def create_app(engine: Any, model_id: str, defaults: Defaults | None = None) ->cs = gen.get_cache_stats()kv = cs["used_tokens"] / cs["max_tokens"] if cs.get("max_tokens") else 0.0except Exception: # noqa: BLE001 (stub engines, page-table mutation mid-walk)- kv = 0.0- return web.Response(body=app["metrics"].render(processing=processing, deferred=queue.qsize(), kv_ratio=kv),+ cs, kv = {}, 0.0+ return web.Response(body=app["metrics"].render(processing=processing, deferred=queue.qsize(), kv_ratio=kv, cache=cs,+ gpu=gpu_memory(getattr(engine, "torch", None))),headers={"Content-Type": "text/plain; version=0.0.4; charset=utf-8"})async def score(request: web.Request) -> web.Response:diff --git a/tools/ds41/serve_metrics.py b/tools/ds41/serve_metrics.pyindex 66f5a36..4734728 100644--- a/tools/ds41/serve_metrics.py+++ b/tools/ds41/serve_metrics.py@@ -4,9 +4,17 @@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.++The kyojin:* metrics have no llama.cpp counterpart: the request count, failures and queue time, what the+server is (version, server, model, sessions, context) and, read live at scrape, the cache's token counts+and the device memory. A value a server does not pass is left out of the body."""from __future__ import annotations+import re+import time+from pathlib import Path+# (name, type, help) in the order the /metrics body renders them.METRICS = [("llamacpp:prompt_tokens_total", "counter", "Total prompt tokens"),@@ -24,17 +32,73 @@ METRICS = [("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"),+ ("kyojin:requests_total", "counter", "Finished requests"),+ ("kyojin:requests_failed_total", "counter", "Requests that ended in an engine error"),+ ("kyojin:queue_seconds_total", "counter", "Time the finished requests waited for a session"),+ ("kyojin:start_time_seconds", "gauge", "Unix time the server began to serve, after the model loaded"),+]++# Rendered only when the server passes the value: (name, type, help).+OPTIONAL = [+ ("kyojin:sessions", "gauge", "Requests the server runs at once"),+ ("kyojin:context_tokens", "gauge", "Context length of one session in tokens"),+ ("kyojin:kv_cache_max_tokens", "gauge", "Capacity of the paged KV cache in tokens"),+ ("kyojin:kv_cache_used_tokens", "gauge", "Tokens in pages referenced by running requests"),+ ("kyojin:kv_cache_free_tokens", "gauge", "Tokens in unreferenced pages that hold no reusable content"),+ ("kyojin:prompt_cache_tokens", "gauge", "Tokens in pages a later request can reuse (the prompt cache)"),+ ("kyojin:gpu_memory_allocated_bytes", "gauge", "Device memory held by tensors of this process"),+ ("kyojin:gpu_memory_reserved_bytes", "gauge", "Device memory reserved by the allocator of this process"),+ ("kyojin:gpu_memory_free_bytes", "gauge", "Free device memory, all processes"),+ ("kyojin:gpu_memory_total_bytes", "gauge", "Total device memory"),]+INFO = ("kyojin:info", "gauge", "Constant 1; the labels name the Kyojin version, the server and the model")+# get_cache_stats() key and gpu_memory() key of each live OPTIONAL gauge+CACHE_KEYS = {"kyojin:kv_cache_max_tokens": "max_tokens", "kyojin:kv_cache_used_tokens": "used_tokens",+ "kyojin:kv_cache_free_tokens": "free_tokens", "kyojin:prompt_cache_tokens": "cached_tokens"}+GPU_KEYS = {"kyojin:gpu_memory_allocated_bytes": "allocated", "kyojin:gpu_memory_reserved_bytes": "reserved",+ "kyojin:gpu_memory_free_bytes": "free", "kyojin:gpu_memory_total_bytes": "total"}def fmt(v: float) -> str:return str(int(v)) if float(v).is_integer() else f"{v:.6f}"+def kyojin_version() -> str:+ """The version in exllamav3/version.py, read as text: importing the package would load the extension."""+ try:+ text = (Path(__file__).resolve().parents[2] / "exllamav3" / "version.py").read_text()+ return re.search(r'__version__\s*=\s*"([^"]+)"', text).group(1)+ except Exception: # noqa: BLE001+ return "unknown"+++def gpu_memory(torch) -> dict | None:+ """Device memory for render(gpu=...): the allocator counters of this process and the device's free and total+ bytes. None without torch or without a device (fake engines in tests)."""+ try:+ free, total = torch.cuda.mem_get_info()+ return {"allocated": torch.cuda.memory_allocated(), "reserved": torch.cuda.memory_reserved(),+ "free": free, "total": total}+ except Exception: # noqa: BLE001+ return None+++def label(value) -> str:+ return str(value).replace("\\", "\\\\").replace("\n", "\\n").replace('"', '\\"')++class Metrics:"""Counters plus the last request's speeds, observed from the engine's eos event."""- def __init__(self) -> None:+ def __init__(self, *, server: str | None = None, model: str | None = None,+ sessions: int | None = None, context: int | None = None) -> None:+ self.info = {"version": kyojin_version(), **({"server": server} if server else {}),+ **({"model": model} if model else {})}+ self.sessions, self.context = sessions, context+ self.start_time = time.time()+ self.requests_total = 0.0+ self.requests_failed_total = 0.0+ self.queue_seconds_total = 0.0self.prompt_tokens_total = 0.0self.prompt_cached_total = 0.0self.prompt_seconds_total = 0.0@@ -49,7 +113,9 @@ class Metrics: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:+ drafts: int = 0, draft_tokens: int = 0, accepted: int = 0, queue_s: float = 0.0) -> None:+ self.requests_total += 1+ self.queue_seconds_total += queue_sself.prompt_tokens_total += prompt_tokensself.prompt_cached_total += cachedself.prompt_seconds_total += prefill_s@@ -64,7 +130,13 @@ class Metrics:if generate_s:self.predicted_tokens_seconds = predicted / generate_s- def render(self, *, processing: int, deferred: int, kv_ratio: float) -> bytes:+ def failed(self) -> None:+ """A request that ended in an engine error (it is not observed, so it is not in requests_total)."""+ self.requests_failed_total += 1++ def render(self, *, processing: int, deferred: int, kv_ratio: float,+ cache: dict | None = None, gpu: dict | None = None) -> bytes:+ """`cache` is the generator's get_cache_stats(), `gpu` is gpu_memory(): both read by the server at scrape."""values = {"llamacpp:prompt_tokens_total": self.prompt_tokens_total,"llamacpp:prompt_tokens_cached_total": self.prompt_cached_total,@@ -80,10 +152,22 @@ class Metrics:"llamacpp:requests_processing": processing,"llamacpp:requests_deferred": deferred,"llamacpp:kv_cache_usage_ratio": kv_ratio,+ "kyojin:requests_total": self.requests_total,+ "kyojin:requests_failed_total": self.requests_failed_total,+ "kyojin:queue_seconds_total": self.queue_seconds_total,+ "kyojin:start_time_seconds": self.start_time,+ "kyojin:sessions": self.sessions,+ "kyojin:context_tokens": self.context,+ **{name: (cache or {}).get(key) for name, key in CACHE_KEYS.items()},+ **{name: (gpu or {}).get(key) for name, key in GPU_KEYS.items()},}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")+ for name, mtype, help_text in METRICS + OPTIONAL:+ if values[name] is not None:+ out.append(f"# HELP {name} {help_text}\n# TYPE {name} {mtype}\n{name} {fmt(values[name])}\n")+ name, mtype, help_text = INFO+ labels = ",".join(f'{k}="{label(v)}"' for k, v in self.info.items())+ out.append(f"# HELP {name} {help_text}\n# TYPE {name} {mtype}\n{name}{{{labels}}} 1\n")return "".join(out).encode()diff --git a/tools/ds41/test_ds41_serve.py b/tools/ds41/test_ds41_serve.pyindex 3a55eba..163d828 100644--- a/tools/ds41/test_ds41_serve.py+++ b/tools/ds41/test_ds41_serve.py@@ -92,6 +92,8 @@ def test_health_models_metrics():assert [x["id"] for x in m["data"]] == [MODEL]met = await c.get("/metrics")assert met.status == 200 and "text/plain" in met.headers["Content-Type"]+ text = await met.text()+ assert "kyojin:requests_total 0\n" in text and f'server="ds41",model="{MODEL}"}} 1\n' in textrun(go())diff --git a/tools/glm/SERVE.md b/tools/glm/SERVE.mdindex d07a369..6387e42 100644--- a/tools/glm/SERVE.md+++ b/tools/glm/SERVE.md@@ -99,6 +99,16 @@ are read live. `spec_decode_num_drafts_total` is derived from the accepted+rejectoken counts divided by `--num-draft` (exact except for a final MTP window truncated by`max_tokens`). A request cancelled mid-stream is not counted in this first version.+The `kyojin:*` metrics have no llama.cpp counterpart and are the same on every Kyojin server:+`kyojin:requests_total` (finished requests), `kyojin:requests_failed_total` (requests that ended in an+engine error; they are not in `requests_total`), `kyojin:queue_seconds_total` (time the finished requests+waited for a session), `kyojin:start_time_seconds`, `kyojin:sessions`, `kyojin:context_tokens` and+`kyojin:info{version, server, model}` (constant 1). Read live at scrape: the cache's token counts+(`kyojin:kv_cache_max_tokens`, `kyojin:kv_cache_used_tokens`, `kyojin:kv_cache_free_tokens`,+`kyojin:prompt_cache_tokens`) and the device memory (`kyojin:gpu_memory_allocated_bytes`,+`kyojin:gpu_memory_reserved_bytes` of this process, `kyojin:gpu_memory_free_bytes`,+`kyojin:gpu_memory_total_bytes` of the device).+### `POST /v1/chat/completions`Honored:diff --git a/tools/glm/serve.py b/tools/glm/serve.pyindex f5f7b3a..faa138c 100644--- a/tools/glm/serve.py+++ b/tools/glm/serve.py@@ -34,7 +34,7 @@ from loopguard import AnswerTap, loop_guard_default # noqa: E402 (answer-phaseimport serve_compat # noqa: E402 (vLLM-style token-id prompts, cache_salt, /tokenize, usage details)from l21_prompt_encode_cache import PromptEncodeCache # noqa: E402 (incremental prompt encode)# serve_metrics.py is a symlink to the shared tools/strix_halo/serve_metrics.py-from serve_metrics import Metrics+from serve_metrics import Metrics, gpu_memory# serve_reqlog.py is a symlink to the shared tools/strix_halo/serve_reqlog.py: one line per request# lifecycle event (numbers and event names only, never prompt or reply text) plus a heartbeat while a job# is queued or prefilling, so "the client went silent" can be lined up with what the server was doing.@@ -1506,7 +1506,8 @@ def create_app(engine: Any, model_id: str, template: str, admin_knobs: bool = Faprocessing = 0 # admitted requests; closure, app config is immutable after startuprunning = 0 # sessions > 1: requests inside generate()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, queue=queue, metrics=Metrics())+ app.update(engine=engine, model_id=model_id, template=template, queue=queue,+ metrics=Metrics(server="glm", model=model_id, sessions=sessions, context=getattr(engine, "ctx", None)))# Request log: off unless KYOJIN_REQLOG_DIR names a directory, in which case every generation request gets a line# per lifecycle event (numbers and event names only, never prompt or reply text) plus an 'alive' heartbeat@@ -1547,7 +1548,7 @@ def create_app(engine: Any, model_id: str, template: str, admin_knobs: bool = Faraise web.HTTPBadRequest(reason="cache_salt is not supported by this engine")return salt- def observe(st: dict[str, Any], prompt_tokens: int) -> None:+ def observe(st: dict[str, Any], prompt_tokens: int, queue_s: float = 0.0) -> None:# The MTP window is a fixed num_draft_tokens per round, so rounds = proposed / window# (exact except for a final window truncated by max_new_tokens). No generator -> no rounds.num_draft = int(getattr(getattr(engine, "greedy_generator", None), "num_draft_tokens", 0) or 0)@@ -1559,7 +1560,7 @@ def create_app(engine: Any, model_id: str, template: str, admin_knobs: bool = Fapredicted=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 // num_draft if proposed and num_draft else 0,- draft_tokens=proposed, accepted=accepted)+ draft_tokens=proposed, accepted=accepted, queue_s=queue_s)async def health(_: web.Request) -> web.Response:return web.json_response({"status": "ok", "source": "kyojin", "model": model_id,@@ -1678,13 +1679,15 @@ def create_app(engine: Any, model_id: str, template: str, admin_knobs: bool = Faif sessions == 1: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)))+ observe(request_stats, body.get("_prompt_tokens") or int(request_stats.get("prompt_tokens", 0)),+ started - (body.get("_queued_at") or started))log_job_done(rid, body, request_stats, started)out.put_nowait(None)if getattr(engine, "prefix_disk", None) is not None:await engine.disk_save() # the reply is out: the host copy of the new pages holds the lock, the write does notexcept Exception as exc:lifecycle.job_error(rid, exc, started)+ app["metrics"].failed()out.put_nowait(exc)finally:processing -= 1@@ -2206,9 +2209,10 @@ def create_app(engine: Any, model_id: str, template: str, admin_knobs: bool = Facs = gen.get_cache_stats()kv = cs["used_tokens"] / cs["max_tokens"] if cs.get("max_tokens") else 0.0except Exception: # noqa: BLE001- kv = 0.0+ cs, kv = {}, 0.0return web.Response(body=app["metrics"].render(- processing=processing, deferred=queue.qsize(), kv_ratio=kv),+ processing=processing, deferred=queue.qsize(), kv_ratio=kv, cache=cs,+ gpu=gpu_memory(getattr(engine, "torch", None))),headers={"Content-Type": "text/plain; version=0.0.4; charset=utf-8"})if getattr(engine, "slot_store", None) is not None:diff --git a/tools/glm/test_serve.py b/tools/glm/test_serve.pyindex 9d23d1c..85cd8d7 100644--- a/tools/glm/test_serve.py+++ b/tools/glm/test_serve.py@@ -498,6 +498,8 @@ class ServeTests(unittest.TestCase):accepted=st["accepted_draft_tokens"])self.assertEqual(v["llamacpp:requests_processing"], 0)self.assertEqual(v["llamacpp:requests_deferred"], 0)+ self.assertEqual((v["kyojin:requests_total"], v["kyojin:requests_failed_total"]), (1, 0))+ self.assertIn(f'kyojin:info{{version="{serve_metrics.kyojin_version()}",server="glm",model="m"}} 1\n', text)self.assertEqual(v["llamacpp:kv_cache_usage_ratio"], 0) # fake engine: no get_cache_statsdef test_stream_handler_finishes_after_stream(self):diff --git a/tools/mimo/SERVE.md b/tools/mimo/SERVE.mdindex 5d2935a..1ccdf75 100644--- a/tools/mimo/SERVE.md+++ b/tools/mimo/SERVE.md@@ -59,7 +59,9 @@ top-level config does not carry `max_position_embeddings` — the GLM fix.`kv_cache_usage_ratio` are read live. `spec_decode_num_drafts_total` counts the engine'sdecode steps (one verification round each while speculating), an upper bound when`--spec-gate` falls back to plain. A request cancelled mid-stream is not counted in this- first version.+ first version. The `kyojin:*` metrics (request count, failures, queue time, version, server and model, sessions,+ context, cache token counts, device memory) are the same on every server: see `GET /metrics` in+ `tools/glm/SERVE.md`.## Diagnostics: the request logdiff --git a/tools/mimo/serve.py b/tools/mimo/serve.pyindex 3029165..0a0d135 100644--- a/tools/mimo/serve.py+++ b/tools/mimo/serve.py@@ -36,7 +36,7 @@ sys.path.append(str(Path(__file__).resolve().parent.parent))import startup_health # noqa: E402 (GET /health with load progress while the model loads)import serve_compat # noqa: E402 (the llama.cpp timings object, shared with the other servers)# serve_metrics.py is a symlink to the shared tools/strix_halo/serve_metrics.py-from serve_metrics import Metrics+from serve_metrics import Metrics, gpu_memory# serve_ping.py is a symlink to the shared tools/strix_halo/serve_ping.py: an SSE comment line every# KYOJIN_SSE_PING_S while a stream has nothing to send yet (off by default), so a long prefill does# not look like a hung server to a client that only watches its socket.@@ -531,7 +531,8 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:lock = asyncio.Lock() # serializes generation with slot save/restoreprocessing = 0 # admitted requests; closure, app config is immutable after startupapp = web.Application(client_max_size=64 * 1024**2, middlewares=[startup_health.json_errors_middleware()])- app.update(engine=engine, model_id=model_id, template=template, queue=queue, metrics=Metrics())+ app.update(engine=engine, model_id=model_id, template=template, queue=queue,+ metrics=Metrics(server="mimo", model=model_id, sessions=1, context=getattr(engine, "ctx", None)))# SSE keep-alive: off unless KYOJIN_SSE_PING_S names an interval (see tools/strix_halo/serve_ping.py).# A request copies this pinger, so its timers are its own; the start-up line reports the setting.ping = ServePing.from_env()@@ -553,7 +554,7 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:"""The log id of the request being handled (None outside a logged route)."""return lifecycle.reqid()- def observe(st: dict[str, Any], prompt_tokens: int) -> None:+ def observe(st: dict[str, Any], prompt_tokens: int, queue_s: float = 0.0) -> None:accepted = int(st.get("accepted_draft_tokens", 0))rejected = int(st.get("rejected_draft_tokens", 0))proposed = accepted + rejected@@ -565,7 +566,7 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application: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)+ draft_tokens=proposed, accepted=accepted, queue_s=queue_s)async def models(_: web.Request) -> web.Response:return web.json_response({"object": "list", "data": [@@ -624,11 +625,12 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application: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)))+ observe(request_stats, body.get("_prompt_tokens") or int(request_stats.get("prompt_tokens", 0)), wait)lifecycle.job_done(rid, request_stats, started, prompt_tokens=body.get("_prompt_tokens"))out.put_nowait(None)except Exception as exc: # noqa: BLE001lifecycle.job_error(rid, exc, started)+ app["metrics"].failed()out.put_nowait(exc)finally:processing -= 1@@ -967,9 +969,10 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:cs = gen.get_cache_stats()kv = cs["used_tokens"] / cs["max_tokens"] if cs.get("max_tokens") else 0.0except Exception: # noqa: BLE001- kv = 0.0+ cs, kv = {}, 0.0return web.Response(body=app["metrics"].render(- processing=processing, deferred=queue.qsize(), kv_ratio=kv),+ processing=processing, deferred=queue.qsize(), kv_ratio=kv, cache=cs,+ gpu=gpu_memory(getattr(engine, "torch", None))),headers={"Content-Type": "text/plain; version=0.0.4; charset=utf-8"})if getattr(engine, "slot_store", None) is not None:diff --git a/tools/mimo/test_serve.py b/tools/mimo/test_serve.pyindex 845bb5d..29a0ede 100644--- a/tools/mimo/test_serve.py+++ b/tools/mimo/test_serve.py@@ -514,6 +514,8 @@ class ServeTests(unittest.TestCase):accepted=st["accepted_draft_tokens"])self.assertEqual(v["llamacpp:requests_processing"], 0)self.assertEqual(v["llamacpp:requests_deferred"], 0)+ self.assertEqual((v["kyojin:requests_total"], v["kyojin:requests_failed_total"]), (1, 0))+ self.assertIn(f'kyojin:info{{version="{serve_metrics.kyojin_version()}",server="mimo",model="m"}} 1\n', text)self.assertEqual(v["llamacpp:kv_cache_usage_ratio"], 0) # fake engine: no get_cache_statsdef test_two_queued_requests_are_both_counted(self):diff --git a/tools/qwen/SERVE.md b/tools/qwen/SERVE.mdindex 7fc761f..135eaaf 100644--- a/tools/qwen/SERVE.md+++ b/tools/qwen/SERVE.md@@ -90,6 +90,15 @@ The pack is tied to one set of weights: download it from the same model repo.they are on the last chunk.- Errors are JSON `{"error": {"message", "type", "code"}}`: 400 for bad requests (including prompt longer than thecontext), 500 for engine errors.+- `GET /metrics`: Prometheus text with the llama.cpp `llamacpp:*` names, for scraping (the collector of the GLM and+ MiMo servers). Counters accumulate when a request completes, on every generation route; a request cancelled+ mid-stream is not counted. `requests_processing`, `requests_deferred` and `kv_cache_usage_ratio` are read live.+ `spec_decode_num_accepted_tokens_total` over `spec_decode_num_draft_tokens_total` is the draft acceptance.+ `spec_decode_num_drafts_total` is derived: a verification step yields one sampled token plus the draft tokens it+ accepts, so the rounds of a request are its new tokens minus its accepted draft tokens (a step that drafted+ nothing counts too; a request that drafted nothing adds none). The `kyojin:*` metrics (request count, failures,+ queue time, version, server and model, sessions, context, cache token counts, device memory) are the same on+ every server: see `GET /metrics` in `tools/glm/SERVE.md`.- `GET /v1/models`, `GET /health` (status, speculation state, vision), `POST /apply-template` (renders the prompt,generates nothing), `GET /slots`, `POST /slots/0?action=save|restore|erase` (llama.cpp slot files),`POST /completion` (llama.cpp style) and `POST /v1/completions` (OpenAI style, stream and non-stream): raw prompt, nodiff --git a/tools/qwen/serve.py b/tools/qwen/serve.pyindex 07e36a7..2023c39 100644--- a/tools/qwen/serve.py+++ b/tools/qwen/serve.py@@ -51,6 +51,9 @@ from serve_ping import ServePing # noqa: E402# serve_reqlog.py is a symlink to the shared tools/strix_halo/serve_reqlog.py: off unless# KYOJIN_REQLOG_DIR names a directory. Its output accounting also feeds the end-of-stream summary here.from serve_reqlog import Lifecycle, ReqLog, StreamWriter, refusal_text, sanitize # noqa: E402+# serve_metrics.py is a symlink to the shared tools/strix_halo/serve_metrics.py: the GET /metrics collector+# (Prometheus text, llama.cpp names) of the GLM and MiMo servers.+from serve_metrics import Metrics, gpu_memory # noqa: E402def _load_mimo():@@ -1675,7 +1678,7 @@ def format_logprobs(entries: list, token_ids: list[int], token_str, chat: bool)# 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",), "/tokenize": ("POST",), "/completion": ("POST",), "/v1/completions": ("POST",), "/slots/{id}": ("POST",), "/admin/knobs": ("GET", "POST")}+ROUTES = {"/health": ("GET",), "/v1/models": ("GET",), "/metrics": ("GET",), "/slots": ("GET",), "/v1/chat/completions": ("POST",), "/apply-template": ("POST",), "/tokenize": ("POST",), "/completion": ("POST",), "/v1/completions": ("POST",), "/slots/{id}": ("POST",), "/admin/knobs": ("GET", "POST")}def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, Any] | None = None,@@ -1690,7 +1693,8 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, Ansalt_state: dict[str, Any] = {"current": None} # cache_salt namespace of the prompt cache (None = requests without a salt)admit_lock = asyncio.Lock()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)+ app.update(engine=engine, model_id=model_id, template=template, defaults=defaults,+ metrics=Metrics(server="qwen", model=model_id, sessions=sessions, context=getattr(engine, "ctx", None)))# SSE keep-alive: off unless KYOJIN_SSE_PING_S names an interval (see tools/strix_halo/serve_ping.py).# A request copies this pinger, so its timers are its own; the start-up line reports the setting.ping = ServePing.from_env()@@ -1724,6 +1728,20 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, An{"id": model_id, "object": "model", "created": 0, "owned_by": "yamz","max_context": getattr(engine, "ctx", None)}]})+ def observe(st: dict[str, Any], prompt_tokens: int, queue_s: float = 0.0) -> None:+ """GET /metrics counters of one finished request. The draft depth changes from round to round on this server+ (spec_policy), so the round count cannot come from proposed / window as on the GLM server. A verification+ step yields the one token the target samples plus the draft tokens it accepts, so the rounds of a request+ are its new tokens minus its accepted draft tokens. A step that drafted nothing counts too."""+ predicted = int(st.get("new_tokens") or 0)+ accepted = int(st.get("accepted_draft_tokens") or 0)+ proposed = accepted + int(st.get("rejected_draft_tokens") or 0)+ app["metrics"].observe(+ prompt_tokens=prompt_tokens, cached=int(st.get("cached_tokens") or 0), predicted=predicted,+ prefill_s=float(st.get("time_prefill") or 0.0), generate_s=float(st.get("time_generate") or 0.0),+ drafts=max(predicted - accepted, 0) if proposed else 0, draft_tokens=proposed, accepted=accepted,+ queue_s=queue_s)+async def health(_: web.Request) -> web.Response:return web.json_response({"status": "ok", "source": "kyojin", "model": model_id, "vision": bool(engine.supports_vision), **startup_health.compiler_health(),**(engine.spec_stats() if hasattr(engine, "spec_stats") else {})})@@ -1814,12 +1832,15 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, Ant = engine.torch.cudaprint(f"qserve: vram alloc={t.memory_allocated() >> 20} MiB peak={t.max_memory_allocated() >> 20} MiB reserved={t.memory_reserved() >> 20} MiB",file=sys.stderr, flush=True)+ if done: # a request cancelled mid-stream leaves no stats: not counted+ observe(done, int(done.get("prompt_tokens") or job.get("prompt_tokens") or 0), wait)lifecycle.job_done(rid, done, started, prompt_tokens=job.get("prompt_tokens"))out.put_nowait(("done", done))if getattr(engine, "prefix_disk", None) is not None:await engine.disk_save(stats) # the reply is out: the host copy of the new pages holds the lock, the write does notexcept Exception as exc: # noqa: BLE001lifecycle.job_error(rid, exc, started)+ app["metrics"].failed()out.put_nowait(exc)finally:queue.task_done()@@ -2412,6 +2433,19 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, Anfor _ in range(held):gate.release()+ 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, a Generator that is+ # being rebuilt and a page-table mutation in the driver thread mid-walk.+ try:+ cs = engine.generator.get_cache_stats()+ kv = cs["used_tokens"] / cs["max_tokens"] if cs.get("max_tokens") else 0.0+ except Exception: # noqa: BLE001+ cs, kv = {}, 0.0+ return web.Response(body=app["metrics"].render(processing=running, deferred=queue.qsize(), kv_ratio=kv, cache=cs,+ gpu=gpu_memory(getattr(engine, "torch", None))),+ headers={"Content-Type": "text/plain; version=0.0.4; charset=utf-8"})+if admin_knobs:import admin_knobs as _adminh = _admin.make_handler(engine, exclusive)@@ -2419,6 +2453,7 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, Anapp.router.add_post("/admin/knobs", h)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", lifecycle.wrapped(completions))app.router.add_post("/apply-template", apply_template)app.router.add_post("/tokenize", tokenize)diff --git a/tools/qwen/test_serve.py b/tools/qwen/test_serve.pyindex c5eb454..e08dab0 100644--- a/tools/qwen/test_serve.py+++ b/tools/qwen/test_serve.py@@ -8,6 +8,7 @@ import ioimport jsonimport osimport sys+import timeimport typesimport unittestimport unittest.mock@@ -951,6 +952,126 @@ class MiscTests(unittest.TestCase):self.assertEqual(serve._partial_tag("abc", ["</think>"]), 0)+class MetricsTests(unittest.TestCase):+ """GET /metrics: the shared llama.cpp-style collector, fed by the worker when a request completes."""+ DRAFT_STATS = {"new_tokens": 7, "prompt_tokens": 11, "cached_tokens": 5, "eos_reason": "stop_token",+ "time_prefill": 0.5, "time_generate": 1.0, "token_ids": [1, 2, 3],+ "accepted_draft_tokens": 4, "rejected_draft_tokens": 2}+ CHAT = ("/v1/chat/completions", {"model": "m", "messages": [{"role": "user", "content": "one two three four"}]})++ @staticmethod+ def scrape(engine, posts=(), method="GET"):+ async def fn(client):+ statuses = [(await client.post(path, json=body)).status for path, body in posts]+ resp = await client.request(method, "/metrics")+ return statuses, resp.status, resp.headers["Content-Type"], await resp.text()+ return with_client(engine, fn)++ @staticmethod+ def samples(text):+ return {line.split()[0]: float(line.split()[1]) for line in text.splitlines() if line and not line.startswith("#")}++ def test_endpoint_reports_a_finished_request(self):+ import serve_metrics+ statuses, status, ctype, text = self.scrape(FakeEngine("hello there", dict(self.DRAFT_STATS)), [self.CHAT])+ self.assertEqual((statuses, status), ([200], 200))+ self.assertEqual(ctype, "text/plain; version=0.0.4; charset=utf-8")+ for name, mtype, _ in serve_metrics.METRICS:+ self.assertIn(f"# HELP {name} ", text)+ self.assertIn(f"# TYPE {name} {mtype}", text)+ v = self.samples(text)+ # 7 new tokens, 4 of them accepted drafts: 3 verification rounds; 4 accepted + 2 rejected = 6 proposed+ serve_metrics.assert_reported(v, self, prompt_tokens=11, cached=5, predicted=7, prefill_s=0.5, generate_s=1.0,+ drafts=3, draft_tokens=6, accepted=4)+ self.assertEqual(v["llamacpp:requests_processing"], 0)+ self.assertEqual(v["llamacpp:requests_deferred"], 0)+ self.assertEqual(v["llamacpp:kv_cache_usage_ratio"], 0)+ self.assertEqual((v["kyojin:requests_total"], v["kyojin:requests_failed_total"]), (1, 0))+ self.assertGreaterEqual(v["kyojin:queue_seconds_total"], 0)+ self.assertEqual((v["kyojin:sessions"], v["kyojin:context_tokens"]), (1, FakeEngine.ctx))+ self.assertAlmostEqual(v["kyojin:start_time_seconds"], time.time(), delta=60)+ self.assertIn(f'kyojin:info{{version="{serve_metrics.kyojin_version()}",server="qwen",model="m"}} 1\n', text)+ for name, mtype, _ in serve_metrics.OPTIONAL: # a fake engine has no cache stats and no device+ if name not in ("kyojin:sessions", "kyojin:context_tokens"):+ self.assertNotIn(name, text)++ def test_every_generation_route_is_counted(self):+ posts = [self.CHAT, ("/completion", {"prompt": "hi"}), ("/v1/completions", {"model": "m", "prompt": "hi"})]+ statuses, _, _, text = self.scrape(FakeEngine("hello there", dict(self.DRAFT_STATS)), posts)+ self.assertEqual(statuses, [200, 200, 200])+ v = self.samples(text)+ self.assertEqual(v["llamacpp:tokens_predicted_total"], 21)+ self.assertEqual(v["llamacpp:prompt_tokens_total"], 33)+ self.assertEqual(v["llamacpp:prompt_tokens_cached_total"], 15)+ self.assertEqual(v["llamacpp:spec_decode_num_drafts_total"], 9)+ self.assertEqual(v["llamacpp:spec_decode_num_draft_tokens_total"], 18)+ self.assertEqual(v["llamacpp:spec_decode_num_accepted_tokens_total"], 12)+ self.assertEqual(v["kyojin:requests_total"], 3)++ def test_request_that_drafted_nothing_adds_no_rounds(self):+ _, _, _, text = self.scrape(FakeEngine("hello there"), [self.CHAT]) # the default stats carry no draft counts+ v = self.samples(text)+ self.assertEqual(v["llamacpp:tokens_predicted_total"], 7)+ self.assertEqual(v["llamacpp:spec_decode_num_drafts_total"], 0)+ self.assertEqual(v["llamacpp:spec_decode_num_draft_tokens_total"], 0)++ def test_idle_server_reports_zeros(self):+ statuses, status, _, text = self.scrape(FakeEngine("x"))+ self.assertEqual((statuses, status), ([], 200))+ static = ("kyojin:start_time_seconds", "kyojin:sessions", "kyojin:context_tokens", "kyojin:info")+ self.assertEqual({v for k, v in self.samples(text).items() if not k.startswith(static)}, {0.0})++ def test_kv_cache_usage_and_token_counts_come_from_the_generator(self):+ engine = FakeEngine("x")+ engine.generator = types.SimpleNamespace(get_cache_stats=lambda: {+ "used_tokens": 512, "max_tokens": 4096, "free_tokens": 1024, "cached_tokens": 2560})+ v = self.samples(self.scrape(engine)[3])+ self.assertEqual(v["llamacpp:kv_cache_usage_ratio"], 0.125)+ self.assertEqual([v[f"kyojin:{k}"] for k in ("kv_cache_max_tokens", "kv_cache_used_tokens", "kv_cache_free_tokens",+ "prompt_cache_tokens")], [4096, 512, 1024, 2560])++ def test_device_memory_comes_from_the_engine_torch(self):+ engine = FakeEngine("x")+ engine.torch = types.SimpleNamespace(cuda=types.SimpleNamespace(+ mem_get_info=lambda: (10, 100), memory_allocated=lambda: 7, memory_reserved=lambda: 9))+ v = self.samples(self.scrape(engine)[3])+ self.assertEqual([v[f"kyojin:gpu_memory_{k}_bytes"] for k in ("allocated", "reserved", "free", "total")], [7, 9, 10, 100])++ def test_failed_request_is_counted_as_failed_only(self):+ class Broken(FakeEngine):+ async def generate(self, prompt, **kw):+ raise RuntimeError("engine fault")+ yield "" # an async generator, as the real one++ statuses, _, _, text = self.scrape(Broken("x"), [self.CHAT])+ v = self.samples(text)+ self.assertEqual(statuses, [500])+ self.assertEqual((v["kyojin:requests_total"], v["kyojin:requests_failed_total"]), (0, 1))+ self.assertEqual(v["llamacpp:tokens_predicted_total"], 0)++ def test_queue_time_of_a_request_that_waited_is_counted(self):+ class Slow(FakeEngine):+ async def generate(self, prompt, **kw):+ await asyncio.sleep(0.05)+ async for piece in super().generate(prompt, **kw):+ yield piece++ async def fn(client):+ body = {"model": "m", "messages": [{"role": "user", "content": "hi"}]}+ rs = await asyncio.gather(*[client.post("/v1/chat/completions", json=body) for _ in range(2)])+ return [r.status for r in rs], await (await client.get("/metrics")).text()+ statuses, text = with_client(Slow("x"), fn) # one session: the second request waits for the first+ v = self.samples(text)+ self.assertEqual((statuses, v["kyojin:requests_total"]), ([200, 200], 2))+ self.assertGreater(v["kyojin:queue_seconds_total"], 0.04)++ def test_wrong_method_answers_405_in_json(self):+ _, status, ctype, text = self.scrape(FakeEngine("x"), method="POST")+ self.assertEqual(status, 405)+ self.assertTrue(ctype.startswith("application/json"))+ self.assertEqual(json.loads(text)["error"]["code"], 405)++class ServeEnvDefaultsTest(unittest.TestCase):def test_prefill_set_is_default_and_overridable(self):d = dict(serve.SERVE_ENV)diff --git a/tools/strix_halo/serve_metrics.py b/tools/strix_halo/serve_metrics.pyindex 66f5a36..4734728 100644--- a/tools/strix_halo/serve_metrics.py+++ b/tools/strix_halo/serve_metrics.py@@ -4,9 +4,17 @@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.++The kyojin:* metrics have no llama.cpp counterpart: the request count, failures and queue time, what the+server is (version, server, model, sessions, context) and, read live at scrape, the cache's token counts+and the device memory. A value a server does not pass is left out of the body."""from __future__ import annotations+import re+import time+from pathlib import Path+# (name, type, help) in the order the /metrics body renders them.METRICS = [("llamacpp:prompt_tokens_total", "counter", "Total prompt tokens"),@@ -24,17 +32,73 @@ METRICS = [("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"),+ ("kyojin:requests_total", "counter", "Finished requests"),+ ("kyojin:requests_failed_total", "counter", "Requests that ended in an engine error"),+ ("kyojin:queue_seconds_total", "counter", "Time the finished requests waited for a session"),+ ("kyojin:start_time_seconds", "gauge", "Unix time the server began to serve, after the model loaded"),+]++# Rendered only when the server passes the value: (name, type, help).+OPTIONAL = [+ ("kyojin:sessions", "gauge", "Requests the server runs at once"),+ ("kyojin:context_tokens", "gauge", "Context length of one session in tokens"),+ ("kyojin:kv_cache_max_tokens", "gauge", "Capacity of the paged KV cache in tokens"),+ ("kyojin:kv_cache_used_tokens", "gauge", "Tokens in pages referenced by running requests"),+ ("kyojin:kv_cache_free_tokens", "gauge", "Tokens in unreferenced pages that hold no reusable content"),+ ("kyojin:prompt_cache_tokens", "gauge", "Tokens in pages a later request can reuse (the prompt cache)"),+ ("kyojin:gpu_memory_allocated_bytes", "gauge", "Device memory held by tensors of this process"),+ ("kyojin:gpu_memory_reserved_bytes", "gauge", "Device memory reserved by the allocator of this process"),+ ("kyojin:gpu_memory_free_bytes", "gauge", "Free device memory, all processes"),+ ("kyojin:gpu_memory_total_bytes", "gauge", "Total device memory"),]+INFO = ("kyojin:info", "gauge", "Constant 1; the labels name the Kyojin version, the server and the model")+# get_cache_stats() key and gpu_memory() key of each live OPTIONAL gauge+CACHE_KEYS = {"kyojin:kv_cache_max_tokens": "max_tokens", "kyojin:kv_cache_used_tokens": "used_tokens",+ "kyojin:kv_cache_free_tokens": "free_tokens", "kyojin:prompt_cache_tokens": "cached_tokens"}+GPU_KEYS = {"kyojin:gpu_memory_allocated_bytes": "allocated", "kyojin:gpu_memory_reserved_bytes": "reserved",+ "kyojin:gpu_memory_free_bytes": "free", "kyojin:gpu_memory_total_bytes": "total"}def fmt(v: float) -> str:return str(int(v)) if float(v).is_integer() else f"{v:.6f}"+def kyojin_version() -> str:+ """The version in exllamav3/version.py, read as text: importing the package would load the extension."""+ try:+ text = (Path(__file__).resolve().parents[2] / "exllamav3" / "version.py").read_text()+ return re.search(r'__version__\s*=\s*"([^"]+)"', text).group(1)+ except Exception: # noqa: BLE001+ return "unknown"+++def gpu_memory(torch) -> dict | None:+ """Device memory for render(gpu=...): the allocator counters of this process and the device's free and total+ bytes. None without torch or without a device (fake engines in tests)."""+ try:+ free, total = torch.cuda.mem_get_info()+ return {"allocated": torch.cuda.memory_allocated(), "reserved": torch.cuda.memory_reserved(),+ "free": free, "total": total}+ except Exception: # noqa: BLE001+ return None+++def label(value) -> str:+ return str(value).replace("\\", "\\\\").replace("\n", "\\n").replace('"', '\\"')++class Metrics:"""Counters plus the last request's speeds, observed from the engine's eos event."""- def __init__(self) -> None:+ def __init__(self, *, server: str | None = None, model: str | None = None,+ sessions: int | None = None, context: int | None = None) -> None:+ self.info = {"version": kyojin_version(), **({"server": server} if server else {}),+ **({"model": model} if model else {})}+ self.sessions, self.context = sessions, context+ self.start_time = time.time()+ self.requests_total = 0.0+ self.requests_failed_total = 0.0+ self.queue_seconds_total = 0.0self.prompt_tokens_total = 0.0self.prompt_cached_total = 0.0self.prompt_seconds_total = 0.0@@ -49,7 +113,9 @@ class Metrics: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:+ drafts: int = 0, draft_tokens: int = 0, accepted: int = 0, queue_s: float = 0.0) -> None:+ self.requests_total += 1+ self.queue_seconds_total += queue_sself.prompt_tokens_total += prompt_tokensself.prompt_cached_total += cachedself.prompt_seconds_total += prefill_s@@ -64,7 +130,13 @@ class Metrics:if generate_s:self.predicted_tokens_seconds = predicted / generate_s- def render(self, *, processing: int, deferred: int, kv_ratio: float) -> bytes:+ def failed(self) -> None:+ """A request that ended in an engine error (it is not observed, so it is not in requests_total)."""+ self.requests_failed_total += 1++ def render(self, *, processing: int, deferred: int, kv_ratio: float,+ cache: dict | None = None, gpu: dict | None = None) -> bytes:+ """`cache` is the generator's get_cache_stats(), `gpu` is gpu_memory(): both read by the server at scrape."""values = {"llamacpp:prompt_tokens_total": self.prompt_tokens_total,"llamacpp:prompt_tokens_cached_total": self.prompt_cached_total,@@ -80,10 +152,22 @@ class Metrics:"llamacpp:requests_processing": processing,"llamacpp:requests_deferred": deferred,"llamacpp:kv_cache_usage_ratio": kv_ratio,+ "kyojin:requests_total": self.requests_total,+ "kyojin:requests_failed_total": self.requests_failed_total,+ "kyojin:queue_seconds_total": self.queue_seconds_total,+ "kyojin:start_time_seconds": self.start_time,+ "kyojin:sessions": self.sessions,+ "kyojin:context_tokens": self.context,+ **{name: (cache or {}).get(key) for name, key in CACHE_KEYS.items()},+ **{name: (gpu or {}).get(key) for name, key in GPU_KEYS.items()},}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")+ for name, mtype, help_text in METRICS + OPTIONAL:+ if values[name] is not None:+ out.append(f"# HELP {name} {help_text}\n# TYPE {name} {mtype}\n{name} {fmt(values[name])}\n")+ name, mtype, help_text = INFO+ labels = ",".join(f'{k}="{label(v)}"' for k, v in self.info.items())+ out.append(f"# HELP {name} {help_text}\n# TYPE {name} {mtype}\n{name}{{{labels}}} 1\n")return "".join(out).encode()