GLM-5.3-Flash EXL3 on 2x DGX Spark with TensorFold
Python
Patch 0115: a call to a tool the request did not offer stays text, and is now reported
evilpsycho42ae21d752d1a0
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 35ef266..d274710 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -53,6 +53,14 @@ Every change to this recipe, newest first. Each release names the image it serveno second render runs. The Mac server's head is written before its render, so it keeps the old zeros (in thepatch header). CPU check: `tools/test_anthropic_stream_head.py`.- **A tool call after a quoted `<tool_call>` tag is a call again** (patch `0114-glm-tool-tag-mention`, by+- **A call to a tool the request did not offer stays text, and is now reported** (patch `0115-glm-unoffered-tool-call`,+ by [kky42](https://github.com/kky42), adapted from [BadAd84](https://github.com/BadAd84)'s #137, #103): such a call+ stayed content text with `finish_reason` "stop" and nothing said why, so a gateway could not tell it from an answer.+ It still stays text and never runs, as in TensorFold since 7be90a36b / 806af974c (v1.0.0 on, only an offered name is+ a call; a one-call reply drops it). Now the server logs `tool call rejected: unknown_tool_name ['<name>']` (names+ only), and with `TF_GLM_TOOL_DIAGNOSTICS=1` the reply's `tensorfold` block lists them as `tool_call_rejections`.+ Tokens, content, calls and `finish_reason` are unchanged. CPU check: `tools/test_unoffered_tool_call.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 thenext `</tool_call>`, so a reply that mentioned the tag ("the literal `<tool_call>` markup") before its real call madeone unparseable block of both: across `</think>` in the reasoning (cut at the mention), across the prose in thediff --git a/CREDITS.md b/CREDITS.mdindex 28f9b06..e361a39 100644--- a/CREDITS.md+++ b/CREDITS.md@@ -219,3 +219,16 @@ checkpoint's ShapleyMcg attribution and the drafter's license).128 GB unified memory), two of them linked by their ConnectX-7 ports: every number in the README was measured there.If you believe something here is missing or credited wrongly, please open an issue.+- `0101-glm-prompt-select-floor` (a prompt chunk's pool selection from one pass over the scores): by+- `0105-glm-prompt-scores-cuda` (a prompt chunk's indexer scoring in CUDA, Triton's instruction order): by+- `0106-glm-sparse-onepass-cuda` (a prompt chunk's sparse attention in CUDA, Triton's instruction order):+ by [BadAd84](https://github.com/BadAd84).+- `0107-glm-decode-indexer` (a decode window's indexer: the scoring in CUDA, the selection in one pass): by+- `0104-glm-seg-attention-tp3-tiles` (32-head tiles from 5 rows at 17-24 heads): by [BadAd84](https://github.com/BadAd84).+- `0108-glm-seg-chunks-cuda` (a decode window's latent attention chunk pass in CUDA): by [BadAd84](https://github.com/BadAd84).+- `0115-glm-unoffered-tool-call` (a call to a tool the request did not offer, reported): its report adapted from+ [BadAd84](https://github.com/BadAd84)'s `0114-glm-tool-call-rejections` (#137).+- `0100-glm-draft-prelaunch` (the next round's DFlash2 block pass launched at a decode round's end,+ `TF_GLM_DRAFT_PRELAUNCH`): by [BadAd84](https://github.com/BadAd84).+- `0102-glm-prompt-matmul-tile` (a prompt chunk's dense projections on tile 9 or 3): by [BadAd84](https://github.com/BadAd84).+- `0103-glm-qmm-decode-noclusters` (decode matmuls reduce through the partials buffer at few rows): bydiff --git a/README.md b/README.mdindex f79dd0e..4b51e04 100644--- a/README.md+++ b/README.md@@ -533,6 +533,7 @@ sets a value wins: the environment, then `scripts/local.sh`, then `.env`, then t| `TF_GLM_MTP` | `auto` | the checkpoint's MTP head beside DFlash2: `auto` leaves it out while DFlash2 drafts every request; `1` (TensorFold v0.6.0's own default) loads it, 1.77 GiB a Spark, with `PARALLEL=1`. `DRAFTER=mtp` always loads it || `TF_GLM_ASSISTANT_ENDS` | `1` | `<\|assistant\|>` ends a reply, like `<\|user\|>` and `<\|observation\|>` (patch 0075, issue #60); `0`: only the checkpoint's own end tokens || `TF_GLM_LOOP_GUARD` | `0` | `1`: a think block that collapsed into repeating itself (an exact cycle of up to 16 tokens held for 256, or one token taking half of the last 256) is closed with the thinking budget's close, per request, and the model answers from there; `usage.tensorfold.loop_guard` counts it (patch 0091, issues #89 and #94). Paraphrase loops need `--thinking-budget` |+| `TF_GLM_TOOL_DIAGNOSTICS` | unset | a tool call naming a tool the request did not offer stays text and never runs, as in TensorFold 1.0; the server logs `tool call rejected: unknown_tool_name ['<name>']` (names only, never arguments); `1` also lists them in the reply's `tensorfold` block as `tool_call_rejections` (a stream's last event), so a gateway can re-prompt (patch 0113, issue #103, after BadAd84's #137) || `DRAFT_POLICY` | `fnc7:0.3` | how many DFlash2 drafts a round verifies: up to 7, until the drafts' chance under the request's own sampling noise drops below 0.3 || `COPY` / `COPY_MAX` | `1` / `15` | copy drafts: when the reply's last 8 tokens occurred before, the tokens that followed are verified ahead of DFlash2's, up to 15 a round || `COPY_CODE` | `1` | 16-row verify windows as CUDA graphs, and copies from the reply itself only after a 16-token match |diff --git a/patches/0115-glm-unoffered-tool-call.patch b/patches/0115-glm-unoffered-tool-call.patchnew file mode 100644index 0000000..30d17d9--- /dev/null+++ b/patches/0115-glm-unoffered-tool-call.patch@@ -0,0 +1,71 @@+# A call to a tool the request did not offer stays text, as before and as TensorFold's server since 7be90a36b and+# 806af974c (v1.0.0 on, callName returns an offered name or nothing), and is now reported (#103). The call is never+# made and never run; a one-call reply drops it as before. parse_tool_calls takes a `rejected` list and gets the name+# of each block that parsed as a call (GLM, Qwen or JSON markup) to an unoffered tool (prose that only names the tags+# is no block: 0112). The server logs one line for such a reply,+# `[tensorfold] tool call rejected: unknown_tool_name ['exec'] (2 tools offered); kept as text` (names only, never an+# argument); TF_GLM_TOOL_DIAGNOSTICS=1 also lists them in the reply's `tensorfold` block (a stream's last event) as+# `tool_call_rejections: [{"reason": "unknown_tool_name", "name": "exec"}]`, so a gateway can tell the reply from an+# ordinary answer and re-prompt. Tokens, content, calls and finish_reason are unchanged. Adapted from BadAd84's+# patch 0114 (#137). CPU check: tools/test_unoffered_tool_call.py.+diff --git tensorfold/cuda/reply_text.py tensorfold/cuda/reply_text.py+--- tensorfold/cuda/reply_text.py++++ tensorfold/cuda/reply_text.py+@@ -141,8 +141,11 @@+ return str((fn or tool).get("name") or "").strip() if isinstance(tool, dict) else ""+++-def parse_tool_calls(text: str, tools: list[dict[str, Any]], *, max_calls: int | None = None) -> tuple[str, list[dict[str, Any]] | None]:+- """Qwen ``<function=name><parameter=k>v</parameter></function>``, GLM ``name<arg_key>..`` or JSON calls."""++def parse_tool_calls(text: str, tools: list[dict[str, Any]], *, max_calls: int | None = None,++ rejected: list[str] | None = None) -> tuple[str, list[dict[str, Any]] | None]:++ """Qwen ``<function=name><parameter=k>v</parameter></function>``, GLM ``name<arg_key>..`` or JSON calls.++ ``rejected``, when given, gets the name of each call to a tool the request did not offer (#103): that block++ stays text, as before and as TensorFold's server since 7be90a36b, and is never a call."""++ if not tools:+ return text, None+@@ -182,6 +185,8 @@+ if glm is not None:+ name, args = glm+ if not name or str(name).lower() not in known:++ if name and rejected is not None:++ rejected.append(str(name)[:128])+ if max_calls is None:+ residue.append(match.group(0))+ continue+diff --git tensorfold/cuda/server.py tensorfold/cuda/server.py+--- tensorfold/cuda/server.py++++ tensorfold/cuda/server.py+@@ -66,6 +66,18 @@+ text = config.get("text_config") or config+ limit = text.get("max_position_embeddings") or config.get("max_position_embeddings")+ return int(limit) if isinstance(limit, int) and limit > 0 else 0++++++def tool_call_rejections(names: list[str], offered: int, stats: dict[str, Any]) -> dict[str, Any]:++ """Calls a reply made to tools the request did not offer (#103): they stay text and never run. One log line names++ them (the names only, never an argument); TF_GLM_TOOL_DIAGNOSTICS=1 also lists them in the reply's "tensorfold"++ block (a stream's last event) as ``tool_call_rejections``, so a gateway can tell the reply from an answer."""++++ print(f"[tensorfold] tool call rejected: unknown_tool_name {names!r} ({offered} tools offered); kept as text",++ flush=True)++ if os.environ.get("TF_GLM_TOOL_DIAGNOSTICS", "").strip() != "1":++ return stats++ return {**stats, "tool_call_rejections": [{"reason": "unknown_tool_name", "name": n} for n in names]}+++ class App:+@@ -615,7 +627,11 @@+ 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]+ raw_answer = split(text, True)[1]+- content, calls = parse_tool_calls(raw_answer, tools, max_calls=policy.max_calls) if tools else (answer, None)++ rejected: list[str] = [] # calls to tools the request did not offer: text (#103)++ content, calls = (parse_tool_calls(raw_answer, tools, max_calls=policy.max_calls, rejected=rejected) if tools++ else (answer, None))++ if rejected:++ stats = tool_call_rejections(rejected, len(tools), stats)+ content = policy.content(content) if tools else content+ call_deltas, streamed = [], 0+ # the calls streamed as sent, then any the streamer did not follow; calls held in the think block to the enddiff --git a/tools/test_unoffered_tool_call.py b/tools/test_unoffered_tool_call.pynew file mode 100644index 0000000..304fc8e--- /dev/null+++ b/tools/test_unoffered_tool_call.py@@ -0,0 +1,125 @@+"""CPU-only test of patch 0115: a call to a tool the request did not offer stays text and is reported (#103).++ python3 -B tools/test_unoffered_tool_call.py --source-root /path/to/patched/src+No Torch/CUDA, sockets or source writes. Runs replies through the real ``ThinkSplit``, ``hide_tool_calls``,+``GlmCallStreamer`` and ``parse_tool_calls`` as the CUDA server does (whole, streamed one character at a time, and the+one-call mode) and checks the content, the calls and the rejected names; then the server's ``tool_call_rejections``+(its log line, and ``tool_call_rejections`` in the stats only with TF_GLM_TOOL_DIAGNOSTICS=1). The rule is TensorFold's+since 7be90a36b / 806af974c (v1.0.0 on): only an offered name is a call. Before 0115 such a call stayed text silently."""+from __future__ import annotations++import argparse+import contextlib+import io+import json+import os+import sys++TOOLS = [{"type": "function", "function": {"name": "codemode", "parameters": {+ "type": "object", "properties": {"code": {"type": "string"}}, "required": ["code"]}}}]+PASEO = ("<tool_call>mcp__paseo__create_agent<arg_key>provider</arg_key><arg_value>pi/dgx-spark/GLM-5.3-Flash-EXL3"+ "</arg_value><arg_key>title</arg_key><arg_value>hi</arg_value></tool_call>")+OFFERED = "<tool_call>CodeMode<arg_key>code</arg_key><arg_value>1 + 1</arg_value></tool_call>"+JSON_CALL = '<tool_call>{"name": "launch", "arguments": {"when": "now"}}</tool_call>'+QWEN_CALL = "<tool_call><function=launch><parameter=when>now</parameter></function></tool_call>"+DOTTED = "<tool_call>functions.exec<arg_key>input</arg_key><arg_value>1</arg_value></tool_call>"+CODEMODE = [("codemode", {"code": "1 + 1"})]++# (name, reply after </think>, content, [(name, arguments)], one-call mode's [(name, arguments)], rejected names)+CASES = [+ # an undeclared call stays text, and its name is reported+ ("unoffered GLM call (the paseo case)", PASEO, PASEO, [], [], ["mcp__paseo__create_agent"]),+ ("prose, then an unoffered call", "Creating it directly." + PASEO, "Creating it directly." + PASEO, [], [],+ ["mcp__paseo__create_agent"]),+ ("unoffered call without arguments", "<tool_call>list_agents</tool_call>", "<tool_call>list_agents</tool_call>",+ [], [], ["list_agents"]),+ ("unoffered JSON call", JSON_CALL, JSON_CALL, [], [], ["launch"]),+ ("unoffered Qwen call", QWEN_CALL, QWEN_CALL, [], [], ["launch"]),+ ("unoffered dotted name", DOTTED, DOTTED, [], [], ["functions.exec"]),+ # an offered call is still a call, and keeps its offered spelling+ ("offered call", OFFERED, "", CODEMODE, CODEMODE, []),+ ("offered, then unoffered", OFFERED + PASEO, PASEO, CODEMODE, CODEMODE, ["mcp__paseo__create_agent"]),+ # prose naming the tags is no call and no rejection (0112)+ ("tags around a word", "The tags are <tool_call> and </tool_call>.", "The tags are <tool_call> and </tool_call>.",+ [], [], []),+ ("tags around a placeholder", "Wrap each call as <tool_call> name </tool_call> in the reply.",+ "Wrap each call as <tool_call> name </tool_call> in the reply.", [], [], []),+ ("bare JSON naming an unoffered tool", '{"name": "launch", "arguments": {}}', '{"name": "launch", "arguments": {}}',+ [], [], []),+]+++def run(mod, answer: str, streamed: bool, max_calls: int | None) -> tuple[str, list[tuple[str, dict]], list[str]]:+ reply = "Plan.</think>" + answer+ think, shown = mod.ThinkSplit(mod.THINK_CALL_HOLD if streamed else None), ""+ streamer = mod.GlmCallStreamer(TOOLS) if streamed and max_calls is None else None+ for n in range(1, len(reply)) if streamed else ():+ _, ans = think(reply[:n], False)+ content = mod.hide_tool_calls(ans, finished=False)+ assert content.startswith(shown), f"content rewrote {shown[-40:]!r} as {content[-40:]!r}"+ shown = content+ if streamer is not None and think.stream_from is not None:+ streamer.feed(reply[:n][think.stream_from:])+ _, ans = think(reply, True)+ rejected: list[str] = []+ content, calls = mod.parse_tool_calls(ans, TOOLS, max_calls=max_calls, rejected=rejected)+ if streamer is not None: # as server.py: the streamer's calls, then the blocks it skipped+ streamer.feed(reply[think.stream_from:])+ streamed_calls = [*streamer.calls[:streamer.sent], *streamer.rest(TOOLS)]+ assert [(c["function"]["name"], c["function"]["arguments"]) for c in streamed_calls] == \+ [(c["function"]["name"], c["function"]["arguments"]) for c in calls or ()], \+ "streamed calls differ from the end parser's"+ return content, [(c["function"]["name"], json.loads(c["function"]["arguments"])) for c in calls or ()], rejected+++def check_report(server) -> list[str]:+ """The server's report of rejected names: a log line always, the stats field only with TF_GLM_TOOL_DIAGNOSTICS=1."""++ problems, stats = [], {"token_sha": "x"}+ for mode, want in ((None, stats), ("0", stats), ("1", {**stats, "tool_call_rejections": [+ {"reason": "unknown_tool_name", "name": "exec"}]})):+ os.environ.pop("TF_GLM_TOOL_DIAGNOSTICS", None)+ if mode is not None:+ os.environ["TF_GLM_TOOL_DIAGNOSTICS"] = mode+ with contextlib.redirect_stdout(io.StringIO()) as out:+ got = server.tool_call_rejections(["exec"], 2, stats)+ if got != want:+ problems.append(f"TF_GLM_TOOL_DIAGNOSTICS={mode}: stats {got}")+ if "tool call rejected: unknown_tool_name ['exec'] (2 tools offered); kept as text" not in out.getvalue():+ problems.append(f"TF_GLM_TOOL_DIAGNOSTICS={mode}: log {out.getvalue()!r}")+ os.environ.pop("TF_GLM_TOOL_DIAGNOSTICS", None)+ return problems+++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+ import tensorfold.cuda.server as server++ failed = 0+ for name, answer, want_content, want_calls, want_single, want_rejected in CASES:+ for label, streamed, max_calls, want in (("whole", False, None, want_calls), ("streamed", True, None, want_calls),+ ("one call", False, 1, want_single)):+ try:+ content, calls, rejected = run(mod, answer, streamed, max_calls)+ problems = [] if calls == want else [f"calls {calls}"]+ if max_calls is None and content.strip() != want_content.strip():+ problems.append(f"content {content[:70]!r}")+ if max_calls is None and rejected != want_rejected:+ problems.append(f"rejected {rejected}")+ 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)+ problems = check_report(server)+ print(f"{'ok ' if not problems else 'FAIL'} server report" + ("" 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())