Skip to content

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

Python

Patch 0114: a tool call after a quoted <tool_call> tag is a call again

evilpsycho420250184efdd1
diff --git a/CHANGELOG.md b/CHANGELOG.md
index bc9d71a..28dc69d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -52,6 +52,18 @@ Every change to this recipe, newest first. Each release names the image it serve
it whole (cache fields 0); the final delta keeps the engine's input/cache_read split, the two totals equal, and
no second render runs. The Mac server's head is written before its render, so it keeps the old zeros (in the
patch header). CPU check: `tools/test_anthropic_stream_head.py`.
+- **A tool call after a quoted `<tool_call>` tag is a call again** (patch `0112-glm-tool-tag-mention`, by
+ [kky42](https://github.com/kky42)): every place the server finds GLM calls ran a block from any `<tool_call>` to the
+ next `</tool_call>`, so a reply that mentioned the tag ("the literal `<tool_call>` markup") before its real call made
+ one unparseable block of both: across `</think>` in the reasoning (cut at the mention), across the prose in the
+ answer. The call came back as content text with `finish_reason` "stop" and no `tool_calls`, and the agent stopped.
+ An opener now starts a block only when a call's head follows (GLM's name then `<arg_key>` or `</tool_call>`, Qwen's
+ `<function=`, or JSON), and a call in the think block does not cross `</think>`. Two Sparks, 30 live replies to five
+ prompts about the tag, each ending in a real `bash` call (seeded; v1.10's image and the same image with only this
+ file changed, 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 two
+ calls). CPU check:
+ `tools/test_think_tag_mention.py`.
- **A prompt that fills beside other replies, ~10-14% sooner** (`FILL_ROWS`, by [BadAd84](https://github.com/BadAd84)):
while other requests decode, a new prompt filled in 1,024-row chunks (TensorFold's `TF_GLM_FILL_ROWS` default),
half the 2,048-row prompt chunk whose buffers the engine keeps anyway. `scripts/config.sh` now sets 2,048 (at
diff --git a/patches/0112-glm-tool-tag-mention.patch b/patches/0112-glm-tool-tag-mention.patch
new file mode 100644
index 0000000..f24ef97
--- /dev/null
+++ b/patches/0112-glm-tool-tag-mention.patch
@@ -0,0 +1,117 @@
+# A <tool_call> tag a reply mentions is text, not the start of a call. Every place the CUDA server finds GLM calls
+# began a block at any "<tool_call>" and ran it to the next "</tool_call>": ThinkSplit's call run (0036/0055), the end
+# parser (parse_tool_calls), the content hider and GlmCallStreamer. A reply that quoted the tag ("the literal
+# `<tool_call>` markup") before its real call made one unparseable block from the mention to the real call's close:
+# in the think block across </think> (the reasoning cut at the mention), in the answer across the prose. The call came
+# back as content text, finish_reason "stop", no tool_calls. Live on two Sparks, 30 seeded replies to five prompts that
+# make the model talk about the tag, each ending in a real bash call, v1.10's image against the same image with only
+# this file changed (every reply token-identical): tool_calls 15/30 -> 30/30, whole and streamed. A streamed mention
+# with no </think> yet could also be held and, past THINK_CALL_HOLD, committed as a call.
+# Now an opener starts a block only when what follows can be a call's head (_call_head: GLM's name then <arg_key> or
+# </tool_call>, Qwen's <function=, or JSON; or the start of one while streaming), so a mention is text and a call's
+# value may hold the tag; and a call block in the think block does not cross </think>. Calls the reply ends on inside
+# the think block (the D5 rule), whole calls, and calls to unoffered tools (still text, #103) are as before.
+# CPU check: tools/test_think_tag_mention.py.
+diff --git tensorfold/cuda/reply_text.py tensorfold/cuda/reply_text.py
+index 55ccf2f..c0acaed 100644
+--- tensorfold/cuda/reply_text.py
++++ tensorfold/cuda/reply_text.py
+@@ -17,6 +17,39 @@ from tensorfold.tool_parameters import decode_parameter, nullable_text, paramete
+
+ _CALL_OPEN, _CALL_CLOSE = "<tool_call>", "</tool_call>"
+ _TOOL_CALL_BLOCK_RE = re.compile(r"<tool_call>\s*(.*?)\s*</tool_call>", re.IGNORECASE | re.DOTALL)
++_CALL_OPEN_RE = re.compile(re.escape(_CALL_OPEN), re.IGNORECASE)
++_QWEN_HEAD = "<function="
++_HEAD_WINDOW = 512 # characters after an opener that decide whether it is a call's (a name, then a tag)
++
++
++def _call_head(text: str, at: int) -> bool:
++ """Whether the text after a ``<tool_call>`` (from ``at``) begins as a call or may still: GLM's name then
++ ``<arg_key>`` or ``</tool_call>``, Qwen's ``<function=``, or JSON. A tag the text only mentions (``the literal
++ `<tool_call>` markup``) does not, and is text: the block a call's markup makes starts at the call's own opener."""
++
++ rest = text[at:at + _HEAD_WINDOW].lstrip()
++ if not rest or rest[0] in "{[" or rest.startswith(_QWEN_HEAD) or _QWEN_HEAD.startswith(rest):
++ return True
++ name = _GLM_NAME.match(rest)
++ if name is None:
++ return False
++ after = rest[name.end():].lstrip()
++ return any(after.startswith(tag) or tag.startswith(after) for tag in (_KEY, _CALL_CLOSE))
++
++
++def _call_blocks(text: str):
++ """``_TOOL_CALL_BLOCK_RE``'s matches, each from an opener ``_call_head`` takes for a call's (mentions skipped)."""
++
++ pos = 0
++ while (opener := _CALL_OPEN_RE.search(text, pos)) is not None:
++ pos = opener.end()
++ if not _call_head(text, pos):
++ continue
++ block = _TOOL_CALL_BLOCK_RE.match(text, opener.start())
++ if block is None:
++ return
++ yield block
++ pos = block.end()
+ _TOOL_FUNCTION_BLOCK_RE = re.compile(r"^\s*<function=([^>\s]+)>\s*(.*?)\s*</function>\s*$", re.IGNORECASE | re.DOTALL)
+ _TOOL_PARAMETER_BLOCK_RE = re.compile(r"<parameter=([^>\s]+)>\n?(.*?)\n?</parameter>", re.IGNORECASE | re.DOTALL)
+
+@@ -89,6 +122,10 @@ def hide_tool_calls(text: str, *, finished: bool) -> str:
+ tail = text[pos:]
+ out.append(tail[: len(tail) - (0 if finished else _partial_tag(tail, _CALL_OPEN))])
+ return "".join(out)
++ if not _call_head(text, start + len(_CALL_OPEN)): # a mentioned tag: text
++ out.append(text[pos:start + len(_CALL_OPEN)])
++ pos = start + len(_CALL_OPEN)
++ continue
+ out.append(text[pos:start])
+ end = text.find(_CALL_CLOSE, start)
+ if end < 0:
+@@ -111,7 +148,7 @@ def parse_tool_calls(text: str, tools: list[dict[str, Any]], *, max_calls: int |
+ calls: list[dict[str, Any]] = []
+ residue: list[str] = []
+ cursor = 0
+- for match in _TOOL_CALL_BLOCK_RE.finditer(text):
++ for match in _call_blocks(text):
+ residue.append(text[cursor:match.start()])
+ cursor = match.end()
+ if max_calls is not None and len(calls) >= max_calls:
+@@ -160,7 +197,9 @@ def parse_tool_calls(text: str, tools: list[dict[str, Any]], *, max_calls: int |
+
+
+ _THINK_CLOSE = "</think>"
+-_CALL_BLOCK = re.compile(r"<tool_call>.*?</tool_call>", re.DOTALL)
++# a call written in the think block ends before its </think>: a tag the reasoning mentions, then the real call after
++# the block closes, are not one block (and a mention opens none: ``_call_head``)
++_CALL_BLOCK = re.compile(r"<tool_call>(?:(?!</think>).)*?</tool_call>", re.DOTALL)
+ THINK_CALL_HOLD = 1024 # characters of a call written inside the think block held before it streams as a call
+ _GLM_TAG = re.compile(r"</?arg_(?:key|value)>")
+ _LAST_WORD = re.compile(r"(\S+)\s*$")
+@@ -209,7 +248,7 @@ def _call_run(text: str, start: int, finished: bool) -> tuple[int, str]:
+ come true, ``"reasoning"`` once text follows it (more reasoning, or an answer after the think block)."""
+
+ end = pos = start
+- while (block := _CALL_BLOCK.match(text, pos)) is not None:
++ while (block := _CALL_BLOCK.match(text, pos)) is not None and _call_head(text, pos + len(_CALL_OPEN)):
+ end = block.end()
+ pos = len(text) - len(text[end:].lstrip())
+ after = text[end:].lstrip()
+@@ -217,6 +256,8 @@ def _call_run(text: str, start: int, finished: bool) -> tuple[int, str]:
+ after = ""
+ if not after:
+ return end, "calls" if finished and end > start else "pending"
++ if after.startswith(_CALL_OPEN) and (not _call_head(after, len(_CALL_OPEN)) or _THINK_CLOSE in after):
++ return end, "reasoning" # a mentioned tag, or a block the think block's close cuts
+ if not finished and (after.startswith(_CALL_OPEN) or _CALL_OPEN.startswith(after)
+ or _THINK_CLOSE.startswith(after)):
+ return end, "pending" # a block, or the think block's close, being written
+@@ -327,6 +368,9 @@ class GlmCallStreamer:
+ self.start = self.pos + at
+ self.pos, self.state = self.start + len(_CALL_OPEN), "name"
+ elif self.state == "name": # the end parser's name: the text before <arg_key> or the end
++ if not _call_head(text, self.pos): # a mentioned tag: text, as the end parser reads it
++ self.state = "outside"
++ continue
+ ends = [at for at in (rest.find(_KEY), rest.find(_CALL_CLOSE)) if at >= 0]
+ if not ends:
+ if len(rest) > 256:
diff --git a/tools/test_think_tag_mention.py b/tools/test_think_tag_mention.py
new file mode 100644
index 0000000..a66bf30
--- /dev/null
+++ b/tools/test_think_tag_mention.py
@@ -0,0 +1,123 @@
+"""CPU-only test of patch 0112: a ``<tool_call>`` tag a reply mentions is text, not the start of a call.
+
+ python3 -B tools/test_think_tag_mention.py --source-root /path/to/patched/src
+No Torch/CUDA, sockets or source writes. Runs replies through the real ``ThinkSplit``, ``parse_tool_calls``,
+``hide_tool_calls`` and ``GlmCallStreamer`` as the CUDA server does, whole and streamed one character at a time (with
+and without the call hold), and checks the reasoning, the content and the calls. Before 0112 a mention matched up to
+the next ``</tool_call>``: in the think block through ``</think>`` to the real call, in the answer through the real
+call, so the call came back as content text with no tool_calls (live on v1.10: every time the model quoted the tag)."""
+from __future__ import annotations
+
+import argparse
+import json
+import sys
+
+BASH = [{"type": "function", "function": {"name": "bash", "parameters": {
+ "type": "object", "properties": {"command": {"type": "string"}}, "required": ["command"]}}}]
+
+
+def call(command: str) -> str:
+ return f"<tool_call>bash<arg_key>command</arg_key><arg_value>{command}</arg_value></tool_call>"
+
+
+CALL, GREP = call("grep -c x s.jsonl"), call("grep -c '<tool_call>' s.jsonl") # GREP's value holds the tag
+LONG = " More reasoning about the session file and what the grep should count." * 20 # > THINK_CALL_HOLD
+# the reply seen live on v1.10 (both blocks shortened): the tag in the reasoning and the answer, and in the value
+LIVE = ("The user says session.jsonl contains a literal tag `<tool_call>` followed by `<arg_key>` markup. I'll run it."
+ "</think>The file contains the literal markup `<tool_call>` instead of an actual tool call. I'll check the saved "
+ "session file for that literal string." + call("grep -c '<tool_call>' /tmp/workspace/documents/session.jsonl"))
+
+# (name, reply, reasoning, content, calls' commands); reasoning and content compared stripped
+CASES = [
+ # the failures: the tag mentioned, then a real call
+ ("mention, close, call", "The literal `<tool_call>...` markup. Let me grep.</think>" + CALL,
+ "The literal `<tool_call>...` markup. Let me grep.", "", ["grep -c x s.jsonl"]),
+ ("mention twice, close, call", "Count `<tool_call>` and `<arg_key>`; `<tool_call>` again.</think>\n" + CALL,
+ "Count `<tool_call>` and `<arg_key>`; `<tool_call>` again.", "", ["grep -c x s.jsonl"]),
+ ("mention, long reasoning, close, call", "The tag `<tool_call>` leaked." + LONG + "</think>" + CALL,
+ "The tag `<tool_call>` leaked." + LONG, "", ["grep -c x s.jsonl"]),
+ ("name-like mention", "A <tool_call>bash and then prose.</think>" + CALL, "A <tool_call>bash and then prose.", "",
+ ["grep -c x s.jsonl"]),
+ ("mention in the answer, call", "Plan.</think>It has the literal `<tool_call>` markup. I'll count it." + GREP,
+ "Plan.", "It has the literal `<tool_call>` markup. I'll count it.", ["grep -c '<tool_call>' s.jsonl"]),
+ ("live v1.10 reply", LIVE,
+ "The user says session.jsonl contains a literal tag `<tool_call>` followed by `<arg_key>` markup. I'll run it.",
+ "The file contains the literal markup `<tool_call>` instead of an actual tool call. I'll check the saved session "
+ "file for that literal string.", ["grep -c '<tool_call>' /tmp/workspace/documents/session.jsonl"]),
+ ("mention, close, no call", "The `<tool_call>` tag.</think>\n\nIt leaked as `<tool_call>` text.",
+ "The `<tool_call>` tag.", "It leaked as `<tool_call>` text.", []),
+ # what already worked and still does: plain calls, and calls inside the think block that end the reply (D5 rule)
+ ("plain close, call", "Plan.</think>" + CALL, "Plan.", "", ["grep -c x s.jsonl"]),
+ ("value holds the tag", "Plan.</think>" + GREP, "Plan.", "", ["grep -c '<tool_call>' s.jsonl"]),
+ ("call ends the think block", "Plan: grep.\n" + CALL, "Plan: grep.", "", ["grep -c x s.jsonl"]),
+ ("call holding the tag ends the think block", "Plan.\n" + GREP, "Plan.", "", ["grep -c '<tool_call>' s.jsonl"]),
+ ("call, then close", "Plan: grep.\n" + CALL + "</think>", "Plan: grep.", "", ["grep -c x s.jsonl"]),
+ ("two calls end the think block", "Plan.\n" + CALL + "\n" + GREP, "Plan.", "",
+ ["grep -c x s.jsonl", "grep -c '<tool_call>' s.jsonl"]),
+ ("call, then more reasoning", "Plan.\n" + CALL + "\nNo, wait.</think>Done.", "Plan.\n" + CALL + "\nNo, wait.",
+ "Done.", []),
+]
+
+
+def run(mod, reply: str, hold: int | None, streamed: bool) -> tuple[str, str, list[str]]:
+ """The CUDA server's path (``server.py``): split, hide calls from the streamed content, stream calls, end parse."""
+
+ think = mod.ThinkSplit(hold)
+ streamer = mod.GlmCallStreamer(BASH) if streamed else None
+ shown_reasoning = shown_content = ""
+
+ def visible(raw: str, finished: bool) -> tuple[str, str]:
+ reasoning, answer = think(raw, finished)
+ return reasoning, answer, mod.hide_tool_calls(answer, finished=finished)
+
+ for n in range(1, len(reply)) if streamed else ():
+ reasoning, _, content = visible(reply[:n], False)
+ # what went out is never taken back
+ assert reasoning.startswith(shown_reasoning), f"reasoning rewrote {shown_reasoning[-40:]!r}"
+ assert content.startswith(shown_content), f"content rewrote {shown_content[-40:]!r} as {content[-40:]!r}"
+ shown_reasoning, shown_content = reasoning, content
+ if think.stream_from is not None:
+ streamer.feed(reply[:n][think.stream_from:])
+ reasoning, answer, _ = visible(reply, True)
+ assert reasoning.startswith(shown_reasoning), f"final reasoning dropped {shown_reasoning[-40:]!r}"
+ content, calls = mod.parse_tool_calls(answer, BASH)
+ assert content.strip().startswith(shown_content.strip()), f"final content dropped {shown_content[-40:]!r}"
+ if streamer is not None and think.stream_from is not None:
+ streamer.feed(reply[think.stream_from:])
+ streamed_calls = [*streamer.calls[:streamer.sent], *streamer.rest(BASH)]
+ if streamed_calls: # the server sends the streamer's calls when it followed any
+ assert [c["function"]["arguments"] for c in streamed_calls] == \
+ [c["function"]["arguments"] for c in calls or ()], "streamed calls differ from the end parser's"
+ return reasoning, content, [json.loads(c["function"]["arguments"])["command"] for c in calls or ()]
+
+
+def main() -> int:
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--source-root", required=True, help="patched TensorFold src/ (holds tensorfold/)")
+ sys.path.insert(0, ap.parse_args().source_root)
+ import tensorfold.cuda.reply_text as mod
+
+ failed = 0
+ for name, reply, want_reasoning, want_content, want_calls in CASES:
+ for label, hold, streamed in (("whole", None, False), ("streamed", None, True),
+ ("streamed+hold", mod.THINK_CALL_HOLD, True)):
+ try:
+ reasoning, content, calls = run(mod, reply, hold, streamed)
+ problems = []
+ if reasoning.strip() != want_reasoning.strip():
+ problems.append(f"reasoning ends {reasoning[-50:]!r}")
+ if content.strip() != want_content.strip():
+ problems.append(f"content {content[:70]!r}")
+ if calls != want_calls:
+ problems.append(f"calls {calls}")
+ except AssertionError as exc:
+ problems = [str(exc)]
+ print(f"{'ok ' if not problems else 'FAIL'} {name} [{label}]" + ("" if not problems else
+ ": " + "; ".join(problems)))
+ failed += bool(problems)
+ print(f"{failed} failed")
+ return 1 if failed else 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())