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
Serve: one llama.cpp timings shape on glm, qwen, mimo and ds41, progressive timings from the engine token counter, prefill/decode tok/s in the per-request line (#156)
Yaniss Amazouz11a8d924a8d7
diff --git a/tools/ds41/serve.py b/tools/ds41/serve.pyindex 0e96241..102040f 100644--- a/tools/ds41/serve.py+++ b/tools/ds41/serve.py@@ -313,7 +313,7 @@ def create_app(engine: Any, model_id: str, defaults: Defaults | None = None) ->queue.task_done()continueprocessing += 1- started = time.perf_counter()+ started = body["_job_at"] = time.perf_counter()first_token = Falsetry:async with admit(body.get("_cache_salt")):@@ -337,6 +337,7 @@ def create_app(engine: Any, model_id: str, defaults: Defaults | None = None) ->**({"stats": request_stats} if sessions > 1 else {})):if not first_token:first_token = True+ body["_first_at"] = time.perf_counter()lifecycle.first_token(rid, started, prompt_tokens=body.get("_prompt_tokens"))out.put_nowait(delta)finally:@@ -497,14 +498,7 @@ def create_app(engine: Any, model_id: str, defaults: Defaults | None = None) ->def timings() -> dict[str, Any]:# llama.cpp names: the swap orchestrator reads cache_n as the verdict of a KV restore- st = request_stats- cache_n = int(st.get("cached_tokens", 0))- pre, gen = st.get("time_prefill") or 0.0, st.get("time_generate") or 0.0- n = int(st.get("new_tokens", 0))- return {"cache_n": cache_n, "prompt_n": max(prompt_tokens - cache_n, 0),- "prompt_ms": pre * 1000, "predicted_n": n, "predicted_ms": gen * 1000,- "prompt_per_second": (prompt_tokens - cache_n) / pre if pre else 0.0,- "predicted_per_second": n / gen if gen else 0.0, **draft_timings(st)}+ return serve_compat.stats_timings(prompt_tokens, request_stats, **draft_timings(request_stats))if body.get("stream", False):response = web.StreamResponse(headers={"Content-Type": "text/event-stream", "Cache-Control": "no-cache"})diff --git a/tools/ds41/serve_reqlog.py b/tools/ds41/serve_reqlog.pyindex e5db9b0..68b39f0 100644--- a/tools/ds41/serve_reqlog.py+++ b/tools/ds41/serve_reqlog.py@@ -385,7 +385,7 @@ class Lifecycle:def job_started(self, rid: str | None, wait: float, **fields: Any) -> None:"""The worker picked the job up: `wait` is the queue time, the rest is what this server knows."""- self.track(rid, "prefill", prompt_tokens=fields.get("prompt_tokens"))+ self.track(rid, "prefill", prompt_tokens=fields.get("prompt_tokens"), wait_s=wait)self.reqlog.log("job_start", req=rid, wait_s=round(wait, 3), **fields)def job_skipped(self, rid: str | None, queued_s: float) -> None:@@ -403,12 +403,22 @@ class Lifecycle:st = stats or {}prompt = int(st.get("prompt_tokens") or prompt_tokens or 0)cache_n = int(st.get("cached_tokens") or 0)+ new_tokens = int(st.get("new_tokens") or 0)+ prefill_s, decode_s = float(st.get("time_prefill") or 0.0), float(st.get("time_generate") or 0.0)+ fresh = max(prompt - cache_n, 0)self.reqlog.log("job_done", req=rid, elapsed_s=round(time.perf_counter() - started, 3),prompt_tokens=prompt, cache_n=cache_n,cache_pct=round(100.0 * cache_n / prompt, 1) if prompt else 0.0,- new_tokens=int(st.get("new_tokens") or 0),- prefill_s=round(float(st.get("time_prefill") or 0.0), 3),- decode_s=round(float(st.get("time_generate") or 0.0), 3))+ new_tokens=new_tokens,+ prefill_s=round(prefill_s, 3), decode_s=round(decode_s, 3),+ prefill_tps=round(fresh / prefill_s, 1) if prefill_s else 0.0,+ decode_tps=round(new_tokens / decode_s, 1) if decode_s else 0.0)+ # The speed line of every request, on stderr whatever the request log says (the Mac server prints the same fields).+ wait = (self.inflight.get(rid) or {}).get("wait_s", 0.0) if rid else 0.0+ print(f"{time.strftime('%H:%M:%S')} req={rid} prompt={fresh} cached={cache_n} gen={new_tokens} queue={wait:.2f}s "+ f"prefill={prefill_s:.2f}s ({fresh / prefill_s if prefill_s else 0.0:.1f} tok/s) "+ f"decode={decode_s:.2f}s ({new_tokens / decode_s if decode_s else 0.0:.1f} tok/s) total={time.perf_counter() - started:.2f}s",+ file=sys.stderr, flush=True)def job_error(self, rid: str | None, exc: BaseException, started: float | None = None) -> None:self.reqlog.log("job_error", req=rid, error=sanitize(exc),diff --git a/tools/glm/serve.py b/tools/glm/serve.pyindex 7d0db0a..513085f 100644--- a/tools/glm/serve.py+++ b/tools/glm/serve.py@@ -945,7 +945,7 @@ class ResidentEngine:cancel: asyncio.Event | None = None,images: list | None = None, stats: dict | None = None, img_stats: dict | None = None,prompt_ids: list[int] | None = None, ignore_eos: bool = False,- loop_guard: bool | None = None) -> AsyncIterator[str]:+ loop_guard: bool | None = None, live: dict | None = None) -> AsyncIterator[str]:"""Yield incremental decoded text. With sessions == 1 the caller serializes access to this method; withsessions > 1 several calls may run at once and the final stats of a request land in `stats`.@@ -999,7 +999,7 @@ class ResidentEngine:stop_conditions=conditions, embeddings=embs or None,**({} if rq is None else {"max_rq_tokens": rq}))if self.sessions > 1:- async for piece in self._run_shared(job, ids, cancel, stats if stats is not None else {}, t0, probe, prompt, ignore_eos, loop_guard):+ async for piece in self._run_shared(job, ids, cancel, stats if stats is not None else {}, t0, probe, prompt, ignore_eos, loop_guard, live):yield piecereturnloop = asyncio.get_running_loop()@@ -1026,6 +1026,8 @@ class ResidentEngine:self.last_stats = guard_stats(hit, seen)returnseen += token_count(event)+ if live is not None and event.get("token_ids") is not None:+ live["n"] = seen # the generator's own count, read by the stream for the progressive timingsif event.get("eos"):self.last_stats = eventif probe is not None:@@ -1136,7 +1138,7 @@ class ResidentEngine:q.put_nowait(evs)async def _run_shared(self, job, ids, cancel, stats: dict, t0: float, probe, prompt: str = "", ignore_eos: bool = False,- loop_guard: bool | None = None) -> AsyncIterator[str]:+ loop_guard: bool | None = None, live: dict | None = None) -> AsyncIterator[str]:"""One request's job in the shared Generator: enqueue on the driver, stream its events, and (whatever way thisends) remove the job, so no leftover job runs inside another request."""q: asyncio.Queue = asyncio.Queue()@@ -1170,6 +1172,8 @@ class ResidentEngine:self.last_stats = statsreturn # the finally block cancels the jobseen += token_count(event)+ if live is not None and event.get("token_ids") is not None:+ live["n"] = seenif event.get("eos"):stats.update(event)self.last_stats = stats@@ -1482,7 +1486,7 @@ def create_app(engine: Any, model_id: str, template: str, admin_knobs: bool = Facontinuestore = getattr(engine, "slot_store", None)processing += 1 # admitted: counted from the dequeue, incl. lock and slot restore- started = time.perf_counter()+ started = body["_job_at"] = time.perf_counter()first_token = False # flipped once, so the log gets exactly one job_first_token linetry:async with admit(body.get("_cache_salt")):@@ -1506,9 +1510,11 @@ def create_app(engine: Any, model_id: str, template: str, admin_knobs: bool = Fa**({"prompt_ids": body["_prompt_ids"]} if body.get("_prompt_ids") is not None else {}),**({"ignore_eos": True} if body.get("_ignore_eos") else {}),**({"loop_guard": body["_loop_guard"]} if body.get("_loop_guard") is not None else {}),+ live=body.setdefault("_live", {}),**({"stats": request_stats} if sessions > 1 else {})):if not first_token:first_token = True+ body["_first_at"] = time.perf_counter()lifecycle.first_token(rid, started,prompt_tokens=body.get("_prompt_tokens"))out.put_nowait(delta)@@ -1673,15 +1679,8 @@ def create_app(engine: Any, model_id: str, template: str, admin_knobs: bool = Fadef timings(raw: str) -> dict[str, Any]:# llama.cpp names: the swap orchestrator reads cache_n as the verdict of a KV restore- st = request_stats- cache_n = int(st.get("cached_tokens", 0))- pre, gen = st.get("time_prefill") or 0.0, st.get("time_generate") or 0.0- n = int(st.get("new_tokens", 0))- return {"cache_n": cache_n, "prompt_n": max(prompt_tokens - cache_n, 0),- "prompt_ms": pre * 1000, "predicted_n": n, "predicted_ms": gen * 1000,- "prompt_per_second": (prompt_tokens - cache_n) / pre if pre else 0.0,- "predicted_per_second": n / gen if gen else 0.0,- **({"loop_guard": st["loop_guard"]} if st.get("loop_guard") else {})}+ return serve_compat.stats_timings(prompt_tokens, request_stats,+ **({"loop_guard": request_stats["loop_guard"]} if request_stats.get("loop_guard") else {}))if body.get("stream", False):response = web.StreamResponse(headers={"Content-Type": "text/event-stream", "Cache-Control": "no-cache"})@@ -1693,6 +1692,7 @@ def create_app(engine: Any, model_id: str, template: str, admin_knobs: bool = Fatext, done, mode = prefix, len(prefix), "reasoning" if prefix else "content"holds = ["</think>", "<think>", TOOL_OPEN] + [x for x in body["_stop"] if x]visible: list[float] = [] # set at the first frame with text in it: the client's first sign of life+ live = serve_compat.LiveTimings(body, prompt_tokens, lambda: request_stats) # progressive timings, once per secondasync def flush(final: bool) -> None:nonlocal done, mode@@ -1706,7 +1706,7 @@ def create_app(engine: Any, model_id: str, template: str, admin_knobs: bool = Favisible.append(time.perf_counter())lifecycle.first_content(body["_reqid"], body["_queued_at"])key = "reasoning_content" if mode == "reasoning" else "content"- await writer.write(sse(event({key: piece})))+ await writer.write(sse(event({key: piece}) | ({"timings": t} if (t := live.take()) else {})))ping.note_output() # the client has text: comments wait for the next silencedone = endif not hits:@@ -1721,6 +1721,8 @@ def create_app(engine: Any, model_id: str, template: str, admin_knobs: bool = Faasync for delta in deltas(writer):text += deltaawait flush(False)+ if (t := live.take()) is not None: # nothing went out for a second (held tool call, tags): an empty delta carries them+ await writer.write(sse(event({}) | {"timings": t}))text, _ = stop_text(text, body["_stop"])await flush(True)message = parse_completion(text)diff --git a/tools/mimo/serve.py b/tools/mimo/serve.pyindex 9f4239f..3029165 100644--- a/tools/mimo/serve.py+++ b/tools/mimo/serve.py@@ -34,6 +34,7 @@ from jinja2.sandbox import ImmutableSandboxedEnvironmentsys.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.pyfrom serve_metrics import Metrics# serve_ping.py is a symlink to the shared tools/strix_halo/serve_ping.py: an SSE comment line every@@ -448,7 +449,7 @@ class ResidentEngine:async def generate(self, prompt: str, *, max_tokens: int, temperature: float, top_p: float,stop: list[str], reset_gate: bool = False,cancel: asyncio.Event | None = None,- images: list | None = None) -> AsyncIterator[str]:+ images: list | None = None, live: dict | None = None) -> AsyncIterator[str]:"""Yield incremental decoded text. The caller serializes access to this method.When `cancel` is set (client gone) the job is cancelled between two generator steps. A step is one@@ -491,6 +492,8 @@ class ResidentEngine:for event in batch:if event.get("error"):raise RuntimeError(str(event["error"]))+ if live is not None and event.get("token_ids") is not None:+ live["n"] = live.get("n", 0) + int(event["token_ids"].numel()) # the generator's own count, read by the streamtext = event.get("text", "")if text:yield text@@ -590,6 +593,7 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:# the difference, and it is logged on its own as wait_s.wait = time.perf_counter() - (body.get("_queued_at") or time.perf_counter())started = time.perf_counter() - wait+ 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 decodelifecycle.job_skipped(rid, wait)out.put_nowait(None)@@ -611,9 +615,11 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:temperature=body.get("temperature", SERVE_DEFAULTS["temperature"]),top_p=body.get("top_p", SERVE_DEFAULTS["top_p"]), stop=body.get("_stop", []),reset_gate=body.get("_reset_gate", False),- cancel=body.get("_cancel"), **({"images": body["_images"]} if body.get("_images") else {})):+ cancel=body.get("_cancel"), live=body.setdefault("_live", {}),+ **({"images": body["_images"]} if body.get("_images") else {})):if not first_token:first_token = True+ body["_first_at"] = time.perf_counter()lifecycle.first_token(rid, started, prompt_tokens=body.get("_prompt_tokens"))out.put_nowait(delta)request_stats.update(getattr(engine, "last_stats", None) or {})@@ -755,14 +761,7 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:def timings() -> dict[str, Any]:# llama.cpp names: the swap orchestrator reads cache_n as the verdict of a KV restore- st = request_stats- cache_n = int(st.get("cached_tokens", 0))- pre, gen = st.get("time_prefill") or 0.0, st.get("time_generate") or 0.0- n = int(st.get("new_tokens", 0))- return {"cache_n": cache_n, "prompt_n": max(prompt_tokens - cache_n, 0),- "prompt_ms": pre * 1000, "predicted_n": n, "predicted_ms": gen * 1000,- "prompt_per_second": (prompt_tokens - cache_n) / pre if pre else 0.0,- "predicted_per_second": n / gen if gen else 0.0}+ return serve_compat.stats_timings(prompt_tokens, request_stats)if body.get("stream", False):response = web.StreamResponse(headers={"Content-Type": "text/event-stream",@@ -780,6 +779,7 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:# A mutable cell, not a flag: the nested flush() assigns it, and a plain name assigned there# would be local to that closure (UnboundLocalError) instead of shared with the handler.seen = {"text": False} # flipped at the first frame with text: the client's first sign of life+ live = serve_compat.LiveTimings(body, prompt_tokens, lambda: request_stats) # progressive timings, once per secondasync def flush(final: bool) -> None:nonlocal done, mode@@ -793,7 +793,7 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:if not seen["text"]:seen["text"] = Truelifecycle.first_content(body["_reqid"], body["_queued_at"])- await writer.write(sse(event({key: piece})))+ await writer.write(sse(event({key: piece}) | ({"timings": t} if (t := live.take()) else {})))ping.note_output() # the client has text: comments wait for the next silencedone = endif not hits:@@ -808,6 +808,8 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:async for delta in deltas(writer):text += deltaawait flush(False)+ if (t := live.take()) is not None: # nothing went out for a second (held tool call, tags): an empty delta carries them+ await writer.write(sse(event({}) | {"timings": t}))text, _ = stop_text(text, body["_stop"])await flush(True)message = parse_completion(text, body.get("tools"))diff --git a/tools/qwen/serve.py b/tools/qwen/serve.pyindex 928db79..2884cdb 100644--- a/tools/qwen/serve.py+++ b/tools/qwen/serve.py@@ -1277,7 +1277,7 @@ class QwenEngine:cancel: asyncio.Event | None = None, seed: int | None = None, reasoning_first: bool = False,thinking_budget: int | None = None, loop_guard: bool | None = None,loop_final: bool | None = None, logprobs: int | None = None, stats: dict[str, Any],- prompt_ids: list[int] | None = None, ignore_eos: bool = False, _mine: list) -> AsyncIterator[str]:+ prompt_ids: list[int] | None = None, ignore_eos: bool = False, live: dict | None = None, _mine: list) -> AsyncIterator[str]:"""Yield decoded text pieces. Final stats land in `stats`. Every job enqueued is appended to `_mine`.Final check (on with the guard, loop_final=False turns it off): when the turn ends normally and the visible text@@ -1373,6 +1373,8 @@ class QwenEngine:lps += self._event_logprobs(ev, len(toks))seg += toksgenerated += len(toks)+ if live is not None and t is not None:+ live["n"] = generated # the engine's own count, read by the stream for the progressive timingsif ev.get("text"):chars += len(ev["text"])vis += ev["text"]@@ -1646,6 +1648,7 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, An# the difference, and it is logged on its own as wait_s.wait = time.perf_counter() - (job.get("_queued_at") or time.perf_counter())started = time.perf_counter() - wait+ job["_job_at"] = time.perf_counter()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 linelifecycle.job_skipped(rid, wait)@@ -1664,7 +1667,7 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, Anfirst_token = False # flipped once, so the log gets exactly one job_first_token linetry:async for delta in engine.generate(- job["prompt"], stats=stats, max_tokens=job["max_tokens"], sampling=job["sampling"],+ job["prompt"], stats=stats, live=job.setdefault("_live", {}), max_tokens=job["max_tokens"], sampling=job["sampling"],**({"prompt_ids": job["prompt_ids"]} if job.get("prompt_ids") is not None else {}),**({"ignore_eos": True} if job.get("ignore_eos") else {}),stop=job["stop"], images=job["images"], speculative=job["speculative"],@@ -1674,6 +1677,7 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, Anloop_final=job.get("loop_final"), logprobs=job.get("logprobs")):if not first_token:first_token = True+ job["_first_at"] = time.perf_counter()lifecycle.first_token(rid, started, prompt_tokens=job.get("prompt_tokens"))out.put_nowait(delta)finally:@@ -1825,11 +1829,7 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, Anreason = "stop"usage = {"prompt_tokens": prompt_tokens, "completion_tokens": n_new,"total_tokens": prompt_tokens + n_new, "prompt_tokens_details": {"cached_tokens": cache_n}}- timings = {"cache_n": cache_n, "prompt_n": max(prompt_tokens - cache_n, 0), "prompt_ms": pre * 1000,- "predicted_n": n_new, "predicted_ms": gen * 1000,- "prompt_per_second": (prompt_tokens - cache_n) / pre if pre else 0.0,- "predicted_per_second": n_new / gen if gen else 0.0,- "speculative": bool(getattr(engine, "spec_on", False))}+ timings = serve_compat.timings(prompt_tokens, cache_n, pre, gen, n_new, speculative=bool(getattr(engine, "spec_on", False)))if stats.get("loop_guard"):timings["loop_guard"] = stats["loop_guard"]if "accepted_draft_tokens" in stats:@@ -1877,6 +1877,7 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, Anping.note_output()stats, full = {}, ""visible = False # flipped at the first frame with text: the client's first sign of life+ live = serve_compat.LiveTimings(job, job["prompt_tokens"], lambda: stats) # progressive timings, once per secondasync for item in pieces(writer, ping, ping_at):if isinstance(item, dict):stats = item@@ -1894,8 +1895,10 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, Anif not visible:visible = Truelifecycle.first_content(job["_reqid"], queued_at)- await writer.write(sse(event({key: piece})))+ await writer.write(sse(event({key: piece}) | ({"timings": t} if (t := live.take()) else {})))ping.note_output() # the client has text: comments wait for the next silence+ if (t := live.take()) is not None: # nothing went out for a second (held tool call, tags): an empty delta carries them+ await writer.write(sse(event({}) | {"timings": t}))for kind, piece in sp.finish():key = "reasoning_content" if kind == "reasoning" else "content"await writer.write(sse(event({key: piece})))diff --git a/tools/serve_compat.py b/tools/serve_compat.pyindex 4557032..1d61be5 100644--- a/tools/serve_compat.py+++ b/tools/serve_compat.py@@ -4,10 +4,12 @@- the `cache_salt` request field- the POST /tokenize reply- the `usage` object with `prompt_tokens_details.cached_tokens`+- the llama.cpp `timings` object (one shape on every server), final and progressive"""from __future__ import annotations-from typing import Any+import time+from typing import Any, Callableclass CompatError(ValueError):@@ -55,6 +57,52 @@ def usage(prompt_tokens: int, completion_tokens: int, cached_tokens: int | Nonereturn out+def timings(prompt_tokens: int, cache_n: int, prefill_s: float, decode_s: float, predicted_n: int, **extra: Any) -> dict[str, Any]:+ """The llama.cpp `timings` object: prompt_n (tokens prefilled, cache hits left out), prompt_ms, prompt_per_second, predicted_n,+ predicted_ms, predicted_per_second, cache_n. The swap orchestrator reads cache_n as the verdict of a KV restore."""+ prompt_n = max(prompt_tokens - cache_n, 0)+ return {"cache_n": cache_n, "prompt_n": prompt_n, "prompt_ms": prefill_s * 1000,+ "prompt_per_second": prompt_n / prefill_s if prefill_s else 0.0,+ "predicted_n": predicted_n, "predicted_ms": decode_s * 1000,+ "predicted_per_second": predicted_n / decode_s if decode_s else 0.0, **extra}+++def stats_timings(prompt_tokens: int, st: dict[str, Any], **extra: Any) -> dict[str, Any]:+ """`timings` from the engine's per-request stats (cached_tokens, time_prefill, time_generate, new_tokens)."""+ return timings(prompt_tokens, int(st.get("cached_tokens", 0)), st.get("time_prefill") or 0.0,+ st.get("time_generate") or 0.0, int(st.get("new_tokens", 0)), **extra)+++class LiveTimings:+ """Progressive `timings` for one streamed reply: `take()` returns the object at most once per `period` seconds, None otherwise.++ Measured numbers only. The worker stamps the job dict: `_job_at` (the job left the queue), `_first_at` (its first token) and+ `_live["n"]` (the engine's own count of generated tokens, updated at each decode event). Prefill time is the span between the first two,+ decode time runs from `_first_at`. While the engine has not reported a count, `take()` returns None; a server whose engine cannot+ report one never builds a LiveTimings and sends `timings` on the final chunk only."""++ PERIOD_S = 1.0++ def __init__(self, job: dict[str, Any], prompt_tokens: int, stats: Callable[[], dict[str, Any]] = lambda: {},+ period: float | None = None, clock: Callable[[], float] = time.perf_counter) -> None:+ self.job, self.prompt_tokens, self.stats = job, prompt_tokens, stats+ self.period, self.clock = self.PERIOD_S if period is None else period, clock+ self.last = None++ def take(self) -> dict[str, Any] | None:+ first, n = self.job.get("_first_at"), (self.job.get("_live") or {}).get("n")+ if first is None or n is None:+ return None+ now = self.clock()+ if self.last is None:+ self.last = first+ if now - self.last < self.period:+ return None+ self.last = now+ return timings(self.prompt_tokens, int(self.stats().get("cached_tokens") or 0),+ max(first - self.job.get("_job_at", first), 0.0), now - first, n)++RQ_MIN_TOKENS = 2048 # smallest reply span a job holds pages for before it yields them (each yield costs a short re-prefill)diff --git a/tools/strix_halo/serve_reqlog.py b/tools/strix_halo/serve_reqlog.pyindex 26ea0ee..4af5533 100644--- a/tools/strix_halo/serve_reqlog.py+++ b/tools/strix_halo/serve_reqlog.py@@ -385,7 +385,7 @@ class Lifecycle:def job_started(self, rid: str | None, wait: float, **fields: Any) -> None:"""The worker picked the job up: `wait` is the queue time, the rest is what this server knows."""- self.track(rid, "prefill", prompt_tokens=fields.get("prompt_tokens"))+ self.track(rid, "prefill", prompt_tokens=fields.get("prompt_tokens"), wait_s=wait)self.reqlog.log("job_start", req=rid, wait_s=round(wait, 3), **fields)def job_skipped(self, rid: str | None, queued_s: float) -> None:@@ -403,12 +403,22 @@ class Lifecycle:st = stats or {}prompt = int(st.get("prompt_tokens") or prompt_tokens or 0)cache_n = int(st.get("cached_tokens") or 0)+ new_tokens = int(st.get("new_tokens") or 0)+ prefill_s, decode_s = float(st.get("time_prefill") or 0.0), float(st.get("time_generate") or 0.0)+ fresh = max(prompt - cache_n, 0)self.reqlog.log("job_done", req=rid, elapsed_s=round(time.perf_counter() - started, 3),prompt_tokens=prompt, cache_n=cache_n,cache_pct=round(100.0 * cache_n / prompt, 1) if prompt else 0.0,- new_tokens=int(st.get("new_tokens") or 0),- prefill_s=round(float(st.get("time_prefill") or 0.0), 3),- decode_s=round(float(st.get("time_generate") or 0.0), 3))+ new_tokens=new_tokens,+ prefill_s=round(prefill_s, 3), decode_s=round(decode_s, 3),+ prefill_tps=round(fresh / prefill_s, 1) if prefill_s else 0.0,+ decode_tps=round(new_tokens / decode_s, 1) if decode_s else 0.0)+ # The speed line of every request, on stderr whatever the request log says (the Mac server prints the same fields).+ wait = (self.inflight.get(rid) or {}).get("wait_s", 0.0) if rid else 0.0+ print(f"{time.strftime('%H:%M:%S')} req={rid} prompt={fresh} cached={cache_n} gen={new_tokens} queue={wait:.2f}s "+ f"prefill={prefill_s:.2f}s ({fresh / prefill_s if prefill_s else 0.0:.1f} tok/s) "+ f"decode={decode_s:.2f}s ({new_tokens / decode_s if decode_s else 0.0:.1f} tok/s) total={time.perf_counter() - started:.2f}s",+ file=sys.stderr, flush=True)def job_error(self, rid: str | None, exc: BaseException, started: float | None = None) -> None:self.reqlog.log("job_error", req=rid, error=sanitize(exc),diff --git a/tools/test_serve_compat.py b/tools/test_serve_compat.pyindex 5aff46e..51ffc17 100644--- a/tools/test_serve_compat.py+++ b/tools/test_serve_compat.py@@ -41,6 +41,41 @@ class RqBudgetTests(unittest.TestCase):self.assertEqual(serve_compat.rq_budget(65536, 4, 64000, 5000), 65536 - 64000) # never beyond the cache+class TimingsTests(unittest.TestCase):+ KEYS = {"prompt_n", "prompt_ms", "prompt_per_second", "predicted_n", "predicted_ms", "predicted_per_second", "cache_n"}++ def test_shape_and_rates(self):+ t = serve_compat.timings(1000, 200, 2.0, 4.0, 80)+ self.assertEqual(set(t), self.KEYS)+ self.assertEqual((t["prompt_n"], t["cache_n"], t["prompt_ms"], t["predicted_ms"]), (800, 200, 2000.0, 4000.0))+ self.assertEqual((t["prompt_per_second"], t["predicted_per_second"]), (400.0, 20.0))+ self.assertEqual(serve_compat.timings(10, 0, 0.0, 0.0, 0)["predicted_per_second"], 0.0)++ def test_stats_timings_reads_engine_stats(self):+ st = {"cached_tokens": 5, "time_prefill": 1.0, "time_generate": 2.0, "new_tokens": 10}+ self.assertEqual(serve_compat.stats_timings(25, st, speculative=True),+ serve_compat.timings(25, 5, 1.0, 2.0, 10, speculative=True))++ def test_live_timings_once_per_period_from_the_engine_count(self):+ now = [100.0]+ job = {"_job_at": 99.0}+ live = serve_compat.LiveTimings(job, 500, lambda: {"cached_tokens": 100}, clock=lambda: now[0])+ self.assertIsNone(live.take()) # no first token yet+ job["_first_at"] = 100.0+ now[0] = 101.0+ self.assertIsNone(live.take()) # the engine has reported no count: nothing is shown+ job["_live"] = {"n": 3}+ t = live.take()+ self.assertEqual(set(t), self.KEYS)+ self.assertEqual((t["predicted_n"], t["prompt_n"], t["cache_n"], t["prompt_ms"], t["predicted_ms"]), (3, 400, 100, 1000.0, 1000.0))+ self.assertEqual(t["predicted_per_second"], 3.0)+ job["_live"]["n"] = 5+ now[0] = 101.9+ self.assertIsNone(live.take()) # once per second at most+ now[0] = 102.0+ self.assertEqual(live.take()["predicted_n"], 5)++class HelperTests(unittest.TestCase):def test_cache_salt(self):self.assertIsNone(serve_compat.cache_salt({}))diff --git a/tools/test_serve_logging.py b/tools/test_serve_logging.pyindex 87b236d..2746e0d 100644--- a/tools/test_serve_logging.py+++ b/tools/test_serve_logging.py@@ -252,5 +252,75 @@ class LoggingVocabularyTests(unittest.TestCase):f"{name}: the heartbeat names no in-flight counter")+class TalkingEngine(FakeEngine):+ """A reply of several words, so a stream has deltas after the first token."""++ async def generate(self, prompt, **kw):+ for n, piece in enumerate(("one ", "two ", "three ", "four "), 1):+ await asyncio.sleep(0.05)+ if kw.get("live") is not None:+ kw["live"]["n"] = n # what the real engines do at each decode event+ yield piece+++class ProgressiveTimingsTests(unittest.TestCase):+ """Every server: the same `timings` object rides on stream chunks while the reply decodes, and on the final chunk."""++ KEYS = {"prompt_n", "prompt_ms", "prompt_per_second", "predicted_n", "predicted_ms", "predicted_per_second", "cache_n"}++ def streamed_timings(self, name: str, period: float, engine=None):+ import json+ serve = load_server(name)+ sc = sys.modules["serve_compat"]+ saved = sc.LiveTimings.PERIOD_S+ sc.LiveTimings.PERIOD_S = period+ got = []++ async def go() -> None:+ from aiohttp.test_utils import TestClient, TestServer+ client = TestClient(TestServer(serve.create_app((engine or TalkingEngine)(), "m", "{{ messages[0].content }}")))+ await client.start_server()+ try:+ r = await client.post("/v1/chat/completions", json={+ "model": "m", "stream": True, "messages": [{"role": "user", "content": "hi"}]})+ for line in (await r.text()).splitlines():+ if line.startswith("data: {"):+ o = json.loads(line[6:])+ got.append((o["choices"][0]["delta"] if o.get("choices") else None, o.get("timings")))+ finally:+ await client.close()++ try:+ asyncio.run(go())+ finally:+ sc.LiveTimings.PERIOD_S = saved+ return got++ def test_partial_timings_before_the_final_one(self):+ for name in ("glm", "qwen", "mimo"):+ chunks = self.streamed_timings(name, 0.0)+ with_timings = [(d, t) for d, t in chunks if t is not None]+ self.assertGreater(len(with_timings), 1, f"{name}: no partial timings before the final chunk")+ for d, t in with_timings:+ self.assertTrue(self.KEYS <= set(t), f"{name}: timings lack {sorted(self.KEYS - set(t))}")+ partial = with_timings[:-1]+ self.assertTrue(all(0 < t["predicted_n"] <= 4 for _, t in partial), f"{name}: partial timings without the engine count")++ def test_an_engine_without_a_live_count_sends_the_final_timings_only(self):+ class Silent(TalkingEngine):+ async def generate(self, prompt, **kw):+ kw.pop("live", None)+ async for piece in super().generate(prompt):+ yield piece+ for name in ("glm", "qwen", "mimo"):+ chunks = self.streamed_timings(name, 0.0, Silent)+ self.assertEqual(len([t for _, t in chunks if t is not None]), 1, f"{name}: an estimate was shown")++ def test_one_second_period_sends_only_the_final_timings(self):+ for name in ("glm", "qwen", "mimo"):+ chunks = self.streamed_timings(name, 60.0)+ self.assertEqual(len([t for _, t in chunks if t is not None]), 1, f"{name}: partial timings under a long period")++if __name__ == "__main__":unittest.main()