The Monitor's live tok/s is a rate over the last seconds, not the mean since the first token
live.tok_s returned `generated / (now - first_token)`: a cumulative mean whose first sample is 1/elapsed. Against an engine paced at 25 tokens/s the Speed card, the header pill and the tok_s sparkline read 27,235.7 tok/s at that first sample - about 1090x the real rate - and then undershot for the first second of every answer (one token counted over up to a second of elapsed time). Because the sparkline scales to the maximum of its 60-sample ring, one such sample also flattened the Speed graph for a minute. tok_s is now the rate over the last RATE_WINDOW_S (2 s), with the mean so far reported only while a request is younger than RATE_MIN_SPAN_S (0.25 s) and its span floored there, so no sample can diverge. The old formula is kept as _tok_s_mean() and still reported (live.tok_s_mean, status.tokens_per_s_mean). The same request fixes a second mis-attribution: a request that ended without a DONE line (engine death, error, client disconnect) recorded the PREVIOUS request's generated/decode_ms as its own decode_tok_s. The engine's counters are now trusted only when its DONE replaced the object captured at request start, and the row carries the engine's own token count as engine_generated. Tests: serve/test_server.py::LiveRate paces a mock engine and polls GET /metrics at 10 ms. Both cases fail without the server.py change (990.0 tok/s recorded for a request that never finished) and pass with it; the rest of the suite is unchanged at 28 tests, OK. The engine's own per-request counters - what the Speed card shows for "last request" - are untouched, and the server's progress and summary log lines keep their whole-request mean on purpose.
This commit is contained in:
1 parent
6e1a7be257
commit
ef14b6ca69
2 files changed
+128
-4
No files matched your search
+35
-4
@@ -48,6 +48,10 @@ from serve.mcp import McpCancelled, hub_from_config # noqa: E402
|
||||
IM_END = "<|im_end|>"
|
||||
IMAGE_PAD = "<|image_pad|>"
|
||||
CTX_SLACK = 8 # `strata --serve` rejects prompt + max_new + 8 > context: keep the same margin here
|
||||
# The live tok/s is a rate over a window, not a mean since the first token: a mean reads ~1/elapsed at the first
|
||||
# token (the Monitor showed five-digit numbers) and then undershoots for the first second of every answer.
|
||||
RATE_WINDOW_S = 2.0
|
||||
RATE_MIN_SPAN_S = 0.25 # younger than this there is no rate yet: the mean so far, with the span floored here
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------------------ engines
|
||||
@@ -543,6 +547,7 @@ class Service:
|
||||
self.embeddings = threading.local() # the current request's image embeddings file (GENI)
|
||||
self.api_key = "" # when set, /v1/* needs it (Bearer or x-api-key)
|
||||
self.status = {"busy": False, "queued": 0} # GET /status: what the model is doing right now
|
||||
self.rate = collections.deque(maxlen=32) # (time, generated) samples for the live tok/s window
|
||||
self.history = collections.deque(maxlen=500) # the last finished requests, newest last (GET /metrics)
|
||||
# since the server started (the Monitor's totals, issue #35)
|
||||
self.totals = {"since": time.time(), "requests": 0, "prompt_tokens": 0, "reused": 0, "output_tokens": 0,
|
||||
@@ -591,10 +596,25 @@ class Service:
|
||||
"""The hardware sampler behind GET /metrics (serve/telemetry.py), recording this server's tok/s too."""
|
||||
if getattr(self, "telemetry", None) is None:
|
||||
from serve.telemetry import Telemetry
|
||||
self.telemetry = Telemetry(extra=lambda: {"tok_s": self._tok_s()},
|
||||
self.telemetry = Telemetry(extra=lambda: {"tok_s": self._tok_s(), "tok_s_mean": self._tok_s_mean()},
|
||||
gpu_index=int(getattr(self, "gpu_index", 0) or 0))
|
||||
|
||||
def _tok_s(self):
|
||||
"""tok/s over the last RATE_WINDOW_S seconds. Returns 0.0 while nothing is generating."""
|
||||
with self.status_lock:
|
||||
s = dict(self.status)
|
||||
rate = list(self.rate)
|
||||
if not s.get("busy") or not s.get("first_token"):
|
||||
return 0.0
|
||||
now = time.time()
|
||||
newest = rate[-1] if rate else None
|
||||
oldest = next(((t, g) for t, g in rate if now - t <= RATE_WINDOW_S), None)
|
||||
if newest and oldest and newest[0] - oldest[0] >= RATE_MIN_SPAN_S:
|
||||
return max(0.0, (newest[1] - oldest[1]) / (newest[0] - oldest[0]))
|
||||
return s["generated"] / max(RATE_MIN_SPAN_S, now - s["first_token"])
|
||||
|
||||
def _tok_s_mean(self):
|
||||
"""The whole-request mean since the first token (the old formula), kept so the two can be compared."""
|
||||
with self.status_lock:
|
||||
s = dict(self.status)
|
||||
if not s.get("busy") or not s.get("first_token"):
|
||||
@@ -621,7 +641,9 @@ class Service:
|
||||
"prompt_read": None, "prompt_total": None, "generated": s.get("generated") if s.get("busy") else None,
|
||||
"max_tokens": s.get("max_tokens") if s.get("busy") else None,
|
||||
"elapsed_s": round(now - s["started"], 1) if s.get("busy") and s.get("started") else None,
|
||||
"tok_s": round(self._tok_s(), 1) if state == "generating" else None}
|
||||
"tok_s": round(self._tok_s(), 1) if state == "generating" else None,
|
||||
"tok_s_mean": round(self._tok_s_mean(), 1) if state == "generating" else None,
|
||||
"tok_s_window_s": RATE_WINDOW_S if state == "generating" else None}
|
||||
if state == "reading" and progress:
|
||||
live["prompt_read"], live["prompt_total"] = progress
|
||||
engine = {"model": self.model, "max_context": self.engine.max_context, "images": self.vision is not None,
|
||||
@@ -684,6 +706,7 @@ class Service:
|
||||
s["generated"] = n
|
||||
if s.get("first_token") is None:
|
||||
s["first_token"] = time.time()
|
||||
self.rate.append((time.time(), n)) # the live rate's window over the last RATE_WINDOW_S
|
||||
for ev in evs:
|
||||
if ev.kind == "reasoning":
|
||||
s["phase"] = "thinking"
|
||||
@@ -723,6 +746,9 @@ class Service:
|
||||
detok, n, finish = Detokenizer(self.tok), 0, "length"
|
||||
raw_ids = [] # every generated id (STRATA_DEBUG: dump raw model text)
|
||||
emb = getattr(self.embeddings, "path", None)
|
||||
# Identity token: only a DONE line replaces engine.last, so a request that died, errored or was
|
||||
# disconnected must not have the PREVIOUS request's decode figures recorded as its own.
|
||||
engine_last0 = getattr(self.engine, "last", None)
|
||||
with self.status_lock:
|
||||
self.status["queued"] += 1
|
||||
try:
|
||||
@@ -739,6 +765,7 @@ class Service:
|
||||
with self.status_lock:
|
||||
self.status.update(busy=True, phase="reading the prompt", prompt_tokens=len(ids), generated=0,
|
||||
started=time.time(), first_token=None, tool=None, tail="", max_tokens=max_new)
|
||||
self.rate.clear() # the previous request's samples must not leak into this one
|
||||
last_print = time.time()
|
||||
gen = self.engine.generate(ids, max_new, sampling, cancel, embeddings=emb) if emb else \
|
||||
self.engine.generate(ids, max_new, sampling, cancel)
|
||||
@@ -784,7 +811,9 @@ class Service:
|
||||
Path(emb).unlink(missing_ok=True)
|
||||
with self.status_lock:
|
||||
if self.status.get("busy"):
|
||||
last = dict(getattr(self.engine, "last", {}) or {})
|
||||
# only this request's DONE counts: same object means no DONE arrived (death, error, disconnect)
|
||||
last = dict(getattr(self.engine, "last", {}) or {}) \
|
||||
if getattr(self.engine, "last", None) is not engine_last0 else {}
|
||||
started = self.status.get("started", time.time())
|
||||
loaded = str((getattr(self.engine, "info", {}) or {}).get("cvec", 0)) not in ("0", "", "None")
|
||||
hit_rate = round(last["hits"] / last["lookups"], 3) if last.get("lookups") else None
|
||||
@@ -793,6 +822,7 @@ class Service:
|
||||
if loaded else None,
|
||||
"time": started, "duration_s": round(time.time() - started, 1), "finish": finish,
|
||||
"prompt_tokens": len(ids), "reused": last.get("reused"), "output_tokens": n,
|
||||
"engine_generated": last.get("generated"),
|
||||
"prompt_ms": last.get("prompt_ms"), "decode_ms": last.get("decode_ms"),
|
||||
"decode_tok_s": round(last["generated"] / (last["decode_ms"] / 1000), 1)
|
||||
if n and last.get("generated") and last.get("decode_ms") else None,
|
||||
@@ -1184,7 +1214,8 @@ def make_handler(svc: Service):
|
||||
if s.get("busy"):
|
||||
s["elapsed_s"] = round(now - s["started"], 1)
|
||||
if s.get("first_token"):
|
||||
s["tokens_per_s"] = round(s["generated"] / max(1e-6, now - s["first_token"]), 1)
|
||||
s["tokens_per_s"] = round(svc._tok_s(), 1)
|
||||
s["tokens_per_s_mean"] = round(svc._tok_s_mean(), 1)
|
||||
for k in ("started", "first_token"):
|
||||
s.pop(k, None)
|
||||
self._json(200, s)
|
||||
|
||||
@@ -7,6 +7,8 @@ from __future__ import annotations
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import unittest
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
@@ -368,6 +370,97 @@ class EngineDeath(unittest.TestCase):
|
||||
httpd.server_close()
|
||||
|
||||
|
||||
class LiveRate(unittest.TestCase):
|
||||
"""The Monitor's Speed readout: live.tok_s is a rate, and a request that never got a DONE keeps no counters.
|
||||
|
||||
It used to be `generated / (now - first_token)` - the mean since the first token, whose first sample is
|
||||
1/elapsed. Against a paced engine that reads five-digit numbers for the first instant of every answer and
|
||||
undershoots for the first second after that. It is now the rate over the last RATE_WINDOW_S, with the mean
|
||||
still available as `live.tok_s_mean` for anyone who wants it."""
|
||||
|
||||
PACE_S = 0.02 # 50 tokens/s: a 30-token answer takes about 0.6 s
|
||||
TOKENS = 30
|
||||
|
||||
def setUp(self):
|
||||
self.tok = ByteTokenizer()
|
||||
self.engine = MockEngine(self.tok, "x" * self.TOKENS, max_context=CTX, delay_s=self.PACE_S)
|
||||
self.svc = Service(self.engine, self.tok, ChatTemplate(ROOT / "serve/chat_template.jinja"))
|
||||
self.httpd = serve(self.svc, port=0)
|
||||
self.base = f"http://127.0.0.1:{self.httpd.server_address[1]}"
|
||||
|
||||
def tearDown(self):
|
||||
self.httpd.shutdown()
|
||||
self.httpd.server_close()
|
||||
|
||||
def metrics(self):
|
||||
with urllib.request.urlopen(self.base + "/metrics", timeout=10) as r:
|
||||
return json.loads(r.read())
|
||||
|
||||
def test_the_live_number_is_a_rate(self):
|
||||
live_samples, stop = [], threading.Event()
|
||||
|
||||
def poll(): # what the Monitor polls, at 10 ms
|
||||
while not stop.is_set():
|
||||
live = self.metrics()["live"]
|
||||
if live["state"] == "generating" and live["tok_s"] is not None:
|
||||
live_samples.append((live["generated"], live["tok_s"], live["tok_s_mean"]))
|
||||
time.sleep(0.01)
|
||||
|
||||
body = json.dumps({"model": "m", "max_tokens": self.TOKENS, "temperature": 0,
|
||||
"messages": [{"role": "user", "content": "hi"}]}).encode()
|
||||
watcher = threading.Thread(target=poll, daemon=True)
|
||||
watcher.start()
|
||||
t0 = time.time()
|
||||
try:
|
||||
with urllib.request.urlopen(urllib.request.Request(self.base + "/v1/chat/completions", data=body,
|
||||
headers={"Content-Type": "application/json"}),
|
||||
timeout=30) as r:
|
||||
usage = json.loads(r.read())["usage"]
|
||||
finally:
|
||||
stop.set()
|
||||
watcher.join(2)
|
||||
true_rate = usage["completion_tokens"] / (time.time() - t0)
|
||||
self.assertGreaterEqual(len(live_samples), 3, "too few live readings to judge the readout")
|
||||
self.assertLess(max(s for _g, s, _m in live_samples), 4 * true_rate,
|
||||
f"live.tok_s peaked at {max(s for _g, s, _m in live_samples):.1f} tok/s "
|
||||
f"for a {true_rate:.1f} tok/s engine")
|
||||
self.assertEqual(self.metrics()["live"]["state"], "idle")
|
||||
self.assertIsNone(self.metrics()["live"]["tok_s"])
|
||||
|
||||
def test_a_request_without_a_done_keeps_no_engine_counters(self):
|
||||
"""An engine that dies mid-answer: the previous request's `last` must not become this row's decode rate."""
|
||||
class HalfDead(MockEngine):
|
||||
last = {"generated": 99, "prompt_tokens": 9, "prompt_ms": 10.0, "decode_ms": 100.0, "finish": "stop"}
|
||||
|
||||
def generate(self, ids, max_new, sampling, cancel, embeddings=None):
|
||||
for i, t in enumerate(super().generate(ids, max_new, sampling, cancel, embeddings)):
|
||||
if i == 3:
|
||||
raise EngineDied("the engine stopped unexpectedly (exit code -9)")
|
||||
yield t
|
||||
|
||||
tok = ByteTokenizer()
|
||||
svc = Service(HalfDead(tok, "x" * self.TOKENS, max_context=CTX), tok,
|
||||
ChatTemplate(ROOT / "serve/chat_template.jinja"))
|
||||
httpd = serve(svc, port=0)
|
||||
base = f"http://127.0.0.1:{httpd.server_address[1]}"
|
||||
try:
|
||||
body = json.dumps({"model": "m", "max_tokens": self.TOKENS, "stream": True,
|
||||
"messages": [{"role": "user", "content": "hi"}]}).encode()
|
||||
with urllib.request.urlopen(urllib.request.Request(base + "/v1/chat/completions", data=body,
|
||||
headers={"Content-Type": "application/json"}),
|
||||
timeout=30) as r:
|
||||
text = r.read().decode()
|
||||
self.assertIn('"error"', text)
|
||||
row = svc.metrics()["requests"][0]
|
||||
self.assertEqual(row["finish"], "error")
|
||||
self.assertEqual(row["output_tokens"], 3)
|
||||
self.assertIsNone(row["decode_tok_s"], "the previous request's counters were recorded as this one's")
|
||||
self.assertIsNone(row["engine_generated"])
|
||||
finally:
|
||||
httpd.shutdown()
|
||||
httpd.server_close()
|
||||
|
||||
|
||||
class SharedSettings(unittest.TestCase):
|
||||
"""The web app's "Use for other apps too": POST /settings makes its Chat settings every client's defaults."""
|
||||
|
||||
|
||||
Reference in new issue
Block a user