Skip to content

GLM-5.3-Flash EXL3 on 2x DGX Spark with TensorFold

Python

Patch 0112: a streamed Anthropic head carries the prompt's token count

evilpsycho426b768fa4267e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5fe7ba6..cf3dba7 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -44,6 +44,14 @@ Every change to this recipe, newest first. Each release names the image it serve
`: keepalive`, on the chat, completions, Messages and Responses streams; SSE clients skip comment lines, and the
events are the same bytes. `SSE_KEEPALIVE_S=0` turns it off; a value that is not a number of seconds stops the
server at start. Non-streamed replies are unchanged. CPU test: `tools/test_sse_keepalive.py`.
+- **A streamed Anthropic reply opens with the prompt's token count** (patch `0112-anthropic-stream-head-usage`,
+ by [kky42](https://github.com/kky42), fixing TensorFold #672): `message_start` carried `usage({})`, all zeros, and
+ the real counts only arrived in the final `message_delta`, so a client that reads prompt counts from the head
+ (Claude Code's context-window indicator) showed ~0% used on every streaming request. The CUDA chat handler now
+ hands its prepared prompt's length to the translated request's wire before the stream head, and the head reports
+ it whole (cache fields 0); the final delta keeps the engine's input/cache_read split, the two totals equal, and
+ no second render runs. The Mac server's head is written before its render, so it keeps the old zeros (in the
+ patch header). CPU check: `tools/test_anthropic_stream_head.py`.
- **A prompt that fills beside other replies, ~10-14% sooner** (`FILL_ROWS`, by [BadAd84](https://github.com/BadAd84)):
while other requests decode, a new prompt filled in 1,024-row chunks (TensorFold's `TF_GLM_FILL_ROWS` default),
half the 2,048-row prompt chunk whose buffers the engine keeps anyway. `scripts/config.sh` now sets 2,048 (at
diff --git a/patches/0112-anthropic-stream-head-usage.patch b/patches/0112-anthropic-stream-head-usage.patch
new file mode 100644
index 0000000..0e41044
--- /dev/null
+++ b/patches/0112-anthropic-stream-head-usage.patch
@@ -0,0 +1,91 @@
+# A streamed Messages reply opens with the prompt's token count, not zeros. message_start carried
+# usage({}), all zeros, and the real counts only landed in self.tokens from the engine's final chunk,
+# so a client that reads prompt counts from the head (Claude Code's context-window indicator) showed
+# ~0% used on every streaming request, live on a Spark (GLM-5.3-Flash-EXL3, test image): message_start
+# {input_tokens: 0, cache_read_input_tokens: 0} while the closing message_delta carried the correct
+# total. The head now names the prompt's full count with cache fields 0 (input_tokens the whole
+# prompt, output_tokens 0, cache_creation_input_tokens 0, cache_read_input_tokens 0), and the final
+# message_delta keeps the engine's input/cache_read split (input = full - cached, cache_read =
+# cached: the share the engine served from kept prompt states, a fresh prompt reports 0), the two
+# totals equal; the whole (non-streamed) reply reports the same split. Mirror of the Zig server's fix
+# (TensorFold PR #672, ad1abffb).
+# The count comes from the prompt the request already rendered, not a second render: the CUDA chat
+# handler's prepared prompt is the same one the final usage's prompt_tokens is len() of (kept-state
+# replay and compaction included), so the handler hands len(prepared.prompt) to the translated
+# request's wire (responses.Wire.prompt_len, passed to the head's opened()) before its stream head is
+# written. The Mac server's stream head is written before app.chat renders (the render rides the job
+# the call submits), so there the count is not known at head time: a second normalize+template+tokenize
+# pass on the request thread would grow TTFT with prompt size, and deferring message_start to the first
+# usage chunk would arrive after the content (the only usage chunk is the last one). The Mac head keeps
+# the old zeros; the Sparks' CUDA server, this recipe's production path, carries the count.
+# Direct chat requests never see this: their wfile is the socket, not a Wire, and the the reply-text and server files
+# (cuda/reply_text.py, cuda/server.py) are untouched, so the patch stacks on them. CPU check:
+# tools/test_anthropic_stream_head.py.
+
+--- tensorfold/server/responses.py
++++ tensorfold/server/responses.py
+@@ -129,12 +129,15 @@
+ """The chat handler's side of its socket: the status and headers, then the JSON body or each stream event; a
+ stream's comment lines (the keep-alives of patch 0111) are written to ``comments`` as they came."""
+
+- def __init__(self, opened: Callable[[], None], event: Callable[[dict[str, Any] | None], None],
++ def __init__(self, opened: Callable[[int], None], event: Callable[[dict[str, Any] | None], None],
+ comments: Any) -> None:
+ self.opened, self.event, self.comments = opened, event, comments
+ self.status: int | None = None
+ self.stream = False
+ self.data = bytearray()
++ # the chat handler's prepared prompt length, set before its stream head: a translated request's
++ # Messages head names the prompt's size (its usage otherwise leaves the client's context read at 0)
++ self.prompt_len = 0
+
+ def write(self, data: bytes) -> int:
+ self.data += data
+@@ -148,7 +151,7 @@
+ kinds = [v.strip() for k, _, v in (line.partition(":") for line in head[1:]) if k.lower() == "content-type"]
+ self.stream = self.status == 200 and bool(kinds) and kinds[0].startswith("text/event-stream")
+ if self.stream:
+- self.opened()
++ self.opened(self.prompt_len)
+ while self.stream and (end := self.data.find(b"\n\n")) >= 0:
+ block = bytes(self.data[:end])
+ del self.data[:end + 2]
+@@ -207,7 +210,7 @@
+ reply = Reply(base, send if request.stream else None,
+ (lambda final: store.put(final, request.added)) if request.store else None)
+
+- def opened() -> None:
++ def opened(_: int = 0) -> None:
+ handler.send_response(200)
+ handler.send_header("Content-Type", "text/event-stream")
+ handler.send_header("Cache-Control", "no-cache")
+--- tensorfold/cuda/http.py
++++ tensorfold/cuda/http.py
+@@ -219,6 +219,10 @@
+ except RequestError as exc:
+ code, _hd = admission_response(exc)
+ return self._json(code, {"error": error_body(exc, field)}, headers=_hd)
++ # a translated request's wire takes the prepared prompt's length, so its stream head names
++ # the prompt's size (its usage otherwise leaves the client's context read at 0)
++ if isinstance(self.wfile, responses.Wire):
++ self.wfile.prompt_len = len(getattr(prepared, "prompt", None) or ())
+ self.send_response(200)
+ self.send_header("Content-Type", "text/event-stream")
+ self.send_header("Cache-Control", "no-cache")
+--- tensorfold/server/anthropic.py
++++ tensorfold/server/anthropic.py
+@@ -72,7 +72,13 @@
+
+ reply = Reply(reply_model(app, body), send)
+
+- def opened() -> None:
++ def opened(prompt_len: int = 0) -> None:
++ if prompt_len:
++ # the head names the prompt's full count with cache fields 0; the split of it the engine
++ # served from kept states (input = full - cached, cache_read = cached) arrives with the
++ # final message_delta, and the whole (non-streamed) reply reports the same split
++ reply.base["usage"] = {"input_tokens": prompt_len, "output_tokens": 0,
++ "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0}
+ handler.send_response(200)
+ handler.send_header("Content-Type", "text/event-stream")
+ handler.send_header("Cache-Control", "no-cache")
diff --git a/tools/test_anthropic_stream_head.py b/tools/test_anthropic_stream_head.py
new file mode 100644
index 0000000..c981953
--- /dev/null
+++ b/tools/test_anthropic_stream_head.py
@@ -0,0 +1,139 @@
+"""CPU-only in-process HTTP test of the Anthropic stream head's usage (patch 0112).
+
+ python3 -B tools/test_anthropic_stream_head.py --source-root /path/to/patched/src [--expect-stock]
+Use --expect-stock on a tree without the patch to reproduce the report: a streamed /v1/messages reply opens with
+message_start.usage all zeros (the prompt's token count only arrives in the final message_delta), so a client that
+reads prompt counts from message_start (Claude Code's context-window indicator) shows ~0% used. With the patch the
+head names the prepared prompt's whole size and the final delta keeps the engine's input/cache_read split, the two
+totals equal.
+
+Runs the real CUDA-server handler (tensorfold.cuda.http) on a loopback port with a stub app: prepare returns a
+24-token prompt, the streamed reply's usage reports 24 prompt tokens of which 3 were cached, so the head must say
+24 and the final delta 21 + 3. No torch, GPU or models.
+"""
+from __future__ import annotations
+
+import argparse
+import json
+import socket
+import sys
+import threading
+from http.server import ThreadingHTTPServer
+from types import SimpleNamespace
+
+PROMPT_TOKENS = 24
+CACHED_TOKENS = 3
+COMPLETION_TOKENS = 2
+
+
+def start(root: str):
+ sys.path.insert(0, root)
+ from tensorfold.cuda.http import make_handler
+
+ class App:
+ model_ids = ["m"]
+ served_name = "m"
+
+ def reply_model(self, body):
+ return "m"
+
+ def prepare(self, body, chat):
+ # the shape the CUDA app's prepare returns: prompt, the tokens the reply's usage counts
+ return SimpleNamespace(prompt=list(range(PROMPT_TOKENS)), max_tokens=8, tools=[],
+ thinking=False, sampling=None, ignore_eos=False, stop=(),
+ vision=None, grammar=None, think_budget=0)
+
+ def admit(self, body, chat, prepared):
+ pass
+
+ def run(self, body, chat, emit, prepared=None, cancelled=None):
+ emit({"content": "hi"})
+ return {"final": {}, "calls": [], "call_deltas": [], "calls_streamed": 0, "finish": "stop",
+ "content": "hi", "reasoning": None, "prompt_tokens": len(prepared.prompt),
+ "completion_tokens": COMPLETION_TOKENS, "cached_tokens": CACHED_TOKENS, "stats": {}}
+
+ server = ThreadingHTTPServer(("127.0.0.1", 0), make_handler(App()))
+ threading.Thread(target=server.serve_forever, daemon=True).start()
+ return server
+
+
+def request(path: str, body: bytes) -> bytes:
+ return (f"POST {path} HTTP/1.1\r\nHost: x\r\nContent-Type: application/json\r\n"
+ f"Content-Length: {len(body)}\r\n\r\n").encode() + body
+
+
+def exchange(port: int, path: str, body: bytes) -> tuple[int, bytes]:
+ """One request on its own connection: the status and the bytes after the headers."""
+ s = socket.create_connection(("127.0.0.1", port), timeout=5)
+ f = s.makefile("rb")
+ s.sendall(request(path, body))
+ status = int(f.readline().split()[1])
+ headers = {}
+ while (line := f.readline()) not in (b"\r\n", b""):
+ name, _, value = line.decode().partition(":")
+ headers[name.strip().lower()] = value.strip()
+ rest = f.read(int(headers["content-length"])) if "content-length" in headers else f.read()
+ s.close()
+ return status, rest
+
+
+def events(body: bytes) -> list[dict]:
+ return [json.loads(line[6:]) for line in body.splitlines() if line.startswith(b"data: ")
+ and line[6:] != b"[DONE]"]
+
+
+def head_usage(body: bytes) -> dict:
+ starts = [e for e in events(body) if e.get("type") == "message_start"]
+ assert len(starts) == 1, f"expected one message_start, got {len(starts)}"
+ return starts[0]["message"]["usage"]
+
+
+def delta_usage(body: bytes) -> dict:
+ deltas = [e for e in events(body) if e.get("type") == "message_delta"]
+ assert len(deltas) == 1, f"expected one message_delta, got {len(deltas)}"
+ return deltas[0]["usage"]
+
+
+def main() -> None:
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--source-root", required=True)
+ ap.add_argument("--expect-stock", action="store_true")
+ args = ap.parse_args()
+ server = start(args.source_root)
+ port = server.server_address[1]
+ stream = json.dumps({"model": "m", "max_tokens": 8, "stream": True,
+ "messages": [{"role": "user", "content": "hi"}]}).encode()
+ _, body = exchange(port, "/v1/messages", stream)
+ start_usage, delta = head_usage(body), delta_usage(body)
+
+ if args.expect_stock:
+ assert start_usage["input_tokens"] == 0 and start_usage["cache_read_input_tokens"] == 0, start_usage
+ assert delta["input_tokens"] == PROMPT_TOKENS - CACHED_TOKENS, delta
+ assert delta["cache_read_input_tokens"] == CACHED_TOKENS, delta
+ print(f"stock: message_start.usage {start_usage}; the count only arrives in the final "
+ f"message_delta {delta} ({delta['input_tokens']}+{delta['cache_read_input_tokens']}={PROMPT_TOKENS})")
+ return
+
+ assert start_usage == {"input_tokens": PROMPT_TOKENS, "output_tokens": 0,
+ "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0}, start_usage
+ assert delta == {"input_tokens": PROMPT_TOKENS - CACHED_TOKENS, "output_tokens": COMPLETION_TOKENS,
+ "cache_creation_input_tokens": 0, "cache_read_input_tokens": CACHED_TOKENS,
+ "output_tokens_details": {"thinking_tokens": 0}}, delta
+ assert start_usage["input_tokens"] == delta["input_tokens"] + delta["cache_read_input_tokens"], \
+ f"head {start_usage} disagrees with the delta's total {delta}"
+ # a whole (non-streamed) reply keeps its usage, and a plain chat stream is untouched by the wire's new attribute
+ _, body = exchange(port, "/v1/messages", json.dumps({"model": "m", "max_tokens": 8,
+ "messages": [{"role": "user", "content": "hi"}]}).encode())
+ whole = json.loads(body)
+ assert whole["usage"]["input_tokens"] == PROMPT_TOKENS - CACHED_TOKENS, whole["usage"]
+ _, body = exchange(port, "/v1/chat/completions", stream)
+ first = [e for e in events(body) if e.get("choices")][0]
+ assert first["choices"][0]["delta"] == {"role": "assistant"}, first
+ last = [e for e in events(body) if e.get("choices")][-1]
+ assert last.get("usage", {}).get("prompt_tokens") == PROMPT_TOKENS, last
+ print(f"patched: message_start.usage {start_usage}; final message_delta.usage {delta} "
+ f"({delta['input_tokens']}+{delta['cache_read_input_tokens']}={PROMPT_TOKENS})")
+
+
+if __name__ == "__main__":
+ main()