GLM-5.3-Flash EXL3 on 2x DGX Spark with TensorFold
Python
Patch 0084 (off by default): TF_GLM_LOOP_GUARD closes a think block that collapsed into repeating itself (#89, #94)
MiaAI-Labf8cb1346a5be
diff --git a/README.md b/README.mdindex 5956b8c..b07a6a6 100644--- a/README.md+++ b/README.md@@ -458,6 +458,7 @@ sets a value wins: the environment, then `scripts/local.sh`, then `.env`, then t| `DRAFTER` | `dflash2` | `dflash2`: IncoAI's DFlash2 drafter, licensed [CC BY-NC-ND 4.0](https://creativecommons.org/licenses/by-nc-nd/4.0/), **non-commercial use only**; +5-10% decode. `mtp`: the checkpoint's own MTP head, one request at a time, which avoids that license (set it before the first `./start.sh` and DFlash2 is never downloaded) || `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 0084, issues #89 and #94). Paraphrase loops need `--thinking-budget` || `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/0084-glm-loop-guard.patch b/patches/0084-glm-loop-guard.patchnew file mode 100644index 0000000..f980edb--- /dev/null+++ b/patches/0084-glm-loop-guard.patch@@ -0,0 +1,142 @@+# TF_GLM_LOOP_GUARD=1 ends a think block that has collapsed into repeating itself (issues #89 and #94; upstream+# ashhart/TensorFold#204 added a guard for the Zig engine only). Per request, on the tokens the target committed, while+# the think block is open: an exact cycle of at most 16 tokens that held for 256 tokens ("maybe maybe maybe ..."), or+# one token taking half of the last 256 (a block that is mostly "the"). The next round's tokens are then replaced by the+# thinking budget's close (newline, </think>, blank line) through the same gate, so the model answers from there. Off by+# default (TF_GLM_LOOP_GUARD=0): nothing is built and no request changes. Requests that do not think never arm it.+# The reply's usage stats carry loop_guard: N when it fired. It does not catch paraphrase loops, which only+# --thinking-budget bounds. Earlier turns' looped reasoning is still resent by agents: TF_GLM_CLEAR_THINKING=1 drops it.++--- tensorfold/cuda/server.py 2026-10-08++++ tensorfold/cuda/server.py 2026-10-08+@@ -4,6 +4,7 @@+ import hashlib+ import inspect+ import json++import os+ import threading+ import time+ from dataclasses import dataclass+@@ -19,6 +20,7 @@+ from tensorfold.server.stopping import stop_options+ from tensorfold.server.tool_policy import ToolCallPolicy+ from tensorfold.engine.call_gate import CallGate, ThinkBudget, call_format, generate_gated++from tensorfold.engine.loop_guard import LoopGuard+ from tensorfold.engine.tool_draft import ToolCallStreamer+ from tensorfold.server.tools import active_tool_specs, tool_choice_requires_call++@@ -506,9 +508,11 @@+ options["probabilities"] = probabilities+ if takes_stop_eos:+ options["stop_eos"] = not prepared.ignore_eos+- shaped = prepared.grammar is not None or prepared.think_budget > 0++ guarded = chat and thinking and os.environ.get("TF_GLM_LOOP_GUARD", "0") == "1"++ shaped = prepared.grammar is not None or prepared.think_budget > 0 or guarded+ think_end = self.tok.token_to_id("</think>") if chat and thinking and shaped else None+ budget = self._think_budget(prepared, think_end)++ guard = LoopGuard(self._think_close(prepared, think_end), think_end) if guarded and think_end is not None else None+ # priority "background" (or a session-title request): after the others, as on the Mac+ background = body.get("priority") == "background" or (chat and is_title_request(body.get("messages"), tools))+ concurrent = getattr(self.engine, "concurrent", False)+@@ -517,7 +521,7 @@+ options["background"] = True # the engine's scheduler orders its lanes and prompts+ # one engine at a time: a background reply yields between rounds (not on two ranks, which decode to the end)+ yielding = background and turns is not None and getattr(self.engine, "tp", 1) == 1+- gates = [g for g in (gate, budget, Yield(turns) if yielding else None) if g is not None]++ gates = [g for g in (gate, budget, guard, Yield(turns) if yielding else None) if g is not None]++ cached: list[int] = [] # the prompt tokens the first run found cached (usage's cached_tokens)++@@ -579,6 +583,8 @@+ if stopped["client"]: # as the Mac server: nothing more is written+ raise RequestCancelled("the client left during the reply")+ stats = {**(stats or {}), "token_sha": token_sha(out)}++ if guard is not None and guard.fires:++ stats["loop_guard"] = guard.fires # the think block collapsed and was closed (TF_GLM_LOOP_GUARD)+ # the model's end token (not a stop string or the token limit) ended the reply: a call it ended inside is+ # closed when it then parses (#22), else its markup is the reply's text; it is never dropped+ ended = bool(out) and out[-1] in ends and not stopped["stop"]+@@ -637,10 +643,18 @@++ if prepared.think_budget <= 0 or think_end is None:+ return None++ return ThinkBudget(prepared.think_budget, self._think_close(prepared, think_end), think_end)++++ def _think_close(self, prepared: PreparedRequest, think_end: int | None) -> list[int]:++ """The tokens that close a think block the server ends: a newline, </think> and a blank line (</think> alone++ under a grammar)."""++++ if think_end is None:++ return []+ close = [*self.tok.encode("\n", add_special_tokens=False).ids, think_end]+ if prepared.grammar is None:+ close += self.tok.encode("\n\n", add_special_tokens=False).ids+- return ThinkBudget(prepared.think_budget, close, think_end)++ return close++ def _glm_calls(self) -> bool:+ """Whether this model writes GLM's ``<arg_key>``/``<arg_value>`` calls (streamed while they are written): its+--- tensorfold/engine/loop_guard.py++++ tensorfold/engine/loop_guard.py+@@ -0,0 +1,61 @@++"""A think block stuck repeating itself ends: the same gate hook as the thinking budget, one guard per request."""++from __future__ import annotations++++from collections import Counter, deque++from typing import Sequence++++WINDOW = 256 # committed think tokens a collapse has to fill++PERIOD = 16 # longest exact cycle (in tokens) that counts as a loop++DOMINANT = 0.5 # share of the window one token id may take before the block counts as collapsed++++++class LoopGuard:++ """Watches the committed tokens of one request while its think block is open. Once they collapse, the next++ round's first token becomes ``close`` (the thinking budget's close; ``ThinkBudget.cut``'s contract). Two collapses++ count:++++ * an exact cycle of at most PERIOD tokens that held for WINDOW tokens in a row ("maybe maybe maybe ...");++ * one token id taking at least DOMINANT of the last WINDOW tokens, the cycle broken by other text ("the" in++ every other word of a degenerate block).++++ Nothing is watched after ``think_end``. The fire latches until the close is committed; ``fires`` counts them.++ The guard holds no engine state and is made per request, so concurrent lanes are independent, and the server's++ gate runs on rank 0 as the budget's does."""++++ def __init__(self, close: Sequence[int], think_end: int) -> None:++ self.close, self.think_end = [int(t) for t in close], int(think_end)++ self.open, self.fired, self.fires = True, False, 0++ self.recent: deque[int] = deque(maxlen=WINDOW)++ self.counts: Counter[int] = Counter()++ self.run = [0] * (PERIOD + 1) # run[p]: consecutive tokens equal to the one p before++ self.last: deque[int] = deque(maxlen=PERIOD)++++ def cut(self, tokens: Sequence[int]) -> tuple[int, list[int]] | None:++ """(0, close) once the block collapsed: the next round's tokens are not the reply, the close is."""++++ if self.open and self.fired and len(tokens):++ return 0, list(self.close)++ return None++++ def observe(self, token: int) -> None:++ token = int(token)++ if not self.open:++ return++ if token == self.think_end:++ self.open = False++ return++ if self.fired:++ return # the close's own tokens arrive here; they are not the model's++ for p in range(1, len(self.last) + 1):++ self.run[p] = self.run[p] + 1 if self.last[-p] == token else 0++ self.last.append(token)++ if len(self.recent) == WINDOW:++ self.counts[self.recent[0]] -= 1++ self.recent.append(token)++ self.counts[token] += 1++ if len(self.recent) == WINDOW and (any(r >= WINDOW for r in self.run) or self.counts[token] >= DOMINANT * WINDOW):++ self.fired = True++ self.fires += 1++++++__all__ = ["LoopGuard"]diff --git a/tools/test_loop_guard.py b/tools/test_loop_guard.pynew file mode 100644index 0000000..6173090--- /dev/null+++ b/tools/test_loop_guard.py@@ -0,0 +1,102 @@+"""CPU-only test of patch 0084's loop guard with the real call_gate.generate_gated.++ python3 -B tools/test_loop_guard.py --source-root /path/to/patched/src+No Torch/CUDA, sockets or source writes. Replays token streams: a clean block, an exact cycle, a mostly-"the" block,+a loop after </think> (not watched), and a loop that starts late, and checks the close lands and the reply goes on."""+from __future__ import annotations++import argparse+import importlib.util+import random+import sys+from pathlib import Path++THINK_END, CLOSE = 7, [10, 7, 11]+++def load(root, name, rel):+ spec = importlib.util.spec_from_file_location(name, Path(root) / rel)+ mod = importlib.util.module_from_spec(spec)+ sys.modules[name] = mod+ spec.loader.exec_module(mod)+ return mod+++def run(gates, stream, rounds=4, cap=3000):+ """Feed ``stream`` (the model's tokens) in rounds of ``rounds`` through generate_gated; after a cut the model+ goes on with the 'answer' [50, 51, 52]. Returns the reply."""+ gated = sys.modules["tf_call_gate"].generate_gated+ reply_out = []++ def generate(ids, count, take):+ tail = list(stream)[len(reply_out):] # the model goes on where the reply stopped+ if CLOSE[-1] in ids: # after the close it answers+ tail = [50, 51, 52, 2]+ while tail and count > 0:+ chunk, tail = tail[:rounds], tail[rounds:]+ chunk = chunk[:count]+ if take(chunk):+ return {}+ count -= len(chunk)+ return {}++ out = []++ def on_tokens(new):+ out.extend(new)+ reply_out[:] = out+ return False++ gated(generate, [0], cap, gates, on_tokens)+ return out+++def main():+ ap = argparse.ArgumentParser()+ ap.add_argument("--source-root", required=True)+ root = ap.parse_args().source_root+ load(root, "tf_call_gate", "tensorfold/engine/call_gate.py")+ guard_mod = load(root, "tf_loop_guard", "tensorfold/engine/loop_guard.py")+ rnd = random.Random(1)+ prose = [rnd.randrange(100, 5000) for _ in range(900)]+ def fresh():+ return guard_mod.LoopGuard(CLOSE, THINK_END)++ # 1. clean thinking, then </think> and an answer: untouched+ clean = prose[:600] + [THINK_END, 50, 51, 2]+ g = fresh(); out = run([g], clean)+ assert out == clean and g.fires == 0, "a clean block must not fire"+ # 2. exact cycle of period 4 after 300 tokens of prose: closed within a window and a round or two+ cyc = prose[:300] + [9, 8, 9, 6] * 400+ g = fresh(); out = run([g], cyc)+ assert g.fires == 1 and CLOSE == out[-len(CLOSE) - 4:-4], (g.fires, out[-12:])+ assert out[-4:] == [50, 51, 52, 2] and len(out) < 300 + 256 + 4 + 8 + len(CLOSE) + 8, len(out)+ # 3. a block that is half 'the' (id 5) between other words+ mixed = []+ for i in range(1200):+ mixed += [5, prose[i % len(prose)]] if i % 3 else [5, 5, prose[i % len(prose)]]+ g = fresh(); out = run([g], mixed)+ assert g.fires == 1 and len(out) < 700, (g.fires, len(out))+ # 4. a loop after </think> is the answer's business, not watched+ after = prose[:50] + [THINK_END] + [3] * 800+ g = fresh(); out = run([g], after)+ assert g.fires == 0 and out == after+ # 5. near cycle (one token in every 12 differs) and common-word prose never fire+ near = []+ for i in range(3000):+ near.append(prose[i % 11] if i % 12 else rnd.randrange(6000, 9000))+ g = fresh(); run([g], near, cap=3000); assert g.fires == 0+ zipf = rnd.choices(range(100, 5100), weights=[1 / r for r in range(1, 5001)], k=5000) # the top token ~11%+ g = fresh(); run([g], zipf, cap=5000); assert g.fires == 0, "natural token frequencies must not fire"+ # 6. two guards are independent (one lane collapses, the other does not)+ a, b = fresh(), fresh()+ run([a], cyc); run([b], clean)+ assert a.fires == 1 and b.fires == 0+ # 7. the budget and the guard together: the earlier cut wins, and the reply still ends once+ tb = sys.modules["tf_call_gate"].ThinkBudget(350, CLOSE, THINK_END)+ g = fresh(); out = run([tb, g], cyc)+ assert out.count(THINK_END) == 1, out.count(THINK_END)+ print("OK: loop guard")+++main()