GLM-5.3-Flash EXL3 on 2x DGX Spark with TensorFold
Python
Patch 0120: a kept state a second conversation goes on from is a shared prefix, so the third conversation on a system prompt still resumes it (issue #121)
BadAd84f66942657949
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 80bd612..6a501f1 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -118,6 +118,18 @@ Every change to this recipe, newest first. Each release names the image it serve`/metrics`) and a rank-0 log line for one prefilling 4096 tokens or more, with where the prompt left the kept stateand what it resumed from. CPU check: `tools/chat_continued_check.py` (fails on the unpatched engine).+- **A system prompt's kept state stays once a second conversation goes on from it** (patch+ `0120-glm-fork-point-shared`, issue #121, diagnosed with a proposed fix by @RyanLeeUPC; by+ [BadAd84](https://github.com/BadAd84)): with a short first message, a conversation's own kept state is the+ system block's state. The next conversation resumed from it and kept a longer state beside it, and past+ `TF_GLM_CACHE_ENTRIES` the system block's state was dropped as superseded, so the third conversation on that+ system prompt prefilled it whole again. A kept state that a prompt goes on from differently than the prompt that+ wrote it is now a shared prefix (kept by recency, `0077`) and no conversation's own turn state+ (`TF_GLM_KEEP_PER_CHAT`); so is one two conversations prefilled at the same time. A conversation's own next turn+ is unchanged. The same replies: only which kept states stay changes. Known limit: with the opt-in+ `TF_GLM_EFFORT_TAIL=1` (`0096`) the generation prompt ends in the effort line, which the conversation's own next turn does+ not repeat at that position, so its own turn state can be taken for a fork (kept by recency instead of superseded-first;+ never a different reply). CPU check: `tools/fork_point_check.py`.- **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 (atdiff --git a/CREDITS.md b/CREDITS.mdindex 59c1513..d74b76b 100644--- a/CREDITS.md+++ b/CREDITS.md@@ -232,6 +232,7 @@ If you believe something here is missing or credited wrongly, please open an iss- `0108-glm-seg-chunks-cuda` (a decode window's latent attention chunk pass in CUDA): by [BadAd84](https://github.com/BadAd84).- `0115-glm-unoffered-tool-call` (a call to a tool the request did not offer, reported): its report adapted from[BadAd84](https://github.com/BadAd84)'s `0114-glm-tool-call-rejections` (#137).+- `0120-glm-fork-point-shared` (a kept state a second conversation goes on from is a shared prefix): the diagnosis and the first fix (the writer's next ids kept with a state, the state flagged when a resumed prompt goes on otherwise, the flag kept when the same ids are kept again) are by [RyanLeeUPC](https://github.com/RyanLeeUPC) in [issue #121](https://github.com/MiaAI-Lab/GLM-5.3-Flash-EXL3-2x-DGX-Sparks-TensorFold/issues/121); the rest by [BadAd84](https://github.com/BadAd84).- `0100-glm-draft-prelaunch` (the next round's DFlash2 block pass launched at a decode round's end,`TF_GLM_DRAFT_PRELAUNCH`): by [BadAd84](https://github.com/BadAd84).- `0102-glm-prompt-matmul-tile` (a prompt chunk's dense projections on tile 9 or 3): by [BadAd84](https://github.com/BadAd84).diff --git a/README.md b/README.mdindex 91be899..96de6ea 100644--- a/README.md+++ b/README.md@@ -553,7 +553,7 @@ 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_QMM_CLUSTERS` | unset | `1`: decode windows' 4-bit matmuls reduce every 2-8 K-slice split in a thread-block cluster, the rule before patch `0103`; unset: the buffer path at up to 64 rows under 28 Mi weight values (the same bits either way) |-| `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_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), and so do states a second conversation went on from differently, such as a short first message's end state (patch `0120`, issue #121, @RyanLeeUPC). 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. 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 |@@ -676,7 +676,7 @@ applied with `patch -p0` in filename order); `start.sh` rebuilds or re-pulls the| Prompt, indexer | `0086-glm-prompt-scores-loop` | a prompt chunk's indexer scoring (`0009`'s `_scores`) takes one row and 32 pool blocks a program (`SCORE_LOOP`), the row's queries loaded once, instead of 4 rows and one block (`TF_GLM_SCORE_RB`, retired), which reloaded every row's queries for each 64-pool block (by [BadAd84](https://github.com/BadAd84)) | the scoring 36% faster at long context (the part of a cold prefill that grows with it); cold prefill at 226k 138.3 -> 126.6 s; the same bits || Prompt, two Sparks | `0010-glm-hc-split`, `0033-glm-prefill-overlap2`, `0017-glm-overlap-priority`, `0022-glm-overlap-normal-priority`, `0064-glm-split-connect-early` | hyper-connection glue split by rows between the Sparks, exchanges overlapped with the next rows' work (`SPLIT`); the split's send/receive connection opened before the weights and the cache pool (issue #36) | 50k prefill ~1,270 -> ~1,730 tok/s with 0009 and 0020; decode rounds pay ~1.5% || Prompt, KDA | `0012-glm-kda-chunked`, `0014-glm-kda-chunked-gb10`, `0039-glm-kda-chunked-kernel` | the linear-attention layers' prompt chunks in chunked (WY) form, one CUDA kernel (`KDA_CHUNKED`) | 50k prefill 29.3 -> 26.4 s, 149k 91.1 -> 84.5 s (one start each) |-| Prompt reuse | `0008-glm-prompt-grid`, `0015-glm-shared-prefix`, `0042-glm-prompt-replay`, `0054-glm-image-prompt-reuse`, `0060-glm-keep-thinking`, `0063-glm-kept-cap-superseded-first`, `0071-glm-shared-prefix-copy`, `0077-glm-kept-cap-shared-by-recency`, `0078-glm-take-over-decide-then-copy` | prompt chunks and kept states on a token grid; a shared system prompt's state reused (copied out of the conversation that wrote it, which keeps its own state, by ezoushen, #43); an identical prompt resumes from its kept end state; prompts with pictures resume too, their kept states told apart by each picture's content (by abhicnv007, issue #11); earlier turns' reasoning kept in the prompt (`TF_GLM_CLEAR_THINKING`, by kky42, #23); past the kept-state cap a conversation's superseded states go first (by Alexbob0, #32), and shared-prefix states by recency only, so a new agent run still finds its system prompt (diagnosed and the fix proposed by meleesciony, #75); a fresh conversation after a long one clones only the kept states that stay, not every one first (reserved +14.8 -> +1.4 GiB after 256k, 21 turns; upstream #421) | [Performance](#performance) |+| Prompt reuse | `0008-glm-prompt-grid`, `0015-glm-shared-prefix`, `0042-glm-prompt-replay`, `0054-glm-image-prompt-reuse`, `0060-glm-keep-thinking`, `0063-glm-kept-cap-superseded-first`, `0071-glm-shared-prefix-copy`, `0077-glm-kept-cap-shared-by-recency`, `0078-glm-take-over-decide-then-copy`, `0120-glm-fork-point-shared` | prompt chunks and kept states on a token grid; a shared system prompt's state reused (copied out of the conversation that wrote it, which keeps its own state, by ezoushen, #43); an identical prompt resumes from its kept end state; prompts with pictures resume too, their kept states told apart by each picture's content (by abhicnv007, issue #11); earlier turns' reasoning kept in the prompt (`TF_GLM_CLEAR_THINKING`, by kky42, #23); past the kept-state cap a conversation's superseded states go first (by Alexbob0, #32), and shared-prefix states by recency only, so a new agent run still finds its system prompt (diagnosed and the fix proposed by meleesciony, #75); a kept state another conversation goes on from differently is a shared prefix too (with a short first message a conversation's own state is the system block's), so the third conversation on a system prompt still resumes it (diagnosed and the fix proposed by RyanLeeUPC, #121); a fresh conversation after a long one clones only the kept states that stay, not every one first (reserved +14.8 -> +1.4 GiB after 256k, 21 turns; upstream #421) | [Performance](#performance) || Decode | `0013-glm-decode-rounds`, `0016-glm-decode-kernels`, `0019-glm-decode-kernels2`, `0031-glm-decode-index-regs` | verify windows of up to 16 rows; faster decode matmuls, hyper-connection mixing and indexer scoring | faster decode rounds; long copy drafts (`COPY_MAX` 15: edit replies 84 -> 119 tok/s) || Decode, memory | `0046-glm-l2-prefetch`, `0047-glm-exl3-decode-loads` | the next kernels' weights prefetched into L2 during each layer's all-gathers (`TF_GLM_L2PF`, adapted from jayleaton/glm53-tensorfold-spark's patch 0460); the routed experts' trellis as 16-byte non-coherent loads a step ahead (`TF_GLM_EXL3_LOADS`, adapted from its patch 0580) | with `TF_ROCE_MAX_KB=512`: one request's prose 48.36 -> 49.68 tok/s, code 59.54 -> 61.49 (+2.7% / +3.3%); 4 at once prose 74.8 -> 76.6, code 100.0 -> 102.7 (two starts each); the same bits || Decode, memory | `0090-glm-expert-launch-order` | the decode expert kernel's blocks launched so that the eight 128-column blocks of one k slice run together and read contiguous memory (`TF_GLM_EXL3_DEC_ORDER=1` or `2`; default `0`, the old order), by Lukasz Raczylo ([lukaszraczylo](https://github.com/lukaszraczylo)) | the author's run: one request +2.2% tok/s (4 at once noisy); the same bits for every value; not yet measured here |diff --git a/patches/0120-glm-fork-point-shared.patch b/patches/0120-glm-fork-point-shared.patchnew file mode 100644index 0000000..0d05393--- /dev/null+++ b/patches/0120-glm-fork-point-shared.patch@@ -0,0 +1,98 @@+# Kept prompt states: a state a second conversation forks from is a shared prefix (issue #121, diagnosed with a+# proposed fix by @RyanLeeUPC).+#+# A conversation keeps its own state at the last grid point before its prompt ends. With a short first message that+# point is the system block's, so that state is the system prompt's state, but it is kept as the conversation's turn+# state: `shared` is set only for admission's shared points, which lie between the resume point and the prompt's own+# point. The next conversation resumes from it, takes its extent over and keeps its own longer state there. Past+# TF_GLM_CACHE_ENTRIES, cap_victim then drops the system prompt's state as superseded at once, and the third+# conversation on that system prompt reads it whole again (hit, miss, until a cold prompt's shared point heals it).+#+# 1. _keep records how the writing prompt goes on past each kept state (`after`: its next 64 ids; keyed ids with+# pictures). In _admitted, a stream that resumes from a state and goes on otherwise forked there from another+# conversation: the state is flagged shared (kept by recency, 0077) and is no conversation's own turn state any+# more (`own` false: TF_GLM_KEEP_PER_CHAT, 0089). It is flagged before the stream's chain is chosen, so the forking+# conversation starts a chain of its own instead of joining the writer's. A conversation resuming its own turn goes+# on as its writer did and is not flagged, so 0063's order (a long chat drops its own earlier turns first) holds.+# A state whose writing prompt ended there takes the line of the first stream that goes on from it.+# 2. Same ids kept again (_keep): the new state stays a shared prefix when the dropped one was one, and becomes one+# when the two prompts went on differently (two conversations prefilled one system block at the same time).+# 3. The spill tier stores `after` with a state (spill.encode takes every field not skipped), so a restored state+# still tells a fork from its writer's next turn.+#+# Both ranks see the same ids, so they decide alike. Only which kept states stay changes: the same replies, the same+# bits. Check: tools/fork_point_check.py. Applies after 0063, 0071, 0077, 0088 and 0089.+--- tensorfold/families/glm5_next/cuda/multi.py++++ tensorfold/families/glm5_next/cuda/multi.py+@@ -243,9 +243,10 @@+ prompts are prefixes of its rows, so one shorter than another in its extent is an earlier point of that+ conversation, superseded by the longer one: the oldest of those goes first, then the least recently used of any.+ A conversation taking many turns thus drops its own earlier turns instead of the only state of a conversation+- that is waiting on a long reply. A shared-prefix state (a system block, where prompts stop sharing) is never+- dropped as superseded: it is what the next conversation or run with that prefix resumes from, and its writer's+- longer state cannot serve them, so it goes by recency only, with the other conversations' latest states.++ that is waiting on a long reply. A shared-prefix state (a system block: where prompts stop sharing, or where a++ second conversation went on from a kept state, ``forks``) is never dropped as superseded: it is what the next++ conversation or run with that prefix resumes from, and its writer's longer state cannot serve them, so it goes by++ recency only, with the other conversations' latest states.+ Deterministic in ``kept``'s order and extents, so both ranks drop the same one."""++ longest: dict[int, int] = {}+@@ -295,6 +296,18 @@+ return lo++++FORK_SPAN = 64 # the ids past a kept state that tell one line from another there (``forks``)++++++def forks(after, ids) -> bool:++ """Two lines past a kept state part: ``after`` (the ids that followed it on the first prompt that wrote or resumed++ it, up to FORK_SPAN) and ``ids`` (another prompt's) differ where both have ids. Nothing on either side: unknown,++ False. A conversation's next turn goes on as its last prompt did; another conversation forked there."""++++ m = min(len(after), len(ids))++ return m > 0 and tuple(after[:m]) != tuple(ids[:m])+++++ 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."""+@@ -1045,6 +1058,21 @@+ code = a["code"]+ dflash = code[0] >= 10 and self.drafts is not None+ policy = decode_policy(code, g.costs) if code[0] else None++ # A prompt that goes on past its kept state otherwise than the prompt that wrote it forked there from another++ # conversation: that state is a shared prefix (a system block) for every later conversation too. Unflagged, a++ # longer state in its extent (its writer's, or this stream's after a takeover) made it "superseded", and past++ # TF_GLM_CACHE_ENTRIES cap_victim dropped it at the next keep, so the third conversation on a system prompt++ # read it whole again (#121). Flagged before the chain below: it is no conversation's own turn state any more++ # (TF_GLM_KEEP_PER_CHAT), and this stream starts a chain of its own. A conversation resuming its own turn goes++ # on as its writer did: unchanged. A state its writer's prompt ended at takes the line of the first stream that++ # goes on from it. Both ranks see the same ids (with pictures: their keyed ids), so they decide alike.++ if hit is not None:++ line = tuple((a["keyed"] if a.get("keyed") is not None else prompt)[cut:cut + FORK_SPAN])++ after = getattr(hit, "after", None) or ()++ if not after:++ hit.after = line++ elif forks(after, line):++ hit.shared, hit.own = True, False+ # 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+@@ -1173,8 +1201,15 @@+ snap.extent = lane.extent+ snap.shared = n in lane.shared+ snap.own, snap.chat = bool(own), int(lane.chat)+- # the same ids: the same prompt, unless pictures are in it (rank 1 has no keys; rank 0 resumes by key)++ # how the prompt that wrote it goes on from here (both ranks): a prompt resuming here that goes on otherwise++ # forked from it (``_admitted``)++ snap.after = tuple((lane.key if lane.images and lane.key is not None else lane.s.prompt)[n:n + FORK_SPAN])++ # the same ids: the same prompt, unless pictures are in it (rank 1 has no keys; rank 0 resumes by key). The new++ # state takes the dropped one's place: a shared prefix stays one, and one two prompts wrote going on differently++ # (two conversations that prefilled one system block at the same time) becomes one+ for c in [c for c in self.kept if c.ids == snap.ids and not (c.images or snap.images)]:++ if getattr(c, "shared", False) or forks(getattr(c, "after", None) or (), snap.after):++ snap.shared, snap.own = True, False+ self._drop(c, spill=False)+ lane.extent.kept.append(snap)+ self.kept.append(snap)diff --git a/tools/fork_point_check.py b/tools/fork_point_check.pynew file mode 100644index 0000000..e66dfd4--- /dev/null+++ b/tools/fork_point_check.py@@ -0,0 +1,389 @@+#!/usr/bin/env python3+"""Checks for the fork-point patch (a kept state that a second conversation forks from is a shared prefix), run inside+the image that scripts/prepare.sh built, no GPU:++ docker run --rm --network none --entrypoint python -v "$PWD/tools/fork_point_check.py:/c.py" <image> /c.py++Two real MultiDecoders, rank 0 deciding and rank 1 applying its messages in-process (``admit``, ``round``, ``finish``,+``apply``: the scheduler's calls), with only the model stubbed: the prompt chunk, the snapshot of the slot's state, the+vision tower and the sampler. Prompts are token ids shaped as the chat template lays them out (a system block, then+``<|user|>``, the message and the generation prompt); the grid (64), the shared-prefix minimum (256), the kept-state+cap (32) and TF_GLM_MULTI_LONE=0 are the recipe's defaults; prompts are filled one at a time (MULTI_PREFILL=0,+FILL_BUDGET_MS=0: the grouped and sliced fills keep states through the same ``_keep``). Exit code 1 when a check fails.++ 1. Issue #121's script: 40 short chats fill the cap, then three conversations on one new system prompt: "Hey", a+ long opener, "Hi". The third must resume the system prompt (before: the first conversation's end state, which is+ the system block's state, was dropped as superseded once the second kept a longer state in its extent).+ 2. An agent's sessions on one system prompt: three openers, one of them runs 7 turns, two new sessions: all resume.+ 3. TF_GLM_KEEP_PER_CHAT=1, the cap not full: the third conversation still resumes (the second one forked, so it is+ not the first one's next turn and does not take the system block's state as its own earlier turn).+ 4. TF_GLM_KEEP_PER_CHAT=2: a conversation that forks from another's first state starts a chain of its own, so its+ turns do not push the other conversation's latest turn out.+ 5. Two conversations on a new system prompt admitted together (both prefill it): the second state with the same ids+ replaces the first and is a shared prefix, so the next conversation still resumes after one of them goes on; and+ a shared-prefix state replaced by one with the same ids stays one.+ 6. Unchanged: a conversation going on as its writer did is not a fork (chat W waits while chat L runs 40 turns, then+ W's turn 2 resumes W's own state, and L's earlier turns are the ones dropped).+ 7. A turn whose prompt ended on the grid: the first reply that goes on from its state is its line, a second (a+ retry) forks, and the state stays past the cap for a third.+ 8. Pictures: the same ids with another picture's content (keyed ids) are a fork.+ 9. The spill tier (--spill-gib) stores the line past a state and restores it.+ 10. The rule (``multi.forks``) on its own.+Every scenario also checks that both ranks keep the same states with the same flags.+"""+import os++os.environ.setdefault("TF_GLM_MULTI_WATCHDOG_S", "0")++import random # noqa: E402+from types import SimpleNamespace as NS # noqa: E402++import torch # noqa: E402++import tensorfold.families.glm5_next.cuda.decode as D # noqa: E402+import tensorfold.families.glm5_next.cuda.forward as F # noqa: E402+import tensorfold.families.glm5_next.cuda.multi as M # noqa: E402+from tensorfold.cuda.streams import Stream # noqa: E402+from tensorfold.families.glm5_next.cuda.multi_tune import MultiSettings # noqa: E402+from tensorfold.families.glm5_next.cuda.pool import ALIGN, Arena, Plane # noqa: E402++GRID, LEAST, ENTRIES = 64, 256, 32+GMASK, SOP, SYSTEM, USER, ASSISTANT, THINK, EOS = 151331, 151333, 151335, 151336, 151337, 151350, 151329+REPLY = 7 # the stubbed sampler's token+POOL = 512 * ALIGN+fails: list[str] = []+++def check(name: str, ok: bool) -> None:+ print(("ok " if ok else "FAIL ") + name, flush=True)+ if not ok:+ fails.append(name)+++# -- the model, stubbed: positions move, states are placeholders ----------------------------------------------------+class SlotState:+ """``forward.State``: only the slot's position matters to the bookkeeping."""++ def __init__(self, *a, **k):+ self.pos, self.cur, self.rec, self.conv = 0, [0], [torch.zeros(1)], torch.zeros(1)++ def reset(self):+ self.pos = 0++ def set_pos(self, n):+ self.pos = n+++def prefill_chunk(e, prompt, start, rows, **k):+ e.st.pos = start + rows+ return torch.zeros(1, 4)+++def take_snapshot(e, ids, pending, *, mtp, drafter=None):+ return D.Snapshot(list(ids), torch.zeros(1), torch.zeros(1), None, -1, -1, tail=[])+++F.State, D.prefill_chunk, D.take_snapshot = SlotState, prefill_chunk, take_snapshot+D.put_ring_tail = lambda st, hit: None+M.sample_streams = lambda w, parts: [[REPLY] for _ in parts]+++class Engine:+ def __init__(self, planes=None, rows=POOL):+ self.w = NS(device="cpu", cfg=NS(eos=[EOS], hidden=8), vocab_offset=0, comm=None, layers=[None], world=2)+ self.slots, self.rows, self.prefill_rows, self.st = NS(count=4), 16, 2048, None+ planes = planes(rows) if planes is not None else [Plane(torch.zeros(rows, 1, dtype=torch.uint8))]+ self.caches = NS(rows=rows, arena=Arena(rows, planes))++ def use(self, st):+ prev, self.st = self.st, st+ return prev+++class Net:+ follower = None+++class Glm:+ """The ``GlmEngine`` the decoder reads (its settings) and talks through (rank 0 to rank 1, in-process)."""++ def __init__(self, rank, net, planes=None, rows=POOL):+ self.rank, self.net, self.e = rank, net, Engine(planes, rows)+ self.w = self.e.w+ self.grid, self.drafter, self.limit, self.serial_only = GRID, None, 1 << 20, False+ self.shared, self.opener, self.cache_entries, self.copy, self.spill_cfg = LEAST, USER, ENTRIES, None, None+ self.multi_window, self.costs, self.model_dir = 64, None, "."+ self.vision = NS(features=lambda prepared: torch.zeros(len(prepared.positions), 8)) # the tower, stubbed++ def _ring(self):+ pass++ def _share(self, msg):+ f = self.net.follower+ f.apply(M.unseal(msg, f.received, 1))+ f.received = (f.received + 1) % M.SEAL_MOD+++def ranks(glm=Glm, planes=None, rows=POOL):+ net = Net() # the recipe's TF_GLM_MULTI_LONE=0 (scripts/config.sh)+ tune = MultiSettings.from_env({"TF_GLM_MULTI_LONE": "0"})+ r0, r1 = (M.MultiDecoder(glm(r, net, planes, rows), 4, verify=object(), tune=tune) for r in (0, 1))+ net.follower = r1+ return r0, r1+++# -- prompts, as the chat template lays them out -------------------------------------------------------------------+rng = random.Random(121)+++def text(n):+ return [rng.randrange(1000, 150000) for _ in range(n)]+++def system_block(n):+ return [GMASK, SOP, SYSTEM] + text(n - 3)+++def turn(msg):+ return [USER] + msg + [ASSISTANT, THINK]+++class Picture:+ """An image prompt's prepared pictures (``s.vision``): their rows' positions and content keys."""++ def __init__(self, positions, key):+ self.positions, self.item_rows, self.item_keys = list(positions), [len(positions)], [key]++ def from_item(self, first):+ return self+++def run(r0, *prompts):+ """Admit the prompts together (a prompt, or (prompt, Picture)), run until each has its first token (a reply of one+ token), finish them; what each resumed (``tensorfold.cached``)."""++ streams = []+ for p in prompts:+ p, vision = p if isinstance(p, tuple) else (p, None)+ streams.append(Stream(list(p), 1, None, draft=True, stop_eos=True, vision=vision))+ for s in streams:+ r0.admit(s)+ while not all(s.done for s in streams):+ r0.finish(r0.round())+ return [s.cached for s in streams]+++def same_on_ranks(r0, r1):+ return [(c.kid, len(c.ids), bool(c.shared)) for c in r0.kept] == [(c.kid, len(c.ids), bool(c.shared))+ for c in r1.kept]+++def fill_cap(r0, count=40):+ for i in range(count): # "Filler conversation i: lorem ipsum ..." + "Say OK."+ run(r0, system_block(310) + turn(text(4)))+++# -- 1: the issue's script ----------------------------------------------------------------------------------------+def issue_script():+ r0, r1 = ranks()+ fill_cap(r0)+ check(f"the 40 short chats fill the cap ({len(r0.kept)} kept states)", len(r0.kept) == ENTRIES)+ sys_ = system_block(14831) # its <|user|> at 14,831: in the grid step that starts at 14,784+ hey, opener, hi = sys_ + turn(text(1)), sys_ + turn(text(48)), sys_ + turn(text(1))+ got = [run(r0, p)[0] for p in (hey, opener, hi)]+ print(f" cached: 'Hey' {got[0]}, long opener {got[1]}, 'Hi' {got[2]} (prompts {len(hey)}, {len(opener)}, "+ f"{len(hi)})")+ check("conversation 1 ('Hey') prefills the new system prompt", got[0] == 0)+ check("conversation 2 (a long opener) resumes the system block (14,784)", got[1] == 14784)+ check("conversation 3 ('Hi') resumes the system block too, past the cap (#121)", got[2] == 14784)+ state = next((c for c in r0.kept if len(c.ids) == 14784), None)+ check("the system block's state is a shared prefix, not a turn state of the first conversation",+ state is not None and state.shared and not state.own)+ check("both ranks keep the same states with the same flags", same_on_ranks(r0, r1))+++# -- 2: an agent's sessions ---------------------------------------------------------------------------------------+def agent_sessions():+ r0, r1 = ranks()+ fill_cap(r0)+ sys_ = system_block(25540) # its <|user|> at 25,540: in the grid step that starts at 25,536+ point = 25536+ hello, howdy, buenos = (sys_ + turn(text(k)) for k in (2, 60, 6)) # the second ends past 25,600: a longer state+ got = [run(r0, p)[0] for p in (hello, howdy, buenos)]+ check(f"three sessions on one system prompt: the 2nd and 3rd resume it ({got})", got == [0, point, point])+ conv, seen = howdy, [] # "Howdy" goes on, 7 turns+ for _ in range(7):+ conv = conv + [REPLY] + text(30) + turn(text(rng.randrange(5, 200)))+ seen.append(run(r0, conv)[0])+ check(f"the session that goes on resumes its own last state every turn ({seen})",+ seen[0] == 25600 and all(b > a for a, b in zip(seen, seen[1:])))+ got = [run(r0, sys_ + turn(text(k)))[0] for k in (4, 9)]+ check(f"two new sessions after it resume the system prompt ({got})", got == [point, point])+ check("both ranks keep the same states with the same flags", same_on_ranks(r0, r1))+++# -- 3 and 4: TF_GLM_KEEP_PER_CHAT ----------------------------------------------------------------------------------+def keep_per_chat():+ saved = M.KEEP_PER_CHAT+ try:+ M.KEEP_PER_CHAT = 1+ r0, r1 = ranks()+ sys_ = system_block(14831)+ got = [run(r0, sys_ + turn(text(k)))[0] for k in (1, 48, 1)]+ check(f"TF_GLM_KEEP_PER_CHAT=1, room left: the third conversation resumes the system block ({got})",+ got == [0, 14784, 14784])+ M.KEEP_PER_CHAT = 2+ r0, r1 = ranks()+ sys_ = system_block(14831)+ a1 = sys_ + turn(text(1)) # A: turn 1 ends at the system block's point+ run(r0, a1)+ a2 = a1 + [REPLY] + text(40) + turn(text(300))+ run(r0, a2) # A: turn 2+ b = sys_ + turn(text(48)) # B forks at the system block, 2 turns+ run(r0, b)+ run(r0, b + [REPLY] + text(40) + turn(text(300)))+ a2_point = len(a2) // GRID * GRID+ got = run(r0, a2 + [REPLY] + text(40) + turn(text(20)))[0] # A: turn 3+ check(f"TF_GLM_KEEP_PER_CHAT=2: a conversation forked from another's first state starts a chain of its own, "+ f"so the other's latest turn stays (A's turn 3 resumed {got}, its turn 2 state is {a2_point})",+ got == a2_point)+ check("both ranks keep the same states with the same flags", same_on_ranks(r0, r1))+ finally:+ M.KEEP_PER_CHAT = saved+++# -- 5: the same ids written by two conversations -------------------------------------------------------------------+def admitted_together():+ r0, r1 = ranks()+ fill_cap(r0)+ sys_ = system_block(14831)+ a, b = sys_ + turn(text(1)), sys_ + turn(text(2))+ got = run(r0, a, b)+ check(f"two conversations admitted together both prefill the new system prompt ({got})", got == [0, 0])+ state = next((c for c in r0.kept if len(c.ids) == 14784), None)+ check("the second state with the system block's ids replaces the first and is a shared prefix",+ state is not None and state.shared and not state.own+ and sum(1 for c in r0.kept if len(c.ids) == 14784) == 1)+ got = run(r0, b + [REPLY] + text(40) + turn(text(300)))[0] # B goes on (as B's own prompt did)+ check(f"B's turn 2 resumes the system block ({got})", got == 14784)+ got = run(r0, sys_ + turn(text(5)))[0]+ check(f"a new conversation still resumes the system block after B went on ({got})", got == 14784)+ check("both ranks keep the same states with the same flags", same_on_ranks(r0, r1))+++def shared_replaced():+ r0, r1 = ranks()+ fill_cap(r0)+ sys_ = system_block(14831)+ r = sys_ + turn(text(1))+ q = r + [REPLY] + text(40) + turn(text(300)) # R's next turn, sent while R's first still prefills+ got = run(r0, q, r) # Q (cold) keeps the system block as a shared point, R then+ check(f"a conversation and its next turn admitted together both prefill ({got})", got == [0, 0])+ state = next((c for c in r0.kept if len(c.ids) == 14784), None) # R's own state, the same ids as Q's point+ check("a shared-prefix state replaced by a state with the same ids stays a shared prefix",+ state is not None and state.shared and not state.own)+ run(r0, r + [REPLY] + text(40) + turn(text(30))) # R goes on (as its prompt did) from it+ got = run(r0, sys_ + turn(text(5)))[0]+ check(f"a new conversation still resumes the system block ({got})", got == 14784)+ check("both ranks keep the same states with the same flags", same_on_ranks(r0, r1))+++# -- 6: what must not change ----------------------------------------------------------------------------------------+def own_turns():+ r0, r1 = ranks()+ fill_cap(r0)+ w = system_block(900) + turn(text(20)) # W's <|user|> in its end's grid step+ w_point = len(w) // GRID * GRID+ run(r0, w) # W: turn 1, then waits+ conv = system_block(705) + turn(text(30)) # L: 40 turns (<|user|> in its end's step)+ flagged = 0+ for _ in range(40):+ run(r0, conv)+ flagged += sum(1 for c in r0.kept if c.shared)+ conv = conv + [REPLY] + text(30) + turn(text(rng.randrange(5, 90)))+ check(f"a conversation going on as its writer did never makes its own turn states shared ({flagged} flagged)",+ flagged == 0)+ got = run(r0, w + [REPLY] + text(30) + turn(text(10)))[0]+ check(f"W's turn 2 after L's 40 turns resumes W's own state ({got} of {w_point}): L dropped its own earlier turns",+ got == w_point)+ check("both ranks keep the same states with the same flags", same_on_ranks(r0, r1))+++# -- 7: a state whose writer's prompt ended there --------------------------------------------------------------------+def retries_on_grid():+ r0, r1 = ranks()+ fill_cap(r0, ENTRIES - 4) # room for the 4 states below, then the cap is reached+ x1 = system_block(14844) + turn(text(1)) # ends on the grid (14,848): its own state ends its prompt+ run(r0, x1)+ run(r0, x1 + [REPLY] + text(40) + turn(text(30))) # its turn 2+ run(r0, x1 + [REPLY] + text(40) + turn(text(30))) # turn 2 again, another reply (a retry)+ fill_cap(r0, 2)+ got = run(r0, x1 + [REPLY] + text(40) + turn(text(10)))[0] # a third reply+ check(f"a turn's state that two replies went on from (its prompt ended on the grid) is kept past the cap ({got})",+ got == len(x1))+ check("both ranks keep the same states with the same flags", same_on_ranks(r0, r1))+++# -- 8: pictures ----------------------------------------------------------------------------------------------------+IMAGE = 151363+++def pictures():+ r0, r1 = ranks()+ fill_cap(r0)+ sys_ = system_block(14784) # its <|user|> at the grid point 14,784+ rows = list(range(14785, 14805)) # 20 picture rows after <|user|>+ one = sys_ + [USER] + [IMAGE] * 20 + text(3) + [ASSISTANT, THINK]+ run(r0, (one, Picture(rows, 5)))+ two = one + [REPLY] + text(40) + turn(text(30)) # the same ids, another picture+ got = run(r0, (two, Picture(rows, 6)))[0]+ check(f"the same question about another picture resumes the system block ({got})", got == 14784)+ got = run(r0, sys_ + turn(text(1)))[0]+ check(f"another picture is a fork too: a text conversation after it still resumes the system block ({got})",+ got == 14784)+ check("both ranks keep the same states with the same flags", same_on_ranks(r0, r1))+++# -- 9: the spill tier (--spill-gib) stores and restores the line past a state ----------------------------------------+def spill_line():+ from tensorfold.cuda import spill++ r0, r1 = ranks()+ sys_ = system_block(14831)+ hey = sys_ + turn(text(1))+ run(r0, hey)+ snap = next(c for c in r0.kept if len(c.ids) == 14784)+ items, layer = spill.encode(snap, skip=M.MultiDecoder._SPILL_SKIP)+ back = spill.decode(layer, dict(items), [f"{D.Snapshot.__module__}:{D.Snapshot.__qualname__}"])+ line = getattr(back, "after", None)+ check("a spilled state's line past it (its writer's prompt) comes back from the spill tier",+ line is not None and tuple(line) == tuple(hey[14784:]))+ check("and still tells another conversation from the writer's next turn",+ M.forks(line, (sys_ + turn(text(48)))[14784:]) and not M.forks(line, (hey + [REPLY] + text(9))[14784:]))+++# -- 10: the rule itself ----------------------------------------------------------------------------------------------+def fork_rule():+ check("the rule: the writer's next turn (its line, then more) is no fork", not M.forks((1, 2, 3), [1, 2, 3, 4]))+ check("the rule: a prompt ending inside the writer's line, agreeing, is no fork", not M.forks((1, 2, 3), [1, 2]))+ check("the rule: another id where both have one is a fork", M.forks((1, 2, 3), [1, 9]) and M.forks([5], (6, 7)))+ check("the rule: nothing known on either side is no fork", not M.forks((), [1]) and not M.forks((1,), []))+++def run_parts(*parts) -> None:+ for part in parts or (issue_script, agent_sessions, keep_per_chat, admitted_together, shared_replaced, own_turns,+ retries_on_grid, pictures, spill_line, fork_rule):+ try:+ part()+ except Exception as exc: # a part that raises fails the check; the rest still run+ check(f"{part.__name__} ran ({type(exc).__name__}: {exc})", False)+++def main() -> int:+ run_parts()+ print("all passed" if not fails else f"FAILED: {fails}")+ return 1 if fails else 0+++if __name__ == "__main__":+ raise SystemExit(main())