Skip to content

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

Python

Opt-in TF_GLM_EFFORT_TAIL=1: the reasoning-effort line at the tail of the prompt (patch 0096, issue #93)

MiaAI-Lab625c02aa32e5
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d991fed..bff2490 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -3,6 +3,18 @@
Every change to this recipe, newest first. Each release names the image it serves: `scripts/prepare.sh` pulls
`ghcr.io/miaai-lab/glm-5.3-flash-exl3-2x-dgx-sparks-tensorfold` by the digest pinned in `scripts/config.sh`.
+## Unreleased
+
+- **Effort line at the tail, opt-in** (patch `0096-effort-tail`, issue #93, reported and measured by jdecker76
+ ([@jdecker76](https://github.com/jdecker76))): the checkpoint's template renders `<|system|>Reasoning Effort: X` at token
+ 3, so a conversation that switches effort or thinking on/off missed the kept prompt entirely (0% cached on ~26k tokens)
+ and prefilled again. `TF_GLM_EFFORT_TAIL=1` renders the line just before `<|assistant|><think>` instead (thinking off
+ has none, as before); the reporter's emulation kept 98 to 99% cached across max, low and off. Off by default and then
+ byte-identical to before: the model saw the line first in training, so run the quality A/B in the README before relying
+ on it. `GlmTokenizer` and the CUDA server's template both honour it, and every rank reads it with the other `TF_GLM_*`
+ switches. CPU test: `tools/test_effort_tail.py` (`--source-root` the patched `src`; `--expect-stock` shows the
+ difference on the unpatched source).
+
## v1.9.1 (2026-10-08): the spill tier's free-disk floor makes room
Image: `v0.6.0-ff5dffc865d3` (`sha256:20275b2be818635a9c711d80a177477488d2c75cad373cc644422295c4fe9f07`), 94 patches (v1.9's, with `0088` updated). Tested live on two Sparks: with
diff --git a/README.md b/README.md
index 7b3e97c..79c8c2e 100644
--- a/README.md
+++ b/README.md
@@ -527,6 +527,7 @@ sets a value wins: the environment, then `scripts/local.sh`, then `.env`, then t
| `TF_GLM_KEEP_PER_CHAT` | `0` (no limit) | at most this many of one conversation's own turn-boundary kept states (patch `0089`, PR #65); shared-prefix and mid-prefill states do not count, the older turns are dropped without a spill. The author runs `2`; `kept_mix` in `/health` shows each conversation's count |
| `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 |
| `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) |
| `MULTI_PREFILL` | `1` | prompts that arrive together are filled in one forward (each with the bits it gets alone); `0`: one after another |
@@ -658,6 +659,7 @@ applied with `patch -p0` in filename order); `start.sh` rebuilds or re-pulls the
| Responses `include` | `0093-responses-include` | `/v1/responses` accepts OpenAI's `include` values and ignores them (reasoning already comes as text, nothing is encrypted); an unknown value or a non-list is still a 400 (issue #73) | the AI SDK's `include: ["reasoning.encrypted_content"]` no longer fails every request |
| Chunked request bodies | `0094-chunked-request-bodies` | a `Transfer-Encoding: chunked` request body (AI SDK clients, Chatbox, proxies) is read like a `Content-Length` one on the chat, completions, tokenizer and Responses routes and the MLX-style server, each route keeping its own size limit (96 MiB for chat); a refused request's body is consumed so it cannot reach the next one. The reader is `request_body.read_body` from TensorFold's 977f2cc by Jordi Posthumus (@JordiPosthumus), which `0084` adds; this patch uses it at the remaining sites (issues #67, #74) | no dechunking proxy; a validation 400 no longer leaves HTML after the JSON on a keep-alive connection |
| 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 |
+| 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 |
| 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
diff --git a/patches/0096-effort-tail.patch b/patches/0096-effort-tail.patch
new file mode 100644
index 0000000..43a5c98
--- /dev/null
+++ b/patches/0096-effort-tail.patch
@@ -0,0 +1,92 @@
+diff --git tensorfold/families/glm5_next/prompts.py tensorfold/families/glm5_next/prompts.py
+--- tensorfold/families/glm5_next/prompts.py
++++ tensorfold/families/glm5_next/prompts.py
+@@ -3,6 +3,8 @@
+ from __future__ import annotations
+
+ import json
++import os
++import re
+ import sys
+ from typing import Any
+
+@@ -74,6 +76,34 @@
+ return out
+
+
++_HEAD_EFFORT = re.compile(r"(\[gMASK\]<sop>)?(<\|system\|>Reasoning Effort: (?:Max|High|Low))")
++
++
++def effort_tail_enabled() -> bool:
++ """``TF_GLM_EFFORT_TAIL=1``: the reasoning-effort line is rendered at the tail of the prompt (issue #93)."""
++
++ value = os.environ.get("TF_GLM_EFFORT_TAIL", "0").strip() or "0"
++ if value not in ("0", "1"):
++ raise ValueError(f"TF_GLM_EFFORT_TAIL={value!r}: expected 0 or 1")
++ return value == "1"
++
++
++def effort_to_tail(text: str, thinking: bool) -> str:
++ """The checkpoint text with its leading effort line moved to just before the generation prompt (thinking on), or
++ gone (thinking off), so the conversation before it renders the same for every effort level and with thinking on or
++ off. Text without the line at its head, or thinking on and not ending in the opened think block, is returned as is."""
++
++ head = _HEAD_EFFORT.match(text)
++ if head is None:
++ return text
++ rest = text[head.end():]
++ if not thinking:
++ return (head.group(1) or "") + rest
++ if not rest.endswith(OPENED):
++ return text
++ return (head.group(1) or "") + rest[:-len(OPENED)] + head.group(2) + OPENED
++
++
+ def thinking_off(text: str) -> str:
+ """The checkpoint text as the thinking-off template renders it: no effort line, an empty think block."""
+
+@@ -92,7 +122,13 @@
+
+ def apply_chat_template(self, messages: Any, *args: Any, tokenize: bool = True, **kwargs: Any) -> Any:
+ messages = agent_history(messages)
+- if kwargs.get("enable_thinking", True) is not False:
++ thinking = kwargs.get("enable_thinking", True) is not False
++ tail = effort_tail_enabled()
++ if thinking and not tail:
+ return self._inner.apply_chat_template(messages, *args, tokenize=tokenize, **kwargs)
+- text = thinking_off(self._inner.apply_chat_template(messages, *args, tokenize=False, **kwargs))
++ text = self._inner.apply_chat_template(messages, *args, tokenize=False, **kwargs)
++ if tail:
++ text = effort_to_tail(text, thinking)
++ if not thinking:
++ text = thinking_off(text)
+ return list(self._inner.encode(text, add_special_tokens=False)) if tokenize else text
+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
+@@ -9,7 +9,7 @@
+ 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
+-from tensorfold.families.glm5_next.prompts import agent_history, thinking_off
++from tensorfold.families.glm5_next.prompts import agent_history, effort_tail_enabled, effort_to_tail, thinking_off
+
+
+ class ThinkingOffTemplate:
+@@ -31,6 +31,8 @@
+ extra = {"clear_thinking": self.clear_thinking, **(extra or {})}
+ text = self.inner.render(agent_history(messages), tools=tools, enable_thinking=enable_thinking, extra=extra,
+ allow_images=allow_images)
++ if effort_tail_enabled(): # TF_GLM_EFFORT_TAIL=1 (issue #93): the effort line goes last, not first
++ text = effort_to_tail(text, bool(enable_thinking))
+ return text if enable_thinking else thinking_off(text)
+
+
+@@ -67,6 +69,7 @@
+ clear = os.environ.get("TF_GLM_CLEAR_THINKING", "0").strip() or "0"
+ if clear not in ("0", "1"):
+ 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")
+
+ def check(self, body: dict[str, Any], *, prepared: PreparedRequest | None = None) -> str | None:
diff --git a/scripts/config.sh b/scripts/config.sh
index 42c8841..8c0e7bd 100644
--- a/scripts/config.sh
+++ b/scripts/config.sh
@@ -219,6 +219,13 @@ export TF_GLM_KEEP_PER_CHAT="${TF_GLM_KEEP_PER_CHAT:-0}"
# Earlier turns keep their reasoning in the prompt (patch 0060), as in zai-org's current template. 1: drop it, as the
# checkpoint's template does; agents then prefill the previous turn's tool loop again at each new user message.
export TF_GLM_CLEAR_THINKING="${TF_GLM_CLEAR_THINKING:-0}"
+# The reasoning-effort line ("<|system|>Reasoning Effort: Max") is token 3 of the checkpoint's prompt, so switching effort
+# or thinking on/off changes the whole prompt and misses the kept-prompt cache (issue #93, by jdecker76). 1 (patch 0096):
+# render it at the tail instead, just before "<|assistant|><think>", so the conversation stays identical across the
+# switches (thinking off has no line, as before). Off by default: it moves a line the model was trained to see first, so
+# check the effort levels still answer differently (tools/toolcheck.py, tools/end_of_turn.py) before relying on it.
+# Not a request field: it changes every thinking-on prompt, and every rank reads it with the other TF_GLM_* switches.
+export TF_GLM_EFFORT_TAIL="${TF_GLM_EFFORT_TAIL:-0}"
# Admission at saturation (patch 0075): past the lanes plus MAX_QUEUED a foreground request is refused with
# 429 + Retry-After (529 overloaded_error through the Anthropic bridge) instead of queueing invisibly. Unset
# queues as every scheduler always has; 0 refuses anything past the lanes. A single-instance deployment with
diff --git a/start.sh b/start.sh
index c118080..a96872a 100755
--- a/start.sh
+++ b/start.sh
@@ -96,6 +96,7 @@ DRY=0; [[ "${DRY_RUN:-0}" == 1 ]] && DRY=1
[[ "$TF_GLM_MULTI_LONE" =~ ^[01]$ ]] || die "TF_GLM_MULTI_LONE is 0 or 1, not $TF_GLM_MULTI_LONE"
[[ "$TF_GLM_MULTI_WINDOW" =~ ^(16|24|32|40|48|56|64)$ ]] || die "TF_GLM_MULTI_WINDOW is 16 to 64 rows in steps of 8, not $TF_GLM_MULTI_WINDOW"
[[ "$TF_GLM_CLEAR_THINKING" =~ ^[01]$ ]] || die "TF_GLM_CLEAR_THINKING is 0 or 1, not $TF_GLM_CLEAR_THINKING"
+[[ "$TF_GLM_EFFORT_TAIL" =~ ^[01]$ ]] || die "TF_GLM_EFFORT_TAIL is 0 or 1, not $TF_GLM_EFFORT_TAIL"
[[ "$TF_GLM_L2PF" =~ ^(0|off|1|bulk|lines|touch)$ ]] || die "TF_GLM_L2PF is 0, 1 (bulk), lines or touch, not $TF_GLM_L2PF"
[[ "$TF_GLM_EXL3_LOADS" =~ ^(0|ldg|1|nc|nc1|nc2|nc4)$ ]] || die "TF_GLM_EXL3_LOADS is 0, nc, nc2 or nc4, not $TF_GLM_EXL3_LOADS"
[[ "$TF_GLM_EXL3_DEC_ORDER" =~ ^[012]$ ]] || die "TF_GLM_EXL3_DEC_ORDER is 0, 1 or 2, not $TF_GLM_EXL3_DEC_ORDER"
diff --git a/tools/test_effort_tail.py b/tools/test_effort_tail.py
new file mode 100644
index 0000000..121e258
--- /dev/null
+++ b/tools/test_effort_tail.py
@@ -0,0 +1,185 @@
+"""CPU-only check of TF_GLM_EFFORT_TAIL (patch 0096, issue #93): the reasoning-effort line rendered at the tail.
+
+ python3 -B tools/test_effort_tail.py --source-root /path/to/patched/src [--model-dir DIR] [--expect-stock]
+The checkpoint's own chat_template.jinja is read (read-only) from --model-dir, or from the Hugging Face cache
+($HF_CACHE, $HF_HOME or ~/.cache/huggingface) snapshot of Mia-AiLab/GLM-5.3-Flash-EXL3-4bpw-TensorFold. Needs jinja2 only;
+token prefixes are compared too when `tokenizers` is installed. --expect-stock, on the unpatched source, shows the
+reported behaviour: with the flag set, the conversation still differs from token 3 on between effort settings.
+"""
+from __future__ import annotations
+
+import argparse
+import copy
+import json
+import os
+import sys
+from pathlib import Path
+
+MODEL = "Mia-AiLab/GLM-5.3-Flash-EXL3-4bpw-TensorFold"
+OPENED = "<|assistant|><think>"
+SETTINGS = {"max": (True, "max"), "default": (True, None), "high": (True, "high"), "low": (True, "low"),
+ "off": (False, None)}
+LINE = {"max": "Max", "default": "Max", "high": "High", "low": "Low"}
+
+TOOLS = [{"type": "function", "function": {"name": "read_file", "description": "Read a file.", "parameters": {
+ "type": "object", "properties": {"path": {"type": "string"}}, "required": ["path"]}}}]
+CONVERSATIONS = {
+ "chat": [
+ {"role": "system", "content": "You are a coding agent."},
+ {"role": "user", "content": "What does main.py do?"},
+ {"role": "assistant", "content": "It starts the server.", "reasoning_content": "Let me think about main.py."},
+ {"role": "user", "content": "And utils.py?"}],
+ "tools": [
+ {"role": "system", "content": "You are a coding agent."},
+ {"role": "user", "content": "Read a.txt and summarise it."},
+ {"role": "assistant", "content": "", "reasoning_content": "I need the file first.", "tool_calls": [
+ {"id": "call_1", "type": "function", "function": {"name": "read_file", "arguments": {"path": "a.txt"}}}]},
+ {"role": "tool", "tool_call_id": "call_1", "content": "hello world"},
+ {"role": "assistant", "content": "It says hello world."},
+ {"role": "user", "content": "Now read b.txt."}],
+}
+
+
+def model_dir(arg):
+ if arg:
+ return Path(arg)
+ root = Path(os.environ.get("HF_CACHE") or os.environ.get("HF_HOME") or Path.home() / ".cache" / "huggingface")
+ snaps = sorted((root / "hub" / f"models--{MODEL.replace('/', '--')}" / "snapshots").glob("*/chat_template.jinja"))
+ if not snaps:
+ sys.exit(f"no chat_template.jinja for {MODEL} under {root}: pass --model-dir")
+ return snaps[-1].parent
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--source-root", required=True)
+ ap.add_argument("--model-dir")
+ ap.add_argument("--expect-stock", action="store_true")
+ args = ap.parse_args()
+ sys.path.insert(0, args.source_root)
+ from tensorfold.cuda.chat_template import ChatTemplate
+ from tensorfold.families.glm5_next import prompts
+ from tensorfold.families.glm5_next.cuda.app import ThinkingOffTemplate
+
+ mdir = model_dir(args.model_dir)
+ inner = ChatTemplate(mdir)
+ wrapped = ThinkingOffTemplate(inner)
+ print(f"template: {mdir / 'chat_template.jinja'}")
+
+ def render(messages, name, tools, flag):
+ think, effort = SETTINGS[name]
+ if flag is None:
+ os.environ.pop("TF_GLM_EFFORT_TAIL", None)
+ else:
+ os.environ["TF_GLM_EFFORT_TAIL"] = flag
+ extra = {"reasoning_effort": effort} if effort else None
+ return wrapped.render(copy.deepcopy(messages), tools=tools, enable_thinking=think, extra=extra)
+
+ def reference(messages, name, tools):
+ """The text before the patch: the checkpoint template, then thinking_off's line removal and empty think block."""
+ think, effort = SETTINGS[name]
+ text = inner.render(copy.deepcopy(messages), tools=tools, enable_thinking=think,
+ extra={"clear_thinking": False, **({"reasoning_effort": effort} if effort else {})})
+ if think:
+ return text
+ text = text.replace("<|system|>Reasoning Effort: Max", "", 1)
+ return text + "</think>" if text.endswith(OPENED) else text
+
+ def before_last_user(text):
+ return text[:text.rindex("<|user|>")]
+
+ tok = None
+ try:
+ from tokenizers import Tokenizer
+ tok = Tokenizer.from_file(str(mdir / "tokenizer.json"))
+ except Exception: # noqa: BLE001 - tokenizers is optional here
+ print("note: `tokenizers` not available, comparing text prefixes only")
+
+ for cname, messages in CONVERSATIONS.items():
+ tools = TOOLS if cname == "tools" else None
+ # (a) flag unset and 0: byte-identical to the template as it rendered before, line at token 3
+ for flag in (None, "0"):
+ for name in SETTINGS:
+ got = render(messages, name, tools, flag)
+ assert got == reference(messages, name, tools), (cname, name, flag, "differs from the stock render")
+ if SETTINGS[name][0]:
+ assert got.startswith(f"[gMASK]<sop><|system|>Reasoning Effort: {LINE[name]}"), (cname, name)
+ if args.expect_stock:
+ tails = {n: before_last_user(render(messages, n, tools, "1")) for n in SETTINGS}
+ assert len(set(tails.values())) > 1, "stock source already keeps the prefix identical"
+ print(f"{cname}: stock, flag set: the prefix still differs between settings, as reported")
+ continue
+ # (b) flag on: everything before the generation prompt is the same for every effort and thinking setting
+ outs = {n: render(messages, n, tools, "1") for n in SETTINGS}
+ prefixes = {n: before_last_user(t) for n, t in outs.items()}
+ assert len(set(prefixes.values())) == 1, (cname, "prefix up to the last user turn differs",
+ {n: p[:60] for n, p in prefixes.items()})
+ for n, t in outs.items():
+ think = SETTINGS[n][0]
+ if think:
+ assert t.count("Reasoning Effort:") == 1, (cname, n, "effort line count", t.count("Reasoning Effort:"))
+ assert t.endswith(f"<|system|>Reasoning Effort: {LINE[n]}{OPENED}"), (cname, n, t[-80:])
+ assert not t.startswith("[gMASK]<sop><|system|>Reasoning Effort"), (cname, n, "still at the head")
+ # same prompt as before with the line moved: put it back at the head and it is the stock text
+ moved = t[:-len(f"<|system|>Reasoning Effort: {LINE[n]}{OPENED}")] + OPENED
+ assert "[gMASK]<sop><|system|>Reasoning Effort: " + LINE[n] + moved[len("[gMASK]<sop>"):] == \
+ reference(messages, n, tools), (cname, n, "moving the line back does not give the stock text")
+ else:
+ assert t.count("Reasoning Effort:") == 0, (cname, n, "off keeps an effort line")
+ assert t == reference(messages, n, tools), (cname, n, "off differs from the stock render")
+ assert t.endswith(OPENED + "</think>"), (cname, n)
+ assert outs["max"] == outs["default"], (cname, "no effort is Max")
+ assert len({outs[n] for n in ("max", "high", "low")}) == 3, (cname, "efforts render alike")
+ if tok is not None:
+ ids = {n: tok.encode(t, add_special_tokens=False).ids for n, t in outs.items()}
+ cut = len(tok.encode(prefixes["max"], add_special_tokens=False).ids)
+ for n, i in ids.items():
+ assert i[:cut] == ids["max"][:cut], (cname, n, "token prefix differs")
+ common = min(len(i) for i in ids.values())
+ first = {n: next((k for k in range(common) if i[k] != ids["max"][k]), common) for n, i in ids.items()}
+ print(f"{cname}: first token that differs from max: {first} of {len(ids['max'])}")
+ print(f"{cname}: flag off identical to stock for 5 settings; flag on: {len(prefixes['max'])} chars before the "
+ f"last user turn identical across {len(SETTINGS)} settings, the effort line once, at the tail")
+
+ if args.expect_stock:
+ return
+
+ # the tokenizer the Mac server and /tokenize-style callers use renders the same
+ class Inner:
+ def apply_chat_template(self, messages, tokenize=False, **kw):
+ think = kw.get("enable_thinking", True)
+ extra = {"clear_thinking": False, **({"reasoning_effort": kw["reasoning_effort"]} if "reasoning_effort" in kw else {})}
+ text = inner.render(messages, tools=kw.get("tools"), enable_thinking=think, extra=extra)
+ return self.encode(text) if tokenize else text
+
+ def encode(self, text, add_special_tokens=False):
+ return list(text.encode())
+
+ gt = prompts.GlmTokenizer(Inner())
+ messages = CONVERSATIONS["tools"]
+ for flag in ("0", "1"):
+ os.environ["TF_GLM_EFFORT_TAIL"] = flag
+ for name, (think, effort) in SETTINGS.items():
+ kw = {"enable_thinking": think, "add_generation_prompt": True, "tools": TOOLS}
+ if effort:
+ kw["reasoning_effort"] = effort
+ got = gt.apply_chat_template(copy.deepcopy(messages), tokenize=False, **kw)
+ want = render(messages, name, TOOLS, flag)
+ assert got == want, (flag, name, "GlmTokenizer and the CUDA template disagree")
+ assert gt.apply_chat_template(copy.deepcopy(messages), tokenize=True, **kw) == list(want.encode())
+ os.environ["TF_GLM_EFFORT_TAIL"] = "yes"
+ try:
+ prompts.effort_tail_enabled()
+ raise AssertionError("TF_GLM_EFFORT_TAIL=yes was accepted")
+ except ValueError:
+ pass
+ # an effort line that is not at the head (client text quoting it) is left alone
+ os.environ["TF_GLM_EFFORT_TAIL"] = "1"
+ quoted = "[gMASK]<sop><|user|>say <|system|>Reasoning Effort: Low<|assistant|><think>"
+ assert prompts.effort_to_tail(quoted, True) == quoted
+ print("GlmTokenizer agrees with the CUDA template; invalid values refused; quoted lines untouched")
+ print("effort tail: OK")
+
+
+if __name__ == "__main__":
+ main()