MLX: count prompt tokens while prefill runs, not when the request ends

The proxy only added a request's prompt tokens from the final usage chunk, so a
long prefill showed as a flat prompt rate and then one spike (prompt size over a
2 s sample), and requests the client abandoned mid-prefill were never counted.
mlx_lm.server already streams ": keepalive <done>/<total>" after each prefill
step; count those as they pass through, and top up from the usage chunk. Also
leave out prompt-cache hits (cached_tokens), which take no processing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QaE1hpvyZTJixEbUUMj9Ca
This commit is contained in:
neil 2026-11-02 13:50:10 -08:00
parent 994659b5e2
commit a250812d42

View file

@ -108,6 +108,13 @@ class Stats:
"ttft_sum": self.ttft_sum, "ttft_count": self.ttft_count}
def _uncached(usage):
"""Prompt tokens the server actually processed: cached prefix tokens cost nothing."""
n = int(usage.get("prompt_tokens") or 0)
cached = (usage.get("prompt_tokens_details") or {}).get("cached_tokens") or 0
return max(n - int(cached), 0)
def make_handler(inner_port, served_name, context, key, stats):
class Proxy(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
@ -201,6 +208,7 @@ def make_handler(inner_port, served_name, context, key, stats):
self.close_connection = True
buf = b""
self._first = False
self._pp = 0 # prompt tokens of this request already counted
while True:
chunk = resp.read1(65536) if hasattr(resp, "read1") else resp.read(4096)
if not chunk:
@ -209,6 +217,8 @@ def make_handler(inner_port, served_name, context, key, stats):
# Forward whole events (the server writes one per token anyway).
while b"\n\n" in buf:
event, buf = buf.split(b"\n\n", 1)
if event.startswith(b": keepalive "):
self._count_progress(event)
usage_only = self._count_event(event)
if not (strip_usage and usage_only):
self.wfile.write(event + b"\n\n")
@ -225,7 +235,7 @@ def make_handler(inner_port, served_name, context, key, stats):
u = json.loads(data).get("usage") or {}
with stats.lock:
stats.gen_total += int(u.get("completion_tokens") or 0)
stats.prompt_total += int(u.get("prompt_tokens") or 0)
stats.prompt_total += _uncached(u)
except (ValueError, AttributeError):
pass
except (BrokenPipeError, ConnectionResetError):
@ -235,6 +245,20 @@ def make_handler(inner_port, served_name, context, key, stats):
with stats.lock:
stats.running -= 1
def _count_progress(self, event):
"""mlx_lm.server sends ': keepalive <done>/<total>' after each prefill step of a
streamed request (counting only the part not found in its prompt cache). Count
those as they arrive so the prompt rate shows prefill while it happens, not as
one spike when the request ends (or never, if the client gives up first)."""
try:
done = int(event[12:].split(b"/")[0])
except ValueError:
return
if done > self._pp:
with stats.lock:
stats.prompt_total += done - self._pp
self._pp = done
def _count_event(self, event):
"""Update token counts; returns True for a usage-only chunk (no choices)."""
if not event.startswith(b"data: {"):
@ -246,8 +270,11 @@ def make_handler(inner_port, served_name, context, key, stats):
u = d.get("usage")
first_token = False
with stats.lock:
if u: # final usage chunk (stream_options.include_usage) is exact; prefer it
stats.prompt_total += int(u.get("prompt_tokens") or 0)
if u: # final usage chunk: top up whatever the progress events didn't cover
rest = _uncached(u) - self._pp
if rest > 0:
stats.prompt_total += rest
self._pp += rest
for c in d.get("choices") or []:
delta = c.get("delta") or {}
if delta.get("content") or delta.get("reasoning") or delta.get("reasoning_content") or delta.get("tool_calls"):