GLM-5.3-Flash EXL3 on 2x DGX Spark with TensorFold
Python
Patch 0119: a conversation keeps its id across a rewind or a resume from disk (TF_GLM_KEEP_PER_CHAT counts it once)
Robert Wojciechowski008732fab572
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 38488f9..80bd612 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -105,6 +105,19 @@ Every change to this recipe, newest first. Each release names the image it serve- an expected value starting with `<think>`: 9 -> 10;- echo `<think>hello</think> world`: 0 -> 5.- **CPU check:** `tools/reply_ids_check.py`.+- **A rewound conversation keeps its id** (patch `0119-glm-chat-continued`, by+ Robert Wojciechowski ([wojo](https://github.com/wojo) on GitHub, [@rwojo](https://x.com/rwojo) on X)): patch+ `0089` gave a stream a new conversation id unless it resumed from one of that conversation's own turn states, so a+ client rewinding before the kept turns (issue #104, @danielbanu), a state read back from the spill tier, or dropped+ states split one session into several ids, and `TF_GLM_KEEP_PER_CHAT` counted each piece on its own: one session+ held more states than the quota. Now the stream joins the conversation whose own kept state its prompt repeats past+ that conversation's first prompt and the first 32 tokens of the reply to it. On two Sparks (PARALLEL=8,+ `TF_GLM_KEEP_PER_CHAT=2`, `TF_GLM_CACHE_ENTRIES=16`), a ~110k-token session rewinding three rounds every fifth of 16+ while six chats fill the cache: before, its states went under 3 ids; after, 1, holding 2 states as asked; replies+ the same drafted and with `draft:false`. New counters `chats_continued`, `chats_continued_prefill_tokens` (`/health`,+ `/metrics`) and a rank-0 log line for one prefilling 4096 tokens or more, with where the prompt left the kept state+ and what it resumed from. CPU check: `tools/chat_continued_check.py` (fails on the unpatched engine).+- **A prompt that fills beside other replies, ~10-14% sooner** (`FILL_ROWS`, by [BadAd84](https://github.com/BadAd84)):while other requests decode, a new prompt filled in 1,024-row chunks (TensorFold's `TF_GLM_FILL_ROWS` default),half the 2,048-row prompt chunk whose buffers the engine keeps anyway. `scripts/config.sh` now sets 2,048 (at@@ -266,7 +279,8 @@ Image: `v0.6.0-ff5dffc865d3` (`sha256:20275b2be818635a9c711d80a177477488d2c75cad50 GiB floor, a 20,469-token prompt is written (0.21 GiB), read back after a restart (prefill 10.96 -> 0.21 s, restore29 ms) and the needle answer is unchanged; with defaults, the smoke test, `tools/anthropiccheck.py` and `tools/toolcheck.py` pass.-- **Spill tier: the free-disk floor makes room** (patch `0088-glm-spill-tier`, #78 by Robert Wojciechowski, @wojo):+- **Spill tier: the free-disk floor makes room** (patch `0088-glm-spill-tier`, #78 by+ Robert Wojciechowski ([wojo](https://github.com/wojo) on GitHub, [@rwojo](https://x.com/rwojo) on X)):a write that would leave less than `SPILL_MIN_FREE_GIB` free now drops the oldest spilled files first, and isskipped only when that cannot make the room (before: always skipped). Writes still queued count as written. Offunless `SPILL_GIB` is set.@@ -369,8 +383,9 @@ contributors' measurements are in the PRs.restore reads on a background thread while other streams keep decoding. Every read is checked against per-blockCRC-32s, and the files are private to you. Prompts with images or video are stored under their pictures'content (`PARALLEL` above 1). It works beside `DISPLAY_KV_MIB` (rows in the display reservation go to and from disk- 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`.+ through a kernel, as the pool's own moves there do). Authored by+ Robert Wojciechowski ([wojo](https://github.com/wojo) on GitHub, [@rwojo](https://x.com/rwojo) on X), 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 bydefault): a byte budget for the device memory the kept prompt states own outside the pool (past it the entry cap'sdiff --git a/CREDITS.md b/CREDITS.mdindex e361a39..59c1513 100644--- a/CREDITS.md+++ b/CREDITS.md@@ -148,6 +148,9 @@ checkpoint's ShapleyMcg attribution and the drafter's license).[kindling spark-os](https://github.com/kindlingai/kindling-spark-os) by Matt Mastracci (Kindling AI). Nothing ofdispram ships here: the ranks import the host's client (`python/dispram.py`, GPL-3.0 with a bundling exception)mounted read-only at run time and talk to `dispramd` (AGPL-3.0) over its socket.+- `0119-glm-chat-continued` (a conversation keeps its id across a rewind or a resume from disk, for patch `0089`'s+ quota by Thomas Wade; issue #104 by [danielbanu](https://github.com/danielbanu)): by+ Robert Wojciechowski ([wojo](https://github.com/wojo) on GitHub, [@rwojo](https://x.com/rwojo) on X).- `0098-glm-mmap-uploads` (the drafter's and the vision tower's tensors copied out of the safetensors mmap beforethey go to the GPU: kindling spark-os's 64 KiB-page kernel): by [BadAd84](https://github.com/BadAd84).- `0090-glm-expert-launch-order` (`TF_GLM_EXL3_DEC_ORDER`: the launch order of the expert decode kernel's blocks): by@@ -156,8 +159,9 @@ checkpoint's ShapleyMcg attribution and the drafter's license).- `docs/hermes-agent.md`, `tools/hermes_benchmark.py` and `tests/test_hermes_benchmark.py` (the Hermes Agent custom-endpointguide and the synthetic speed harness with its tests): by Steve Darlow ([kerpopule](https://github.com/kerpopule)),in [PR #52](https://github.com/MiaAI-Lab/GLM-5.3-Flash-EXL3-2x-DGX-Sparks-TensorFold/pull/52).-- `0088-glm-spill-tier` (kept prompt states on local disk, `SPILL_GIB`): authored by Robert Wojciechowski- ([wojo](https://github.com/wojo)): `tensorfold/cuda/spill.py` and its hooks in the GLM engine, `multi.py` and the+- `0088-glm-spill-tier` (kept prompt states on local disk, `SPILL_GIB`): authored by+ Robert Wojciechowski ([wojo](https://github.com/wojo) on GitHub, [@rwojo](https://x.com/rwojo) on X):+ `tensorfold/cuda/spill.py` and its hooks in the GLM engine, `multi.py` and theserver, in [PR #78](https://github.com/MiaAI-Lab/GLM-5.3-Flash-EXL3-2x-DGX-Sparks-TensorFold/pull/78). What itbuilds on, by its authors: the idea of persisting session state on NVMe per rank was proposed in MiaAI-Lab'sGLM-5.3-Flash vLLM kit ([pull request #232](https://github.com/MiaAI-Lab/GLM-5.3-Flash-EXL3-2x-DGX-Sparks/pull/232)diff --git a/NOTICE b/NOTICEindex 86fae77..869e030 100644--- a/NOTICE+++ b/NOTICE@@ -97,7 +97,7 @@ glm53-tensorfold-spark(https://github.com/ashhart/TensorFold/pull/218, Apache-2.0), applied to v0.6.0 unchanged:tensorfold/server/cancellation.py's client-gone check asks poll() instead of select().patches/0088-glm-spill-tier.patch (tensorfold/cuda/spill.py and its hooks in the GLM engine and multi.py) is authored- by Robert Wojciechowski (wojo, https://github.com/wojo). Its multi-rank design (an NVMe tier for kept prompt states,+ by Robert Wojciechowski (GitHub @wojo, X @rwojo). Its multi-rank design (an NVMe tier for kept prompt states,one directory a rank, rank 0 deciding, an agreement on every read, a reconcile at start) is that of patch 0250 ofthat project, authored by Jay Leaton; the code is a new implementation for this recipe's pool and kept prompts.diff --git a/README.md b/README.mdindex 295d3d2..91be899 100644--- a/README.md+++ b/README.md@@ -14,7 +14,7 @@Serve **GLM-5.3-Flash** from two NVIDIA DGX Sparks (GB10, 128 GB each, linked by their ConnectX-7 ports) through anOpenAI-compatible API, with **4 concurrent requests**, the model's full **1,048,576-token context** and **image andvideo input**. It runs [TensorFold](https://github.com/ashhart/TensorFold) v0.6.0 on both Sparks (one rank on each)-in NVIDIA's PyTorch container, plus 96 patches (65 of v1.4, 3 for 3 Sparks, experimental, 1 for up to 8 requests at once, 1 for stopping serial requests, 5 of v1.6: a shared system prompt keeps each conversation's history, the display reservation in the pool and the pool compacting before it evicts, by [ezoushen](https://github.com/ezoushen); queued requests whose client left dropped at once, by [desy0305](https://github.com/desy0305); `<|assistant|>` ending a reply; 1 of v1.7.1: a new agent run keeps its system prompt's state once the kept-state cap is full, diagnosed and the fix proposed 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); 1 fix since v1.7.1: a fresh conversation after a long one no longer runs out of memory; 5 of v1.8: pictures read once and quoted media markers, by [ThomasWadeZ](https://github.com/ThomasWadeZ), capacity refusals, by [johnwhited](https://github.com/johnwhited); and 12 of v1.9: the Anthropic Messages API, backported by [Eduardo Florencio](https://github.com/eduffd) from upstream work by [evilpsycho42](https://github.com/evilpsycho42), [ashhart](https://github.com/ashhart) and [Jordi Posthumus](https://github.com/JordiPosthumus); long-context decode and prefill and the display reservation on kindling spark-os, by [BadAd84](https://github.com/BadAd84); a spill tier for kept prompt states, by [Robert Wojciechowski](https://github.com/wojo); kept-state limits, by [Thomas Wade](https://github.com/ThomasWadeZ); the expert decode launch order, by [Lukasz Raczylo](https://github.com/lukaszraczylo); a loop guard, chunked bodies, Responses `include`, streamed admission and checked draft candidates; and 2 of v1.10: the reasoning-effort line at the prompt's tail, opt-in, reported by [jdecker76](https://github.com/jdecker76) in [issue #93](https://github.com/MiaAI-Lab/GLM-5.3-Flash-EXL3-2x-DGX-Sparks-TensorFold/issues/93); and the kept-state count as a share of the pool, diagnosed 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)): DFlash2 and copy drafts, 4-bit dense weights, an FP8 KV cache,+in NVIDIA's PyTorch container, plus 96 patches (65 of v1.4, 3 for 3 Sparks, experimental, 1 for up to 8 requests at once, 1 for stopping serial requests, 5 of v1.6: a shared system prompt keeps each conversation's history, the display reservation in the pool and the pool compacting before it evicts, by [ezoushen](https://github.com/ezoushen); queued requests whose client left dropped at once, by [desy0305](https://github.com/desy0305); `<|assistant|>` ending a reply; 1 of v1.7.1: a new agent run keeps its system prompt's state once the kept-state cap is full, diagnosed and the fix proposed 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); 1 fix since v1.7.1: a fresh conversation after a long one no longer runs out of memory; 5 of v1.8: pictures read once and quoted media markers, by [ThomasWadeZ](https://github.com/ThomasWadeZ), capacity refusals, by [johnwhited](https://github.com/johnwhited); and 12 of v1.9: the Anthropic Messages API, backported by [Eduardo Florencio](https://github.com/eduffd) from upstream work by [evilpsycho42](https://github.com/evilpsycho42), [ashhart](https://github.com/ashhart) and [Jordi Posthumus](https://github.com/JordiPosthumus); long-context decode and prefill and the display reservation on kindling spark-os, by [BadAd84](https://github.com/BadAd84); a spill tier for kept prompt states, by Robert Wojciechowski ([wojo](https://github.com/wojo) on GitHub, [@rwojo](https://x.com/rwojo) on X); kept-state limits, by [Thomas Wade](https://github.com/ThomasWadeZ); the expert decode launch order, by [Lukasz Raczylo](https://github.com/lukaszraczylo); a loop guard, chunked bodies, Responses `include`, streamed admission and checked draft candidates; and 2 of v1.10: the reasoning-effort line at the prompt's tail, opt-in, reported by [jdecker76](https://github.com/jdecker76) in [issue #93](https://github.com/MiaAI-Lab/GLM-5.3-Flash-EXL3-2x-DGX-Sparks-TensorFold/issues/93); and the kept-state count as a share of the pool, diagnosed 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)): DFlash2 and copy drafts, 4-bit dense weights, an FP8 KV cache,faster prompt kernels, a one-shot RoCE all-gather between the Sparks, several requests over one shared cache pool,vision, tool calling, `/tokenize` and `/metrics`.@@ -331,7 +331,7 @@ The KV pool keeps a few conversations' prompt states (`TF_GLM_CACHE_ENTRIES`, anleaves it, and every one after a restart, costs a full prefill on its next turn (~2 minutes at 200k tokens). With`SPILL_GIB=64` (and `SPILL_DIR`, the same absolute path on every Spark) a kept state that leaves the pool is written tothat directory on each Spark, and a later request that extends it reads it back instead (patch `0088-glm-spill-tier`,-authored by Robert Wojciechowski, [wojo](https://github.com/wojo), in [PR #78](https://github.com/MiaAI-Lab/GLM-5.3-Flash-EXL3-2x-DGX-Sparks-TensorFold/pull/78)).+authored by Robert Wojciechowski ([wojo](https://github.com/wojo) on GitHub, [@rwojo](https://x.com/rwojo) on X), in [PR #78](https://github.com/MiaAI-Lab/GLM-5.3-Flash-EXL3-2x-DGX-Sparks-TensorFold/pull/78)).With `PARALLEL` above 1, past `SPILL_HIGHWATER` (0.70) of the pool the states eviction would take next are writtenearly, in the background, so an eviction frees its rows at once; a clean stop writes what is kept (`SPILL_FLUSH_S`,60 s). A restore reads on a background thread while the other requests keep decoding.@@ -556,7 +556,7 @@ sets a value wins: the environment, then `scripts/local.sh`, then `.env`, then t| `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): on two Sparks at the defaults each state reserves ~91 MiB of a ~7.5 GiB budget, so 32 states already take ~38%: `50` gives ~42 states, the ceiling ~63 (each costs 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_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. A conversation keeps its id when a client rewinds before its kept turns or it resumes from disk (patch `0119`), so the quota counts it once; `chats_continued` in `/health` counts those streams. 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_EXIT_ON_BROKEN` | `0` | `1`: when the concurrent GLM decoder latches an error that leaves the ranks out of step, log its first cause and exit the process with code 1 immediately, so a supervisor can restart both ranks. Independent of the stall watchdog. With `0`, requests still fail, but `/health` reports `ok: false` and `broken` (exception type and reason); `/metrics` exposes `tensorfold_health:ok` as 0. A GPU fault may still require host recovery; use supervisor restart backoff. || `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 |@@ -705,9 +705,10 @@ 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 || 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) |+| 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) on GitHub, [@rwojo](https://x.com/rwojo) on X), #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 |+| Conversation ids | `0119-glm-chat-continued` | a stream that continues its conversation without resuming from that conversation's own turn state (an in-turn rewind before the kept turns, issue #104; a state read back from disk; dropped states) keeps the conversation's id instead of starting a new one, so `TF_GLM_KEEP_PER_CHAT` counts the conversation once; `/health` `chats_continued`, `chats_continued_prefill_tokens`, and a log line for one prefilling 4096 tokens or more, with where it left the kept state (by Robert Wojciechowski ([wojo](https://github.com/wojo) on GitHub, [@rwojo](https://x.com/rwojo) on X)) | with `TF_GLM_KEEP_PER_CHAT=0` (the default) only the counters and the log line || 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 || Broken engine | `0118-glm-broken-health-exit` | `/health` reports `ok: false` with its first broken cause, `/metrics` exposes `tensorfold_health:ok`, and opt-in `TF_GLM_EXIT_ON_BROKEN=1` exits non-zero on the latch | broken state is visible; default process lifetime unchanged || 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/0088-glm-spill-tier.patch b/patches/0088-glm-spill-tier.patchindex 6d05c2a..51097ef 100644--- a/patches/0088-glm-spill-tier.patch+++ b/patches/0088-glm-spill-tier.patch@@ -2,7 +2,8 @@# every rank and are read back beside decoding streams when a request extends them, also after a clean restart. New# tensorfold/cuda/spill.py (no model code), hooks in the one-stream and --parallel paths. With 0072's display span the# rows there go to and from disk through a kernel, as 0072's own moves do (CUDA refuses a memcpy across its two-# registrations); a request 0073 cancels leaves the tier's read bookkeeping too. By @wojo, Apache-2.0.+# registrations); a request 0073 cancels leaves the tier's read bookkeeping too.+# By Robert Wojciechowski (GitHub @wojo, X @rwojo), Apache-2.0.diff --git tensorfold/cli.py tensorfold/cli.pyindex c2e3768..c57336d 100644--- tensorfold/cli.py@@ -142,7 +143,7 @@ index 0000000..c7a8eb8+read is used only when it worked on every rank, and at start only entries every rank holds are kept, in rank 0's+order.+-+Credits: wojo (Robert Wojciechowski, https://github.com/wojo) wrote this module and its hooks. The idea of NVMe session++Credits: Robert Wojciechowski (GitHub @wojo, X @rwojo) wrote this module and its hooks. The idea of NVMe session+state per rank was proposed in MiaAI-Lab's GLM-5.3-Flash vLLM kit pull request #232, authored by gabewillen (the idea+only, no code). The multi-rank design (one directory a rank, rank 0 deciding, an agreement on every read, a reconcile+at start) is that of patch 0250 of jayleaton/glm53-tensorfold-spark, authored by Jay Leaton (Apache-2.0). The filediff --git a/patches/0119-glm-chat-continued.patch b/patches/0119-glm-chat-continued.patchnew file mode 100644index 0000000..a5c2e1a--- /dev/null+++ b/patches/0119-glm-chat-continued.patch@@ -0,0 +1,150 @@+# Kept states: a stream that continues its conversation without resuming from that conversation's own turn state keeps+# the conversation id (patch 0089 minted a new one), so TF_GLM_KEEP_PER_CHAT counts the conversation once. That+# happens when a client rewinds before the kept turns (an edit, a regenerate, a tool loop re-sent: issue #104), when a+# state comes back from the spill tier, or when the conversation's states were dropped. The conversation is the one+# whose own kept state the prompt repeats past its first prompt and the first 32 tokens of the reply to it, ids no other+# conversation wrote. /health and /metrics count these streams and their prefill (chats_continued,+# chats_continued_prefill_tokens); rank 0 logs one prefilling 4096 tokens or more, with where the prompt left the kept+# state and what it resumed from. Builds on 0089-glm-kept-state (Thomas Wade, PR #65).+# By Robert Wojciechowski (GitHub @wojo, X @rwojo). Apache-2.0.+diff --git tensorfold/families/glm5_next/cuda/multi.py tensorfold/families/glm5_next/cuda/multi.py+index 06f33e7..9eccfff 100644+--- tensorfold/families/glm5_next/cuda/multi.py++++ tensorfold/families/glm5_next/cuda/multi.py+@@ -249,6 +249,44 @@ def cap_victim(kept: list):+ return kept[0]++++# a conversation's first reply: the tokens of it a later prompt must repeat to continue that conversation++CHAT_MATCH = 32++# a continued conversation's prefill from this many tokens on is logged (rank 0)++CHAT_LOG_TOKENS = 4096++++++def continued_chat(kept: list, prompt: list[int], roots: dict[int, int]):++ """The kept state of the conversation a prompt continues when it did not resume from one of that conversation's own++ turn states (it fell back to a shared prefix, to a state read back from disk or a paused prefill, or to nothing):++ the most recently used own state whose ids repeat the prompt past its conversation's first prompt (``roots``: its++ length) and the first ``CHAT_MATCH`` tokens of the reply to it. Only that conversation wrote those, so a second++ conversation behind the same system prompt and opening message does not join it, and an edit of the first message++ starts a new one. None when there is none. Deterministic in ``kept``'s order, so both ranks agree."""++++ for c in reversed(kept):++ chat = getattr(c, "chat", 0)++ if not getattr(c, "own", False) or chat not in roots or getattr(c, "images", False):++ continue++ n = roots[chat] + CHAT_MATCH++ if len(c.ids) >= n and len(prompt) >= n and c.ids[n - 1] == prompt[n - 1] and c.ids[:n] == prompt[:n]:++ return c++ return None++++++def common_prefix(a: list[int], b: list[int]) -> int:++ """The tokens two id lists share from the start."""++++ n = min(len(a), len(b))++ lo, hi = 0, n # a[:lo] == b[:lo]; the first difference is before hi++ while lo < hi:++ mid = (lo + hi + 1) // 2++ if a[lo:mid] == b[lo:mid]:++ lo = mid++ else:++ hi = mid - 1++ return lo+++++ def multi_code(code: list[int], dflash: bool, dflash_policy: list[int]) -> list[int]:+ """A request's policy code under --parallel: serial stays serial; auto becomes TF_GLM_DFLASH_POLICY; an MTP+ policy its DFlash2 twin; without a draft model, serial."""+@@ -562,6 +600,8 @@ class MultiDecoder:+ self.disk = self._spill_store() # --spill-gib: the disk tier for kept prompts (cuda/spill.py)+ self.next_sid = self.next_kid = self.next_order = 0+ self.next_chat = 0++ self.chat_roots: dict[int, int] = {} # each conversation's first prompt length (continued_chat)++ self.chats_continued = self.chats_continued_prefill = 0+ self.outbox: list[int] = []+ self.idle = True+ self.broken: Exception | None = None+@@ -591,6 +631,10 @@ class MultiDecoder:+ "paused": sum(l.decoding and l.paused for l in lanes)},+ "pool_tokens": self.pool.rows, "pool_free_tokens": self.pool.free_rows(),+ "kept_prompts": len(self.kept),++ # streams that continued their conversation without resuming from its own turn state (a rewind before++ # its kept states, or they were dropped or read back from disk), and the tokens those prefilled++ "chats_continued": self.chats_continued,++ "chats_continued_prefill_tokens": self.chats_continued_prefill,+ "kept_bytes": self._held_bytes(), "kept_bytes_cap": self.kept_bytes_cap,+ # what the slots are holding. own = a conversation's turn-boundary state (capped by+ # TF_GLM_KEEP_PER_CHAT); shared = a shared-prefix point or a mid-prefill pause state (not capped);+@@ -976,13 +1020,24 @@ class MultiDecoder:+ code = a["code"]+ dflash = code[0] >= 10 and self.drafts is not None+ policy = decode_policy(code, g.costs) if code[0] else None+- # the conversation this stream belongs to: the chain it resumed from when that state is a turn's own, else a+- # new one (a shared-prefix state belongs to everyone, so resuming from it starts no chain)++ # the conversation this stream belongs to: the chain it resumed from when that state is a turn's own; else the++ # one whose own state it still repeats past that conversation's first reply (it rewound before its kept turns,++ # or resumed from a shared prefix, from disk or from nothing: continued_chat); else a new one+ if hit is not None and getattr(hit, "own", False) and getattr(hit, "chat", 0):+ chat = hit.chat+ else:+- self.next_chat += 1+- chat = self.next_chat++ # (draft:false never resumes, by design: not a continuation to count, and it keeps no state)++ prior = None if a["images"] or not a["draft"] else continued_chat(self.kept, prompt, self.chat_roots)++ if prior is not None:++ chat = prior.chat++ self._continued(chat, prior, hit, cut, prompt)++ else:++ self.next_chat += 1++ chat = self.next_chat++ self.chat_roots[chat] = len(prompt)++ if len(self.chat_roots) > 4 * max(16, self.g.cache_entries): # conversations no kept state is in++ live = {getattr(c, "chat", 0) for c in self.kept} | {chat}++ self.chat_roots = {k: v for k, v in self.chat_roots.items() if k in live}+ lane = Lane(s, a["sid"], a["slot"], x, st, self.next_order, code, spec, policy, dflash, feed=feed,+ constraint=constraint, images=a["images"], chat=chat)+ if a.get("keyed") is not None: # rank 1 too: its kept states are stored and matched by them+@@ -1021,6 +1076,25 @@ class MultiDecoder:+ lane.t0 = s.started+ self.lanes[lane.sid] = lane+++ def _continued(self, chat: int, prior, hit, cut: int, prompt: list[int]) -> None:++ """Both ranks: a stream continues conversation ``chat`` without resuming from its own turn state (``prior``:++ that conversation's state it repeats; ``hit``: what it resumed from, None for nothing). Counted; rank 0 logs a++ large prefill with where the prompt left the kept state and what it resumed from."""++++ self.chats_continued += 1++ self.chats_continued_prefill += len(prompt) - cut++ if self.rank or len(prompt) - cut < CHAT_LOG_TOKENS:++ return++ source = ("nothing" if hit is None else "a shared prefix" if getattr(hit, "shared", False)++ else "a state that is not a turn's own (read back from disk, or a paused prefill)")++ at = common_prefix(prior.ids, prompt)++ why = (f"it went back to token {at}, before that conversation's newest kept state ({len(prior.ids)} tokens)"++ if at < len(prior.ids) else++ f"its kept state of {len(prior.ids)} tokens could not serve it (no DFlash2 window, off the grid, or "++ "draft:false)")++ print(f"[tensorfold] conversation {chat}: resumed at {cut} of {len(prompt)} tokens from {source}, "++ f"prefilling {len(prompt) - cut}; {why}", flush=True)+++ def _ctx(self, lane: Lane):+ """The lane's slot's DFlash2 context."""+ return self.drafts.contexts[lane.slot]+diff --git tensorfold/server/metrics.py tensorfold/server/metrics.py+index c96a9a8..ed8b409 100644+--- tensorfold/server/metrics.py++++ tensorfold/server/metrics.py+@@ -192,6 +192,12 @@ _HEALTH_GAUGES = (+ ("pool_free_tokens", "Pool rows no stream or kept prompt holds."),+ ("kept_prompts", "Prompt states kept in the pool for reuse."),+ )++# the GLM engine's conversation counters: streams that continued a conversation without its own kept turn state++_HEALTH_TOTALS += (++ ("chats_continued", "counter",++ "Streams that continued a conversation without resuming from its own turn state (a rewind, or it was dropped)."),++ ("chats_continued_prefill_tokens", "counter", "Prompt tokens those streams prefilled."),++)+++ def _health(lines: list[str], app: Any) -> None:diff --git a/tools/chat_continued_check.py b/tools/chat_continued_check.pynew file mode 100644index 0000000..2763faf--- /dev/null+++ b/tools/chat_continued_check.py@@ -0,0 +1,84 @@+#!/usr/bin/env python3+"""Checks for patch 0119 (a conversation keeps its id when a stream continues it without its own turn state), run+inside the image that scripts/prepare.sh built:++ docker run --rm --entrypoint python -v "$PWD/tools/chat_continued_check.py:/c.py" tensorfold-glm53:v0.6.0 /c.py++continued_chat on stubbed kept states (no GPU or model): issue #104's in-turn rewind before the kept turns continues+its conversation; another conversation behind the same system prompt and opening message, an edit of the first message,+shared and picture states start or skip as before; the most recently used match wins; the counters and the log line of+a large prefill (rank 0 only). Exit code 1 when a check fails.+"""+import contextlib+import io+from types import SimpleNamespace as NS++import tensorfold.families.glm5_next.cuda.multi as M++SYSTEM = list(range(100000, 100900)) # a 900-token system prompt every conversation shares+OPEN = list(range(200000, 200100)) # and the same 100-token opening message+fails: list[str] = []+++def check(name: str, ok: bool) -> None:+ print(("ok " if ok else "FAIL ") + name)+ if not ok:+ fails.append(name)+++def state(ids, chat, own=True, images=False):+ return NS(ids=list(ids), chat=chat, own=own, images=images)+++def convo(seed, turns, first=SYSTEM + OPEN):+ """A conversation's prompts: the first one, then each turn appending a reply and a tool result of its own."""+ prompts, ids = [list(first)], list(first)+ for t in range(turns):+ ids = ids + [seed * 1000 + t * 50 + k for k in range(50)]+ prompts.append(list(ids))+ return prompts+++big = list(range(500000))+check("common_prefix", M.common_prefix([1, 2, 3, 4], [1, 2, 9]) == 2 and M.common_prefix([1, 2, 3], [1, 2, 3, 4]) == 3+ and M.common_prefix([], [1]) == 0 and M.common_prefix(big, big[:123457] + [-1] + big[123458:]) == 123457)++a, b = convo(7, 6), convo(8, 6)+roots = {1: len(a[0])}+kept = [state(SYSTEM, 0, own=False), state(a[5], 1), state(a[6], 1)]+check("a rewind before the kept turns continues its conversation (#104)",+ M.continued_chat(kept, a[3] + [9, 9, 9], roots) is kept[-1])+check("another conversation behind the same system prompt and opening starts its own",+ M.continued_chat(kept, b[2], roots) is None)+check("a prompt that has not repeated the first reply yet starts its own",+ M.continued_chat(kept, a[0] + [5] * 10, roots) is None)+edited = SYSTEM + OPEN[:50] + [0] * 50 + a[2][len(a[0]):]+check("an edit of the first message starts a new conversation", M.continued_chat(kept, edited, roots) is None)+check("shared, picture and forgotten conversations' states are skipped",+ M.continued_chat([state(a[4], 1, own=False)], a[2] + [1], roots) is None+ and M.continued_chat([state(a[4], 1, images=True)], a[2] + [1], roots) is None+ and M.continued_chat([state(a[4], 2)], a[2] + [1], roots) is None)+two = M.continued_chat([state(a[3], 1), state(a[4], 2)], a[2] + [1], {1: len(a[0]), 2: len(a[0])})+check("the most recently used match wins", two is not None and two.chat == 2)++d = object.__new__(M.MultiDecoder)+d.rank, d.chats_continued, d.chats_continued_prefill = 0, 0, 0+long = convo(7, 200)+prior, prompt = state(long[200], 1), long[150] + [9]+out = io.StringIO()+with contextlib.redirect_stdout(out):+ d._continued(1, prior, NS(shared=True, ids=SYSTEM), len(SYSTEM), prompt)+text = out.getvalue()+check("counted and logged: where it resumed, from what, where it went back",+ (d.chats_continued, d.chats_continued_prefill) == (1, len(prompt) - len(SYSTEM))+ and "conversation 1: resumed at 900 of" in text and "from a shared prefix" in text+ and f"went back to token {len(long[150])}" in text)+out = io.StringIO()+with contextlib.redirect_stdout(out):+ d._continued(1, prior, None, len(prompt) - 10, prompt) # a small prefill: counted, not logged+ d.rank = 1+ d._continued(1, prior, None, 0, prompt) # rank 1 counts, never logs+check("a small prefill and rank 1: counted, not logged", d.chats_continued == 3 and out.getvalue() == "")++print("all passed" if not fails else f"{len(fails)} failed")+raise SystemExit(1 if fails else 0)