GLM-5.3-Flash EXL3 on 2x DGX Spark with TensorFold
Python
Patch 0121: kept reasoning restored in one pass over the conversation
Christopher A. Williamson813dafb92065
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 7bf5951..1da5443 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -141,6 +141,18 @@ Every change to this recipe, newest first. Each release names the image it serve`TF_GLM_EFFORT_TAIL=1` (`0096`) the generation prompt ends in the effort line, which the conversation's own next turn doesnot repeat at that position, so its own turn state can be taken for a fork (kept by recency instead of superseded-first;never a different reply). CPU check: `tools/fork_point_check.py`.+- **Long agent sessions no longer stall before each request starts** (patch `0121-glm-kept-reasoning-linear`, by+ [cawilliamson](https://github.com/cawilliamson)): `KeptReasoning.restore` (patch `0036`) looks up the reasoning of+ every assistant tool step a client sent back without any, by a signature of the conversation before that step, and+ rebuilt that signature from the whole history for every step: each request re-encoded and hashed its conversation+ once per tool step, the square of its length, in Python with the GIL held, before admission (so outside the TTFT+ metric) and with the engine loop and every other stream stopped meanwhile. A client that returns empty think blocks+ bare makes nearly every step a candidate. Three Sparks, `PARALLEL=4`, a real ~2,000-message, ~404k-token agent+ session replayed fully cached (`prefill_s` 0.2): 4.8-5.3 s before the response headers, the thread inside+ `kept_reasoning.restore` in every stack dump; the fixed part of each turn grew from ~0.4 s at ~100k tokens to ~7 s+ at ~400k while decode held ~45-55 tok/s. One running SHA-256 over the message shapes, copied at each step, makes it+ one pass: that session's restore 4.06 -> 0.014 s, the same restores (the same history in each key; ids are still+ tried first). CPU check: `tools/kept_reasoning_check.py` (fails on the unpatched source).- **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 (atdiff --git a/CREDITS.md b/CREDITS.mdindex 4564793..d9f0623 100644--- a/CREDITS.md+++ b/CREDITS.md@@ -209,6 +209,8 @@ checkpoint's ShapleyMcg attribution and the drafter's license).- `0118-glm-broken-health-exit` (`/health` and `/metrics` report a broken engine; opt-in `TF_GLM_EXIT_ON_BROKEN`): by[bblicke1](https://github.com/bblicke1), [pull request #146](https://github.com/MiaAI-Lab/GLM-5.3-Flash-EXL3-2x-DGX-Sparks-TensorFold/pull/146).- `0120-glm-fork-point-shared` (a kept state a second conversation goes on from is a shared prefix): the diagnosis and the first fix (the writer's next ids kept with a state, the state flagged when a resumed prompt goes on otherwise, the flag kept when the same ids are kept again) are by [RyanLeeUPC](https://github.com/RyanLeeUPC) in [issue #121](https://github.com/MiaAI-Lab/GLM-5.3-Flash-EXL3-2x-DGX-Sparks-TensorFold/issues/121); the rest by [BadAd84](https://github.com/BadAd84).+- `0121-glm-kept-reasoning-linear` (kept reasoning restored in one pass over the conversation): by+ [cawilliamson](https://github.com/cawilliamson).- Every patch, except the parts credited above: by MiaAI-Lab, developed with[Claude Code](https://claude.com/claude-code), under the Apache License 2.0; the TensorFold code the patches modify orquote as context stays under TensorFold's licenses (Apache 2.0, and MIT for code written before v0.6.0; seediff --git a/README.md b/README.mdindex d24d4d5..8110b44 100644--- a/README.md+++ b/README.md@@ -721,6 +721,7 @@ applied with `patch -p0` in filename order); `start.sh` rebuilds or re-pulls the| Streamed admission | `0095-stream-admission` | with `TF_GLM_MAX_QUEUED` set, a streamed request to a full server is answered 429 + `Retry-After: 5` before the stream opens; `0082` checked inside `submit`, after the 200 and the headers had gone out, so a streaming client (opencode, Claude Code) got a 200 with the error as an event and never saw a retryable status (issue #50) | the same refusal for streamed and plain requests || Stream keep-alive | `0111-server-sse-keepalive` | a streamed reply that has sent nothing for `TENSORFOLD_SSE_KEEPALIVE_S` seconds (15; `0`: off) writes an SSE comment line, `: keepalive`, on the chat, completions, Messages and Responses streams; a request waiting for a lane or filling a long prompt was silent from its first event to its first token, and a proxy in front cut it as idle (reported behind a Cloudflare Tunnel: every such stream at ~125 s; issue #106, with the first version of this patch by stevehansen) | the same events, byte for byte; no stream silent for longer than the setting || Effort line at the tail | `0096-effort-tail` | opt-in `TF_GLM_EFFORT_TAIL=1`: the reasoning-effort line is rendered before the generation prompt, not at token 3, so changing effort or thinking on/off no longer misses the kept prompt and re-prefills the whole conversation (issue #93, reported and measured by jdecker76); off, every prompt is byte-identical to before | the same prompts as before |+| Kept reasoning in one pass | `0121-glm-kept-reasoning-linear` | `KeptReasoning.restore` (`0036`) keys each assistant tool step a client sent back without reasoning by one running SHA-256 over the conversation before it, instead of re-encoding that whole conversation for every step (the square of its length, with the GIL held: ~4-5 s a request at ~2,000 messages) (by [cawilliamson](https://github.com/cawilliamson)) | the same restored reasoning; a long agent session's requests no longer stop the engine loop before admission || Concurrent fill | `0062-glm-sliced-fill` | a new prompt's chunks run in layer slices (`FILL_BUDGET_MS`) with decode rounds between them, drafted as usual (`FILL_DRAFTS`), both ranks on the same layer boundaries; the chunk's buffers kept between slices, grouped fills, cache moves and cancellation mid-fill; whole forwards when nothing else decodes | with smooth streaming, the other replies' pauses during a 25k-token fill 630-690 ms -> 81-149 ms (table below) |Concurrent prompt fill and smooth streaming on two Sparks (`PARALLEL=4`, DFlash2, 1,024-row chunks): three 400-token@@ -781,6 +782,7 @@ with [sparkDash](https://github.com/MiaAI-Lab/sparkDash) ([Performance](#perform| `tools/test_broken_health_exit.py --source-root DIR` | CPU-only broken-state checks against patched TensorFold: settings, first cause, request refusal, round/load/drop errors, health and metrics, subprocess exit (no Torch/GPU) || `tools/test_queued_cancellation.py --source-root DIR` | patch 0073's checks on the CPU, against TensorFold's source with the patches applied (no GPU, no server): requests that wait while every slot is busy and whose client leaves are dropped at once, in queue order; `--expect-stock` before 0073 shows the old wait || `tools/test_sse_keepalive.py --source-root DIR` | patch 0111's checks on the CPU, against TensorFold's source with the patches applied (no GPU, no server): every streaming route of the real handler, over a stub that stays silent for 3 s, gets `: keepalive` about once a second with `TENSORFOLD_SSE_KEEPALIVE_S=1` and none after its last event; without its comment lines each stream is byte-identical to the stream with `0`; non-streamed replies unchanged; no thread outlives its request; `--expect-stock` before 0111 shows the silence |+| `tools/kept_reasoning_check.py --source-root DIR` | patch 0121's checks on the CPU, against TensorFold's source with the patches applied: `restore` against the stock implementation (embedded) on 300 random agent conversations (LRU eviction, renumbered ids and re-serialised arguments included), and one pass over a ~2,100-message conversation; `--expect-stock` reproduces the quadratic restore on the unpatched source || `tools/end_of_turn.py [label] [max_cut]` | 8 short French coding prompts, thinking off: counts the replies that run to `max_tokens` (48 requests) and measures P(end of turn) right after each reply's closing code fence; exit 1 above `max_cut` cut replies (default 4) || `tools/prompt_reuse.py [size]` | a ~33k-token conversation takes three more turns, each after a request of another conversation with the same system prompt (an agent and its sub-agents); exit 1 when a turn resumes less than 90% of its prompt. Needs `PARALLEL` above 1 || `tools/picture_turns.py [pictures] [size]` | a chat of ~`size` tokens (default 40000) gets one new 1920x1080 picture a turn (default 12), with a text turn after each; exit 1 when a turn re-reads more than the new picture, which is what a picture cap that moves with the picture count does from the 9th picture on |diff --git a/patches/0121-glm-kept-reasoning-linear.patch b/patches/0121-glm-kept-reasoning-linear.patchnew file mode 100644index 0000000..ff11ebe--- /dev/null+++ b/patches/0121-glm-kept-reasoning-linear.patch@@ -0,0 +1,113 @@+# Kept reasoning is restored in one pass over the conversation. KeptReasoning.restore (patch 0036) keyed each assistant+# tool step that came back without reasoning by a signature of the whole conversation before it, rebuilt for every+# step: each one re-encoded and hashed every earlier message, so a request cost the square of its length, in Python+# with the GIL held, before admission and outside the TTFT metric. An agent client that sends empty think blocks back+# bare (pi does) makes nearly every step a candidate: ~4-5 s a request at ~2,000 messages / ~400k tokens, with the+# engine loop and every other stream stopped meanwhile. _History keeps one running SHA-256 over the message shapes+# (each length-prefixed) and copies it at each step: one pass a request. The same keys cover the same history (role,+# stripped text, calls; no ids or reasoning), ids are still tried first, so the same steps are restored with the same+# reasoning; the key format is new, which only matters within one process. tools/kept_reasoning_check.py.++diff --git tensorfold/families/glm5_next/cuda/kept_reasoning.py tensorfold/families/glm5_next/cuda/kept_reasoning.py+--- tensorfold/families/glm5_next/cuda/kept_reasoning.py++++ tensorfold/families/glm5_next/cuda/kept_reasoning.py+@@ -14,6 +14,11 @@++ ``TF_GLM_KEEP_REASONING``: replies kept (default 1024; 0 turns this off); ``TF_GLM_KEEP_REASONING_MB``: their text+ at most (default 32 MiB); the oldest go first.++++Keys are one running SHA-256 over the conversation's message shapes (``_History``): ``restore`` copies it at each++step, so a request costs one pass over its messages. Before, each step re-encoded every message before it, so a++request cost the square of its length, with the GIL held: ~5 s at 404k tokens / 2,020 messages, the engine loop and++every other stream stopped meanwhile.+ """++ from __future__ import annotations+@@ -69,25 +74,54 @@+ return out+++-def signature(history: list[Any], calls: Any) -> str:+- """The key of ``calls`` written after ``history``: each message's role, text (stripped, as the template renders+- it) and calls, without ids or reasoning, then the calls."""++def _encode(value: Any) -> bytes:++ text = json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"), default=str)++ return text.encode("utf-8", "surrogatepass")++- shape = []+- for m in history:++++class _History:++ """A running hash of a conversation's message shapes (role, text stripped as the template renders it, calls;++ no ids or reasoning), each length-prefixed: the key of calls after any prefix costs one copy of the hash."""++++ def __init__(self) -> None:++ self.hash = hashlib.sha256(b"tf-kept-reasoning-v2\0")++++ def add(self, m: Any) -> None:+ if not isinstance(m, dict):+- continue++ return+ entry = [str(m.get("role") or ""), _text(m.get("content")).strip()]+ if m.get("role") == "assistant" and m.get("tool_calls"):+ entry.append(_calls(m.get("tool_calls")))+- shape.append(entry)+- text = json.dumps([shape, _calls(calls)], ensure_ascii=False, sort_keys=True, separators=(",", ":"), default=str)+- return "sig:" + hashlib.sha256(text.encode("utf-8", "surrogatepass")).hexdigest()++ data = _encode(entry)++ self.hash.update(len(data).to_bytes(8, "little"))++ self.hash.update(data)++++ def key(self, calls: Any) -> str:++ h = self.hash.copy()++ data = _encode(_calls(calls))++ h.update(b"\xffcalls")++ h.update(len(data).to_bytes(8, "little"))++ h.update(data)++ return "sig:" + h.hexdigest()+++-def _keys(history: list[Any], calls: Any) -> list[str]:++def signature(history: list[Any], calls: Any) -> str:++ """The key of ``calls`` written after ``history``: each message's role, text (stripped, as the template renders++ it) and calls, without ids or reasoning, then the calls."""++++ run = _History()++ for m in history:++ run.add(m)++ return run.key(calls)++++++def _ids(calls: Any) -> list[str]:+ ids = [c.get("id") for c in calls if isinstance(c, dict)] if isinstance(calls, list) else []+- return [i for i in ids if isinstance(i, str) and _OUR_ID.match(i)] + [signature(history, calls)]++ return [i for i in ids if isinstance(i, str) and _OUR_ID.match(i)]++++++def _keys(history: list[Any], calls: Any) -> list[str]:++ return _ids(calls) + [signature(history, calls)]+++ class KeptReasoning:+@@ -143,13 +177,15 @@+ if not isinstance(messages, list) or not self.items:+ return messages+ out = None++ run = _History()+ for i, m in enumerate(messages):+- if not (isinstance(m, dict) and m.get("role") == "assistant" and m.get("tool_calls")++ if (isinstance(m, dict) and m.get("role") == "assistant" and m.get("tool_calls")+ and not _text(m.get("reasoning_content")).strip() and not _text(m.get("reasoning")).strip()+ and "</think>" not in _text(m.get("content"))):+- continue+- kept = self._find(_keys(messages[:i], m["tool_calls"]))+- if kept is not None:+- out = out if out is not None else list(messages)+- out[i] = {**m, "reasoning_content": kept}++ # the ids first (cheap), then the conversation's key: the order ``_keys`` gives them++ kept = self._find(_ids(m["tool_calls"])) or self._find([run.key(m["tool_calls"])])++ if kept is not None:++ out = out if out is not None else list(messages)++ out[i] = {**m, "reasoning_content": kept}++ run.add(m) # the shape has no reasoning: the same before or after a restore+ return messages if out is None else outdiff --git a/tools/kept_reasoning_check.py b/tools/kept_reasoning_check.pynew file mode 100644index 0000000..0dd3c07--- /dev/null+++ b/tools/kept_reasoning_check.py@@ -0,0 +1,211 @@+"""CPU check of patch 0121: KeptReasoning.restore in one pass over the conversation, the same restores as before.++ python3 -B tools/kept_reasoning_check.py --source-root /path/to/patched/src+Use --expect-stock on the unpatched source to reproduce the cost: restore() re-encodes and hashes the whole+conversation before every assistant tool step that came back without reasoning, so one request costs the square of+its length (seconds at ~2,000 messages, with the GIL held).+Loads tensorfold/families/glm5_next/cuda/kept_reasoning.py by its path (no torch, GPU or model) and compares it with+the stock implementation, embedded below as the oracle, on random agent conversations: the same restored messages,+the same copy-or-not, LRU eviction included.+"""+from __future__ import annotations++import argparse+import copy+import hashlib+import importlib.util+import json+import random+import re+import sys+import threading+import time+from collections import OrderedDict+from pathlib import Path+from typing import Any++# ------------------------------------------------------------------ the stock implementation (patch 0036), the oracle+_OUR_ID = re.compile(r"^call_[0-9a-f]{24}$")+++def _text(content: Any) -> str:+ if isinstance(content, str):+ return content+ if isinstance(content, list):+ return "".join(p["text"] for p in content if isinstance(p, dict) and isinstance(p.get("text"), str))+ return ""+++def _arguments(value: Any) -> Any:+ if isinstance(value, str):+ try:+ return json.loads(value) if value.strip() else {}+ except ValueError:+ return value+ return {} if value is None else value+++def _calls(calls: Any) -> list[list[Any]]:+ out = []+ for call in calls if isinstance(calls, list) else []:+ fn = call.get("function") if isinstance(call, dict) and isinstance(call.get("function"), dict) else {}+ out.append([str(fn.get("name") or ""), _arguments(fn.get("arguments"))])+ return out+++def _signature(history: list[Any], calls: Any) -> str:+ shape = []+ for m in history:+ if not isinstance(m, dict):+ continue+ entry = [str(m.get("role") or ""), _text(m.get("content")).strip()]+ if m.get("role") == "assistant" and m.get("tool_calls"):+ entry.append(_calls(m.get("tool_calls")))+ shape.append(entry)+ text = json.dumps([shape, _calls(calls)], ensure_ascii=False, sort_keys=True, separators=(",", ":"), default=str)+ return "sig:" + hashlib.sha256(text.encode("utf-8", "surrogatepass")).hexdigest()+++def _keys(history: list[Any], calls: Any) -> list[str]:+ ids = [c.get("id") for c in calls if isinstance(c, dict)] if isinstance(calls, list) else []+ return [i for i in ids if isinstance(i, str) and _OUR_ID.match(i)] + [_signature(history, calls)]+++class StockKeptReasoning:+ def __init__(self, entries: int = 1024, chars: int = 32 << 20) -> None:+ self.entries, self.chars = int(entries), int(chars)+ self.items: OrderedDict[int, tuple[str, tuple[str, ...]]] = OrderedDict()+ self.by_key: dict[str, int] = {}+ self.size = self.next = 0+ self.lock = threading.Lock()++ def remember(self, messages: Any, calls: Any, reasoning: Any) -> None:+ if not calls or not isinstance(reasoning, str) or not reasoning.strip() or len(reasoning) > self.chars:+ return+ keys = tuple(_keys(messages if isinstance(messages, list) else [], calls))+ with self.lock:+ n, self.next = self.next, self.next + 1+ self.items[n] = (reasoning, keys)+ self.size += len(reasoning)+ for key in keys:+ self.by_key[key] = n+ while len(self.items) > self.entries or self.size > self.chars:+ old, (text, old_keys) = self.items.popitem(last=False)+ self.size -= len(text)+ for key in old_keys:+ if self.by_key.get(key) == old:+ del self.by_key[key]++ def _find(self, keys: list[str]) -> str | None:+ with self.lock:+ for key in keys:+ n = self.by_key.get(key)+ if n is not None:+ self.items.move_to_end(n)+ return self.items[n][0]+ return None++ def restore(self, messages: Any) -> Any:+ if not isinstance(messages, list) or not self.items:+ return messages+ out = None+ for i, m in enumerate(messages):+ if not (isinstance(m, dict) and m.get("role") == "assistant" and m.get("tool_calls")+ and not _text(m.get("reasoning_content")).strip() and not _text(m.get("reasoning")).strip()+ and "</think>" not in _text(m.get("content"))):+ continue+ kept = self._find(_keys(messages[:i], m["tool_calls"]))+ if kept is not None:+ out = out if out is not None else list(messages)+ out[i] = {**m, "reasoning_content": kept}+ return messages if out is None else out+++# ------------------------------------------------------------------ the check+def load(root: str):+ path = Path(root) / "tensorfold/families/glm5_next/cuda/kept_reasoning.py"+ spec = importlib.util.spec_from_file_location("kept_reasoning_under_test", path)+ mod = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(mod)+ return mod+++def conversation(r: random.Random, steps: int):+ """An agent conversation as a client sends it back, and the replies the server saw (messages before, calls, reasoning)."""++ msgs: list[Any] = [{"role": "system", "content": "system " + str(r.random())}]+ replies = []+ for s in range(steps):+ if r.random() < 0.08:+ msgs.append({"role": "user", "content": f"user {s} {r.random()}"})+ if r.random() < 0.02:+ msgs.append("not a message") # skipped by the shape+ cid = f"call_{r.getrandbits(96):024x}" if r.random() < 0.5 else f"toolu_{s}"+ calls = [{"id": cid, "type": "function",+ "function": {"name": r.choice(["read", "bash"]), "arguments": json.dumps({"p": s, "q": r.random()})}}]+ reasoning = r.choice(["", " ", f"thinking {s} {r.random()}"]) # empty think blocks are common in tool loops+ replies.append((copy.deepcopy(msgs), calls, reasoning))+ sent = {"role": "assistant", "content": r.choice(["", "ok", None]), "tool_calls": copy.deepcopy(calls)}+ mode = r.random()+ if mode < 0.15 and reasoning.strip():+ sent["reasoning_content"] = reasoning # a client that sends it back+ elif mode < 0.25:+ sent["tool_calls"][0]["id"] = f"renumbered_{s}" # a client that renumbers ids: found by the signature+ elif mode < 0.30: # re-serialised arguments: the same signature+ args = json.loads(calls[0]["function"]["arguments"])+ sent["tool_calls"][0]["function"]["arguments"] = json.dumps(args, indent=1)+ msgs.append(sent)+ msgs.append({"role": "tool", "tool_call_id": sent["tool_calls"][0]["id"], "content": f"result {s} " * 50})+ return msgs, replies+++def drive(cls, msgs, replies, entries: int):+ kept = cls(entries, 32 << 20)+ for before, calls, reasoning in replies:+ kept.remember(before, calls, reasoning)+ return kept.restore(msgs)+++def timed_restore(cls, msgs, replies) -> float:+ kept = cls()+ kept.remember(replies[0][0], replies[0][1], "seed") # a non-empty store, as on a live server+ bare = [({k: v for k, v in m.items() if k != "reasoning_content"} if isinstance(m, dict) else m) for m in msgs]+ t0 = time.perf_counter()+ kept.restore(bare)+ return time.perf_counter() - t0+++def main() -> int:+ ap = argparse.ArgumentParser()+ ap.add_argument("--source-root", required=True)+ ap.add_argument("--expect-stock", action="store_true")+ args = ap.parse_args()+ mod = load(args.source_root)++ r = random.Random(7)+ restored = 0+ for trial in range(300):+ msgs, replies = conversation(r, r.randint(1, 60))+ entries = r.choice([1024, 8, 3]) # small LRUs exercise eviction+ want = drive(StockKeptReasoning, msgs, replies, entries)+ got = drive(mod.KeptReasoning, msgs, replies, entries)+ assert got == want, f"trial {trial}: restore differs from stock"+ assert (got is msgs) == (want is msgs), f"trial {trial}: copy semantics differ from stock"+ restored += sum(1 for a, b in zip(msgs, got) if a is not b)+ print(f"300 conversations, {restored} steps restored: the same restores as stock")++ msgs, replies = conversation(random.Random(1), 1000) # ~2,100 messages: a long agent session+ stock = timed_restore(StockKeptReasoning, msgs, replies)+ here = timed_restore(mod.KeptReasoning, msgs, replies)+ print(f"restore over {len(msgs)} messages: stock {stock:.3f} s, this source {here:.3f} s")+ if args.expect_stock:+ assert here > stock / 4, "this source restores in one pass: is it patched?"+ print("stock: restore re-encodes the conversation before every step (the square of its length)")+ return 0+ assert here * 20 < stock, "restore is not one pass over the conversation"+ print("kept reasoning: one pass a request, the same restores")+ return 0+++if __name__ == "__main__":+ sys.exit(main())