Skip to content

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

Python

0089: README rows, config.sh, CHANGELOG, CREDITS for Thomas Wade; tools/kept_state_check.py

MiaAI-Lab1538ec79e76d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 289973a..1055b2a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -49,6 +49,13 @@ Every change to this recipe, newest first. Each release names the image it serve
through a kernel, as the pool's own moves there do). Authored by Robert Wojciechowski
([wojo](https://github.com/wojo), PR #78); credits in `NOTICE` and `CREDITS.md`.
Numbers: README, "Spill tier".
+- **Kept-state limits** (patch `0089-glm-kept-state`; `TF_GLM_KEPT_BYTES_GIB`, `TF_GLM_KEEP_PER_CHAT`; both off by
+ default): a byte budget for the device memory the kept prompt states own outside the pool (past it the entry cap's
+ victim order drops states, rank 0 deciding, and freed blocks go back to the driver once 512 MB has piled up), and a
+ per-conversation quota of turn-boundary states, so one long chat cannot fill the entries alone. States dropped by
+ either limit are not written to the spill tier (`0088`). `/health` gains `kept_bytes`, `kept_bytes_cap` and
+ `kept_mix`. Authored by Thomas Wade ([ThomasWadeZ](https://github.com/ThomasWadeZ), PR #65); the PR's copy-over-cut
+ part is `0071` already and is not included.
## v1.8 (2026-10-06): pictures read once, quoted markers, capacity refusals, and the take-over memory fix
diff --git a/CREDITS.md b/CREDITS.md
index 8efdd28..216c387 100644
--- a/CREDITS.md
+++ b/CREDITS.md
@@ -148,6 +148,10 @@ checkpoint's ShapleyMcg attribution and the drafter's license).
read, private file modes, a per-Spark weights fingerprint and naming a rank whose settings differ are those of the
session tier of [JSpark3](https://github.com/jakejharris/jspark3) v2.0.1 by
[jakejharris](https://github.com/jakejharris). The code is new.
+- `0089-glm-kept-state` (a byte budget for the kept states and a per-conversation quota, `TF_GLM_KEPT_BYTES_GIB` and
+ `TF_GLM_KEEP_PER_CHAT`): authored by Thomas Wade ([ThomasWadeZ](https://github.com/ThomasWadeZ)) in
+ [PR #65](https://github.com/MiaAI-Lab/GLM-5.3-Flash-EXL3-2x-DGX-Sparks-TensorFold/pull/65) (Apache 2.0); rebased
+ onto the current patches, with both limits off by default and their drops kept out of the spill tier, by MiaAI-Lab.
- Every patch, except the parts credited above: by MiaAI-Lab, developed with
[Claude Code](https://claude.com/claude-code), under the Apache License 2.0; the TensorFold code the patches modify or
quote as context stays under TensorFold's licenses (Apache 2.0, and MIT for code written before v0.6.0; see
diff --git a/README.md b/README.md
index 58e80d0..b8c0210 100644
--- a/README.md
+++ b/README.md
@@ -517,6 +517,8 @@ sets a value wins: the environment, then `scripts/local.sh`, then `.env`, then t
| `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_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 |
| `TF_GLM_CLEAR_THINKING` | `0` | `1`: drop earlier turns' reasoning from the prompt, as the checkpoint's template does (agents then prefill the previous turn's tool loop again); a request's `chat_template_kwargs.clear_thinking` wins |
| `TF_GLM_MAX_QUEUED` | unset | admission at saturation (patch `0082`): past the lanes plus this many queued foreground requests, a request is refused with 429 + `Retry-After: 5` instead of queueing; unset queues as every scheduler always has, `0` refuses anything past the lanes (by johnwhited, #48) |
@@ -642,6 +644,7 @@ applied with `patch -p0` in filename order); `start.sh` rebuilds or re-pulls the
| Delivery abort | `0083-tfcap-delivery-abort` | a stream whose delivery callback raises (broken pipe, reset, timeout) ends at once and frees its lane, instead of the exception escaping and the lane leaking until generation ends (by johnwhited, #48) | a client that dies mid-reply no longer holds a lane |
| 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 |
| 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 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 |
| Concurrent fill | `0062-glm-sliced-fill` | a new prompt's chunks run in layer slices (`FILL_BUDGET_MS`) with decode rounds between them, drafted as usual (`FILL_DRAFTS`), both ranks on the same layer boundaries; the chunk's buffers kept between slices, grouped fills, cache moves and cancellation mid-fill; whole forwards when nothing else decodes | with smooth streaming, the other replies' pauses during a 25k-token fill 630-690 ms -> 81-149 ms (table below) |
Concurrent prompt fill and smooth streaming on two Sparks (`PARALLEL=4`, DFlash2, 1,024-row chunks): three 400-token
diff --git a/scripts/config.sh b/scripts/config.sh
index 0abd630..4e81097 100644
--- a/scripts/config.sh
+++ b/scripts/config.sh
@@ -207,6 +207,15 @@ 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}"
+# 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 the
+# least valuable state is dropped (by the same order as the entry count's) and freed blocks go back to the driver.
+# TF_GLM_KEEP_PER_CHAT keeps at most this many of one conversation's own turn-boundary states (the author runs 2; 0 is
+# no limit): one long chat can no longer fill the entries alone. Neither is written to the spill tier when it drops.
+# /health shows kept_bytes, kept_bytes_cap and kept_mix.
+export TF_GLM_KEPT_BYTES_GIB="${TF_GLM_KEPT_BYTES_GIB:-0}"
+export TF_GLM_KEEP_PER_CHAT="${TF_GLM_KEEP_PER_CHAT:-0}"
# Earlier turns keep their reasoning in the prompt (patch 0060), as in zai-org's current template. 1: drop it, as the
# checkpoint's template does; agents then prefill the previous turn's tool loop again at each new user message.
export TF_GLM_CLEAR_THINKING="${TF_GLM_CLEAR_THINKING:-0}"
diff --git a/tools/kept_state_check.py b/tools/kept_state_check.py
new file mode 100644
index 0000000..459ec66
--- /dev/null
+++ b/tools/kept_state_check.py
@@ -0,0 +1,114 @@
+#!/usr/bin/env python3
+"""Checks for patch 0089 (the kept-state byte budget and per-conversation quota), run inside the image that
+scripts/prepare.sh built:
+
+ docker run --rm --entrypoint python -v "$PWD/tools/kept_state_check.py:/c.py" tensorfold-glm53:v0.6.0 /c.py
+
+MultiDecoder's _keep, _drop and _evict on the real Pool with a stubbed snapshot (no GPU or model): both limits off by
+default (nothing dropped, nothing spilled), the quota keeping a conversation's newest states and not counting shared
+ones, the byte budget evicting to its size with one EVICT op a victim, neither limit writing to the spill tier while the
+entry cap's drops do. Exit code 1 when a check fails.
+"""
+from types import SimpleNamespace as NS
+
+import torch
+
+import tensorfold.families.glm5_next.cuda.multi as M
+import tensorfold.families.glm5_next.cuda.decode as D
+from tensorfold.families.glm5_next.cuda.pool import ALIGN, Pool, align_up
+
+MB = 1 << 20
+fails: list[str] = []
+
+
+def check(name: str, ok: bool) -> None:
+ print(("ok " if ok else "FAIL ") + name)
+ if not ok:
+ fails.append(name)
+
+
+def fake_take(e, ids, pending, mtp, drafter):
+ return NS(ids=list(ids), rec=torch.zeros(e.size * MB // 4, dtype=torch.float32), 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
+nx = [0]
+
+
+def dec(entries=32, size=100, cap=0):
+ m = object.__new__(M.MultiDecoder)
+ m.pool = Pool(1000 * ALIGN)
+ m.kept, m.lanes, m.partial, m.ops, m.spilled = [], {}, None, [], []
+ m.e = NS(size=size, use=lambda st: None)
+ m.g = NS(cache_entries=entries)
+ m.rank, m.next_kid, m.kept_bytes_cap = 0, 0, cap
+ m.disk = object() # the spill tier "on": _spill records what it is asked
+ m._spill = lambda c, leaving=False, keep=frozenset(): m.spilled.append(c.kid) or True
+ m._emit = lambda op, p: m.ops.append((op, list(p)))
+ m._ctx = lambda lane: None
+ return m
+
+
+def lane(m, chat, toks):
+ x = m.pool.add(nx[0] * ALIGN * 2, align_up(toks))
+ nx[0] += 1
+ x.kept, x.owner = [], None
+ return NS(st=None, s=NS(prompt=list(range(chat * 1000, chat * 1000 + toks + 10))), dflash=False, key=None,
+ images=False, extent=x, shared=[], chat=chat)
+
+
+check("defaults: no quota, no byte cap", M.KEEP_PER_CHAT == 0 and M.KEPT_BYTES_CAP == 0)
+
+m = dec()
+l = lane(m, 1, 64)
+for i in range(6):
+ m._keep(l, 64 + i, own=True)
+check("off: all six of one chat kept, nothing evicted or spilled", len(m.kept) == 6 and not m.ops and not m.spilled)
+
+M.KEEP_PER_CHAT = 2
+m = dec()
+l = lane(m, 1, 64)
+for i in range(5):
+ m._keep(l, 64 + i, own=True)
+check("quota keeps 2 own states of one chat", sum(1 for c in m.kept if c.own) == 2)
+check("quota keeps the newest", sorted(len(c.ids) for c in m.kept) == [67, 68])
+check("quota drops are not spilled", not m.spilled)
+sh = lane(m, 2, 64)
+m._keep(sh, 64)
+m._keep(sh, 66)
+check("shared states are not counted", sum(1 for c in m.kept if not c.own) == 2)
+a, b = lane(m, 3, 64), lane(m, 4, 64)
+for i in range(3):
+ m._keep(a, 64 + i, own=True)
+ m._keep(b, 64 + i, own=True)
+check("two chats each hold their own quota", sum(1 for c in m.kept if c.own and c.chat == 3) == 2
+ and sum(1 for c in m.kept if c.own and c.chat == 4) == 2)
+
+M.KEEP_PER_CHAT = 0
+m = dec(cap=250 * MB)
+ls = [lane(m, i, 64) for i in range(6)]
+for i, l in enumerate(ls):
+ m._keep(l, 64 + i)
+check("byte cap: evicts down to 250 MB (2 states of 100 MB)", m._held_bytes() <= 250 * MB and len(m.kept) == 2)
+check("byte cap: one EVICT op a victim, marked no-spill",
+ [p[1] for op, p in m.ops if op == M.EVICT] == [0, 0, 0, 0])
+check("byte cap: nothing spilled", not m.spilled)
+
+m = dec(entries=2)
+ls = [lane(m, i, 64) for i in range(4)]
+for i, l in enumerate(ls):
+ m._keep(l, 64 + i)
+check("entry cap: still spills what it drops", len(m.kept) == 2 and len(m.spilled) == 2)
+
+# rank 1 applies the EVICT: the same drop, no spill
+r = dec(cap=250 * MB)
+r.rank = 1
+x = lane(r, 9, 64)
+r._keep(x, 64)
+c = r.kept[0]
+r._drop(c, spill=False)
+check("rank 1: EVICT without spill drops and does not write", not r.kept and not r.spilled)
+
+print("all passed" if not fails else f"FAILED: {fails}")
+raise SystemExit(1 if fails else 0)