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 first-token time, cancellations, request age, evictions and finish reasons to the shared collector (#231)

Alessandro Del Prete2495025907f3
diff --git a/tools/ds41/serve.py b/tools/ds41/serve.py
index b1273d0..2727007 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, gpu_memory # noqa: E402 (symlink to the shared tools/strix_halo/serve_metrics.py)
+from serve_metrics import Metrics, cache_evictions, 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
@@ -242,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, queue_s: float = 0.0) -> None:
+ def observe(st: dict[str, Any], prompt_tokens: int, queue_s: float = 0.0, first_token_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))
@@ -253,7 +253,8 @@ 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, queue_s=queue_s)
+ draft_tokens=proposed, accepted=accepted, queue_s=queue_s, first_token_s=first_token_s,
+ reason=st.get("eos_reason"))
async def health(_: web.Request) -> web.Response:
return web.json_response({"status": "ok", "source": "kyojin", "model": model_id,
@@ -310,6 +311,7 @@ def create_app(engine: Any, model_id: str, defaults: Defaults | None = None) ->
rid = body.get("_reqid")
if cancel is not None and cancel.is_set(): # the client left while the job was queued: no prefill, no decode
lifecycle.job_skipped(rid, time.perf_counter() - (body.get("_queued_at") or time.perf_counter()))
+ app["metrics"].cancelled()
out.put_nowait(None)
queue.task_done()
continue
@@ -325,6 +327,7 @@ def create_app(engine: Any, model_id: str, defaults: Defaults | None = None) ->
processing=processing, running=running)
if sessions == 1:
engine.last_stats = {} # a cancelled or failed job must not re-count the previous one
+ run = app["metrics"].begin()
try:
async for delta in engine.generate(
body["_prompt"],
@@ -343,11 +346,14 @@ def create_app(engine: Any, model_id: str, defaults: Defaults | None = None) ->
out.put_nowait(delta)
finally:
running -= 1
+ app["metrics"].end(run)
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)),
- started - (body.get("_queued_at") or started))
+ started - (body.get("_queued_at") or started), (body.get("_first_at") or started) - started)
+ elif cancel is not None and cancel.is_set(): # cancelled while it ran: no stats
+ app["metrics"].cancelled()
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)
@@ -826,7 +832,8 @@ def create_app(engine: Any, model_id: str, defaults: Defaults | None = None) ->
except Exception: # noqa: BLE001 (stub engines, page-table mutation mid-walk)
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))),
+ gpu=gpu_memory(getattr(engine, "torch", None)),
+ evictions=cache_evictions(gen)),
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.py
index 4734728..71718db 100644
--- a/tools/ds41/serve_metrics.py
+++ b/tools/ds41/serve_metrics.py
@@ -5,9 +5,10 @@ Counters accumulate when a request completes (the HTTP layer observes the engine
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.
+The kyojin:* metrics have no llama.cpp counterpart: the request count, failures, cancellations and finish
+reasons, the queue time and the time to the first token, what the server is (version, server, model, sessions,
+context) and, read live at scrape, the age of the oldest running request, the cache's token counts and
+evictions and the device memory. A value a server does not pass is left out of the body.
"""
from __future__ import annotations
@@ -34,7 +35,10 @@ METRICS = [
"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:requests_cancelled_total", "counter", "Requests the client cancelled, while queued or while running"),
("kyojin:queue_seconds_total", "counter", "Time the finished requests waited for a session"),
+ ("kyojin:first_token_seconds_total", "counter", "Time the finished requests took from their start to the first token"),
+ ("kyojin:oldest_request_age_seconds", "gauge", "Run time of the oldest running request, 0 when none runs"),
("kyojin:start_time_seconds", "gauge", "Unix time the server began to serve, after the model loaded"),
]
@@ -46,12 +50,16 @@ OPTIONAL = [
("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:prompt_cache_evictions_total", "counter",
+ "Reusable prompt-cache pages given to new content; starts again at 0 when the cache is dropped"),
("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")
+# One sample per stop reason seen so far (label reason); rendered once a request has finished.
+FINISH = ("kyojin:finish_reasons_total", "counter", "Finished requests by the stop reason the engine reports")
# 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"}
@@ -83,6 +91,15 @@ def gpu_memory(torch) -> dict | None:
return None
+def cache_evictions(generator) -> int | None:
+ """Evicted prompt-cache pages for render(evictions=...): the complete pages the page table gave to new
+ content. None without a paged cache (fake engines in tests)."""
+ try:
+ return generator.pagetable.metrics["evictions_live"]
+ except Exception: # noqa: BLE001
+ return None
+
+
def label(value) -> str:
return str(value).replace("\\", "\\\\").replace("\n", "\\n").replace('"', '\\"')
@@ -98,7 +115,12 @@ class Metrics:
self.start_time = time.time()
self.requests_total = 0.0
self.requests_failed_total = 0.0
+ self.requests_cancelled_total = 0.0
self.queue_seconds_total = 0.0
+ self.first_token_seconds_total = 0.0
+ self.finish_reasons: dict[str, int] = {}
+ self.running: dict[int, float] = {} # begin() token -> start time of a request that runs now
+ self.serial = 0
self.prompt_tokens_total = 0.0
self.prompt_cached_total = 0.0
self.prompt_seconds_total = 0.0
@@ -113,9 +135,13 @@ 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, queue_s: float = 0.0) -> None:
+ drafts: int = 0, draft_tokens: int = 0, accepted: int = 0, queue_s: float = 0.0,
+ first_token_s: float = 0.0, reason: str | None = None) -> None:
self.requests_total += 1
self.queue_seconds_total += queue_s
+ self.first_token_seconds_total += first_token_s
+ if reason:
+ self.finish_reasons[str(reason)] = self.finish_reasons.get(str(reason), 0) + 1
self.prompt_tokens_total += prompt_tokens
self.prompt_cached_total += cached
self.prompt_seconds_total += prefill_s
@@ -134,9 +160,23 @@ class Metrics:
"""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 cancelled(self) -> None:
+ """A request the client cancelled, queued or running (it is not observed, so it is not in requests_total)."""
+ self.requests_cancelled_total += 1
+
+ def begin(self) -> int:
+ """A request starts to run: the token for end(). The oldest one that still runs sets oldest_request_age_seconds."""
+ self.serial += 1
+ self.running[self.serial] = time.perf_counter()
+ return self.serial
+
+ def end(self, token: int | None) -> None:
+ self.running.pop(token, None)
+
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."""
+ cache: dict | None = None, gpu: dict | None = None, evictions: int | None = None) -> bytes:
+ """`cache` is the generator's get_cache_stats(), `gpu` is gpu_memory(), `evictions` is cache_evictions():
+ all read by the server at scrape."""
values = {
"llamacpp:prompt_tokens_total": self.prompt_tokens_total,
"llamacpp:prompt_tokens_cached_total": self.prompt_cached_total,
@@ -154,17 +194,26 @@ class Metrics:
"llamacpp:kv_cache_usage_ratio": kv_ratio,
"kyojin:requests_total": self.requests_total,
"kyojin:requests_failed_total": self.requests_failed_total,
+ "kyojin:requests_cancelled_total": self.requests_cancelled_total,
"kyojin:queue_seconds_total": self.queue_seconds_total,
+ "kyojin:first_token_seconds_total": self.first_token_seconds_total,
+ "kyojin:oldest_request_age_seconds":
+ time.perf_counter() - min(self.running.values()) if self.running else 0.0,
"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()},
+ "kyojin:prompt_cache_evictions_total": evictions,
}
out = []
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")
+ if self.finish_reasons:
+ name, mtype, help_text = FINISH
+ out.append(f"# HELP {name} {help_text}\n# TYPE {name} {mtype}\n")
+ out.extend(f'{name}{{reason="{label(r)}"}} {n}\n' for r, n in sorted(self.finish_reasons.items()))
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")
diff --git a/tools/ds41/test_ds41_serve.py b/tools/ds41/test_ds41_serve.py
index 163d828..499e281 100644
--- a/tools/ds41/test_ds41_serve.py
+++ b/tools/ds41/test_ds41_serve.py
@@ -93,7 +93,7 @@ def test_health_models_metrics():
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 text
+ assert "kyojin:requests_total 0\n" in text and "kyojin:requests_cancelled_total 0\n" in text and f'server="ds41",model="{MODEL}"}} 1\n' in text
run(go())
diff --git a/tools/glm/SERVE.md b/tools/glm/SERVE.md
index 6387e42..61aa71c 100644
--- a/tools/glm/SERVE.md
+++ b/tools/glm/SERVE.md
@@ -97,17 +97,23 @@ Prometheus text (llama.cpp `llamacpp:*` names) for scraping. Counters accumulate
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`). A request cancelled mid-stream is not counted in this first version.
+`max_tokens`). A cancelled request counts only in `kyojin:requests_cancelled_total`.
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).
+engine error) and `kyojin:requests_cancelled_total` (requests the client cancelled, while queued or while
+running); the last two are not in `requests_total`. `kyojin:finish_reasons_total{reason}` splits the
+finished requests by the stop reason the engine reports (`stop_token`, `stop_string`, `max_new_tokens`
+and so on). `kyojin:queue_seconds_total` is the time the finished requests waited for a session and
+`kyojin:first_token_seconds_total` the time from their start to the first token; each one over
+`requests_total` is a mean. Then `kyojin:start_time_seconds`, `kyojin:sessions`, `kyojin:context_tokens`
+and `kyojin:info{version, server, model}` (constant 1). Read live at scrape:
+`kyojin:oldest_request_age_seconds` (run time of the oldest running request, 0 when none runs), the
+cache's token counts (`kyojin:kv_cache_max_tokens`, `kyojin:kv_cache_used_tokens`,
+`kyojin:kv_cache_free_tokens`, `kyojin:prompt_cache_tokens`), `kyojin:prompt_cache_evictions_total`
+(reusable prompt-cache pages the page table gave to new content; it starts again at 0 when the cache is
+dropped) 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`
diff --git a/tools/glm/serve.py b/tools/glm/serve.py
index faa138c..40d1392 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-phase
import 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, gpu_memory
+from serve_metrics import Metrics, cache_evictions, 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.
@@ -1548,7 +1548,7 @@ def create_app(engine: Any, model_id: str, template: str, admin_knobs: bool = Fa
raise web.HTTPBadRequest(reason="cache_salt is not supported by this engine")
return salt
- def observe(st: dict[str, Any], prompt_tokens: int, queue_s: float = 0.0) -> None:
+ def observe(st: dict[str, Any], prompt_tokens: int, queue_s: float = 0.0, first_token_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)
@@ -1560,7 +1560,8 @@ def create_app(engine: Any, model_id: str, template: str, admin_knobs: bool = Fa
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 // num_draft if proposed and num_draft else 0,
- draft_tokens=proposed, accepted=accepted, queue_s=queue_s)
+ draft_tokens=proposed, accepted=accepted, queue_s=queue_s, first_token_s=first_token_s,
+ reason=st.get("eos_reason"))
async def health(_: web.Request) -> web.Response:
return web.json_response({"status": "ok", "source": "kyojin", "model": model_id,
@@ -1635,6 +1636,7 @@ def create_app(engine: Any, model_id: str, template: str, admin_knobs: bool = Fa
rid = body.get("_reqid")
if cancel is not None and cancel.is_set(): # the client left while the job was queued: no prefill, no decode
lifecycle.job_skipped(rid, time.perf_counter() - (body.get("_queued_at") or time.perf_counter()))
+ app["metrics"].cancelled()
out.put_nowait(None)
queue.task_done()
continue
@@ -1654,6 +1656,7 @@ def create_app(engine: Any, model_id: str, template: str, admin_knobs: bool = Fa
store.busy = True
if sessions == 1:
engine.last_stats = {} # a cancelled or failed job must not re-count the previous one
+ run = app["metrics"].begin()
try:
async for delta in engine.generate(
body["_prompt"],
@@ -1674,13 +1677,16 @@ def create_app(engine: Any, model_id: str, template: str, admin_knobs: bool = Fa
out.put_nowait(delta)
finally:
running -= 1
+ app["metrics"].end(run)
if sessions > 1 and store is not None:
store.busy = running > 0
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)),
- started - (body.get("_queued_at") or started))
+ started - (body.get("_queued_at") or started), (body.get("_first_at") or started) - started)
+ elif cancel is not None and cancel.is_set(): # cancelled while it ran: no stats
+ app["metrics"].cancelled()
log_job_done(rid, body, request_stats, started)
out.put_nowait(None)
if getattr(engine, "prefix_disk", None) is not None:
@@ -2212,7 +2218,7 @@ def create_app(engine: Any, model_id: str, template: str, admin_knobs: bool = Fa
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))),
+ gpu=gpu_memory(getattr(engine, "torch", None)), evictions=cache_evictions(gen)),
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.py
index 85cd8d7..ccbdce4 100644
--- a/tools/glm/test_serve.py
+++ b/tools/glm/test_serve.py
@@ -500,6 +500,8 @@ class ServeTests(unittest.TestCase):
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["kyojin:requests_cancelled_total"], v["kyojin:oldest_request_age_seconds"]), (0, 0))
+ self.assertGreaterEqual(v["kyojin:first_token_seconds_total"], 0)
self.assertEqual(v["llamacpp:kv_cache_usage_ratio"], 0) # fake engine: no get_cache_stats
def test_stream_handler_finishes_after_stream(self):
diff --git a/tools/mimo/SERVE.md b/tools/mimo/SERVE.md
index 1ccdf75..cad070b 100644
--- a/tools/mimo/SERVE.md
+++ b/tools/mimo/SERVE.md
@@ -58,9 +58,10 @@ top-level config does not carry `max_position_embeddings` — the GLM fix.
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. A request cancelled mid-stream is not counted in this
- 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
+ `--spec-gate` falls back to plain. A cancelled request counts only in
+ `kyojin:requests_cancelled_total`. The `kyojin:*` metrics (request count, failures, cancellations, finish reasons,
+ queue time, time to first token, oldest request age, version, server and model, sessions, context, cache token
+ counts and evictions, device memory) are the same on every server: see `GET /metrics` in
`tools/glm/SERVE.md`.
## Diagnostics: the request log
diff --git a/tools/mimo/serve.py b/tools/mimo/serve.py
index 0a0d135..230f58e 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, gpu_memory
+from serve_metrics import Metrics, cache_evictions, 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.
@@ -554,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, queue_s: float = 0.0) -> None:
+ def observe(st: dict[str, Any], prompt_tokens: int, queue_s: float = 0.0, first_token_s: float = 0.0) -> None:
accepted = int(st.get("accepted_draft_tokens", 0))
rejected = int(st.get("rejected_draft_tokens", 0))
proposed = accepted + rejected
@@ -566,7 +566,8 @@ 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, queue_s=queue_s)
+ draft_tokens=proposed, accepted=accepted, queue_s=queue_s, first_token_s=first_token_s,
+ reason=st.get("eos_reason"))
async def models(_: web.Request) -> web.Response:
return web.json_response({"object": "list", "data": [
@@ -597,11 +598,13 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
body["_job_at"] = time.perf_counter()
if cancel is not None and cancel.is_set(): # the client left while the job was queued: no prefill, no decode
lifecycle.job_skipped(rid, wait)
+ app["metrics"].cancelled()
out.put_nowait(None)
queue.task_done()
continue
store = getattr(engine, "slot_store", None)
processing += 1 # admitted: counted from the dequeue, incl. lock and slot restore
+ run = None
try:
async with lock:
if store is not None:
@@ -610,6 +613,7 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
images=len(body.get("_images") or ()),
messages=len(body.get("messages") or ()), processing=processing)
first_token = False # flipped once, so the log gets exactly one job_first_token line
+ run = app["metrics"].begin()
async for delta in engine.generate(
body["_prompt"],
max_tokens=token_limit(body),
@@ -625,7 +629,10 @@ 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)), wait)
+ observe(request_stats, body.get("_prompt_tokens") or int(request_stats.get("prompt_tokens", 0)), wait,
+ (body.get("_first_at") or body["_job_at"]) - body["_job_at"])
+ elif cancel is not None and cancel.is_set(): # cancelled while it ran: no stats
+ app["metrics"].cancelled()
lifecycle.job_done(rid, request_stats, started, prompt_tokens=body.get("_prompt_tokens"))
out.put_nowait(None)
except Exception as exc: # noqa: BLE001
@@ -634,6 +641,7 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
out.put_nowait(exc)
finally:
processing -= 1
+ app["metrics"].end(run)
if store is not None:
store.busy = False
queue.task_done()
@@ -972,7 +980,7 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
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))),
+ gpu=gpu_memory(getattr(engine, "torch", None)), evictions=cache_evictions(gen)),
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.py
index 29a0ede..08414b4 100644
--- a/tools/mimo/test_serve.py
+++ b/tools/mimo/test_serve.py
@@ -516,6 +516,8 @@ class ServeTests(unittest.TestCase):
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["kyojin:requests_cancelled_total"], v["kyojin:oldest_request_age_seconds"]), (0, 0))
+ self.assertGreaterEqual(v["kyojin:first_token_seconds_total"], 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):
diff --git a/tools/qwen/SERVE.md b/tools/qwen/SERVE.md
index 135eaaf..088f8d2 100644
--- a/tools/qwen/SERVE.md
+++ b/tools/qwen/SERVE.md
@@ -91,13 +91,14 @@ The pack is tied to one set of weights: download it from the same model repo.
- Errors are JSON `{"error": {"message", "type", "code"}}`: 400 for bad requests (including prompt longer than the
context), 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.
+ MiMo servers). Counters accumulate when a request completes, on every generation route; a cancelled request
+ counts only in `kyojin:requests_cancelled_total`. `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
+ cancellations, finish reasons, queue time, time to first token, oldest request age, version, server and model,
+ sessions, context, cache token counts and evictions, 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),
diff --git a/tools/qwen/serve.py b/tools/qwen/serve.py
index 94ab484..b2a00de 100644
--- a/tools/qwen/serve.py
+++ b/tools/qwen/serve.py
@@ -53,7 +53,7 @@ from serve_ping import ServePing # noqa: E402
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: E402
+from serve_metrics import Metrics, cache_evictions, gpu_memory # noqa: E402
def _load_mimo():
@@ -1728,7 +1728,7 @@ 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:
+ def observe(st: dict[str, Any], prompt_tokens: int, queue_s: float = 0.0, first_token_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
@@ -1740,7 +1740,8 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, An
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)
+ queue_s=queue_s, first_token_s=first_token_s,
+ reason=st.get("eos_reason"))
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(),
@@ -1790,6 +1791,7 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, An
if job.get("cancel") is not None and job["cancel"].is_set():
# the client left while the job was queued: no prefill, no decode, one line
lifecycle.job_skipped(rid, wait)
+ app["metrics"].cancelled()
out.put_nowait(("done", {}))
queue.task_done()
continue
@@ -1803,6 +1805,7 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, An
images=len(job.get("images") or ()),
messages=job.get("messages"), sessions=sessions, running=running)
first_token = False # flipped once, so the log gets exactly one job_first_token line
+ run = app["metrics"].begin()
try:
async for delta in engine.generate(
job["prompt"], stats=stats, live=job.setdefault("_live", {}), max_tokens=job["max_tokens"], sampling=job["sampling"],
@@ -1820,6 +1823,7 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, An
out.put_nowait(delta)
finally:
running -= 1
+ app["metrics"].end(run)
if store is not None:
store.busy = running > 0
# a fake engine (tests) fills only last_stats
@@ -1832,8 +1836,11 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, An
t = engine.torch.cuda
print(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)
+ if done:
+ observe(done, int(done.get("prompt_tokens") or job.get("prompt_tokens") or 0), wait,
+ (job.get("_first_at") or job["_job_at"]) - job["_job_at"])
+ elif job.get("cancel") is not None and job["cancel"].is_set(): # cancelled while it ran: no stats
+ app["metrics"].cancelled()
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:
@@ -2443,7 +2450,8 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, An
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))),
+ gpu=gpu_memory(getattr(engine, "torch", None)),
+ evictions=cache_evictions(getattr(engine, "generator", None))),
headers={"Content-Type": "text/plain; version=0.0.4; charset=utf-8"})
if admin_knobs:
diff --git a/tools/qwen/test_serve.py b/tools/qwen/test_serve.py
index e08dab0..e384b45 100644
--- a/tools/qwen/test_serve.py
+++ b/tools/qwen/test_serve.py
@@ -987,7 +987,11 @@ class MetricsTests(unittest.TestCase):
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.assertEqual((v["kyojin:requests_cancelled_total"], v["kyojin:oldest_request_age_seconds"]), (0, 0))
self.assertGreaterEqual(v["kyojin:queue_seconds_total"], 0)
+ self.assertGreaterEqual(v["kyojin:first_token_seconds_total"], 0)
+ self.assertIn("# TYPE kyojin:finish_reasons_total counter\n", text)
+ self.assertEqual(v['kyojin:finish_reasons_total{reason="stop_token"}'], 1)
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)
@@ -1007,6 +1011,7 @@ class MetricsTests(unittest.TestCase):
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)
+ self.assertEqual(v['kyojin:finish_reasons_total{reason="stop_token"}'], 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
@@ -1030,6 +1035,14 @@ class MetricsTests(unittest.TestCase):
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_evictions_come_from_the_page_table(self):
+ engine = FakeEngine("x")
+ engine.generator = types.SimpleNamespace(get_cache_stats=lambda: {"used_tokens": 0, "max_tokens": 4096},
+ pagetable=types.SimpleNamespace(metrics={"evictions_live": 3}))
+ text = self.scrape(engine)[3]
+ self.assertIn("# TYPE kyojin:prompt_cache_evictions_total counter\n", text)
+ self.assertEqual(self.samples(text)["kyojin:prompt_cache_evictions_total"], 3)
+
def test_device_memory_comes_from_the_engine_torch(self):
engine = FakeEngine("x")
engine.torch = types.SimpleNamespace(cuda=types.SimpleNamespace(
@@ -1049,6 +1062,52 @@ class MetricsTests(unittest.TestCase):
self.assertEqual((v["kyojin:requests_total"], v["kyojin:requests_failed_total"]), (0, 1))
self.assertEqual(v["llamacpp:tokens_predicted_total"], 0)
+ def test_request_cancelled_while_it_runs_is_counted_as_cancelled_only(self):
+ class Endless(FakeEngine):
+ async def generate(self, prompt, cancel=None, **kw):
+ while not cancel.is_set(): # the real engine too returns without stats once the client left
+ await asyncio.sleep(0.005)
+ yield "word "
+
+ async def fn(client):
+ body = {"model": "m", "stream": True, "messages": [{"role": "user", "content": "hi"}]}
+ r = await client.post("/v1/chat/completions", json=body)
+ await r.content.readline()
+ r.close()
+ for _ in range(100):
+ await asyncio.sleep(0.05)
+ text = await (await client.get("/metrics")).text()
+ if self.samples(text)["kyojin:requests_cancelled_total"]:
+ break
+ return text
+ text = with_client(Endless(""), fn)
+ v = self.samples(text)
+ self.assertEqual((v["kyojin:requests_total"], v["kyojin:requests_cancelled_total"]), (0, 1))
+ self.assertEqual((v["llamacpp:requests_processing"], v["kyojin:oldest_request_age_seconds"]), (0, 0))
+ self.assertEqual(v["llamacpp:tokens_predicted_total"], 0)
+ self.assertNotIn("kyojin:finish_reasons_total", text)
+
+ def test_first_token_time_and_the_age_of_a_running_request(self):
+ class Slow(FakeEngine):
+ async def generate(self, prompt, **kw):
+ await asyncio.sleep(0.3)
+ async for piece in super().generate(prompt, **kw):
+ yield piece
+
+ async def fn(client):
+ body = {"model": "m", "messages": [{"role": "user", "content": "hi"}]}
+ req = asyncio.ensure_future(client.post("/v1/chat/completions", json=body))
+ await asyncio.sleep(0.15)
+ running = await (await client.get("/metrics")).text()
+ return (await req).status, running, await (await client.get("/metrics")).text()
+ status, running, done = with_client(Slow("x"), fn)
+ r, d = self.samples(running), self.samples(done)
+ self.assertEqual(status, 200)
+ self.assertGreater(r["kyojin:oldest_request_age_seconds"], 0.02) # it runs: its age shows, nothing else yet
+ self.assertEqual((r["kyojin:first_token_seconds_total"], r["kyojin:requests_total"]), (0, 0))
+ self.assertEqual(d["kyojin:oldest_request_age_seconds"], 0)
+ self.assertGreater(d["kyojin:first_token_seconds_total"], 0.25) # the engine's 0.3 s before its first piece
+
def test_queue_time_of_a_request_that_waited_is_counted(self):
class Slow(FakeEngine):
async def generate(self, prompt, **kw):
diff --git a/tools/strix_halo/serve_metrics.py b/tools/strix_halo/serve_metrics.py
index 4734728..71718db 100644
--- a/tools/strix_halo/serve_metrics.py
+++ b/tools/strix_halo/serve_metrics.py
@@ -5,9 +5,10 @@ Counters accumulate when a request completes (the HTTP layer observes the engine
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.
+The kyojin:* metrics have no llama.cpp counterpart: the request count, failures, cancellations and finish
+reasons, the queue time and the time to the first token, what the server is (version, server, model, sessions,
+context) and, read live at scrape, the age of the oldest running request, the cache's token counts and
+evictions and the device memory. A value a server does not pass is left out of the body.
"""
from __future__ import annotations
@@ -34,7 +35,10 @@ METRICS = [
"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:requests_cancelled_total", "counter", "Requests the client cancelled, while queued or while running"),
("kyojin:queue_seconds_total", "counter", "Time the finished requests waited for a session"),
+ ("kyojin:first_token_seconds_total", "counter", "Time the finished requests took from their start to the first token"),
+ ("kyojin:oldest_request_age_seconds", "gauge", "Run time of the oldest running request, 0 when none runs"),
("kyojin:start_time_seconds", "gauge", "Unix time the server began to serve, after the model loaded"),
]
@@ -46,12 +50,16 @@ OPTIONAL = [
("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:prompt_cache_evictions_total", "counter",
+ "Reusable prompt-cache pages given to new content; starts again at 0 when the cache is dropped"),
("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")
+# One sample per stop reason seen so far (label reason); rendered once a request has finished.
+FINISH = ("kyojin:finish_reasons_total", "counter", "Finished requests by the stop reason the engine reports")
# 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"}
@@ -83,6 +91,15 @@ def gpu_memory(torch) -> dict | None:
return None
+def cache_evictions(generator) -> int | None:
+ """Evicted prompt-cache pages for render(evictions=...): the complete pages the page table gave to new
+ content. None without a paged cache (fake engines in tests)."""
+ try:
+ return generator.pagetable.metrics["evictions_live"]
+ except Exception: # noqa: BLE001
+ return None
+
+
def label(value) -> str:
return str(value).replace("\\", "\\\\").replace("\n", "\\n").replace('"', '\\"')
@@ -98,7 +115,12 @@ class Metrics:
self.start_time = time.time()
self.requests_total = 0.0
self.requests_failed_total = 0.0
+ self.requests_cancelled_total = 0.0
self.queue_seconds_total = 0.0
+ self.first_token_seconds_total = 0.0
+ self.finish_reasons: dict[str, int] = {}
+ self.running: dict[int, float] = {} # begin() token -> start time of a request that runs now
+ self.serial = 0
self.prompt_tokens_total = 0.0
self.prompt_cached_total = 0.0
self.prompt_seconds_total = 0.0
@@ -113,9 +135,13 @@ 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, queue_s: float = 0.0) -> None:
+ drafts: int = 0, draft_tokens: int = 0, accepted: int = 0, queue_s: float = 0.0,
+ first_token_s: float = 0.0, reason: str | None = None) -> None:
self.requests_total += 1
self.queue_seconds_total += queue_s
+ self.first_token_seconds_total += first_token_s
+ if reason:
+ self.finish_reasons[str(reason)] = self.finish_reasons.get(str(reason), 0) + 1
self.prompt_tokens_total += prompt_tokens
self.prompt_cached_total += cached
self.prompt_seconds_total += prefill_s
@@ -134,9 +160,23 @@ class Metrics:
"""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 cancelled(self) -> None:
+ """A request the client cancelled, queued or running (it is not observed, so it is not in requests_total)."""
+ self.requests_cancelled_total += 1
+
+ def begin(self) -> int:
+ """A request starts to run: the token for end(). The oldest one that still runs sets oldest_request_age_seconds."""
+ self.serial += 1
+ self.running[self.serial] = time.perf_counter()
+ return self.serial
+
+ def end(self, token: int | None) -> None:
+ self.running.pop(token, None)
+
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."""
+ cache: dict | None = None, gpu: dict | None = None, evictions: int | None = None) -> bytes:
+ """`cache` is the generator's get_cache_stats(), `gpu` is gpu_memory(), `evictions` is cache_evictions():
+ all read by the server at scrape."""
values = {
"llamacpp:prompt_tokens_total": self.prompt_tokens_total,
"llamacpp:prompt_tokens_cached_total": self.prompt_cached_total,
@@ -154,17 +194,26 @@ class Metrics:
"llamacpp:kv_cache_usage_ratio": kv_ratio,
"kyojin:requests_total": self.requests_total,
"kyojin:requests_failed_total": self.requests_failed_total,
+ "kyojin:requests_cancelled_total": self.requests_cancelled_total,
"kyojin:queue_seconds_total": self.queue_seconds_total,
+ "kyojin:first_token_seconds_total": self.first_token_seconds_total,
+ "kyojin:oldest_request_age_seconds":
+ time.perf_counter() - min(self.running.values()) if self.running else 0.0,
"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()},
+ "kyojin:prompt_cache_evictions_total": evictions,
}
out = []
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")
+ if self.finish_reasons:
+ name, mtype, help_text = FINISH
+ out.append(f"# HELP {name} {help_text}\n# TYPE {name} {mtype}\n")
+ out.extend(f'{name}{{reason="{label(r)}"}} {n}\n' for r, n in sorted(self.finish_reasons.items()))
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")