Skip to content

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

Python

Patch 0117: GLM's reply markup is read at its marker tokens

ahinore6fd8e5b706d3
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 58a767d..cfa900b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -89,6 +89,22 @@ Every change to this recipe, newest first. Each release names the image it serve
failing assertion starts with `</think>` 4 (3) -> 8 (7). A quote the model writes as text inside its reasoning
still ends the reasoning where the reply is split today (at the first `</think>` in the text). CPU check:
`tools/literal_tokens_check.py`.
+- **A `<tool_call>` or `</think>` the reply spells as text stays text** (patch `0117-glm-reply-marker-ids`, by [ahinore](https://github.com/ahinore)):
+ GLM writes its markup as single tokens, but the server read the decoded reply as text.
+ - **What went wrong:**
+ - a `</think>` the model quoted in its reasoning ended the reasoning there;
+ - an example call written as text became a real `tool_calls` entry;
+ - a real call whose argument contains `</arg_value>`, `</tool_call>` or `</think>` was cut.
+ - **The fix:**
+ - each marker token in the reply is recorded with the occurrence of its text it wrote;
+ - every other occurrence is made inert at the same length before the parsers read the reply (`ThinkSplit`, the call hiding and streaming, the end parser, #22's closing), so the parsers are unchanged;
+ - everything the server sends has the text back.
+ - **Scope:** a reply without spelled markup parses as before; `TF_GLM_REPLY_IDS=0` turns it off; other families are unchanged. It is the reply's side of patch 0122's rule and applies with or without it. It ports `TENSORFOLD_REPLY_IDS` from [bertholomus/TensorFold@113a151c](https://github.com/bertholomus/TensorFold/commit/113a151cc69dba111a3bab3f9d6f33cb0dac61c5).
+ - **Measured:** four Sparks with 0122, 10 sampled replies per case, recorded and parsed both ways. The answer was right:
+ - which side of a failing assertion starts with `</think>`: 4 -> 7;
+ - an expected value starting with `<think>`: 9 -> 10;
+ - echo `<think>hello</think> world`: 0 -> 5.
+ - **CPU check:** `tools/reply_ids_check.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/README.md b/README.md
index c8bf128..6528af2 100644
--- a/README.md
+++ b/README.md
@@ -561,6 +561,7 @@ sets a value wins: the environment, then `scripts/local.sh`, then `.env`, then t
| `TF_GLM_CLEAR_THINKING` | `0` | `1`: drop earlier turns' reasoning from the prompt, as the checkpoint's template does (agents then prefill the previous turn's tool loop again); a request's `chat_template_kwargs.clear_thinking` wins |
| `TF_GLM_EFFORT_TAIL` | `0` | `1` (patch `0096`, issue #93, reported by [jdecker76](https://github.com/jdecker76)): render the reasoning-effort line just before `<\|assistant\|><think>` instead of at token 3, so switching effort or thinking on/off keeps the conversation's kept prompt (the reporter measured 0% cached becoming 98%); the model was trained with the line first, so check that Low and High still change the answers before you rely on it (`tools/toolcheck.py`, `tools/end_of_turn.py`). The previous turn's last tokens prefill again |
| `TF_GLM_LITERAL_TOKENS` | `1` | added-token text a request quotes stays text (patch `0116`); `0`: every match of an added token's text in the rendered prompt is that token, as before |
+| `TF_GLM_REPLY_IDS` | `1` | GLM's reply markup (`</think>`, `<tool_call>`, the argument tags) is markup only where the reply's own marker tokens wrote it (patch `0117`); `0`: every match of a tag's text in the decoded reply is markup, as before |
| `NUCLEUS_UNION` | `1` | `TENSORFOLD_NUCLEUS_UNION` (patch `0034`): a sampled step with top_p below 1 and top_k off tests the ranks' candidates together for the nucleus, instead of each rank alone (which sent almost every step to a whole-vocabulary CPU sort: ~15 tok/s against greedy's ~58); the same draws, byte for byte (`tools/test_nucleus_union.py`); `0`: stock (issue #91) |
| `TF_GLM_MAX_QUEUED` | unset | admission at saturation (patch `0082`): past the lanes plus this many queued foreground requests, a request is refused with 429 + `Retry-After: 5` instead of queueing; unset queues as every scheduler always has, `0` refuses anything past the lanes (by johnwhited, #48) |
| `SSE_KEEPALIVE_S` | `15` | `TENSORFOLD_SSE_KEEPALIVE_S` (patch `0111`): a streamed reply that has sent nothing for this many seconds (waiting for a lane, filling a long prompt) writes an SSE comment line, `: keepalive`, so a proxy in front does not cut it as idle (Cloudflare: after about two minutes, issue #106); clients skip comment lines, and the events are the same bytes. Every streaming route; `0`: off |
@@ -697,6 +698,7 @@ applied with `patch -p0` in filename order); `start.sh` rebuilds or re-pulls the
| Picture cache | `0079-glm-picture-cache` | the vision frontend reads a request's pictures once, not on every turn of the chat: what reading each source cost (rows, key, digest, canvas) is kept by the source's bytes and handed back on later turns (host memory only; `TENSORFOLD_GLM_PICTURE_CACHE`, by ThomasWadeZ, #63) | 10 pictures in a chat, a later turn's first token 0.43-0.46 s -> 0.16-0.19 s; prompt tokens and replies identical |
| Quoted markers | `0080-vision-quoted-markers` | every picture and clip of a request is marked with a per-request nonce, and a marker not behind one stays text: quoting the template's picture span in a prompt, a log or a refusal no longer counts as media, while a template or client that drops a picture is still refused (by ThomasWadeZ, #64) | a request quoting the picture span beside a real picture: 400 -> 200, the right answer |
| Quoted added tokens | `0116-glm-literal-added-tokens` | a request's text that quotes one of the checkpoint's added tokens (a `<think>` from another model's output, a `<tool_call>` in a file or a tool's description, a `<\|user\|>` in a log) is encoded as ordinary text, not as that token: messages, reasoning, call arguments (JSON-escaped ones too) and the tools' definitions are masked before the template renders, so the template's own tokens stay tokens; GLM's kept reasoning is put back first; `/nothink`, assistant turns with their reasoning inline and requests with pictures as before (`TF_GLM_LITERAL_TOKENS=0` turns it off) | a prompt without such text: the same ids; replies writing a quoted `</think>` as the token 7-8 -> 0 of 10, an expected value starting with `<think>` written right 0 -> 10 of 10 (two and four Sparks) |
+| Reply markup by token | `0117-glm-reply-marker-ids` | the reply's markup is read at its marker tokens: a `</think>` the model quotes in its reasoning, an example call written as text and a call argument that spells `</arg_value>` or `</tool_call>` are text, not markup (each marker token's occurrence is recorded; the others are made inert at the same length for the parsers and given back in what is sent); a reply without spelled markup as before (`TF_GLM_REPLY_IDS=0` turns it off; a port of bertholomus/TensorFold's `TENSORFOLD_REPLY_IDS`) | with 0122, four Sparks: echo `<think>hello</think> world` right 0 -> 5 of 10, which side starts with `</think>` 4 -> 7 of 10; an example call no longer becomes a `tool_calls` entry (CPU check) |
| Capacity status | `0081-tfcap-capacity-status` | every capacity refusal renders the same way: 429 with `Retry-After: 5` (was a bare 503 at two sites, a 400 on the generate path) (by johnwhited, #48) | a refused request's client can back off instead of stacking |
| Admission control | `0082-tfcap-admission-cap` | `TF_GLM_MAX_QUEUED` (unset: queue, as before; a number: past the lanes plus that many queued foreground requests, refuse) turns saturation into a refusal instead of an invisible queue (by johnwhited, #48) | with `TF_GLM_MAX_QUEUED=0`, the fifth request on four lanes: 429 at once with `Retry-After: 5`; unset, it queues as before |
| Delivery abort | `0083-tfcap-delivery-abort` | a stream whose delivery callback raises (broken pipe, reset, timeout) ends at once and frees its lane, instead of the exception escaping and the lane leaking until generation ends (by johnwhited, #48) | a client that dies mid-reply no longer holds a lane |
@@ -761,6 +763,7 @@ with [sparkDash](https://github.com/MiaAI-Lab/sparkDash) ([Performance](#perform
| `tools/toolcheck.py` | makes a tool call with an array parameter and checks it comes back as a JSON array |
| `tools/test_get_bodies.py --source-root DIR` | patch 0113's checks on the CPU, against TensorFold's source with the patches applied: the real CUDA handler on a loopback port, GETs and a DELETE with Content-Length and chunked bodies, each followed by more requests on the same keep-alive connection, and a GET body past the limit closing it; `--expect-stock` reproduces the leaked body's 400 on the unpatched source |
| `tools/literal_tokens_check.py <checkpoint dir>` | patch 0116's checks, run in the image (CPU only, see the file): on the checkpoint's own tokenizer and template, quoted added tokens encode as text and everything else as before, the exceptions keep the old ids, GLM's kept reasoning is still put back, other families' `App` is unchanged |
+| `tools/reply_ids_check.py <checkpoint dir>` | patch 0117's checks, run in the image (CPU only, see the file): through the chat route on the checkpoint's own tokenizer, whole and streamed, spelled markup stays text, real calls and the think split as before, nothing inert reaches a client; the switch on in `GlmApp`, off with `TF_GLM_REPLY_IDS=0` and in other families |
| `tools/display_kv_check.py [--gpu]` | patch 0072's checks, run in the image (`docker run ... --entrypoint python`, see the file): the setting, the span's mapping and unwinding through a fake driver, the carved planes and the pool's copies; with `--gpu`, the real span on a Spark whose display reservation is free |
| `tools/qmm_noclusters_check.py [--time]` | patch 0103's checks: the installed 4-bit matmul against a build of the same sources with the old cluster rule, bit for bit at every decode shape of TP=4, TP=3 and TP=2 and at the 28 Mi edge, the path each call takes (and with `TF_GLM_QMM_CLUSTERS=1`), and a CUDA graph on side streams; run in the image on one GPU (`docker run --gpus all ... --entrypoint python`, see the file); `--time` prints the old and new paths' times |
| `tools/pool_pressure.py [size]` | on a fresh server with nothing else sending requests: two conversations of ~`size` tokens (default 30000) take a turn each, others fill the pool, then each takes another turn; exit 1 when a turn resumes less than 90% of its previous prompt, 2 when the kept-prompt cap stops the fill first (a smaller pool runs it faster: `CONTEXT=131072 KV_POOL_GIB=0.5`) |
diff --git a/patches/0117-glm-reply-marker-ids.patch b/patches/0117-glm-reply-marker-ids.patch
new file mode 100644
index 0000000..c6804d4
--- /dev/null
+++ b/patches/0117-glm-reply-marker-ids.patch
@@ -0,0 +1,194 @@
+--- tensorfold/cuda/reply_text.py
++++ tensorfold/cuda/reply_text.py
+@@ -7,6 +7,7 @@
+ from __future__ import annotations
+
+ import json
++import os
+ import re
+ import uuid
+ from typing import Any
+@@ -221,6 +222,97 @@
+ or _THINK_CLOSE.startswith(after)):
+ return end, "pending" # a block, or the think block's close, being written
+ return end, "reasoning"
++
++
++# patch 0117 (TF_GLM_REPLY_IDS): GLM's reply markup, which its tokenizer holds as single tokens
++GLM_MARKERS = ("<think>", "</think>", "<tool_call>", "</tool_call>", "<arg_key>", "</arg_key>", "<arg_value>",
++ "</arg_value>")
++_INERT = chr(0xE000) # a spelled marker's last character while the parsers read it (the same length)
++_INERT_JSON = chr(92) + "ue000" # that character as json.dumps(ensure_ascii=True) writes it
++
++
++class ReplyMarks:
++ """TF_GLM_REPLY_IDS (patch 0117, on unless 0): GLM's reply markup is markup only where the reply's own marker
++ tokens wrote it. ``</think>``, ``<tool_call>`` and the argument tags are single tokens; the same text spelled in
++ ordinary tokens (a quoted tag, an example call, an echoed document) is words. ``reply()`` follows one reply;
++ its ``mask`` makes those spellings inert at the same length, so the text parsers (the think split, the call
++ hiding and streaming, the end parser, the closing of a cut call) keep their offsets and skip them, and
++ ``unmask`` gives them back in what is sent. Patch 0122 is the request's side of the same rule."""
++
++ def __init__(self, tok: Any, markers: tuple[str, ...] = GLM_MARKERS) -> None:
++ self.tok = tok
++ self.ids: dict[int, str] = {}
++ for mark in markers:
++ token = tok.token_to_id(mark)
++ if token is not None and tok.decode([token], skip_special_tokens=False) == mark:
++ self.ids[token] = mark
++ self.inert = {mark: mark[:-1] + _INERT for mark in self.ids.values()}
++
++ @classmethod
++ def from_env(cls, tok: Any) -> "ReplyMarks | None":
++ value = os.environ.get("TF_GLM_REPLY_IDS", "1").strip() or "1"
++ if value not in ("0", "1"):
++ raise ValueError(f"TF_GLM_REPLY_IDS={value!r}: expected 0 or 1")
++ if value == "0":
++ return None
++ marks = cls(tok)
++ print(f"[tensorfold] reply markup is read at its {len(marks.ids)} marker tokens; the same text spelled in "
++ f"ordinary tokens stays words (TF_GLM_REPLY_IDS=0 turns it off)", flush=True)
++ return marks
++
++ def reply(self) -> "_ReplyMarks":
++ return _ReplyMarks(self)
++
++ def unmask(self, value: Any) -> Any:
++ """``value`` (text, or the lists and dicts of a delta or a reply) with every inert marker given back."""
++
++ if isinstance(value, str):
++ if _INERT not in value and _INERT_JSON not in value:
++ return value
++ for mark, inert in self.inert.items():
++ value = value.replace(inert, mark).replace(mark[:-1] + _INERT_JSON, mark)
++ return value
++ if isinstance(value, list):
++ return [self.unmask(v) for v in value]
++ if isinstance(value, tuple):
++ return tuple(self.unmask(v) for v in value)
++ if isinstance(value, dict):
++ return {k: self.unmask(v) for k, v in value.items()}
++ return value
++
++
++class _ReplyMarks:
++ """One reply's real markers: for each marker's text, which of its occurrences the reply's marker tokens wrote
++ (the occurrences of that text in the decode before each such token), read as the tokens arrive."""
++
++ def __init__(self, marks: ReplyMarks) -> None:
++ self.marks = marks
++ self.real: dict[str, set[int]] = {mark: set() for mark in marks.ids.values()}
++ self.seen = 0
++
++ def mask(self, text: str, tokens: list[int]) -> str:
++ ids = self.marks.ids
++ for at in range(self.seen, len(tokens)):
++ mark = ids.get(tokens[at])
++ if mark is not None:
++ self.real[mark].add(self.marks.tok.decode(tokens[:at], skip_special_tokens=False).count(mark))
++ self.seen = len(tokens)
++ cuts = []
++ for mark, real in self.real.items():
++ at, n = text.find(mark), 0
++ while at >= 0:
++ if n not in real:
++ cuts.append((at, mark))
++ n += 1
++ at = text.find(mark, at + len(mark))
++ if not cuts:
++ return text
++ out, done = [], 0
++ for at, mark in sorted(cuts):
++ out += [text[done:at], self.marks.inert[mark]]
++ done = at + len(mark)
++ out.append(text[done:])
++ return "".join(out)
+
+
+ class ThinkSplit:
+--- tensorfold/cuda/server.py
++++ tensorfold/cuda/server.py
+@@ -399,6 +399,16 @@
+ xml_stream = ToolCallStreamer(tools) if tools and not glm_calls and not policy.single else None
+ answer_raw = [""]
+ closing = [""] # what closes a GLM call the reply ended inside on an end token (#22)
++ # patch 0117: GLM's markup is markup only at the reply's own marker tokens (TF_GLM_REPLY_IDS); the parsers
++ # read the reply with its spelled markers inert, and what is sent has them back
++ marks = getattr(self, "reply_ids", None) if chat else None
++ reply_marks = marks.reply() if marks is not None else None
++
++ def mask(text: str) -> str:
++ return reply_marks.mask(text, out) if reply_marks is not None else text
++
++ def unmask(value: Any) -> Any:
++ return marks.unmask(value) if reply_marks is not None else value
+ # GLM's calls written inside the think block: calls when the reply ends on them (``ThinkSplit``)
+ think = (ThinkSplit(THINK_CALL_HOLD if calls_stream is not None else None) if glm_calls and chat and thinking
+ else None)
+@@ -419,7 +429,7 @@
+ raw = stream.final() if finished else stream.text
+ # stop strings match the generated text, reasoning included, before it is split (as on the Mac)
+ raw = stops.visible(raw, partial=not finished) if stops.strings else raw
+- raw = raw + closing[0] if finished else raw
++ raw = mask(raw) + closing[0] if finished else mask(raw)
+ reasoning, answer = split(raw, finished)
+ answer_raw[0] = answer
+ if tools:
+@@ -448,10 +458,10 @@
+ reasoning, answer, raw = visible(False)
+ delta: dict[str, Any] = {}
+ if len(reasoning) > sent["reasoning"]:
+- delta["reasoning_content"] = reasoning[sent["reasoning"]:]
++ delta["reasoning_content"] = unmask(reasoning)[sent["reasoning"]:]
+ sent["reasoning"] = len(reasoning)
+ if len(answer) > sent["content"]:
+- delta["content"] = answer[sent["content"]:]
++ delta["content"] = unmask(answer)[sent["content"]:]
+ sent["content"] = len(answer)
+ return delta, raw
+
+@@ -491,7 +501,7 @@
+ wrote = True
+ parts: list[dict[str, Any]] = []
+ if calls_stream is not None and not stopped["client"]:
+- parts += calls_stream.feed(call_text(raw))
++ parts += unmask(calls_stream.feed(call_text(raw)))
+ if parts or wrote:
+ quiet_since[0] = time.monotonic()
+ elif calls_stream.open and time.monotonic() - quiet_since[0] >= CALL_KEEPALIVE_S:
+@@ -607,13 +617,13 @@
+ ended = bool(out) and out[-1] in ends and not stopped["stop"]
+ if ended and glm_calls:
+ final_raw = stream.final()
+- closing[0] = close_glm_call(stops.visible(final_raw) if stops.strings else final_raw, tools)
++ closing[0] = close_glm_call(mask(stops.visible(final_raw) if stops.strings else final_raw), tools)
+ reasoning, answer, raw = visible(True)
+ final: dict[str, Any] = {}
+ if len(reasoning) > sent["reasoning"]:
+ final["reasoning_content"] = reasoning[sent["reasoning"]:]
+ raw_text = self.tok.decode([t for t in out if t not in ends], skip_special_tokens=False)
+- text = stops.visible(raw_text) + closing[0]
++ text = mask(stops.visible(raw_text)) + closing[0]
+ raw_answer = split(text, True)[1]
+ content, calls = parse_tool_calls(raw_answer, tools, max_calls=policy.max_calls) if tools else (answer, None)
+ content = policy.content(content) if tools else content
+@@ -636,6 +646,8 @@
+ final["content"] = tail
+ finish = "tool_calls" if calls and not cut else ("stop" if stopped["stop"] or (out and out[-1] in ends)
+ else "length")
++ final, calls, call_deltas = unmask(final), unmask(calls), unmask(call_deltas)
++ content, reasoning = unmask(content), unmask(reasoning)
+ if body.get("return_token_ids"): # the reply's ids in the "tensorfold" block, for exactness checks
+ stats = {**(stats or {}), "token_ids": [int(t) for t in out]}
+ logprobs = (self._probability_decoder.format(probabilities.emitted(out), ends)
+--- tensorfold/families/glm5_next/cuda/app.py
++++ tensorfold/families/glm5_next/cuda/app.py
+@@ -64,6 +64,8 @@
+
+ def __init__(self, engine, model_dir, served: str, **kwargs: Any) -> None:
+ super().__init__(engine, model_dir, served, **kwargs)
++ from tensorfold.cuda.reply_text import ReplyMarks
++ self.reply_ids = ReplyMarks.from_env(self.tok) # patch 0117: the reply's markup at its marker tokens only
+ if self.vision is not None:
+ media_template(self.template, Path(model_dir))
+ clear = os.environ.get("TF_GLM_CLEAR_THINKING", "0").strip() or "0"
diff --git a/tools/reply_ids_check.py b/tools/reply_ids_check.py
new file mode 100644
index 0000000..cb670ec
--- /dev/null
+++ b/tools/reply_ids_check.py
@@ -0,0 +1,202 @@
+#!/usr/bin/env python3
+"""tools/reply_ids_check.py <checkpoint dir>: patch 0117, run in the image (CPU only, the server stopped or not).
+
+GLM writes its markup (`</think>`, `<tool_call>`, `<arg_key>`, `<arg_value>` and their closers) as single tokens. The
+same text spelled in ordinary tokens (a quoted tag, an example call, a file being written) used to be read as markup
+by the server's text parsers. With the patch it is words. Checked through the CUDA server's chat route (`App.run`
+behind `make_handler`, as the server runs it) on the checkpoint's own tokenizer:
+
+1. A scripted engine writes each case's reply as token ids: text in ordinary tokens (the tokenizer with its added
+ tokens left out, so a spelled tag is `</` `think` `>` and the like) and the marker tokens where the reply writes
+ real markup. Each case runs whole and streamed, with the patch and without it (the old text parse).
+2. The cases: a `</think>` quoted in the reasoning; an example call written as text in the answer; a call quoted in
+ the reasoning before a real call; a real call whose argument spells `</arg_value></tool_call></think>`; a plain
+ reply and a plain call. With the patch every case gives its expected reasoning, content and calls, the streamed
+ deltas join to the whole reply, and no inert character reaches a client; a reply without spelled markup is the
+ same with the patch as without it.
+3. `GlmApp` turns the patch on, `TF_GLM_REPLY_IDS=0` turns it off, and the shared `App` (every other family) has it
+ off.
+Prints one line per case and N/N cases ok; exit 1 on any failure.
+
+ docker run --rm --network none -e CUDA_VISIBLE_DEVICES= --entrypoint python3 \
+ -v "$PWD/tools/reply_ids_check.py:/c.py:ro" -v "$HOME/.cache/huggingface:/root/.cache/huggingface:ro" \
+ tensorfold-glm53:v0.6.0 /c.py \
+ /root/.cache/huggingface/hub/models--Mia-AiLab--GLM-5.3-Flash-EXL3-4bpw-TensorFold/snapshots/<rev>
+"""
+import contextlib
+import http.client
+import inspect
+import json
+import os
+import sys
+import tempfile
+import threading
+from http.server import ThreadingHTTPServer
+from pathlib import Path
+
+from tokenizers import Tokenizer
+
+from tensorfold.cuda import server
+from tensorfold.cuda.reply_text import ReplyMarks
+
+model = sys.argv[1]
+tok = Tokenizer.from_file(f"{model}/tokenizer.json")
+spec = json.loads(Path(f"{model}/tokenizer.json").read_text(encoding="utf-8"))
+spec["added_tokens"] = []
+plain = Tokenizer.from_str(json.dumps(spec))
+ID = {m: tok.token_to_id(m) for m in ("<think>", "</think>", "<tool_call>", "</tool_call>", "<arg_key>", "</arg_key>",
+ "<arg_value>", "</arg_value>", "<|user|>")}
+assert all(v is not None for v in ID.values()), ID
+EOS = ID["<|user|>"]
+TOOLS = [{"type": "function", "function": {"name": "terminal", "description": "run a shell command",
+ "parameters": {"type": "object", "properties": {"command": {"type": "string"}}, "required": ["command"]}}}]
+
+
+def ids(*parts):
+ """Strings as ordinary tokens; ("<tool_call>",) and the like as the marker token."""
+
+ out = []
+ for p in parts:
+ out += [ID[p[0]]] if isinstance(p, tuple) else plain.encode(p, add_special_tokens=False).ids
+ return out
+
+
+def real_call(command):
+ return [("<tool_call>",), "terminal", ("<arg_key>",), "command", ("</arg_key>",), ("<arg_value>",), command,
+ ("</arg_value>",), ("</tool_call>",)]
+
+
+SPELLED_CALL = "<tool_call>terminal<arg_key>command</arg_key><arg_value>ls</arg_value></tool_call>"
+CASES = [
+ # name, tools, reply parts, expected reasoning, content, calls [(name, arguments)]
+ ("quoted </think> in reasoning, echoed tags in the answer", False,
+ ["The user wants <think>hello</think> world back.", ("</think>",), "<think>hello</think> world"],
+ "The user wants <think>hello</think> world back.", "<think>hello</think> world", None),
+ ("an example call written as text: words, not a call", True,
+ ["Explain the format.", ("</think>",), "A call looks like " + SPELLED_CALL + " in GLM."],
+ "Explain the format.", "A call looks like " + SPELLED_CALL + " in GLM.", None),
+ ("a call quoted in the reasoning, a real call after the close", True,
+ ["I could write " + SPELLED_CALL + " myself.", ("</think>",), *real_call("ls -la")],
+ "I could write " + SPELLED_CALL + " myself.", "", [("terminal", {"command": "ls -la"})]),
+ ("a real call whose argument spells the closers", True,
+ ["Write the file.", ("</think>",), *real_call("echo '</arg_value></tool_call></think>' > x")],
+ "Write the file.", "", [("terminal", {"command": "echo '</arg_value></tool_call></think>' > x"})]),
+ ("plain reply: the same as without the patch", True,
+ ["Plan.", ("</think>",), "Done."], "Plan.", "Done.", None),
+ ("plain call: the same as without the patch", True,
+ ["Run it.", ("</think>",), *real_call("ls")], "Run it.", "", [("terminal", {"command": "ls"})]),
+]
+
+
+class Engine:
+ eos = (EOS,)
+
+ def __init__(self, reply):
+ self.reply = reply
+
+ def generate(self, prompt, max_tokens, sampling, on_tokens, draft=True):
+ for at in range(0, len(self.reply), 3):
+ if on_tokens(self.reply[at:at + 3]):
+ break
+ return {"rounds": 1 + len(self.reply) // 3, "decode_s": 0.1}
+
+
+TEMPLATE = ("{% for m in messages %}{{ m.role }}:{{ m.content }};{% endfor %}{% if tools %}tools;{% endif %}"
+ "assistant:{% if enable_thinking %}<think>{% endif %}")
+
+
+def app_for(reply, patched, tmp):
+ (tmp / "tokenizer_config.json").write_text(json.dumps({"chat_template": TEMPLATE}))
+ app = server.App.__new__(server.App)
+ app.engine, app.served, app.tok = Engine(reply + [EOS]), "glm-check", tok
+ app.template = server.ChatTemplate(tmp)
+ app.default_thinking, app.reasoning_effort, app.thinking_budget = True, None, 0
+ app.sampling, app.max_tokens = {"temperature": 0.0}, 4096
+ app.native_context_window = app.context_window = 0
+ app.lock = threading.Lock()
+ app.reply_ids = ReplyMarks(tok) if patched else None
+ return app
+
+
+def http_server(app):
+ httpd = ThreadingHTTPServer(("127.0.0.1", 0), server.make_handler(app))
+ worker = threading.Thread(target=httpd.serve_forever, kwargs={"poll_interval": 0.01}, daemon=True)
+ worker.start()
+ try:
+ yield httpd.server_port
+ finally:
+ httpd.shutdown()
+ httpd.server_close()
+
+
+def ask(app, tools, stream):
+ body = {"messages": [{"role": "user", "content": "Hi"}], "stream": stream}
+ if tools:
+ body["tools"] = TOOLS
+ with http_server(app) as port:
+ c = http.client.HTTPConnection("127.0.0.1", port, timeout=30)
+ c.request("POST", "/v1/chat/completions", json.dumps(body), {"Content-Type": "application/json"})
+ r = c.getresponse()
+ text = r.read().decode()
+ c.close()
+ assert r.status == 200, (r.status, text[:300])
+ if not stream:
+ m = json.loads(text)["choices"][0]["message"]
+ calls = [(c["function"]["name"], json.loads(c["function"]["arguments"])) for c in m.get("tool_calls") or []]
+ return m.get("reasoning_content") or "", m.get("content") or "", calls or None, text
+ reasoning, content, calls = "", "", {}
+ for line in text.splitlines():
+ if not line.startswith("data: ") or line == "data: [DONE]":
+ continue
+ for ch in json.loads(line[6:]).get("choices") or []:
+ d = ch.get("delta") or {}
+ reasoning += d.get("reasoning_content") or ""
+ content += d.get("content") or ""
+ for c in d.get("tool_calls") or []:
+ slot = calls.setdefault(c.get("index", 0), ["", ""])
+ fn = c.get("function") or {}
+ slot[0] += fn.get("name") or ""
+ slot[1] += fn.get("arguments") or ""
+ got = [(n, json.loads(a)) for n, a in (calls[k] for k in sorted(calls))]
+ return reasoning, content, got or None, text
+
+
+fails = 0
+with tempfile.TemporaryDirectory() as d:
+ tmp = Path(d)
+ for name, tools, parts, want_r, want_c, want_calls in CASES:
+ reply = ids(*parts)
+ want = (want_r, want_c, want_calls)
+ rows = {}
+ for patched in (True, False):
+ for stream in (False, True):
+ r, c, calls, raw = ask(app_for(reply, patched, tmp), tools, stream)
+ leaked = chr(0xE000) in raw or chr(92) + "ue000" in raw
+ rows[(patched, stream)] = ((r.strip(), c.strip(), calls), leaked)
+ good = all(rows[(True, s)][0] == want and not rows[(True, s)][1] for s in (False, True))
+ spelled = rows[(False, False)][0] != want
+ if name.startswith("plain"):
+ good = good and not spelled
+ fails += not good
+ print(f"{'ok ' if good else 'FAIL'} {name}")
+ for (patched, stream), (got, leak) in rows.items():
+ mark = "" if got == want else (" <- the bug" if not patched else " <- WRONG")
+ print(f" {'0117' if patched else 'text'} {'stream' if stream else 'whole '}: reasoning={got[0]!r} "
+ f"content={got[1]!r} calls={got[2]!r}{' INERT LEAKED' if leak else ''}{mark}")
+
+# the switch: GlmApp turns it on from the environment, 0 turns it off, every other family's App has none
+from tensorfold.families.glm5_next.cuda.app import GlmApp # noqa: E402
+
+on = ReplyMarks.from_env(tok)
+os.environ["TF_GLM_REPLY_IDS"] = "0"
+off = ReplyMarks.from_env(tok)
+del os.environ["TF_GLM_REPLY_IDS"]
+switch = (on is not None and len(on.ids) == 8 and off is None
+ and "ReplyMarks.from_env(self.tok)" in inspect.getsource(GlmApp.__init__)
+ and getattr(server.App.__new__(server.App), "reply_ids", None) is None)
+fails += not switch
+print(f"{'ok ' if switch else 'FAIL'} the switch: GlmApp on ({len(on.ids) if on else 0} marker tokens), "
+ f"TF_GLM_REPLY_IDS=0 off, other families' App off")
+print(f"{len(CASES) + 1 - fails}/{len(CASES) + 1} cases ok")
+sys.exit(1 if fails else 0)