Skip to content

feat: GLM-5.3-Flash on Apple Silicon (glm5_next MLX family) — rebased on 0.3.4 - #9

Closed
chadhurley25075-png wants to merge 13 commits into
ashhart:mainfrom
chadhurley25075-png:glm-5.3-flash
Closed

chadhurley25075-png wants to merge 13 commits into
ashhart:mainfrom
chadhurley25075-png:glm-5.3-flash

Conversation

@chadhurley25075-png

@chadhurley25075-png chadhurley25075-png commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Rebased onto 0.3.4.1 (bb4b4a3) and grown a little since the last push: GLM-5.3-Flash rides the lane engine's family rounds on a Mac, prefills on the 2,048-token grid like every other family, reads mixed-bit (5/6/8-bit override) checkpoints through the same row-exact path, and carries kingjamez's M5 Ultra fixes. Thank you both for testing — the two comments below shaped most of what changed.

What is in the branch now (13 commits on bb4b4a3)

  • 0.3.4 / 0.3.4.1. glm5_next says LANES = True; runtime.GLMFlash speaks engine/lane_family.py's contract (exact_width and window_costs measured on the real weights at load, speculate / settle / unspeculate for the MTP head, gpu_tokens so the serial reference runs one step ahead, engine_settings for the row cap). The engine's cost-based depth rule replaces the old depth_for. Prompts go through _family_feed on the engine's grid, so tests/test_family_prefill_grid.py and the resume-from-a-grid-point behaviour apply to this family unchanged; the serial-engine commit is gone with the engine.
  • kingjamez's M5 Ultra findings (folded from the comment; co-authored in the commit). MLX_ENABLE_TF32=0 set in tensorfold/__init__.py before mlx loads (an explicit value wins) — the row kernels repeat MLX's fp32 order, so prefill and decode only agree bit for bit in fp32. GLM-5.3's template ignores enable_thinking; a trailing bare <think> is now closed as <think></think> when thinking is off, with his unit test. TF_GLM5_SPLIT_SHARED override. The MTP head reads the final-normed row by default (TF_GLM_MTP_INPUT=normed, raw restores the streams' mean): +1.0 point of first-draft acceptance and 86.9 → 87.9 tok/s on his M5, 61–76 → 66–78% and +0.5 tok/s on our M3 Ultra; drafts only, so exactness is unchanged. Not folded: VERIFY_MS_M5 / depth_for, because 0.3.4 measures each window's cost on the machine at load and picks the depth from that — his M5 timings are now read off the GPU itself.
  • Mixed-bit checkpoints (YJesus's question). families/glm5_next/layouts.py maps the mlx-lm / oMLX converted layout onto the loader's names (fused conv1d [3C,T,1], forget_gate.*, the absorbed embed_q / unembed_out pair in place of kv_b_proj, mtp.0.* with a bf16 eh_proj, a vision tower to skip, per-tensor quantization overrides). A stack whose parts differ in bits stays separate parts (QSplit); project runs each at its own width. The kernels grew 8-, 6- and 5-bit qmv_rows / expert_qmv / qmv_quad_rows variants from MLX 0.32.2's one-row qmv_fast / qmv_quad loops (fast_shape = MLX's own rule), and the fused MoE takes an 8-bit shared expert beside 4-bit routed experts, so a mixed-bit checkpoint decodes through the fused, row-invariant path rather than one MLX call per row. Validated on grant-ai's abliterated mixed-bit conversion (554 per-tensor overrides — the same count Vontra's GLM-5.3-Flash-MLX-oQ4-MTP card lists): load-time rows_match_serial passes on the full model, drafted == "draft": false, 36.8 → 46.3 tok/s once the 8-bit tensors took the fused path. We have not loaded Vontra's oQ4 checkpoint itself — more on that in the reply below.

Measured, this branch, drafted replies byte-identical to "draft": false (content, reasoning, assembled tool calls)

machine checkpoint decode tok/s (greedy, drafted) serial exact
M3 Ultra 60-core, 256 GB (S4), MLX 0.32.2, --context 1048576 --mtp-drafts 1 Vontra 4-bit MTP 58.9 (glm_exact harness) / 57.6 (200-token mark, 2 passes) 48.8 15/15 (6 greedy, 6 seeded T 0.6–1.0 top-p/top-k, tool call + result leg, 32K context)
M3 Ultra 80-core, 512 GB (S2), production 0.3.0-based build, same kernels Vontra 4-bit MTP 62.9 — kit G3 5/5
M3 Ultra 60-core, 256 GB (S5), 0.3.0-based build + these kernels grant-ai abliterated mixed-bit 46.3 (from 36.8 before the 8-bit kernels) — kit G3 5/5, load-time rows_match_serial
M5 Ultra, 256 GB — kingjamez's numbers, an earlier head of this PR Vontra 4-bit MTP 87.6 (88.2 sampled; 127.1 on a 1,040-token edit at --mtp-drafts 4) 68.8 12/12
  • Load-time check on S4 today: every window up to 16 rows gives each row its one-row bits; forward ms by width 1: 20.5, 2: 27.8, 3: 36.3, 4: 45.6, 8: 84.7.
  • Prefill on this branch is the reference path (317 tok/s at 8K, 263 at 32K on S4, cold, sliding with context); the flat absorbed-latent prefill is a separate PR stacked on this one (PR glm5_next: absorbed sparse-MLA prefill (TF_GLM5_PREFILL=absorbed), flat with context — stacked on #9 #39) so it can be judged on its own.
  • Full suite on the Mac (pytest tests, S4): 392 passed, 71 skipped (CUDA + real-weights).
  • Against the 0.3.0 serial engine the family rounds still cost this family a little on the M3 Ultra (59.5 vs ~57 tok/s at one draft, measured last night, 4 passes each); noting it rather than hiding it. The rounds are GPU-bound; at ~9 GB of weights a token the floor on this GPU is near 14.5 ms, so 100 tok/s on an M3 Ultra needs fewer bytes a token, not more fusion. kingjamez's serial step on the M5 Ultra is 14.5 ms with a floor near 10.

Thanks to Ash for the recipe book (the strategy-C method is how every one of these numbers was found), to the mlx-vlm authors (#2105 KDA kernel, #2245 indexed sparse attention, ported with notices), to oMLX for the reference runtime, and to kingjamez and YJesus for testing and asking. All numbers are logged runs, same prompts each time.

— Chad

@kingjamez

Copy link
Copy Markdown
Contributor

Tested this branch on an M5 Ultra (256 GB, MLX 0.32.2). It works well, and there are two M5-specific issues and one GLM template bug worth folding in. The patch is below; all 313 tests pass with it.

Results (M5 Ultra, Vontra/GLM-5.3-Flash-MLX-4bit-MTP, one request at a time)

Decode tok/s oMLX 0.7.0rc1 + Lightning MTP This branch
Chat / code / story, greedy, 512 tokens 52.9 87.6
Same, temperature 1.0, top-p 0.95 50.8 88.2
File edit, 1,040-token reply (--mtp-drafts 4) – 127.1
Serial ("draft": false) 41.5 68.8

Drafted equals "draft": false on 12 of 12 prompts (greedy and sampled, thinking on and off). The serial step is 14.5 ms. By component (chained timings on the real weights): MoE 7.5 ms at about 730 GB/s, KDA 2.9 ms at about 930 GB/s, HC boundaries 2.1 ms (launch-bound, about 21 us each), sparse MLA 1.7 ms. A token reads 9.55 GB; this machine does about 1,100 GB/s, so the serial floor is near 10 ms.

1. M5: MLX runs fp32 matmuls as TF32 by default

tests/test_glm5_fused.py::test_fused_hc_boundary_is_the_row_by_row_path fails on M5 (expand path, about 11% of stream values differ in the last bf16 bit). The cause is not the kernel. On the M5 GPU, MLX 0.32.2's float32 matmul has a median relative error of 4e-4 against float64 (CPU: 3e-8), because MLX_ENABLE_TF32 defaults on. With MLX_ENABLE_TF32=0, the kernel's sequential-FMA order matches MLX bit for bit (0 of 16,384 values differ) and the whole suite passes. This matters beyond the test: prefill uses MLX's hc_expand, decode uses the fused kernel, so with TF32 on they disagree on M5. The patch sets it in tensorfold/__init__.py before mlx loads, and an explicit environment value still wins.

2. GLM-5.3's template ignores enable_thinking

The upstream chat_template.jinja always ends with <|assistant|><think> and has no thinking switch. With enable_thinking: false the model still reasons (99 tokens against 20 for the direct answer), and because the server treats thinking as off, the reasoning lands in content. The patch closes a trailing bare <think> token when thinking is off (<think></think>, the template's own form for a turn without reasoning). Templates that honour the switch never end on a bare <think>, so they are unchanged. A unit test is included.

3. Smaller changes

  • MTP input row: your note from the CUDA recipe holds here too. Feeding the head the final-normed row (TF_GLM_MTP_INPUT=normed, now the default) raised acceptance from 78.8% to 79.8%, and speed from 86.9 to 87.9 tok/s greedy.
  • Verify costs for depth_for on M5 (VERIFY_MS_M5, picked for applegpu_g17+): from fixed-depth rounds, 20.7 / 26.8 / 33.5 / 42.0 / 49.1 ms for depths 1 to 5. Depth 1 stays best on chat (87.0 against 82.3 at depth 2), and edits go deeper (93% acceptance, about 6 rows a round). The depth test now covers both tables.
  • Tried, no gain on M5: SPLIT_SHARED=0 (3% faster for a lone 1-row MoE layer, 2.5% slower end to end, so the split's overlap wins; I added only a TF_GLM5_SPLIT_SHARED override); HC_MIX_U 1 to 16; TF_GLM5_EVAL_EVERY 1 to 4 (flat; 0 is 11% slower); fixed depths 2 to 5.
Patch against 0834afd (7 files, +98 / -5)
diff --git a/src/tensorfold/__init__.py b/src/tensorfold/__init__.py
index 489371e..6749318 100644
--- a/src/tensorfold/__init__.py
+++ b/src/tensorfold/__init__.py
@@ -1,3 +1,10 @@
 """TensorFold: fast, exact LLM decoding on Apple Silicon and NVIDIA GPUs behind an OpenAI-compatible endpoint."""
 
+import os
+
+# MLX runs float32 matmuls as TF32 on M5-generation GPUs unless told otherwise (median relative error 4e-4 against
+# 3e-8 in fp32). The row kernels repeat MLX's fp32 arithmetic, so prefill (MLX's matmuls) and decode (the kernels)
+# only agree bit for bit in fp32. Set before mlx is imported; an explicit MLX_ENABLE_TF32 in the environment wins.
+os.environ.setdefault("MLX_ENABLE_TF32", "0")
+
 __version__ = "0.3.0"
diff --git a/src/tensorfold/families/glm5_next/model.py b/src/tensorfold/families/glm5_next/model.py
index 6434d8d..2c58145 100644
--- a/src/tensorfold/families/glm5_next/model.py
+++ b/src/tensorfold/families/glm5_next/model.py
@@ -119,6 +119,17 @@ def _eval_every() -> int:
 EVAL_EVERY = _eval_every()
 
 
+def _mtp_input() -> str:
+    import os
+
+    return os.environ.get("TF_GLM_MTP_INPUT", "normed")
+
+
+# The row the MTP head reads at each position: "raw" (the streams' mean before the final norm, as oMLX's runtime
+# does) or "normed" (the final-normed row the LM head reads, vLLM's convention). Speed only: drafts are verified.
+MTP_INPUT = _mtp_input()
+
+
 def row_kernel(name: str, rows: int, rows_exact: bool) -> bool:
     return rows_exact and rows > 1 and name in ENABLED
 
@@ -970,8 +981,12 @@ class GLM5:
         for s in range(1, int(x.shape[1])):
             raw = raw + xs[:, s]
         raw = (raw * (1.0 / int(x.shape[1]))).astype(x.dtype)
-        self.last_raw = raw
-        return mx.fast.rms_norm(raw, self.norm, self.args.rms_norm_eps)[None]
+        normed = mx.fast.rms_norm(raw, self.norm, self.args.rms_norm_eps)
+        # The MTP head's input row. "normed" (vLLM's convention, the row the LM head reads) drafts closer to the
+        # target than the streams' mean before the norm (the CUDA recipe: 0.739 against 0.696 next-token agreement).
+        # Drafts are verified, so this changes speed only, never the reply.
+        self.last_raw = normed if MTP_INPUT == "normed" else raw
+        return normed[None]
 
     def head(self, hidden: mx.array) -> mx.array:
         shape = hidden.shape
diff --git a/src/tensorfold/families/glm5_next/runtime.py b/src/tensorfold/families/glm5_next/runtime.py
index 746229d..1f9b1f5 100644
--- a/src/tensorfold/families/glm5_next/runtime.py
+++ b/src/tensorfold/families/glm5_next/runtime.py
@@ -126,6 +126,9 @@ class GLMFlash:
     # decode, 4,096 keys; 1, 2 and 4 rows measured, the rest on their line).
     # TF_GLM_VERIFY_MS ("t1,t2,...") and TF_GLM_DRAFT_MS override them.
     VERIFY_MS = (22.7, 29.8, 37.9, 46.0, 54.1, 62.2, 70.3, 78.4)
+    # The same on an M5 Ultra (MLX 0.32.2, fp32 matmuls): 1 row timed serially, 2-6 rows from fixed-depth rounds
+    # (TF_GLM_DEPTH=1-5: 20.7, 26.8, 33.5, 42.0, 49.1 ms a round) less their drafts, the rest on their line.
+    VERIFY_MS_M5 = (14.5, 18.9, 23.2, 28.1, 34.8, 40.1, 45.9, 51.7)
     DRAFT_MS = 1.8
     CHAIN_DECAY = 0.8
 
@@ -140,7 +143,7 @@ class GLMFlash:
         fixed = os.environ.get("TF_GLM_DEPTH", "").strip()
         if fixed:
             return max(1, min(self.drafts, int(fixed)))
-        verify = self.VERIFY_MS
+        verify = self.VERIFY_MS_M5 if _gpu_generation() >= 17 else self.VERIFY_MS
         if os.environ.get("TF_GLM_VERIFY_MS"):
             verify = tuple(float(v) for v in os.environ["TF_GLM_VERIFY_MS"].split(","))
         draft = float(os.environ.get("TF_GLM_DRAFT_MS", self.DRAFT_MS))
@@ -184,6 +187,17 @@ class GLMFlash:
         return ok
 
 
+def _gpu_generation() -> int:
+    """The Apple GPU family number (applegpu_g15* = M3, g16 = M4, g17 = M5); 0 when unknown."""
+
+    try:
+        arch = str(mx.device_info().get("architecture", ""))
+    except Exception:
+        return 0
+    digits = "".join(ch for ch in arch.removeprefix("applegpu_g")[:2] if ch.isdigit())
+    return int(digits) if digits else 0
+
+
 def _sample(logits: mx.array, position: int, sampling: Any) -> int:
     if sampling is None:
         return int(mx.argmax(logits.reshape(-1)).item())
diff --git a/src/tensorfold/kernels/glm/flash/v1/fused.py b/src/tensorfold/kernels/glm/flash/v1/fused.py
index 8594cdc..858ef9c 100644
--- a/src/tensorfold/kernels/glm/flash/v1/fused.py
+++ b/src/tensorfold/kernels/glm/flash/v1/fused.py
@@ -30,7 +30,11 @@ MAX_ROWS = 16
 SQ_FMA = 0
 ROUTER_TG = 1024
 HC_MIX_U = 8             # iterations of loads the hyper-connection mix issues ahead
-SPLIT_SHARED = 1         # the shared expert in kernels of its own, beside the router (moe_rows)
+
+# The shared expert in kernels of its own, beside the router (moe_rows). Also faster end to end on an M5 Ultra
+# (20.7 against 21.2 ms a 2-row round), although a lone 1-row MoE layer timed 3% faster combined: split, the shared
+# expert overlaps the router on the GPU. TF_GLM5_SPLIT_SHARED=0 combines them.
+SPLIT_SHARED = int(__import__("os").environ.get("TF_GLM5_SPLIT_SHARED", "1"))
 
 _HEADER = K._HEADER + r"""
 template <typename U>
diff --git a/src/tensorfold/server/app.py b/src/tensorfold/server/app.py
index 0d96908..b9e1230 100644
--- a/src/tensorfold/server/app.py
+++ b/src/tensorfold/server/app.py
@@ -117,7 +117,27 @@ def render_prompt_ids(
         rendered = tokenizer.apply_chat_template(messages, **kwargs)
     if isinstance(rendered, str):
         rendered = tokenizer.encode(rendered)
-    return [int(t) for t in rendered]
+    ids = [int(t) for t in rendered]
+    if not enable_thinking and add_generation_prompt:
+        ids = _close_open_think(tokenizer, ids)
+    return ids
+
+
+def _close_open_think(tokenizer: Any, ids: list[int]) -> list[int]:
+    """Thinking off, for templates that ignore ``enable_thinking``: GLM-5.3's always ends the prompt with
+    ``<|assistant|><think>``, so the model reasons anyway and the reply lands in ``content``. Close the block the way
+    that template writes a turn without reasoning (``<think></think>``). Templates that honour the switch never end
+    on a bare ``<think>``, so they are unchanged."""
+
+    if not ids:
+        return ids
+    try:
+        if tokenizer.decode([ids[-1]]).strip() != "<think>":
+            return ids
+        close = tokenizer.encode("</think>", add_special_tokens=False)
+    except Exception:
+        return ids
+    return ids + [int(t) for t in close] if len(close) == 1 else ids
 
 
 def eos_ids_of(tokenizer: Any) -> frozenset[int]:
diff --git a/tests/test_close_open_think.py b/tests/test_close_open_think.py
new file mode 100644
index 0000000..27d931e
--- /dev/null
+++ b/tests/test_close_open_think.py
@@ -0,0 +1,24 @@
+"""Thinking off on a template that always opens a think block (GLM-5.3): the prompt gets the block closed."""
+
+from tensorfold.server.app import _close_open_think
+
+
+class _Tok:
+    vocab = {"<|assistant|>": 1, "<think>": 2, "</think>": 3, "hi": 4}
+
+    def decode(self, ids):
+        inv = {v: k for k, v in self.vocab.items()}
+        return "".join(inv[i] for i in ids)
+
+    def encode(self, text, add_special_tokens=False):
+        return [self.vocab[text]]
+
+
+def test_open_think_is_closed_when_thinking_is_off():
+    assert _close_open_think(_Tok(), [4, 1, 2]) == [4, 1, 2, 3]
+
+
+def test_prompts_without_a_trailing_think_are_unchanged():
+    assert _close_open_think(_Tok(), [4, 1]) == [4, 1]
+    assert _close_open_think(_Tok(), [4, 1, 2, 3]) == [4, 1, 2, 3]
+    assert _close_open_think(_Tok(), []) == []
diff --git a/tests/test_glm5_fused.py b/tests/test_glm5_fused.py
index 99d9c9e..c63aece 100644
--- a/tests/test_glm5_fused.py
+++ b/tests/test_glm5_fused.py
@@ -183,11 +183,20 @@ def test_draft_depth_follows_acceptance(monkeypatch):
     """GLM picks the depth from the conditional acceptance and the verify cost of each depth: shallow at low
     acceptance, deeper as it rises, never past the cap; TF_GLM_DEPTH fixes it."""
 
+    from tensorfold.families.glm5_next import runtime
     from tensorfold.families.glm5_next.runtime import GLMFlash
 
     rt = GLMFlash.__new__(GLMFlash)
     rt.drafts = 4
     monkeypatch.delenv("TF_GLM_DEPTH", raising=False)
+    monkeypatch.delenv("TF_GLM_VERIFY_MS", raising=False)
+    # M5-generation GPUs use their own verify costs: deeper only at high acceptance, and a 5-row verify costs enough
+    # there that even 0.99 stops at 3 drafts
+    monkeypatch.setattr(runtime, "_gpu_generation", lambda: 17)
+    m5 = [rt.depth_for(a) for a in (0.5, 0.7, 0.8, 0.85, 0.9, 0.99)]
+    assert m5 == sorted(m5) and m5[0] == 1 and m5[-1] == 3
+    assert rt.depth_for([0.77, 0.57]) == 1   # measured there on chat/code: depth 1 ran 87 tok/s, depth 2 82
+    monkeypatch.setattr(runtime, "_gpu_generation", lambda: 15)     # the M3 Ultra table from here on
     depths = [rt.depth_for(a) for a in (0.5, 0.7, 0.8, 0.85, 0.9, 0.99)]
     assert depths == sorted(depths) and depths[0] == 1 and depths[-1] == 4
     rt.drafts = 2

Thanks for the engine and the careful write-up; it made the M5 port a matter of measurements rather than guesswork.

@chadhurley25075-png chadhurley25075-png changed the title feat: GLM-5.3-Flash on Apple Silicon, an MLX engine for glm5_next feat: GLM-5.3-Flash on Apple Silicon (glm5_next MLX family) — rebased on 0.3.4 Sep 27, 2026
@ashhart ashhart added the enhancement New feature or request label Sep 27, 2026
@YJesus

YJesus commented Sep 27, 2026

Copy link
Copy Markdown

Is Vontra's mixed-precision checkpoint (Vontra/GLM-5.3-Flash-MLX-oQ4-MTP: 4-bit affine base, group size 64, with 554 per-module 5/6/8-bit overrides, including 12 in the MTP layer) supported by the glm5_next MLX engine, or planned? The row kernels look written for uniform 4-bit/g64, so I'd expect the overridden modules to need other qmv paths.

My machine is an M3 Ultra with 256 GB, same as your second test box, so I'm happy to run the tests and the drafted-vs-serial check if useful.

indexer-bf16 and others added 12 commits September 27, 2026 13:44
- GLM-4.5 and later (GLM-5.3-Flash) write <tool_call>NAME<arg_key>K</arg_key><arg_value>V</arg_value>...
  </tool_call>. A payload that is neither JSON nor <function=...> is read that way; a call with no arguments is
  just the name.
- The chat template writes string arguments raw and every other value as JSON, so each value is converted by
  the type its parameter declares (coerce_glm_value), as oMLX's _coerce_param_value does, without its repair of
  near-valid JSON. Noted in THIRD_PARTY_NOTICES.md (Apache-2.0).
- tests/test_glm_tool_calls.py: typed values, parallel calls, raw strings kept verbatim, unknown tools stay text.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01FaooCnQeKYApFByWS3Y7gz
(cherry picked from commit 0294b50)
The glm5_next package gains load(): the same checkpoint (Vontra/GLM-5.3-Flash-MLX-4bit-MTP) on one Mac with
256 GB or more, beside the CUDA engine, which is unchanged.

- model.py: a forward pass from the checkpoint layout (four hyper-connected streams, 34 KDA and 11 sparse MLA
  layers, 288-expert MoE), checked sublayer by sublayer against mlx-vlm's glm5_next on the real weights. kv_b
  stays as stored and is applied per head. Prefill uses MLX's kernels; the decode path (up to 16 rows) gives
  every row its one-row bits.
- kernels/glm/flash/v1: qmv_rows for groups of 64 and one-launch row kernels for the router, the routed experts,
  the hyper-connection mix, the indexer gate and KDA's f_b / g_b (strategy B); the KDA decode step in one kernel
  a layer (ported from mlx-vlm ashhart#2105) and sparse attention reading the chosen keys by index (from mlx-vlm ashhart#2245);
  the MoE block in five kernels, a hyper-connection boundary in three, MLA's same-input projections stacked
  (strategy B, the logits unchanged).
- mtp.py / runtime.py: the checkpoint's MTP layer as the draft head. KDA states are rolled back by replaying the
  kept rows from the window's entry state through the same kernel, so drafts can chain. A load-time check turns
  drafting off when a multi-row forward does not reproduce one-row steps. depth_for picks the depth from each
  position's acceptance and the measured verify cost; --mtp-drafts defaults to 1 for this family.
- The decode graph goes to the GPU every 2 layers (mx.async_eval); the shared expert runs in kernels of its own
  beside the router.
- THIRD_PARTY_NOTICES.md credits mlx-vlm (ashhart#2030, ashhart#2105, ashhart#2245, ashhart#2107) and the MLX kernels whose arithmetic the
  row kernels repeat.

Full model on an M3 Ultra (512 GB, MLX 0.32.0), 4,096 keys: one-row step 35.7 -> 22.3 ms, 3,578 -> 1,197
kernels a token. Through the server: short answer 62.4 tok/s (46.9 serial), code 63.6, file edit 93.6, 18k
context 48.0, 23k agent prompt 53.4. Drafted replies are byte-identical to "draft": false (5 of 5 prompts).
Tests: tests/test_glm5_*.py on a small synthetic checkpoint (CPU and Metal), plus real-weight tests with
TF_GLM5_MODEL set.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01FaooCnQeKYApFByWS3Y7gz
(cherry picked from commit ca6c4bd)
- README: the model row (182 GB, 256 GB Mac), what the checkpoint needs (MLX 0.32.2 or later on a 256 GB Mac),
  the M3 Ultra speeds, the --mtp-drafts default, the kernel folder.
- RUNBOOK: the pull, and the MLX version to install.
- docs/recipes/glm-5.3-flash.md: an Apple Silicon (MLX) section after the DGX Spark recipe: what decides the
  speed, what paid, speeds and fixed depths, where the time goes, tried and rejected, traps, exactness, limits.
- The recipe book lists it among the Mac families.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01FaooCnQeKYApFByWS3Y7gz
(cherry picked from commit 0834afd)
The serial engine is gone in 0.3.4; glm5_next now declares LANES = True and its runtime speaks
engine.lane_family's contract, as Flash Next does: exact_width and window_costs measured at load
(check_windows), speculate/settle/unspeculate for the MTP head with chained drafts kept on the GPU,
one-step-ahead rounds for the serial reference (gpu_tokens), and engine_settings for the row cap.
The engine's own cost-based depth rule replaces the runtime's depth_for. Tests drive LaneEngine.
…5_next

check() no longer refuses Mia's EXL3 checkpoint on a Mac itself (require_readable does, through
QUANT_METHODS), so the CUDA experiment's check runs the same everywhere; the hub test takes a
family's own kernel_version prefix.
…-5.3-Flash) — layouts.py name map, fused conv, absorbed embed_q/unembed_out, mtp.0 head with bf16 eh_proj, mixed-bit tensors (QSplit stacks, per-row projections), lossless bf16 for fp32 mixes/routers; tests on a converted twin

(cherry picked from commit a1c345c76c069ac0d9b45cf7b60e3f50948368d7)
…e MTP head on the loading thread (a lazy load first evaluated in a request thread raised 'no Stream(cpu, 0)')

(cherry picked from commit 27f83095451166931eaf778cb0f6f3a0cf2e30b1)
…quad_rows) with MLX 0.32.2's one-row qmv_fast and qmv_quad loops, an 8-bit shared expert in the fused MoE, an opt-in 8-bit f_b/g_b fold in the KDA kernel; tests at the abliterated checkpoint's widths

(cherry picked from commit d9285042ed52213a27fb0793af2c46598393ed21)
…t, a bare <think> closed when thinking is off, TF_GLM5_SPLIT_SHARED, the MTP head reads the normed row by default

From kingjamez's test of PR ashhart#9 on an M5 Ultra (256 GB, MLX 0.32.2; 87.6 tok/s greedy drafted, 68.8 serial,
12 of 12 prompts drafted == "draft": false):

- MLX runs fp32 matmuls as TF32 on M5-generation GPUs by default (median relative error 4e-4 against 3e-8), so
  prefill (MLX's hc_expand) and decode (the row kernels' sequential FMA order) disagreed in the last bf16 bit on
  ~11% of stream values. tensorfold/__init__.py sets MLX_ENABLE_TF32=0 before mlx loads; an explicit value wins.
- GLM-5.3's chat template ignores enable_thinking and always ends the prompt on <|assistant|><think>, so with
  thinking off the model reasoned anyway (99 tokens against 20) and the reasoning landed in content. The server
  closes a trailing bare <think> as the template's own no-reasoning turn (<think></think>); templates that honour
  the switch never end on a bare <think>. His unit test is included.
- TF_GLM5_SPLIT_SHARED=0 combines the shared expert with the router (split stays the default: 3% faster for a
  lone 1-row MoE layer, 2.5% slower end to end on the M5).
- The MTP head reads the final-normed row by default (TF_GLM_MTP_INPUT=normed; raw restores the streams' mean;
  TF_GLM_MTP_NORMED=0/1 still works): 78.8 -> 79.8% first-draft acceptance and 86.9 -> 87.9 tok/s on the M5,
  61-76 -> 66-78% and +0.5 tok/s on the M3 Ultra. Drafts only, so exactness is unchanged either way.

Not folded: VERIFY_MS_M5 and the depth_for table — 0.3.4 dropped depth_for; the lane engine now measures each
window's cost at load and picks the depth from those, so his M5 timings are read off the machine itself.

Co-authored-by: kingjamez <[email protected]>
…TP row and the absorbed prefill move out of Next
@chadhurley25075-png

Copy link
Copy Markdown
Contributor Author

kingjamez — thank you. This is the best kind of review: three findings, each with the measurement that proves it, and a patch that applied almost as written. I folded it into the branch (now on 0.3.4.1) and credited you in the commit and the PR body.

What went in, from your comment:

  • MLX_ENABLE_TF32=0 at import (tensorfold/__init__.py, before mlx loads; an explicit environment value wins). Your diagnosis that it is MLX's fp32 matmul rather than the kernel is the part I would not have found without an M5 in the house — thank you for that especially. It also explains why the prefill-vs-decode bit difference is a fixed hazard on M5 and not on M3.
  • Closing a bare <think> when thinking is off (_close_open_think in server/app.py), with your test file verbatim. You are right that GLM-5.3's template has no switch at all; 99 tokens of reasoning landing in content is exactly what we saw on the seats before this.
  • TF_GLM5_SPLIT_SHARED as an override, split kept as the default, your 20.7 vs 21.2 ms round in the comment.
  • MTP head reads the normed row by default. I had it in as an off-by-default switch (TF_GLM_MTP_NORMED) because on the M3 Ultra it moved speed by only +0.5 tok/s; your +1.0 tok/s and +1.0 point of acceptance on the M5 point the same way, so TF_GLM_MTP_INPUT=normed is the default now and raw restores the streams' mean (the old name still works).

What I did not fold, and why: VERIFY_MS_M5 and the depth_for table. 0.3.4 removed depth_for — the lane engine now times each window width on the real weights at load (check_windows) and picks the chain depth from those measured costs and the stream's recent acceptance, so your 20.7 / 26.8 / 33.5 / 42.0 / 49.1 ms rounds are read off the machine rather than tabled. If you see the depth rule choose worse than your fixed table did on the M5 (chat at depth 1 87.0 vs 82.3 at depth 2), that would be worth a line here and I will chase it.

Measured today on our M3 Ultra (60-core, S4) with everything folded: 15/15 drafted == "draft": false, 58.9 (glm_exact harness) / 57.6 (200-token mark, 2 passes) tok/s greedy drafted (48.8 serial), full suite 392 passed / 71 skipped. Your 87.6 / 68.8 on the M5 Ultra is in the PR's table with your name on it.

Two things still open on our side that your machine would answer better than ours: (1) does the 0.3.4.1 grid prefill hold resumed == fresh for you at 8K / 32K on the M5 with TF32 off — on the M3 it does by construction now, but the M5 is where the bits used to differ; (2) whether the absorbed-latent prefill in the stacked PR is flat with context on the M5 the way it is on the M3 (336 / 333 / 307 tok/s at 10K / 35K / 103K). No obligation — you have already given this PR more than its share.

— Chad

@chadhurley25075-png

Copy link
Copy Markdown
Contributor Author

YJesus — thank you for asking this precisely; it is the right question, and the honest answer when you asked was "no, the kernels were 4-bit/g64 only." As of this push the answer is yes for the layout and the widths that checkpoint uses, validated on a sibling checkpoint, not yet on that exact one.

What the branch does now:

  • families/glm5_next/layouts.py reads the mlx-lm / oMLX converted layout (the one Vontra/GLM-5.3-Flash-MLX-oQ4-MTP and grant-ai's abliterated conversion share): fused conv1d, forget_gate.*, the absorbed embed_q / unembed_out pair instead of kv_b_proj, mtp.0.* with a bf16 eh_proj, the vision tower skipped, and the per-tensor quantization overrides from config.json.
  • Mixed stacks stay as separate parts (QSplit) and each part runs at its own width. The row kernels grew 8-, 6- and 5-bit qmv_rows / expert_qmv / qmv_quad_rows variants transcribed from MLX 0.32.2's one-row qmv_fast / qmv_quad loops (same expression shapes, so a row in a window gets MLX's one-row bits), and the fused MoE takes an 8-bit shared expert beside 4-bit routed experts. So the overridden modules take their own row-exact paths rather than the qmv_wide MLX would use for M ≥ 2 rows — which is exactly the thing you expected them to need.
  • Not folded into the fused path: an 8-bit f_b / g_b inside the KDA kernel exists but is opt-in (TF_GLM5_KDA_BITS8=1), because on the checkpoint we tested the kernel's recurrent state differs from the ops path by 1 ulp and would move the serial reference; those two small projections run through MLX ops instead, exact by construction.

What we validated it on: grant-ai's abliterated mixed-bit GLM-5.3-Flash on an M3 Ultra 256 GB — routed experts 4-bit, attention / shared experts / lm_head 8-bit, 5/6-bit in a handful of layers and the MTP block, 554 per-tensor overrides, the same count the oQ4 card lists, which is what makes me think the two conversions came off the same recipe. Results: load-time rows_match_serial passes on the full model, drafted replies byte-identical to "draft": false (5/5 in our kit, 41 GPU tests over every width × 2..32 rows against MLX's one-row loop), decode 36.8 → 46.3 tok/s once the 8-bit tensors took the fused path, context 1,048,576.

What we have not done: loaded Vontra/GLM-5.3-Flash-MLX-oQ4-MTP itself. If its 554 overrides sit on the same tensors at the same widths (the loader reads them from config.json, so it should just work), it should load and pass check_windows unchanged — but I would rather say "should" than claim it. Since your machine is the same class as our second test box, your offer is exactly the test this needs: tensorfold serve <oQ4 dir> --context 131072 and watch for the [glm5] exact window N rows line at load (N ≥ 2 means the multi-row path reproduced one-row bits on your weights), then a drafted vs "draft": false pair on a few prompts. If N comes back 1 or a pair differs, the load log's check_report and the checkpoint's quantization block would tell us which tensor's width we missed, and I will add it.

Thank you for offering the machine — that is how this branch got the M5 numbers too.

— Chad

@ashhart

ashhart commented Sep 27, 2026

Copy link
Copy Markdown
Owner

Thanks @chadhurley25075-png for the GLM-5.3-Flash Mac implementation, and @kingjamez for the M5 follow-up. It's integrated and exact on real weights; what's left is a memory decision for 256 GB Macs and a prefill comparison against a standard, so it moves to 0.3.5.1 in the next few days. The PR stays open until then, and you'll both be credited as authors when it lands.

@kingjamez

Copy link
Copy Markdown
Contributor

Thanks for folding those in, Chad. I ran this branch with #39 on top (bfebff3) on the M5 Ultra (256 GB, MLX 0.32.2). Full suite passes: 459 passed, 4 skipped.

1. resumed == fresh with TF32 off: yes, at 8K and 32K. Heads up for anyone repeating it: point the fresh server at an empty --snapshot-dir, otherwise it reloads the on-disk snapshots and resumes anyway.

2. Absorbed prefill on the M5: much flatter, not quite flat.

prompt reference absorbed oMLX, same Mac
16K 830 tok/s 809 666
64K 417 710 693
139K 224 (623 s) 578 (241 s) 673 (207 s)

Drafted == serial 12/12 in both modes, short decode about 85 tok/s either way.

@YJesus: Vontra/GLM-5.3-Flash-MLX-oQ4-MTP loads. The log shows 554 tensors on the 8/6/5-bit kernels and exact window 16 rows. Drafted == serial 12/12, 69.8 tok/s greedy on the M5 (oMLX does 54.1 on the same checkpoint). oMLX needed mlp_layer_types and indexer_types trimmed from 46 to 45 entries to load it; this branch is fine with the trimmed config.

One new issue: decode stays slower after a very long prompt until the server restarts. Short-prompt decode after a single 139K prompt:

build fresh after 139K
reference 85.0 69.2
absorbed 84.8 76.2
absorbed + fix 83.8 84.2

The cause is MLX's freed-buffer cache holding large buffers from the long prefill. It isn't residency (different from #30, which is a one-round stall). Calling mx.clear_cache() after each request fixes it with no cost I could measure. It's a few lines next to the done log in server/app.py, with TF_CLEAR_CACHE_AFTER_REQUEST=0 to turn it off. Happy to open it as a PR against main since it applies to every family.

Also, check_windows on the M5 lands within 2% of the verify costs I measured by hand, so dropping the fixed table was the right call.

@Moutonc

Moutonc commented Sep 28, 2026

Copy link
Copy Markdown

Posted by Claude (Anthropic's AI assistant) on behalf of @Moutonc.

Independent second-machine run of this PR on a Mac Studio M3 Ultra, 256 GB (macOS 27.0, Python
3.12.12, MLX 0.32.2, mlx-lm 0.31.3). Same GPU generation as your bench box but a different memory
configuration, so mostly a reproduction check. It reproduces closely, and GLM-5.3-Flash serves
correctly here.

tensorfold serve <local MLX-4bit-MTP checkpoint> --context 65536 --no-thinking --snapshot-dir none,
no DFlash2 drafter present, so MTP-only drafts. Loaded in 127.4 s, drafts: on — the 16-row
load-time exactness check passes on this machine.

Forward time by window width — your figures against ours:

rows yours (ms) ours (ms)
1 20.7 20.894
2 28.0 28.061
3 36.5 36.478
4 45.8 45.197
8 84.2 83.684
16 159.4 158.662
MTP step 1.28 1.359

Within ~1% at every width.

Tool calling (3 single-shot calls plus a multi-turn agent loop: the model calls run_tests,
receives a failure, fixes its code, calls again, then stops cleanly):

  • 3/3 single-shot, each returning a proper tool_calls array with finish_reason: "tool_calls"
  • agent loop completed: 4 parsed calls, 0 malformed, no raw tool syntax leaked into content

That exercises the GLM <arg_key>/<arg_value> parser this PR adds to server/http.py, which is
shared-code surface rather than family-local, so it seemed worth confirming explicitly.

Coding, for what it's worth: 28/29 on a small suite of five edge-case-heavy problems graded by
hidden pytest assertions (one assertion missed in a TTL-cache problem), 57 s total. Two caveats that
make this weak evidence in both directions — it ran thinking off, and the suite is saturated for
us (two other local engines we test score 29/29 on it), so it mainly demonstrates nothing is
grossly broken rather than ranking anything.

One note that may save someone time: tools/bench_openai.py can't run against a server at
default settings, because its fibonacci-raw prompt is kind: "completion" and with thinking on
the tokens go to reasoning_content while text stays empty (TypeError: ... 'NoneType' and 'float'). --no-thinking works around it. Same thing I mentioned on #30; flagging here only
because it bites when benchmarking this branch too.

Happy to re-run any of the above with different flags, with thinking on, or at longer contexts.

ashhart pushed a commit that referenced this pull request Sep 28, 2026
… lane engine

Pull request #9 by chadhurley25075-png: the same MLX 4-bit checkpoint
(Vontra/GLM-5.3-Flash-MLX-4bit-MTP) on one Mac with 256 GB or more, beside the
CUDA engine, which is unchanged.

- glm5_next/model.py: a forward pass written from the checkpoint layout (four
  hyper-connected streams, 34 KDA and 11 sparse MLA layers, 288-expert MoE).
  Prompt chunks take MLX's kernels; the decode path (up to 16 rows) gives every
  row its one-row bits.
- kernels/glm/flash/v1: qmv_rows for groups of 64, one-launch row kernels for
  the router, the routed experts, the hyper-connection mix, the indexer gate and
  KDA's f_b / g_b; the KDA decode step in one kernel a layer (ported from
  mlx-vlm #2105) and sparse attention reading its chosen keys by index (from
  mlx-vlm #2245); the MoE block in five kernels, a hyper-connection boundary in
  three.
- mtp.py / runtime.py: the checkpoint's MTP layer as the draft head, on the
  lane engine's family rounds: exact_width and window_costs measured at load,
  speculate / settle / unspeculate, one-step-ahead serial rounds. A rejected
  draft's KDA state is rebuilt by replaying the kept rows through the same
  kernel.
- GLM tool calls (<tool_call>NAME<arg_key>..</arg_key><arg_value>..</arg_value>)
  parsed into OpenAI tool_calls.
- Recipe, README, RUNBOOK and THIRD_PARTY_NOTICES (mlx-vlm, oMLX).
- Tests on a small synthetic checkpoint, CPU and Metal.

Adapted by the maintainer to land on release-0.3.5:
- README: 0.3.5's text kept where the pull request extended the old "known
  limit" paragraph; 0.3.5's prefill grid removed that limit.
- The tool-call hunk moved from server/http.py to server/tools.py, where 0.3.5
  keeps the parser, and reads 0.3.5's per-tool schema map instead of its own
  lookup; the test imports it from there.
- The family contract changes 0.3.5 needs (absorb_draft_context's start) follow
  in the next commit.
- The recipe describes the contributor's two Macs by chip and memory (M3 Ultra,
  512 GB and 256 GB).

Rebased onto the 0.3.5 release by the maintainer: the release condensed the README, runbook and recipes, so this commit's edits to them, written for the longer documents, give way to the release's text; a later maintainer commit states GLM's Mac engine in the new format. The third-party notices keep this commit's section.
ashhart pushed a commit that referenced this pull request Sep 28, 2026
…he MTP head reads the normed row

kingjamez's patch from the pull request #9 thread, tested on an M5 Ultra (256 GB, MLX 0.32.2): drafted replies
equal "draft": false on 12 of 12 prompts, 87.6 tok/s greedy against 68.8 serial.

- MLX runs fp32 matmuls as TF32 on M5-generation GPUs (MLX_ENABLE_TF32 defaults on). The row kernels repeat
  MLX's fp32 arithmetic, so the fused hyper-connection kernel and the row-by-row path disagreed in the last bit
  there. With MLX_ENABLE_TF32=0 they agree on every value.
- GLM-5.3's chat template ignores enable_thinking and always ends the prompt with <|assistant|><think>, so with
  thinking off the model still reasoned and its reasoning landed in content. A trailing bare <think> is now
  closed (<think></think>, the template's own turn without reasoning) when thinking is off.
- The MTP head reads the final-normed row, the one the LM head reads: first-draft acceptance 78.8% to 79.8% on
  the M5 Ultra.

Adapted by the maintainer to land on release-0.3.5:
- TF32: the patch set MLX_ENABLE_TF32=0 for every family in tensorfold/__init__.py. Here it is in GLM's
  MLX_ENV, which the CLI applies before MLX starts, so the other families keep the arithmetic they were
  qualified with; tests/conftest.py sets it for the test session.
- The <think> fix sits in server/text.py beside render_prompt_ids, where 0.3.5 renders prompts.
- The rebased pull request had the normed input behind TF_GLM_MTP_NORMED, off. Both testers measured it at
  least as good, so it is the only path and the switch is gone.
- Not taken: the M5 verify-cost table for depth_for (the rebased pull request replaced depth_for with the
  engine's own depth rule on window costs measured at load, which measures an M5 as it is) and the
  TF_GLM5_SPLIT_SHARED override (measured no faster; the split stays).
ashhart pushed a commit that referenced this pull request Sep 28, 2026
From pull request #9 by chadhurley25075-png (its commits after the first
integration): the loader reads the layout mlx_lm.convert and oMLX write
(grant-ai's abliterated conversion, for one) beside the original one.
layouts.py maps either layout's tensor names onto one set of short names
(hyper-connections, the forget gate, the MTP layer as mtp.0). The KDA layer
takes one fused conv over q | k | v, MLA takes the absorbed embed_q /
unembed_out pair in place of kv_b_proj, the MTP head reads an unquantized
bf16 eh_proj (Dense), fp32 router and hyper-connection mixes holding bf16
values go bf16, and projections stacked from differently quantized parts stay
separate calls (QSplit). Stacked switch_mlp experts are read at load, so a
request thread never evaluates a lazy load (the pull request's load fix).
Tests write the synthetic checkpoint in that layout and check it loads,
computes the same function and drafts exactly.

Adapted by the maintainer: moved from the pull request's single model.py into
the split engine (linear.py, kda.py, mla.py, weights.py, mtp.py and has_mtp in
the package); the test imports follow, and its check of the per-head keys and
values is gone with the reference prefill that computed them.
ashhart pushed a commit that referenced this pull request Sep 28, 2026
…ints

From pull request #9 by chadhurley25075-png: MLX's one-row qmv_fast loop at
its other affine widths (5, 6 and 8 bits, groups of 64), so the tensors a
mixed-bit conversion stores at those widths keep one-row bits in a verify
window. qmv_rows and expert_qmv take them where MLX itself would run
qmv_fast (fast_shape: N % 8 == 0 and K whole blocks), qmv_quad_rows takes
8-bit 64- and 128-input matrices, the fused MoE runs an 8-bit (or 5- or
6-bit) shared expert in its own kernels, and the fused KDA step can fold
8-bit f_b / g_b, opt-in through TF_GLM5_KDA_BITS8 because it moves the
serial reference on such a checkpoint. check() says how many tensors take
these kernels. Tests: every width against MLX's one-row call at the shapes
a mixed conversion stores, windows of 2 to 32 rows.

Adapted by the maintainer: the new kernel sources live in widths.py (the
kernels module would pass 600 lines), the MoE changes in moe.py and the
header in fused.py as the split engine has them, the tests call the split
modules and state each test matrix's format. The pull request's
tools/s5_partial_exact.py, a one-off check on its author's machine, is not
included.
ashhart pushed a commit that referenced this pull request Sep 28, 2026
…5.3-Flash recipe

From pull request #9 by chadhurley25075-png: the two on-disk layouts, the
per-tensor overrides mlx-lm's converter writes, the kernels that read those
widths, the numbers measured on grant-ai's abliterated conversion on a
256 GB M3 Ultra, and the absorbed prefill's numbers against the old path.

Adapted by the maintainer: the 0.3.5 release condensed the recipe, so the
pull request's notes are restated briefly in the release's format under an
Apple Silicon heading.
@ashhart

ashhart commented Sep 28, 2026

Copy link
Copy Markdown
Owner

Thank you, @chadhurley25075-png. GLM-5.3-Flash on Apple Silicon is in TensorFold 0.3.6. Your glm5_next family (5d5140e) and the mixed-bit layout, 5/6/8-bit row kernels and recipe (dc207e6, 4bb7786, 1f84d15) shipped under your name. We added shared rounds for concurrent streams, the 85% allowance on 256 GB Macs and one tool-call parser. On an M3 Ultra, GLM now decodes at 1.86-2.08x mlx-vlm with drafted replies byte-identical to serial ones, and processes prompts at or above mlx-vlm from 2k to 32k tokens. I'm closing this because the commits reached main through a rewritten history rather than a merge. You made GLM on a Mac real. Thank you, and we'd love more from you.

Release: https://github.com/ashhart/TensorFold/releases/tag/v0.3.6

@ashhart ashhart closed this Sep 28, 2026
bertholomus referenced this pull request in bertholomus/TensorFold Oct 7, 2026
…uest's "loop_guard"), default off

GitHub #6: a long agentic turn can loop in its reasoning ("OK. / Writing. / Let me write.") to max_tokens and answer
nothing. call_gate.ThinkLoop watches a thinking reply: when, in 3 windows of 1024 reply tokens in a row, fewer than 2 %
of the window's token 8-grams are new (GitHub #9's novelty signal, on token ids), the reply gets the thinking
budget's close (a newline, </think>, a blank line) and goes on to its answer (generate_gated's cut). A decision
on the committed tokens alone; replies that do not loop are untouched. Off by default: TF_LOOP_GUARD=1 makes it the
server's default, "loop_guard": true / false sets it a request. Not under a grammar or a thinking budget.
bertholomus referenced this pull request in bertholomus/TensorFold Oct 7, 2026
sethforprivacy pushed a commit to sethforprivacy/TensorFold that referenced this pull request Oct 14, 2026
…from forwards timed at load; every stream's drafts in one command buffer
sethforprivacy pushed a commit to sethforprivacy/TensorFold that referenced this pull request Oct 14, 2026
…atch-lone

Conflicts: backend.zig keeps both the think import and batch_costs, and both the lone handoff counter and ashhart#9's
serial-drafts and costs fields; flashnext_batch_host.zig's startup line names both the drafts mode and the lone
driver; tensorfold.zig's test root takes both backend.zig and batch_costs.zig.
sethforprivacy pushed a commit to sethforprivacy/TensorFold that referenced this pull request Oct 14, 2026
…atch-sessions

Conflicts: backend.zig keeps the sized-session fields beside ashhart#9's serial-drafts and costs; session.zig keeps moveTo
beside ashhart#9's encodeDrafts and heldDrafts; flashnext_batch_host.zig sets the sized sessions, then times the costs (on
a session too small to time, ashhart#9 serves unpriced), and its startup line lists the sessions and the drafts mode;
tensorfold.zig's test root takes both slots.zig and batch_costs.zig.
swbiggart pushed a commit to swbiggart/TensorFold-upstream that referenced this pull request Oct 20, 2026
…ything new (tp2 ashhart#18)

--loop-guard watched only for an exact cycle of at most eight tokens. A templated reasoning loop, each line fresh
while its token 8-grams recycle, has no such cycle: @Capicua25x saw the guard fire 0 times on 6 such runaways in
production traffic (tp2 ashhart#18). The guard now also counts, in windows of 1,024 reply tokens while the think block is
open, the share of the window's token 8-grams (with the 7 tokens before it) that no earlier window had; that many
windows in a row under 2% close the think block the way a cycle does. This is our Python engine's
call_gate.ThinkLoop (the novelty signal of tp2 ashhart#9, on token ids), next to cycleAt, which stays the first check.

- TENSORFOLD_LOOP_WINDOWS: the dry windows in a row (default 10; 0: exact cycles only). Python's 3 cut a legitimate
  long deliberation in @Capicua25x's traffic; 10 still caught every runaway they captured.
- runtime.loop.novelty: the closing window's share of new grams; the server log says loop=novelty:0.0000.
- Without --loop-guard nothing changes. With it, a reply with an exact cycle closes as before and reports
  runtime.loop.period; only a reply the cycle check misses can close earlier.
- loopCut finds the window end in a round's tokens, so drafted rounds close where single tokens do. As in
  ThinkLoop.cut, only a batch's first window end may fire (rounds are far shorter than a window).

Tests: each window's share equals the Python reference's (a loop of 13, and a three-letter LCG text over 60
windows); the fire points equal the reference's on four sequences at 3 and 10 windows, a token at a time and in
rounds of 7 and 48; a loop of 13 closes thinking through the lane engine, drafted equal to plain.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
(cherry picked from commit 94725fbbf0cb834343e6e6f5f23307a7f4f37bfb)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants