GLM-5.3-Flash EXL3 on 2x DGX Spark with TensorFold
Python
0097: the kept-state count can follow a share of the pool's memory (TF_GLM_CACHE_SHARE_PCT, issue #84)
MiaAI-Labd6571a2a6f59
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b3e52e6..433a221 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -21,6 +21,15 @@ Every change to this recipe, newest first. Each release names the image it serveon it. `GlmTokenizer` and the CUDA server's template both honour it, and every rank reads it with the other `TF_GLM_*`switches. CPU test: `tools/test_effort_tail.py` (`--source-root` the patched `src`; `--expect-stock` shows thedifference on the unpatched source).+- **Kept-state count follows a share of the pool** (patch `0097-glm-kept-entries-share`, issue #84, diagnosed by+ @jdecker76): `TF_GLM_CACHE_ENTRIES` (32) is a count, but each kept state is a reservation of ~45 MiB (KDA recurrent+ state, conv window, DFlash2 window copy; flat in the context length) taken from the pool's budget, so finished+ one-shot conversations pushed live ones out with millions of pool tokens free. `TF_GLM_CACHE_SHARE_PCT` (default 0:+ off) makes the count at least that share of the budget (25: 71 states); the same count sizes the reservation, so the+ start-up estimate is unchanged and the pool shrinks by it. Any count is cut to three quarters of the budget, logged+ (past it the states would own memory the estimate never counted). Every admission also rebuilt an int64 array of+ every kept state's ids to find shared prefixes (112 ms for 32 states of 200k tokens): built once per state now.+ Check: `tools/kept_cap_check.py`.## v1.9.1 (2026-10-08): the spill tier's free-disk floor makes roomdiff --git a/CREDITS.md b/CREDITS.mdindex fd42b47..521996e 100644--- a/CREDITS.md+++ b/CREDITS.md@@ -109,6 +109,9 @@ checkpoint's ShapleyMcg attribution and the drafter's license).- `0077-glm-kept-cap-shared-by-recency` (a new agent run keeps its system prompt's state once the kept-state cap isfull): the diagnosis, and the fix of evicting shared-prefix states by recency only, by[meleesciony](https://github.com/meleesciony) in [issue #75](https://github.com/MiaAI-Lab/GLM-5.3-Flash-EXL3-2x-DGX-Sparks-TensorFold/issues/75); the code is our own.+- `0097-glm-kept-entries-share` (the kept-state count as a share of the pool's memory, `TF_GLM_CACHE_SHARE_PCT`): the+ diagnosis (a count cap against a pool sized in tokens, with the reporter's measured eviction pattern and the 128+ workaround) is by [jdecker76](https://github.com/jdecker76) in [issue #84](https://github.com/MiaAI-Lab/GLM-5.3-Flash-EXL3-2x-DGX-Sparks-TensorFold/issues/84); the code is our own.- `0078-glm-take-over-decide-then-copy` (a fresh conversation after a long one clones only the kept states that stay):by [m-naoki-m](https://github.com/m-naoki-m), also proposed upstream as[TensorFold PR #421](https://github.com/ashhart/TensorFold/pull/421).diff --git a/README.md b/README.mdindex a2acd65..bff6a76 100644--- a/README.md+++ b/README.md@@ -522,7 +522,8 @@ sets a value wins: the environment, then `scripts/local.sh`, then `.env`, then t| `TF_ROCE_WAIT_S` | `300` | seconds a RoCE all-gather waits for the other Spark before it fails (1 to 3600; the patch's own default is 20, which a late peer on long prompts outlasted, issue #54); until the engine is built, each gather first meets the peer in an NCCL barrier, so a long first start (kernels compiling) does not run into it || `TF_GLM_MULTI_WINDOW` | `32`, `64` past 4 requests | with `PARALLEL` above 1, the rows of every request's verify window together in a round (16 to 64 in steps of 8): with more requests at once each one's drafts get fewer of them (8 requests' code: 141.2 / 160.3 / 167.0 tok/s at 32 / 48 / 64 rows); past 32 rows `TF_ROCE_MAX_KB` rises with it (64: 1024) unless you set it. Exact at any size || `TF_GLM_MULTI_LONE` | `0` | `1`: with `PARALLEL` above 1, a request decoding alone runs on the one-stream graphs (+0.6-0.9%), but its move to the pool's first rows evicts other conversations' kept prompts there (issues #12, #13); `0`: on the batched ones |-| `TF_GLM_CACHE_ENTRIES` | `32` | kept prompt states at most (TensorFold's default is 8); past this count a conversation's earlier (superseded) states go first, then the least recently used, however much of the pool is free (patch `0063`, @Alexbob0); shared-prefix states (a system block) go by recency only, so a new run of an agent still finds its system prompt (patch `0077`, issue #75, @meleesciony). An agent request keeps 1 to 3 (issue #17); each costs ~45 MiB at start |+| `TF_GLM_CACHE_ENTRIES` | `32` | kept prompt states at most (TensorFold's default is 8); past this count a conversation's earlier (superseded) states go first, then the least recently used, however much of the pool is free (patch `0063`, @Alexbob0); shared-prefix states (a system block) go by recency only, so a new run of an agent still finds its system prompt (patch `0077`, issue #75, @meleesciony). An agent request keeps 1 to 3 (issue #17); each costs ~45 MiB at start, reserved out of the pool's `KV_POOL_GIB` budget (the pool shrinks by it, the estimate does not change), flat in the context length. Symptom of too few: `/health` `kept_prompts` stuck at the count while `pool_free_tokens` is large (issue #84, @jdecker76); see `TF_GLM_CACHE_SHARE_PCT` |+| `TF_GLM_CACHE_SHARE_PCT` | `0` (off) | make the kept-state count at least this share of the `KV_POOL_GIB` budget (patch `0097`, issue #84 by @jdecker76): `25` is 71 states of ~45 MiB (~3.1 GiB, ~25% fewer pool tokens), so the pool's tokens, not 32 finished one-shot conversations, decide when a live conversation goes. Any count is cut to three quarters of the budget (logged at start): past that the reservation would exceed the estimate. Set the same on every Spark || `TF_GLM_KEPT_BYTES_GIB` | `0` (no cap) | a byte budget for the kept states together (patch `0089`, by Thomas Wade, [ThomasWadeZ](https://github.com/ThomasWadeZ), PR #65): the device memory they own outside the pool (recurrent state, DFlash2 window copies: hundreds of MB each with long contexts); past it states are dropped in the entry cap's order (not written to the spill tier) and freed blocks go back to the driver. The author runs `4`; `kept_bytes` / `kept_bytes_cap` in `/health` || `TF_GLM_KEEP_PER_CHAT` | `0` (no limit) | at most this many of one conversation's own turn-boundary kept states (patch `0089`, PR #65); shared-prefix and mid-prefill states do not count, the older turns are dropped without a spill. The author runs `2`; `kept_mix` in `/health` shows each conversation's count || `TF_GLM_MULTI_WATCHDOG_S` / `TF_GLM_MULTI_WATCHDOG_EXIT` | `300` / `0` | a rank stuck this many seconds in one step prints every thread's stack to its log (`/health`'s `iteration_s` shows how long the current step has run); `EXIT=1`: the server then exits (code 1) instead of waiting, so a supervisor can restart it. Both ranks also check that they received the same message each step, and stop with an error naming it if not |@@ -655,6 +656,7 @@ applied with `patch -p0` in filename order); `start.sh` rebuilds or re-pulls the| Anthropic Messages | `0084-anthropic-messages` | Anthropic's `/v1/messages` (also `/messages`, with `/count_tokens` suffixes), translated to the same chat completion the OpenAI route serves — text and image blocks, `tool_use` / `tool_result`, thinking, `stop_sequences`, `output_config` effort/JSON schema — with Anthropic SSE streaming and bodies capped at 32 MiB (upstream v0.6.3, by [evilpsycho42](https://github.com/evilpsycho42) and [ashhart](https://github.com/ashhart), request bodies by [Jordi Posthumus](https://github.com/JordiPosthumus); backported by [Eduardo Florencio](https://github.com/eduffd)) | Claude Code and the Anthropic SDKs work against the server directly, without a translating proxy || Checked draft candidates | `0092-glm-draft-candidates-checked` | the drafter checks each block pass's candidate ids against the vocabulary; on an id outside it (issue #80: a float's bits read as an id) it logs the value, copies the rows again once the device is idle, and fails only if they are still bad | a rare drafter `IndexError` is retried (and its cause logged) instead of killing a rank || Spill tier | `0088-glm-spill-tier` | kept prompt states written to local disk on every Spark when they leave the pool (early, in the background, past `SPILL_HIGHWATER`) and read back beside decoding streams, also after a clean restart (`SPILL_GIB`, off by default; authored by Robert Wojciechowski, [wojo](https://github.com/wojo), #78) | [Spill tier](#spill-tier-optional) |+| Kept-state count | `0097-glm-kept-entries-share` | `TF_GLM_CACHE_SHARE_PCT` (the kept-state count as a share of the pool's memory; a ceiling at three quarters of it, so the reservation stays inside the estimate) and the kept states' key arrays built once, not at every admission (issue #84, @jdecker76) || Kept-state limits | `0089-glm-kept-state` | `TF_GLM_KEPT_BYTES_GIB` (a byte budget for the kept states, with the freed blocks handed back to the driver) and `TF_GLM_KEEP_PER_CHAT` (a per-conversation quota of turn-boundary states), both off by default; `/health` `kept_bytes`, `kept_mix` (authored by Thomas Wade, [ThomasWadeZ](https://github.com/ThomasWadeZ), #65) | with both at 0, nothing changes || Responses `include` | `0093-responses-include` | `/v1/responses` accepts OpenAI's `include` values and ignores them (reasoning already comes as text, nothing is encrypted); an unknown value or a non-list is still a 400 (issue #73) | the AI SDK's `include: ["reasoning.encrypted_content"]` no longer fails every request || Chunked request bodies | `0094-chunked-request-bodies` | a `Transfer-Encoding: chunked` request body (AI SDK clients, Chatbox, proxies) is read like a `Content-Length` one on the chat, completions, tokenizer and Responses routes and the MLX-style server, each route keeping its own size limit (96 MiB for chat); a refused request's body is consumed so it cannot reach the next one. The reader is `request_body.read_body` from TensorFold's 977f2cc by Jordi Posthumus (@JordiPosthumus), which `0084` adds; this patch uses it at the remaining sites (issues #67, #74) | no dechunking proxy; a validation 400 no longer leaves HTML after the JSON on a keep-alive connection |diff --git a/patches/0097-glm-kept-entries-share.patch b/patches/0097-glm-kept-entries-share.patchnew file mode 100644index 0000000..231e23b--- /dev/null+++ b/patches/0097-glm-kept-entries-share.patch@@ -0,0 +1,109 @@+# Kept prompt states: the count can follow a share of the pool's memory (issue #84, reported by @jdecker76).+#+# TF_GLM_CACHE_ENTRIES is a memory reservation as well as a limit: --parallel reserves ENTRIES x (a KDA recurrent state+# + conv window + the DFlash2 window copy, ~45 MiB at GLM-5.3-Flash's geometry; flat in the context length, the window+# is bounded) out of the budget TF_GLM_CACHE_GIB leaves the pool beyond the window, and the pool takes the rest. 32+# entries are ~1.4 GiB of 12.5, so a pool of millions of free tokens still evicted a live conversation at the 33rd+# state, and an explicit 128 reserved 5.7 GiB.+#+# 1. TF_GLM_CACHE_SHARE_PCT (default 0: off, the count stays TF_GLM_CACHE_ENTRIES): the count is at least that share of+# the pool's budget in states (25: 71 states). The same count sizes the reservation (the pool shrinks by it, the+# start-up estimate does not change) and bounds `kept`, on every rank (the largest rank's state cost decides).+# 2. Any count (explicit or derived) is cut to three quarters of the budget, logged: past that the reservation would+# take memory the estimate never counted (pool beyond the window = 0, states in the reserve).+# 3. Every admission rebuilt an int64 array of every kept state's ids to look for shared prefixes (112 ms for 32 states+# of 200k tokens, before the prefill starts): a state's array is built once, with the state.+#+# Merge order: after 0089 (whose byte budget, TF_GLM_KEPT_BYTES_GIB, bounds the DFlash2 window copies when long).+diff --git tensorfold/families/glm5_next/cuda/engine.py tensorfold/families/glm5_next/cuda/engine.py+--- tensorfold/families/glm5_next/cuda/engine.py++++ tensorfold/families/glm5_next/cuda/engine.py+@@ -195,6 +195,31 @@+ return out[-SHARED_MOST:]++++def kept_entries(configured: int, share_pct: float, budget: int, state: int) -> tuple[int, str]:++ """How many kept prompt states ``--parallel`` reserves memory for and keeps: (count, a note for the log, "" when++ nothing changed).++++ Each kept state owns ``state`` bytes outside the pool (its KDA recurrent state and conv window, the indexer rings'++ tail and the DFlash2 window copy: ~45 MiB), reserved at start out of ``budget`` (what TF_GLM_CACHE_GIB leaves the++ pool beyond the window), so the count is a memory reservation, not only a limit. ``share_pct`` (TF_GLM_CACHE_SHARE_PCT,++ 0: off) makes the count at least that share of the budget -- a pool-sized count, so a pool of millions of free++ tokens is not pushed empty by 32 one-shot conversations. Past three quarters of the budget the count is cut: the++ states would own memory the start-up estimate never counted. Pure arithmetic, the same on every rank."""++++ state = max(1, state)++ n = max(1, configured)++ note = ""++ if share_pct > 0:++ n = max(n, int(budget * min(share_pct, 75.0) / 100 // state))++ note = f"{n} (at least {share_pct:g}% of the {budget / 2 ** 30:.1f} GiB the pool shares, ~{state >> 20} MiB each)"++ ceiling = max(1, int(budget * 0.75) // state)++ if n > ceiling:++ n = ceiling++ note = (f"{n}, not the {configured} asked: they would take more than three quarters of the {budget / 2 ** 30:.1f} "++ f"GiB the pool shares ({state >> 20} MiB each reserved at start)")++ return n, note+++++ def user_opener(model_dir: Path) -> int | None:+ """The id of GLM's ``<|user|>`` role token (the first one ends the system block), or None without a tokenizer."""++@@ -712,10 +737,16 @@+ text = read_config(model_dir)+ g = geometry(text)+ per_token = max(1, -(-(g.bytes_at(capacity + 65536) - g.bytes_at(capacity)) // 65536))+- states = int(os.environ.get("TF_GLM_CACHE_ENTRIES", "8")) * (slot_bytes(text, world, rows=0, rank=rank) // 2 ++- (22 << 20))+ # TF_GLM_DISPLAY_KV_MIB: the display reservation's bytes too, which free memory never counted+ display = display_kv.credit()++ # one kept state's fixed cost outside the pool, the largest of any rank's: every rank derives the same count++ state = max(slot_bytes(text, world, rows=0, rank=r) // 2 + (22 << 20) for r in range(world))++ self.entries, why = kept_entries(int(os.environ.get("TF_GLM_CACHE_ENTRIES", "8")),++ float(os.environ.get("TF_GLM_CACHE_SHARE_PCT", "0") or 0),++ self.cache_bytes + display, state)++ if rank == 0 and why:++ print(f"[tensorfold] kept prompt states: {why}", flush=True)++ states = self.entries * (slot_bytes(text, world, rows=0, rank=rank) // 2 + (22 << 20))+ pool_rows = (capacity + max(0, self.cache_bytes + display - states) // per_token) // ALIGN * ALIGN+ display_rows = pool_rows - (capacity + max(0, self.cache_bytes - states) // per_token) // ALIGN * ALIGN+ if pool_rows < ALIGN:+@@ -832,7 +863,7 @@+ # kept conversations (decode.Snapshot, least recently used first) and the live caches' ids; states and saved rows stay within cache_bytes+ self.cache: list = []+ self.live: list[int] = []+- self.cache_entries = int(os.environ.get("TF_GLM_CACHE_ENTRIES", "8"))++ self.cache_entries = getattr(self, "entries", None) or int(os.environ.get("TF_GLM_CACHE_ENTRIES", "8"))+ self.spill = self._spill_store() if spill is not None and parallel == 1 else None # (multi: its own)+ if parallel > 1:+ from .multi import GlmScheduler, MultiDecoder+diff --git tensorfold/families/glm5_next/cuda/multi.py tensorfold/families/glm5_next/cuda/multi.py+--- tensorfold/families/glm5_next/cuda/multi.py++++ tensorfold/families/glm5_next/cuda/multi.py+@@ -216,6 +216,16 @@+ KEPT_BYTES_CAP = kept_bytes_cap()++++def known_key(c):++ """A kept state's key as an int64 array, converted once: every admission scans all of ``kept`` for the prefix a++ new prompt shares, and rebuilding the array each time cost O(kept states x their tokens) a request."""++++ arr = getattr(c, "key_array", None)++ if arr is None:++ arr = c.key_array = np.asarray(c.key, dtype=np.int64)++ return arr+++++ def cap_victim(kept: list):+ """The kept prompt to drop past TF_GLM_CACHE_ENTRIES (``kept``: least recently used first). An extent's kept+ prompts are prefixes of its rows, so one shorter than another in its extent is an earlier point of that+@@ -861,7 +871,7 @@+ cut = len(hit.ids) if hit is not None else 0+ shared: list[int] = []+ if draft and key is not None and g.shared:+- known = [np.asarray(c.key, dtype=np.int64) for c in self.kept if c.key is not None]++ known = [known_key(c) for c in self.kept if c.key is not None]+ shared = shared_points(key, cut, grid_point(len(prompt), cut, self.grid), self.grid, g.shared, known,+ g.opener)+ sid = self.next_siddiff --git a/scripts/config.sh b/scripts/config.shindex 8c0e7bd..e6af9e6 100644--- a/scripts/config.sh+++ b/scripts/config.sh@@ -207,6 +207,12 @@ fi# or four alternating conversations push each other out (issue #17). Each entry reserves its fixed state (~45 MiB) at# start: 32 takes ~1 GiB more than 8.export TF_GLM_CACHE_ENTRIES="${TF_GLM_CACHE_ENTRIES:-32}"+# TF_GLM_CACHE_SHARE_PCT (patch 0097, off by default; issue #84 by @jdecker76): the count above is also a memory+# reservation (the pool shrinks by ~45 MiB an entry; the estimate is unchanged), so a pool with millions of free tokens+# can still evict a live conversation at the 33rd state. A share makes the count at least that part of KV_POOL_GIB's+# budget: 25 is 71 states, ~3.1 GiB of the 12.5. Any count is cut to 75% of the budget, logged at start. Watch+# /health kept_prompts against pool_free_tokens: kept_prompts pinned at the count with a free pool is this symptom.+export TF_GLM_CACHE_SHARE_PCT="${TF_GLM_CACHE_SHARE_PCT:-0}"# Two more limits on the kept states (patch 0089, both off by default; PR #65 by Thomas Wade): TF_GLM_KEPT_BYTES_GIB# caps the device memory the kept states own outside the pool (their DFlash2 window copies and recurrent state, ~45 MiB# each without a window, hundreds of MB with long ones), together: 0 is no cap, 4 is the author's value; past it thediff --git a/tools/kept_cap_check.py b/tools/kept_cap_check.pynew file mode 100644index 0000000..4e32889--- /dev/null+++ b/tools/kept_cap_check.py@@ -0,0 +1,100 @@+#!/usr/bin/env python3+"""Checks for patch 0097 (the kept-state count follows a share of the pool's memory), run inside the image that+scripts/prepare.sh built:++ docker run --rm --entrypoint python -v "$PWD/tools/kept_cap_check.py:/c.py" tensorfold-glm53:v0.6.0 /c.py++engine.kept_entries' arithmetic (off by default: the configured count, no note; a share of the budget; the three quarter+ceiling that keeps the reservation inside the start-up estimate), and MultiDecoder._keep on the real Pool with a stubbed+snapshot (no GPU or model): the derived count keeps more than 32 states while the pool has room, the default evicts at+32, and the cached key arrays equal the ones built each time. Exit code 1 when a check fails.+"""+import time+from types import SimpleNamespace as NS++import numpy as np+import torch++import tensorfold.families.glm5_next.cuda.decode as D+import tensorfold.families.glm5_next.cuda.multi as M+from tensorfold.families.glm5_next.cuda.engine import kept_entries+from tensorfold.families.glm5_next.cuda.pool import ALIGN, Pool, align_up++MB, GIB = 1 << 20, 1 << 30+fails: list[str] = []+++def check(name: str, ok: bool) -> None:+ print(("ok " if ok else "FAIL ") + name)+ if not ok:+ fails.append(name)+++# -- the count --------------------------------------------------------------------------------------------------------+STATE, BUDGET = 45 * MB, int(12.5 * GIB) # one state's fixed cost; KV_POOL_GIB's budget+check("off: the configured count, no note", kept_entries(32, 0, BUDGET, STATE) == (32, ""))+n, note = kept_entries(32, 25, BUDGET, STATE)+check("25%: a quarter of the budget in states (71 of 45 MiB)", n == 71 and note and n * STATE <= BUDGET * 0.25)+check("never below the configured count", kept_entries(128, 5, BUDGET, STATE)[0] == 128)+check("a share past 75% is read as 75%", kept_entries(32, 100, BUDGET, STATE)[0] == int(BUDGET * 0.75 // STATE))+n, note = kept_entries(400, 0, BUDGET, STATE)+check("an explicit count past 3/4 of the budget is cut (the estimate would not cover it)",+ n == int(BUDGET * 0.75 // STATE) and "three quarters" in note and n * STATE <= BUDGET * 0.75)+check("a small budget still keeps one", kept_entries(32, 0, 10 * MB, STATE)[0] == 1)+check("the same on every rank (pure)", kept_entries(32, 25, BUDGET, STATE) == kept_entries(32, 25, BUDGET, STATE))++# -- _keep with the count ---------------------------------------------------------------------------------------------+def fake_take(e, ids, pending, mtp, drafter):+ return NS(ids=list(ids), rec=torch.zeros(1), conv=torch.zeros(1), pending=None, drafter_rows=None, head=None,+ tail=None, rows=None, nbytes=0, mtp_len=-1)+++D.take_snapshot = fake_take+++def dec(entries):+ m = object.__new__(M.MultiDecoder)+ m.pool = Pool(4000 * ALIGN)+ m.kept, m.lanes, m.partial, m.ops, m.spilled = [], {}, None, [], []+ m.e = NS(size=1, use=lambda st: None)+ m.g = NS(cache_entries=entries)+ m.rank, m.next_kid, m.kept_bytes_cap, m.disk = 0, 0, 0, None+ m._emit = lambda op, p: m.ops.append((op, list(p)))+ m._ctx = lambda lane: None+ return m+++def one_shots(m, count, first=0):+ for i in range(first, first + count):+ x = m.pool.add(i * ALIGN * 2, align_up(64))+ x.kept, x.owner = [], None+ lane = NS(st=None, s=NS(prompt=list(range(i * 1000, i * 1000 + 80))), dflash=False, key=None, images=False,+ extent=x, shared=[], chat=i)+ m._keep(lane, 64, own=True)+++m = dec(32)+one_shots(m, 60)+check("default 32: 60 finished conversations leave 32 states", len(m.kept) == 32)+m = dec(kept_entries(32, 25, BUDGET, STATE)[0])+one_shots(m, 60)+check("25% share: all 60 kept while the pool has room", len(m.kept) == 60 and m.pool.free_rows() > 0)+one_shots(m, 40, first=60)+check("25% share: past 71 the count still bounds the states", len(m.kept) == 71)++# -- the cached key array ---------------------------------------------------------------------------------------------+keys = [list(range(i, i + 200_000)) for i in range(32)]+cs = [NS(key=k) for k in keys]+t0 = time.perf_counter()+fresh = [np.asarray(c.key, dtype=np.int64) for c in cs]+t_fresh = time.perf_counter() - t0+first = [M.known_key(c) for c in cs]+t0 = time.perf_counter()+again = [M.known_key(c) for c in cs]+t_again = time.perf_counter() - t0+check("known_key equals np.asarray(key, int64)", all(np.array_equal(a, b) for a, b in zip(fresh, first)))+check("known_key is built once", all(a is b for a, b in zip(first, again)) and t_again < t_fresh / 50)+print(f" 32 keys of 200k tokens: {t_fresh * 1000:.0f} ms each admission before, {t_again * 1000:.2f} ms now")++print("all passed" if not fails else f"FAILED: {fails}")+raise SystemExit(1 if fails else 0)