GLM-5.3-Flash EXL3 on 2x DGX Spark with TensorFold
Python
Patch 0116: a quoted added token stays text (`<think>`, `<tool_call>`, `<|user|>` in a request)
iegamo65169c514ab7
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex d274710..58a767d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -74,6 +74,21 @@ Every change to this recipe, newest first. Each release names the image it servechanged, token-identical replies): `tool_calls` 15/30 -> 30/30, whole and streamed alike, and call markup in`content` 18 -> 0. A whole example call the model quotes is still read as a call, as before (3 of the 30 gave twocalls). CPU check: `tools/test_think_tag_mention.py`.+- **A quoted `<think>` stays text** (patch `0116-glm-literal-added-tokens`, by [ahinore](https://github.com/ahinore)):+ the chat route renders a request into one string and encodes it whole, and HF tokenizers takes every added+ token's text out of a string, special or not (`<think>` and `</think>` are not special), so a request that only+ quoted one got that token: an agent reading another model's raw output, a chat template or a log saw `<think>`,+ `</think>`, `<tool_call>` or `<|user|>` as the tokens themselves, and wrote such a quote back as the token, where+ the reply's reasoning/content split broke. The request's text (content, reasoning, call arguments, JSON-escaped+ ones too, and the tools' definitions) is now masked before the template renders and encoded as text, around the+ template's own tokens; GLM's kept reasoning is put back before masking, so it is still found for clients that+ renumber call ids. A prompt without such text encodes to the same ids; `/nothink`, assistant turns with their+ reasoning inline and requests with pictures are as before; `TF_GLM_LITERAL_TOKENS=0` turns it off. The same+ prompts as tokens and as text, 10 sampled replies each, two Sparks (four): replies that wrote a quoted `</think>`+ as the token 7 (8) -> 0; an expected value starting with `<think>` written right 0 (0) -> 10 (10); which side of a+ 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 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/README.md b/README.mdindex 4b51e04..c8bf128 100644--- a/README.md+++ b/README.md@@ -560,6 +560,7 @@ sets a value wins: the environment, then `scripts/local.sh`, then `.env`, then t| `TF_GLM_MULTI_WATCHDOG_S` / `TF_GLM_MULTI_WATCHDOG_EXIT` | `300` / `0` | a rank stuck this many seconds in one step prints every thread's stack to its log (`/health`'s `iteration_s` shows how long the current step has run); `EXIT=1`: the server then exits (code 1) instead of waiting, so a supervisor can restart it. Both ranks also check that they received the same message each step, and stop with an error naming it if not || `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 || `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 |@@ -695,6 +696,7 @@ applied with `patch -p0` in filename order); `start.sh` rebuilds or re-pulls the| Loop guard | `0091-glm-loop-guard` | `TF_GLM_LOOP_GUARD=1` (off by default): a think block that collapsed into repeating itself (an exact cycle of up to 16 tokens held for 256 tokens, or one token taking half of the last 256) is closed with the thinking budget's close and the model answers from there (issues #89, #94); `usage.tensorfold.loop_guard` counts it | off: nothing changes; on: a looping reply ends instead of running to `max_tokens` || 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) || 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 |@@ -758,6 +760,7 @@ with [sparkDash](https://github.com/MiaAI-Lab/sparkDash) ([Performance](#perform| `tools/needle.py [label] [size]` | hides a passphrase in a ~195k-token prompt (the prompt comes out at ~0.8 x `size` tokens) and checks the model returns it || `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/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/0116-glm-literal-added-tokens.patch b/patches/0116-glm-literal-added-tokens.patchnew file mode 100644index 0000000..b720615--- /dev/null+++ b/patches/0116-glm-literal-added-tokens.patch@@ -0,0 +1,267 @@+diff --git tensorfold/cuda/server.py tensorfold/cuda/server.py+--- tensorfold/cuda/server.py++++ tensorfold/cuda/server.py+@@ -215,18 +215,27 @@+ raise RequestError("messages must be a list")+ from tensorfold.server.prompts import has_images, prepare_images, tool_media_parts++- def render(messages: list[dict[str, Any]], **images: bool) -> str: # text renders as it always has++ def render(messages: list[dict[str, Any]], tools=tools,++ **images: bool) -> str: # text renders as it always has+ try:+ return self.template.render(messages, tools=tools, enable_thinking=thinking, extra=kwargs,+ **images)+ except TemplateError as exc: # the checkpoint's template refuses the request (``raise_exception``)+ raise RequestError(f"the chat template rejected the request: {exc}") from exc+++ # patch 0116: text from the request (a <think> quoted in a message, a <tool_call> in a file or in a tool's++ # description, a <|user|> in a log) stays text where a family sets ``literal`` (GLM): masked here, after++ # what the family adds to the messages, and encoded as text below. Pictures go through prepare_images,++ # unmasked.++ literal = getattr(self, "literal", None)++ messages, shown_tools, masked = body["messages"], tools, False++ if literal is not None:++ messages, shown_tools, masked = literal.mask(self._messages_to_mask(messages), tools)+ # no --vision: a tool result's pictures as the template's own "unable to process" reminder (GLM)+- reminded = (tool_media_parts(body["messages"]) if getattr(self, "tool_media_reminders", False)++ reminded = (tool_media_parts(messages) if getattr(self, "tool_media_reminders", False)+ and getattr(self, "vision", None) is None else None)+ if reminded is not None:+- text = render(reminded, allow_images=True)++ text = render(reminded, shown_tools, allow_images=True)+ elif has_images(body["messages"]):+ rendered = prepare_images(self.vision, body["messages"],+ lambda messages: render(messages, allow_images=True),+@@ -235,8 +244,8 @@+ self.sampling_for(body, rendered.tokens), ignore_eos=ignore_eos, stop=stop,+ vision=rendered.vision, grammar=compiled, think_budget=budget)+ else:+- text = render(body["messages"])+- prompt = self._encode_ids(text, False)++ text = render(messages, shown_tools)++ prompt = literal.encode(self.tok, text) if masked else self._encode_ids(text, False)+ elif isinstance(body.get("prompt"), list): # token ids (vLLM's and OpenAI's form): served as given+ prompt = self.token_ids(body["prompt"])+ else:+@@ -249,6 +258,12 @@+ # sampling is resolved here, so a malformed control is refused before a stream opens+ return PreparedRequest(prompt, max_tokens, tools, thinking, self.sampling_for(body, prompt),+ ignore_eos=ignore_eos, stop=stop, grammar=compiled, think_budget=budget)++++ def _messages_to_mask(self, messages: Any) -> Any:++ """The messages ``literal`` masks (patch 0116): as sent. A family that adds to them before its template++ renders them adds it here first, so what it adds is masked too and it reads the messages as sent."""++++ return messages++ def token_ids(self, value: Any, field: str = "prompt") -> list[int]:+ """Token ids as a request gives them (a list, or a list holding one list); RequestError outside the vocabulary."""+diff --git tensorfold/families/glm5_next/cuda/app.py tensorfold/families/glm5_next/cuda/app.py+--- tensorfold/families/glm5_next/cuda/app.py++++ tensorfold/families/glm5_next/cuda/app.py+@@ -6,6 +6,7 @@+ from pathlib import Path+ from typing import Any, Callable+++from tensorfold.cuda.literal_tokens import LiteralTokens+ from tensorfold.cuda.server import App, PreparedRequest, RequestError+ from tensorfold.server.errors import CONTEXT_LIMIT+ from tensorfold.families.glm5_next.cuda.kept_reasoning import KeptReasoning+@@ -71,6 +72,15 @@+ raise ValueError(f"TF_GLM_CLEAR_THINKING={clear!r}: expected 0 or 1")+ effort_tail_enabled() # a typo fails at load, not at the first request+ self.template = ThinkingOffTemplate(self.template, KeptReasoning.from_env(), clear_thinking=clear == "1")++ self.literal = LiteralTokens.from_env(self.tok) # patch 0116: added-token text in a request stays text++++ def _messages_to_mask(self, messages: Any) -> Any:++ """The kept reasoning put back before the messages are masked (patch 0116): found by the messages as sent++ (``remember`` keyed them so), and masked like reasoning a client sends back. The template's own ``restore``++ is then left only the steps found nowhere."""++++ kept = getattr(self.template, "kept", None)++ return kept.restore(messages) if kept is not None else messages++ def check(self, body: dict[str, Any], *, prepared: PreparedRequest | None = None) -> str | None:+ """Validate the rendered prompt plus max_tokens against the engine context limit before streaming."""+diff --git tensorfold/cuda/literal_tokens.py tensorfold/cuda/literal_tokens.py+new file mode 100644+--- /dev/null++++ tensorfold/cuda/literal_tokens.py+@@ -0,0 +1,177 @@++"""Added-token text inside a chat request, tokenized as text.++++The chat template renders the messages (and the tools' definitions) into one string and the server encodes it++whole, so a request that only mentions an added token (a ``<think>`` quoted from another model's output, a++``<tool_call>`` in a file being edited or in a tool's description, a ``<|user|>`` pasted from a log) became that++token. The model never saw the text, and a reply quoting it broke the reasoning/content split. Here the request's++text is masked before rendering (one private-use character per guarded token), the template renders around the masks,++and each mask is encoded as its token's text, split so that no added token can match. The tokens the template itself++writes are untouched, and a request without any guarded text encodes exactly as before.++++Masked: every message's content, its ``reasoning_content`` / ``reasoning``, its calls' arguments (parsed when they++are a JSON object, so an escaped ``\\u003cthink\\u003e`` the template would write back as ``<think>`` is caught too),++and the tools' definitions. Not masked: ``/nothink`` (GLM's no-thinking switch in a user turn), an assistant turn that++carries its reasoning inline (``<think>...</think>answer`` with no ``reasoning_content``: the template splits it++there), and a request that already holds one of the private-use characters used as masks.++++``TF_GLM_LITERAL_TOKENS=0`` turns it off.++"""++from __future__ import annotations++++import json++import os++import re++from typing import Any++++# Kept as a token even inside a user's text: GLM reads "/nothink" in a user turn as its no-thinking switch.++KEEP = frozenset({"/nothink"})++_BASE = 0xE000 # Unicode private use area: one character per guarded token++++++class LiteralTokens:++ """Masks guarded added-token text in a request, and encodes a rendered prompt with the masks as plain text."""++++ def __init__(self, tok: Any):++ decoder = tok.get_added_tokens_decoder()++ added_ids = set(decoder)++ texts = sorted({t.content for t in decoder.values()} - KEEP, key=len, reverse=True) # longest first++ self.plain: dict[str, list[int]] = {} # mask character -> the token's text as ordinary tokens++ self._mask_of: dict[str, str] = {}++ for text in texts:++ ids = _as_text(tok, text, added_ids)++ if ids is None:++ continue++ mask = chr(_BASE + len(self.plain))++ self.plain[mask] = ids++ self._mask_of[text] = mask++ self._find = re.compile("|".join(re.escape(t) for t in self._mask_of)) if self._mask_of else None++ self._split = re.compile("(" + "|".join(map(re.escape, self.plain)) + ")") if self.plain else None++ self._span = (_BASE, _BASE + len(self.plain))++++ @classmethod++ def from_env(cls, tok: Any) -> "LiteralTokens | None":++ if os.environ.get("TF_GLM_LITERAL_TOKENS", "1") == "0":++ return None++ guard = cls(tok)++ print(f"[tensorfold] added-token text in requests is tokenized as text ({len(guard.plain)} tokens guarded; "++ f"TF_GLM_LITERAL_TOKENS=0 turns it off)", flush=True)++ return guard++++ # -- masking -----------------------------------------------------------------------------------------------------++++ def mask(self, messages: Any, tools: Any = None) -> tuple[Any, Any, bool]:++ """``(messages, tools, True)`` with guarded text masked, or both unchanged and False.++++ Only a prompt rendered from what this returned True for goes through ``encode``: a private-use character a++ client sent itself is then never read as a mask (such a request is left unmasked)."""++++ if self._find is None or not isinstance(messages, list):++ return messages, tools, False++ request = [messages, tools]++ if _any_string(request, self._collides): # a private-use character of ours already in the request++ return messages, tools, False++ if not _any_string(request, self._maybe):++ return messages, tools, False++ return ([self._message(m) if isinstance(m, dict) else m for m in messages],++ self._sub(tools) if tools is not None else None, True)++++ def _maybe(self, text: str) -> bool:++ """Guarded text, or a JSON escape that may decode to some (in a call's arguments)."""++++ return bool(self._find.search(text)) or "\\u" in text++++ def _message(self, message: dict[str, Any]) -> dict[str, Any]:++ out = dict(message)++ separated = isinstance(out.get("reasoning_content"), str) or isinstance(out.get("reasoning"), str)++ # An assistant turn that carries its reasoning inline ("<think>...</think>answer") is left as the template++ # expects it; every other content is text.++ inline = out.get("role") == "assistant" and not separated and "</think>" in _flat_text(out.get("content"))++ if "content" in out and not inline:++ out["content"] = self._sub(out["content"])++ for key in ("reasoning_content", "reasoning"):++ if isinstance(out.get(key), str):++ out[key] = self._sub(out[key])++ if isinstance(out.get("tool_calls"), list):++ out["tool_calls"] = [self._call(call) for call in out["tool_calls"]]++ return out++++ def _call(self, call: Any) -> Any:++ if not isinstance(call, dict) or not isinstance(call.get("function"), dict):++ return call++ function = dict(call["function"])++ arguments = function.get("arguments")++ if isinstance(arguments, str):++ # The template writes the arguments' values, not their JSON: a JSON object's values are masked as the++ # template will see them (escapes decoded), and handed on as the mapping the server would parse anyway.++ try:++ parsed = json.loads(arguments)++ except ValueError:++ parsed = None++ if isinstance(parsed, dict):++ masked = self._sub(parsed)++ function["arguments"] = masked if masked != parsed else arguments++ else:++ function["arguments"] = self._sub(arguments)++ elif arguments is not None:++ function["arguments"] = self._sub(arguments)++ return {**call, "function": function}++++ def _sub(self, value: Any) -> Any:++ """Masks guarded text in every string a value holds, mapping keys included."""++++ if isinstance(value, str):++ return self._find.sub(lambda m: self._mask_of[m.group(0)], value)++ if isinstance(value, list):++ return [self._sub(v) for v in value]++ if isinstance(value, dict):++ return {self._sub(k): self._sub(v) for k, v in value.items()}++ return value++++ def _collides(self, text: str) -> bool:++ lo, hi = self._span++ return any(lo <= ord(c) < hi for c in text)++++ # -- encoding ----------------------------------------------------------------------------------------------------++++ def encode(self, tok: Any, text: str) -> list[int]:++ """A prompt rendered from a masked request (``mask`` returned True), each mask encoded as its token's text.++++ The text between masks is encoded in one batch call (Python's GIL released); HF tokenizers encodes the text++ around an added token on its own too, so those pieces' ids are unchanged."""++++ parts = [p for p in self._split.split(text) if p]++ pieces = [p for p in parts if p not in self.plain]++ encoded = iter(tok.encode_batch_fast(pieces, add_special_tokens=False) if pieces else ())++ ids: list[int] = []++ for part in parts:++ ids.extend(self.plain[part] if part in self.plain else next(encoded).ids)++ return ids++++++def _as_text(tok: Any, text: str, added_ids: set[int]) -> list[int] | None:++ """The token's text as ordinary tokens: encoded in two pieces so the added token cannot match."""++++ for cut in range(1, len(text)):++ ids = (tok.encode(text[:cut], add_special_tokens=False).ids++ + tok.encode(text[cut:], add_special_tokens=False).ids)++ if not added_ids.intersection(ids) and tok.decode(ids, skip_special_tokens=False) == text:++ return ids++ return None++++++def _any_string(value: Any, test) -> bool:++ if isinstance(value, str):++ return bool(test(value))++ if isinstance(value, list):++ return any(_any_string(v, test) for v in value)++ if isinstance(value, dict):++ return any(_any_string(k, test) or _any_string(v, test) for k, v in value.items())++ return False++++++def _flat_text(content: Any) -> str:++ if isinstance(content, str):++ return content++ if isinstance(content, list):++ return "".join(p.get("text", "") for p in content if isinstance(p, dict) and isinstance(p.get("text"), str))++ return ""diff --git a/tools/literal_tokens_check.py b/tools/literal_tokens_check.pynew file mode 100644index 0000000..e934857--- /dev/null+++ b/tools/literal_tokens_check.py@@ -0,0 +1,223 @@+#!/usr/bin/env python3+"""tools/literal_tokens_check.py <checkpoint dir>: patch 0116, run in the image (CPU only, the server stopped or not).++A request that quotes an added token's text (a `<think>` from another model's output, a `<tool_call>` in a file being+edited or in a tool's description, a `<|user|>` in a log) used to reach the model as that token. With the patch it is+text, and nothing else in the prompt changes. Checked on the checkpoint's own tokenizer and chat template:++1. A prompt without any guarded text: the same ids as before, the messages object not even copied.+2. Quoted tags in a user turn, an assistant turn (content, reasoning_content, tool-call arguments, also JSON-escaped+ ones), a tool result and a tool's description: the prompt decodes to exactly the text it used to, the quoted tags+ are ordinary tokens, the template's own tokens (the roles, the generation prompt's `<think>`, the tool-call markup)+ are still tokens; and the old path does turn the quotes into tokens.+3. The exceptions keep the old ids: an assistant turn with its reasoning inline (`<think>...</think>answer`, no+ `reasoning_content`, which the template splits itself), `/nothink` (GLM's switch in a user turn), and a request+ that already holds one of the private-use characters used as masks.+4. Every guarded token's text encodes to ordinary tokens that decode back to it; the batch encode of the pieces+ between masks equals encoding each piece alone.+5. The server's own `_prepare` and `tokenize`, on stand-ins with the real tokenizer and template: GLM's app (`GlmApp`,+ which turns the patch on) and the shared `App` (every other family: off). The chat route and `/tokenize` agree, a+ plain chat gives the unpatched ids, the request's tools reach the reply parser unmasked, GLM's kept reasoning is+ still found for a client that renumbers call ids (it is put back before masking) and its quoted tags are text,+ `TF_GLM_LITERAL_TOKENS=0` turns the patch off, and a ~200k-token history costs about the same to encode.+Prints PASS / FAIL lines and ALL PASS; exit 1 on any FAIL.++ docker run --rm --network none -e CUDA_VISIBLE_DEVICES= --entrypoint python3 \+ -v "$PWD/tools/literal_tokens_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 json+import os+import random+import sys+import time+from pathlib import Path+from types import SimpleNamespace++from tensorfold.cuda.chat_template import ChatTemplate+from tensorfold.cuda.literal_tokens import LiteralTokens+from tensorfold.cuda.server import App+from tensorfold.families.glm5_next.cuda.app import GlmApp, ThinkingOffTemplate+from tensorfold.families.glm5_next.cuda.kept_reasoning import KeptReasoning+from tokenizers import Tokenizer++fails = 0+++def check(name, ok, detail=""):+ global fails+ print(("PASS " if ok else "FAIL ") + name + (f" [{detail}]" if detail and not ok else ""), flush=True)+ fails += not ok+++model_dir = Path(sys.argv[1])+tok = Tokenizer.from_file(str(model_dir / "tokenizer.json"))+template = ChatTemplate(model_dir)+literal = LiteralTokens(tok)+ADDED = set(tok.get_added_tokens_decoder())+THINK, END, USER = tok.token_to_id("<think>"), tok.token_to_id("</think>"), tok.token_to_id("<|user|>")+CALL = tok.token_to_id("<tool_call>")+print(f"{len(literal.plain)} added tokens guarded; <think> as text: {literal.plain[literal._mask_of['<think>']]}")+TOOLS = [{"type": "function", "function": {"name": "terminal", "description": "run a shell command",+ "parameters": {"type": "object", "properties": {"command": {"type": "string"}}, "required": ["command"]}}}]+++def old(messages, tools=None):+ text = template.render(messages, tools=tools, enable_thinking=True)+ return text, tok.encode(text, add_special_tokens=False).ids+++def new(messages, tools=None):+ masked, shown, applied = literal.mask(messages, tools)+ text = template.render(masked, tools=shown, enable_thinking=True)+ return masked, (literal.encode(tok, text) if applied else tok.encode(text, add_special_tokens=False).ids)+++def text_of(ids):+ return tok.decode(ids, skip_special_tokens=False)+++# 1. nothing to guard+m = [{"role": "system", "content": "You are helpful."}, {"role": "user", "content": "Rust の所有権を説明して"}]+(_, ids_old), (masked, ids_new) = old(m), new(m)+check("1 plain prompt: the same ids", ids_new == ids_old)+check("1 plain prompt: the messages untouched", masked is m)++# 2. quoted tags+m = [{"role": "user", "content": "Print this as is: <think>hello</think> world, <|user|> and <tool_call>x</tool_call>"}]+(text, ids_old), (_, ids_new) = old(m), new(m)+own = text.count("<think>") - 1 # the generation prompt's own <think>+check("2 user turn: the same text", text_of(ids_new) == text, repr(text_of(ids_new)[-120:]))+check("2 user turn: the quoted <think> / </think> are text", ids_new.count(THINK) == own and+ ids_new.count(END) == text.count("</think>") - 1, f"<think> x{ids_new.count(THINK)}, template's own x{own}")+check("2 user turn: the old path made them tokens", ids_old.count(THINK) == own + 1)+check("2 user turn: a quoted <|user|> is no role token", ids_new.count(USER) == ids_old.count(USER) - 1)++m = [{"role": "user", "content": "write the baseline"},+ {"role": "assistant", "content": "the baseline starts with <think>", "reasoning_content": "it opens <think>",+ "tool_calls": [{"id": "c1", "type": "function",+ "function": {"name": "patch", "arguments": "{\"new\": \"\\\"<think>\\\\nOkay\\\"\"}"}}]},+ {"role": "tool", "tool_call_id": "c1", "content": "left: \"<think>\\nOkay\" right: \"</think>\\nOkay\""},+ {"role": "user", "content": "go on"}]+(text, ids_old), (_, ids_new) = old(m), new(m)+check("2 agent turns: the same text", text_of(ids_new) == text)+check("2 agent turns: content, reasoning, arguments and tool result quote as text",+ ids_new.count(THINK) < ids_old.count(THINK) and ids_new.count(END) < ids_old.count(END),+ f"<think> x{ids_old.count(THINK)} -> x{ids_new.count(THINK)}")+check("2 agent turns: the template's own <tool_call> is still a token", ids_new.count(CALL) == text.count("<tool_call>"))++esc = json.dumps({"command": "printf '<think>'"}) # Python keeps '<'; Go's encoder writes <+esc = esc.replace("<", "\\u003c").replace(">", "\\u003e")+m = [{"role": "user", "content": "run it"},+ {"role": "assistant", "content": "", "reasoning_content": "run",+ "tool_calls": [{"id": "c1", "type": "function", "function": {"name": "terminal", "arguments": esc}}]},+ {"role": "tool", "tool_call_id": "c1", "content": "ok"}]+(text, ids_old), (_, ids_new) = old(m, TOOLS), new(m, TOOLS)+check("2 JSON-escaped arguments (\\u003cthink\\u003e): the same text, the tag as text",+ text_of(ids_new) == text and "printf '<think>'" in text and ids_new.count(THINK) == ids_old.count(THINK) - 1,+ f"<think> x{ids_old.count(THINK)} -> x{ids_new.count(THINK)}")++tools = [{"type": "function", "function": {"name": "edit_template", "description": "edit a chat template: keep "+ "<tool_call> and </tool_call> as they are", "parameters": {"type": "object", "properties": {}}}}]+m = [{"role": "user", "content": "hi"}]+(text, ids_old), (_, ids_new) = old(m, tools), new(m, tools)+check("2 a tool's description: the same text, its tags as text",+ text_of(ids_new) == text and ids_new.count(CALL) == ids_old.count(CALL) - 1,+ f"<tool_call> x{ids_old.count(CALL)} -> x{ids_new.count(CALL)}")++m = [{"role": "user", "content": [{"type": "text", "text": "a part with <think>"}, {"type": "text", "text": " more"}]}]+(text, ids_old), (_, ids_new) = old(m), new(m)+check("2 multi-part text: the same text, the tag as text",+ text_of(ids_new) == text and ids_new.count(THINK) == text.count("<think>") - 1)++# 3. exceptions: the old ids+for name, m in (("an inline-reasoning assistant turn", [{"role": "user", "content": "q"},+ {"role": "assistant", "content": "<think>r</think>answer"}, {"role": "user", "content": "q2"}]),+ ("/nothink in a user turn", [{"role": "user", "content": "1+1 /nothink"}]),+ ("a mask character already in the request", [{"role": "user", "content": chr(0xE000) + " <think>"}])):+ (_, ids_old), (masked, ids_new) = old(m), new(m)+ check(f"3 {name}: the same ids", ids_new == ids_old)+check("3 a mask character already in the request: not masked", literal.mask(m)[2] is False)++# 4. the masks' own text, and the batch encode+bad = [t for t, mask in literal._mask_of.items() if ADDED.intersection(literal.plain[mask])+ or text_of(literal.plain[mask]) != t]+check("4 every guarded token's text: ordinary tokens that decode back to it", not bad, ", ".join(bad[:5]))+rng = random.Random(0)+words = ["fn", "main", "所有権", " ", "\n", "\t", "é", "😀", "{", "}", "\"", "\\n", "<", ">", "|", "think", "tool"]+tags = list(literal._mask_of)+ok = True+for _ in range(300):+ pieces = ["".join(rng.choice(words) for _ in range(rng.randint(0, 12))) for _ in range(rng.randint(1, 6))]+ text = "".join(p + rng.choice(tags) for p in pieces)+ masked, _, applied = literal.mask([{"role": "user", "content": text}])+ s = masked[0]["content"]+ want = [i for part in literal._split.split(s) if part+ for i in (literal.plain[part] if part in literal.plain else tok.encode(part, add_special_tokens=False).ids)]+ ok &= applied and literal.encode(tok, s) == want and text_of(want) == text+check("4 300 random texts with tags: the batch encode equals encoding each piece, and decodes to the text", ok)+++# 5. the server's own _prepare and tokenize+def app(cls, guard, kept=None):+ a = object.__new__(cls)+ a.engine = SimpleNamespace(supports_logprobs=False)+ a.vision = None+ a.served, a.aliases, a.model_dir = "GLM-5.3-Flash-EXL3", (), model_dir+ a.tok = tok+ a.template = ThinkingOffTemplate(template, kept) if cls is GlmApp else template+ if guard is not None:+ a.literal = guard+ a.default_thinking, a.reasoning_effort, a.thinking_budget = True, "high", 0+ a.sampling = {"temperature": 1.0, "top_k": 20, "top_p": 0.95}+ a.max_tokens, a.native_context_window, a.context_window = 32768, 1048576, 1048576+ return a+++kept = KeptReasoning()+patched, unpatched = app(GlmApp, literal, kept), app(GlmApp, None, kept)+body = lambda messages, **kw: {"model": "GLM-5.3-Flash-EXL3", "messages": messages, "max_tokens": 64, **kw}+plain = body([{"role": "user", "content": "こんにちは"}])+check("5 GlmApp, a plain chat: the unpatched ids", patched._prepare(plain, True).prompt ==+ unpatched._prepare(plain, True).prompt)+tagged = body([{"role": "user", "content": "Print as is: <think>hello</think> world"}])+p, u = patched._prepare(tagged, True).prompt, unpatched._prepare(tagged, True).prompt+check("5 GlmApp, quoted tags: the same text, one <think> token fewer",+ text_of(p) == text_of(u) and p.count(THINK) == u.count(THINK) - 1)+check("5 /tokenize agrees with the chat route", patched.tokenize({"messages": tagged["messages"]})["tokens"] == p)+shared = app(App, None)+s = shared._prepare(tagged, True).prompt+check("5 the shared App (other families): off, every quoted tag still a token",+ not hasattr(shared, "literal") and s.count(THINK) == text_of(s).count("<think>"))+described = body([{"role": "user", "content": "hi"}], tools=tools)+check("5 a tool described with tags: the reply parser gets the tools unmasked",+ patched._prepare(described, True).tools == unpatched._prepare(described, True).tools)++# kept reasoning: a client that drops it and renumbers the call ids, in a conversation that quotes a tag+history = [{"role": "user", "content": "make the test expect <think> first"}]+call = {"type": "function", "function": {"name": "terminal", "arguments": "{\"command\": \"cargo test\"}"}}+kept.remember(history, [{**call, "id": "call_0123456789abcdef01234567"}], "The output must open with <think>, so run it.")+later = body(history + [{"role": "assistant", "content": "", "tool_calls": [{**call, "id": "renumbered-1"}]},+ {"role": "tool", "tool_call_id": "renumbered-1", "content": "1 passed"}], tools=TOOLS)+p, u = patched._prepare(later, True).prompt, unpatched._prepare(later, True).prompt+check("5 kept reasoning: put back for a client that renumbers ids, as without the patch",+ "The output must open with" in text_of(p) and text_of(p) == text_of(u))+check("5 kept reasoning: its quoted tag is text too", p.count(THINK) == u.count(THINK) - 2,+ f"<think> x{u.count(THINK)} -> x{p.count(THINK)} (the user's and the kept reasoning's: 2 fewer)")++os.environ["TF_GLM_LITERAL_TOKENS"] = "0"+check("5 TF_GLM_LITERAL_TOKENS=0: off", LiteralTokens.from_env(tok) is None)+del os.environ["TF_GLM_LITERAL_TOKENS"]+check("5 the startup line otherwise", LiteralTokens.from_env(tok) is not None)+chunk = "fn main() { println!(\"hello\"); } // 所有権と借用の説明。 " * 40+long = body([{"role": "user" if i % 2 == 0 else "assistant", "content": chunk + (" <think>" if i % 50 == 0 else "")}+ for i in range(300)])+t0 = time.perf_counter(); n = len(unpatched._prepare(long, True).prompt)+t1 = time.perf_counter(); patched._prepare(long, True)+t2 = time.perf_counter()+print(f" a {n:,}-token history with 6 quoted tags: unpatched {t1 - t0:.2f} s, patched {t2 - t1:.2f} s")+check("5 a long history: about the same cost", t2 - t1 <= 1.5 * (t1 - t0) + 0.2)++print("ALL PASS" if not fails else f"{fails} FAILED")+sys.exit(1 if fails else 0)