GLM-5.3-Flash EXL3 on 2x DGX Spark with TensorFold
Python
Patch 0128: spill tier in blocks shared by later turns, written when kept (net diff of PR #124)
Robert Wojciechowski9c89161825af
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c9c389e..ceff1ba 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -285,6 +285,53 @@ Every change to this recipe, newest first. Each release names the image it serveconnection) before answering; a request without one reads nothing. CPU test: `tools/test_get_bodies.py` (fails onthe unpatched source).- **Broken concurrent GLM engine is visible** (patch `0118-glm-broken-health-exit`): `/health` reports `ok: false` and its first error in `broken`; `/metrics` exposes `tensorfold_health:ok`. Opt-in `TF_GLM_EXIT_ON_BROKEN=1` logs the cause and exits with code 1 as soon as the broken state latches. The existing stall watchdog is unchanged. The cause shown in `/health` is cut at 200 characters. CPU check: `tools/test_broken_health_exit.py`.+- **Spill tier, blocks** (patch `0128-glm-spill-blocks`; with `PARALLEL` above 1 and `SPILL_GIB` set; off by default):+ every kept prompt state is written to local disk when it is kept, in blocks of 2,048 tokens that later turns and forks+ of the same conversation share, so a conversation resumes from disk after an eviction, a clean restart, a `kill -9` or+ a watchdog restart, and a turn writes only its new rows (a 10.4k-token turn of a 50k conversation: 68 MiB, not the+ whole state). Each conversation keeps its newest `SPILL_TURNS` (4) states, older turns trimmed as each one is written+ (each held a ~91 MB small part; the rows stay, the newest turn names them), and small parts go to disk with O_DIRECT,+ so the page cache keeps no copy. Room goes by conversation: old turns beyond `SPILL_TURNS`, abandoned forks, whole+ conversations least recently used, shared system prompts last; `SPILL_QUOTA` caps one conversation's share (#122,+ reported by [xiepengqi](https://github.com/xiepengqi): one conversation's per-turn states filled 128 GiB in 30 minutes+ and pushed the others out). The free-disk floor makes room in the same order. Blocks with equal bytes are linked, not+ written twice. Rank 0 asks every Spark before a read (HAS). The block layout, the lineage, writing at keep through a+ pinned ring and the fsync order are those of+ [PR #118](https://github.com/MiaAI-Lab/GLM-5.3-Flash-EXL3-2x-DGX-Sparks-TensorFold/pull/118) by+ [BadAd84](https://github.com/BadAd84), brought into the spill tier so there is one tier and one set of settings. The+ one-stream engine (`PARALLEL=1`) keeps its file a state. `SPILL_HIGHWATER` no longer changes anything.+ A restore reads ahead on 8 threads into pinned slots (`TF_GLM_SPILL_READ_BLOCKS`, 16) and the engine copies the+ blocks read between rounds (`TF_GLM_SPILL_LOAD_MS`, 40 ms, one budget for every restore in flight, each first in+ turn; beside decoding streams a restore ends only once those copies are done, rather than its end copying the+ read-ahead in one pause), as #118 does: issued from the reader's own thread, each+ copy waited on the decode loop (~0.25 ms a call against ~9 us idle), so a 260k-token restore beside a decoding stream+ took 1.0-1.3 s on two Sparks and 8.6-12.7 s on three (measured by [BadAd84](https://github.com/BadAd84)); now+ 0.54-0.61 s with 32 blocks read ahead (idle 0.40-0.46 s), the same replies. The read-ahead's first blocks go in the+ two 64 MiB read buffers pinned at start (ten blocks on two Sparks); the rest is pinned before the pool is sized, in+ power-of-two pieces, so that comes out of the pool, not the margin it keeps (the default 16 blocks: ~14k tokens at+ `PARALLEL=4`; 9 costs the pool nothing). The write ring's size is `TF_GLM_SPILL_STAGE_MIB` (256 MiB). A restore+ whose read fails on one Spark (a damaged or missing block) ends on every Spark and the+ prompt is computed again: a Spark with more blocks left than read slots (above ~65k tokens) waited for ever for the+ slots its own copies held (a ~100k-token conversation with damaged blocks on two Sparks: the request hung until the+ client gave up after 15 minutes; now answered in 50 s, its prompt recomputed). CPU check: `hang` in+ `tools/spill_blocks_check.py`. Rows copied to host memory before they go (`release`) have their own cap,+ `SPILL_RELEASE_MIB` (an eighth of `MEMORY_RESERVE_GIB` by default, not the 16 GiB write backlog); a state past it is+ not stored. One engine a `SPILL_DIR` (a flock on `.lock-rank<N>`: a second engine runs without the tier and says+ why), and temporary files opened `O_EXCL | O_NOFOLLOW`.+- **A system prompt prefilled once for every agent** (patch `0128`, `PREFIX_WAIT=1`, off by default: it changes+ admission also with `SPILL_GIB=0`): a request whose prompt starts+ with what another request is still prefilling waits for that state, apart from the queue, then resumes from it. Six+ agents at once on a fresh 12k-token system prompt: all answered in 14.7-15.0 s instead of 45.7-47.0 s, the slowest+ first token 13.5-13.8 s instead of 45.0-46.2 s, the same replies. Counted in `/health` (`prefix_waits`,+ `prefix_wait_tokens`) and `/metrics` (`prefix_waits_total`, `prefix_wait_tokens_total`).+- `tools/kept_state_check.py`: the spill tier writes a state when it is kept, not when it is dropped.+ `tools/test_queued_cancellation.py`: the scheduler's prefix-wait list. `tools/spill_blocks_check.py` (CPU): the+ block store and its hooks in `multi.py` (a read only reads; the engine copies, rank 1 as far as LOADPART says), the+ room (the files each eviction step deletes, the eviction order, a point being read, blocks a new state names), old+ turns trimmed (`SPILL_TURNS`), the quota, the floor, a restart with torn, orphaned and foreign files, older builds+ pruned, the release cap, temporary files and the folder lock, and the prefix wait (off by default; what it waits+ for, its release, the scheduler holding a request apart); `tools/spill_blocks_mutants.sh` runs it on faithful+ mutants of each fix. Its whole-run watchdog is 900 s by default (`TEST_TIMEOUT_S`).## v1.10 (2026-10-08): the effort line at the tail (opt-in), a kept-state share, and a checked second raildiff --git a/CREDITS.md b/CREDITS.mdindex c2847b8..5bcb7a7 100644--- a/CREDITS.md+++ b/CREDITS.md@@ -176,6 +176,18 @@ 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 thesession tier of [JSpark3](https://github.com/jakejharris/jspark3) v2.0.1 by[jakejharris](https://github.com/jakejharris). The code is new.+- `0128-glm-spill-blocks` (the spill tier's block store and the in-flight prefix wait, `SPILL_GIB` with `PARALLEL`+ above 1, `PREFIX_WAIT`): the block layout (blocks of the pool's alignment named by a hash chained over the ids and+ salted with the state's lineage), the lineage, writing a state when it is kept through a pinned staging ring between+ rounds, copying rows still waiting before they are freed or overwritten (`release`), and the fsync order are those+ of the NVMe KV tier by [BadAd84](https://github.com/BadAd84) in+ [PR #118](https://github.com/MiaAI-Lab/GLM-5.3-Flash-EXL3-2x-DGX-Sparks-TensorFold/pull/118) (Apache 2.0), carried+ over into `tensorfold/cuda/spill_blocks.py`; the rest (lineage forks at each resume point, eviction by conversation+ and the quota from [issue #122](https://github.com/MiaAI-Lab/GLM-5.3-Flash-EXL3-2x-DGX-Sparks-TensorFold/issues/122),+ reported by [xiepengqi](https://github.com/xiepengqi), the free-disk floor making room in that order, content dedup+ by hard link, reads on a CUDA stream beside decoding after every rank's HAS, pictures by content keys, and the+ prefix wait) by Robert Wojciechowski ([wojo](https://github.com/wojo) on GitHub, [@rwojo](https://x.com/rwojo) on X).+ It builds on `0088-glm-spill-tier`, whose credits above apply to the tier around it.- `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); rebaseddiff --git a/NOTICE b/NOTICEindex 869e030..566ef32 100644--- a/NOTICE+++ b/NOTICE@@ -100,6 +100,10 @@ glm53-tensorfold-sparkby 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.+ patches/0128-glm-spill-blocks.patch (tensorfold/cuda/spill_blocks.py and its hooks in multi.py) carries over the+ block layout, lineage, write-at-keep ring, release and fsync order of the NVMe KV tier in pull request #118 of this+ project, authored by BadAd84 (https://github.com/BadAd84); the rest is authored by+ Robert Wojciechowski (GitHub @wojo, X @rwojo), and it builds on patches/0088-glm-spill-tier.patch above.Contributions to this project (Apache-2.0, through its issues and pull requests)patches/0054-glm-image-prompt-reuse.patch: by abhicnv007 (issue #11), with two review changes by MiaAI-Lab.diff --git a/README.md b/README.mdindex 0b2576d..699c63c 100644--- a/README.md+++ b/README.md@@ -339,36 +339,110 @@ with that window and says so (free memory on both Sparks for the full one). OtheThe KV pool keeps a few conversations' prompt states (`TF_GLM_CACHE_ENTRIES`, and what the pool holds); one thatleaves 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 to-that 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) 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 written-early, 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.--Two Sparks, `PARALLEL=4`, `SPILL_GIB=64`, `SPILL_HIGHWATER=0.70` against v1.5 (two runs each; first-token means;-"resumed" = at least half the prompt came from a kept state, in the pool or on disk):--| Workload | v1.5 | Spill tier |+`SPILL_GIB=64` (and `SPILL_DIR`, the same absolute path on every Spark) every kept state of `SPILL_MIN_TOKENS` (8,192)+or more is written to that directory on each Spark when it is kept, and a later request that extends it reads it back+instead of prefilling (patch `0088-glm-spill-tier`, 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+its block store, patch `0128-glm-spill-blocks`, carries over the NVMe KV tier of+[PR #118](https://github.com/MiaAI-Lab/GLM-5.3-Flash-EXL3-2x-DGX-Sparks-TensorFold/pull/118) by+[BadAd84](https://github.com/BadAd84)).++How it stores (`PARALLEL` above 1):++- **Blocks a later turn shares.** Rows go to disk in blocks of 2,048 tokens, named by a hash chained over the token ids+ and the state's lineage (the computation it belongs to: a request that resumed from a state keeps that state's+ block names up to its resume point and forks its own from the block holding it). A later turn of a conversation, or+ a fork that resumed from it, names the blocks its earlier turns wrote and writes only its new ones; a block whose+ bytes equal one already on disk is linked to it instead of written again.+- **Written when kept, so it survives a crash.** Only a kept state's small part (its recurrences and DFlash2 window)+ and the block its end cuts (whose last pooled-key row is still filling) are copied off the GPU when it is kept; its+ other rows go to disk a few blocks between rounds (4; 2 and 8 measured the same) through a pinned ring (`TF_GLM_SPILL_STAGE_MIB`, 256 MiB),+ written with O_DIRECT (the page cache shares a GB10's memory). A conversation resumes from disk after an eviction, a clean restart, a `kill -9` or a+ watchdog restart. A clean stop writes what still waits (`SPILL_FLUSH_S`, 60 s). Rows freed or overwritten before+ their write (a full pool, a stream taking over an extent) are copied to host memory first, at most+ `SPILL_RELEASE_MIB` of them at once (default an eighth of `MEMORY_RESERVE_GIB`: 1.8 GiB at 14.5; on a GB10 that+ memory is the pool's and the reserve's); a state past it is not stored (`/health` `spill.release_dropped`,+ `host_mb`).+- **Reads beside decoding.** A restore reads its blocks ahead on 8 threads (2 were slower, 4 to 16 the same) into pinned slots+ (`TF_GLM_SPILL_READ_BLOCKS`, 16 blocks: on two Sparks the read buffers pinned at start hold the first ten and the+ rest is pinned before the pool is sized, in power-of-two pieces, so the pool pays for those (~14k tokens at+ `PARALLEL=4`) rather than the margin it keeps; 9 costs the pool nothing), checks each against its CRC-32, and the engine copies the blocks read into the+ pool between rounds (at most `TF_GLM_SPILL_LOAD_MS`, 40 ms, a gap, shared by every restore in flight), so the other requests keep decoding and the read+ never waits for them (copies issued from the reader's own thread waited on the decode loop for every call); while+ other requests decode, a restore ends only once those budgeted copies are done (the read runs ahead of them by up to+ the read-ahead, which its end would otherwise copy in one pause); a file that fails is dropped on every Spark and the+ prompt is prefilled. Rank 0 asks every Spark before a read; a read happens only when all hold the state.+- **Pictures** (`PARALLEL` above 1): stored under their content keys, so a request resumes one only with the same+ pictures in the same places.+- **One engine a folder.** Each Spark's engine holds `SPILL_DIR/.lock-rank<N>` (flock, let go when the process ends,+ `kill -9` too). A second engine on the same folder (another checkout, a test run) is told so and runs without the+ tier, rather than writing the same files and pruning the other's build. Files go to a temporary name opened+ `O_EXCL | O_NOFOLLOW` (never an existing file, never through a symlink), are fsynced and renamed.++Old turns. Every turn keeps its own small part (~91 MB a Spark: the recurrent state and DFlash2 window at that+point, the same size at any length), while the rows are shared, so a long agent loop would store one small part a+turn. As soon as a state is written, its conversation's path keeps the newest `SPILL_TURNS` (4) states and the older+ones go (`trimmed_turns`): they free only their small part, since the newest turn still names every block. A request+can then resume from any of the last 4 turns (a regenerate, an edited last message, a rewound tool call); an edit+further back resumes from the shared system prompt and prefills the rest. `SPILL_TURNS=2` suits heavy agent loops or a+small disk, 8 or more chats with frequent deep edits, `0` keeps every turn until room is needed. Forks off the path (an+edited message's old branch) stay until room is needed.++Room. At most `SPILL_GIB` a Spark, and no write leaves less than `SPILL_MIN_FREE_GIB` (50) GiB free on its file system.+When either needs room, states go in this order (blocks go once no state names them):++1. a conversation's old turns beyond the newest `SPILL_TURNS` on the path of its most recently used state (only with+ `SPILL_TURNS=0`, or the newest one then: they are gone already otherwise);+2. abandoned forks (an edited or retried message): a conversation's states off that path, least recently used first;+3. whole conversations, least recently used first;+4. shared-prefix states (a system prompt other conversations resume from), last.++A conversation is the branch below the shared system-prompt state it extends ([issue #122](https://github.com/MiaAI-Lab/GLM-5.3-Flash-EXL3-2x-DGX-Sparks-TensorFold/issues/122),+reported by [xiepengqi](https://github.com/xiepengqi): one conversation's per-turn states filled the disk and pushed+the others out). `SPILL_QUOTA` (a fraction of+`SPILL_GIB`, off by default) caps one conversation: past it, it trims its own old turns and forks first, so one busy+conversation cannot push every other one off the disk. If nothing can make the room, the state is not written.++Two Sparks, `PARALLEL=8`, `SPILL_GIB=64`, every reply compared to a fresh `draft: false` one (temperature 0):++| Case | Result |+| --- | --- |+| A 40k-token conversation kept 3 s before `kill -9` of every rank | resumed from disk after the restart, same reply, 1.4 s (fresh 21.8 s) |+| The same after a clean restart; a turn that adds 10.4k tokens to it | resumed, same reply, 1.2 s (fresh 27.0 s); the turn wrote 68 MiB (6 new blocks), not the whole state |+| 4 conversations growing 30k to 45k tokens over 7 turns each, at once | decode 27.99 tok/s together with the tier on and off; 1.2 GiB written for 28 kept states; dirty pages as with it off |+| A picture prompt across a clean restart | resumed, same reply |+| Restore of a 40k-token state | 147 ms (median) |+| Restore of a 260k-token state beside a decoding stream | 0.54-0.61 s (idle 0.40-0.46 s; 1.0-1.3 s with the copies on the reader's thread; 0.87 s with 16 read-ahead blocks, 0.69 s with 24); its first token 1.3-1.4 s; the decoding stream 46.2-46.3 tok/s (46.4 without the read) |+| An agent rewinding its last two rounds every 4th of 16 (~110k tokens, issue #104), 6 chats filling the cache | the 3 rewinds prefilled 22, 66 and 67 tokens (before: 22, 109,186 and 4,227); same replies |++Files: `spill-<build>/rank<N>/blocks/` (about 6.2 MB a 1,000 tokens a Spark) and `points/` (each state's ids and+small part), owned by you and readable only by you (they hold your prompts' tokens). Its counters are in `/health`+(`spill`: states, blocks, bytes written in all and linked, what each eviction step dropped, restores and their+p50/p95; what fills it: conversations, the largest one's bytes, share of the cap and tokens, the five largest, shared+prefixes, abandoned forks, turns kept on one path; whether it pays: `disk_lookups`, `disk_hits`, `has_refused` (a+rank lacking the state); the cap, turns and quota) and `/metrics` (`spill_*`). Each build gets its own folder, so a+new image starts the tier empty (the previous build's folder is kept until the next). With `PARALLEL=1` the one-stream engine writes a kept state to one file when memory drops it, as before.+`SPILL_HIGHWATER` no longer changes anything (states are written when kept). Design and credits: `NOTICE`,+`CREDITS.md`; the tier's core (`tensorfold/cuda/spill.py`, `tensorfold/cuda/spill_blocks.py`) is model-agnostic.++### A system prompt prefilled once for every agent++Agents that start at the same moment on a system prompt the server has not kept yet (a cold start, a new harness or+harness version, a changed tool list or instructions) would each prefill it, side by side. A request whose prompt+starts with a point another request is still prefilling (its system block's end, a shared-prefix point) now waits for+that state, apart from the queue, and resumes from it: the system prompt is prefilled once, and every agent's first+token comes sooner (`PREFIX_WAIT=1`; off by default, since it changes admission also with the spill tier off). Six agents at once on a fresh 12k-token system+prompt, two Sparks, `PARALLEL=8`, every reply equal to its own fresh `draft: false` one:++| | Without | With || --- | --- | --- |-| 15 conversations of 200k tokens resent after others pushed them out | 7-10 of 15 resumed, 40-64 s | 15 of 15, 0.6 s |-| The same 15 after a clean restart | 1 of 15, 110 s | 15 of 15, 0.8 s |-| 4 of them returning at once | 117-135 s | 4.3-5.8 s |-| 2 agents, 24 requests of 60k shared + 40k own, resent | 23 s | 0.5 s |-| A 200k prompt back while 3 streams decode: its first token; their tok/s meanwhile | 199-202 s; 78-80 -> 25 | 2.2-2.4 s; 78-80 -> 60-65 |-| Cold prefill, 8k to 256k tokens (nothing to resume) | 1,623-1,966 tok/s | within 2% (1,595-1,933) |-| Decode, tok/s (prose x1 / x4, structured x1 / x4), full pool | 44.0 / 90.9 / 86.6 / 176.8 | 44.0 / 90.7 / 86.6 / 177.1 |--A restored state gives the same tokens as a fresh prefill (256 greedy tokens, `draft: false`, compared after a clean-restart and after `kill -9`). Every 8 MiB of a file carries a CRC-32 that is checked on each read; a file that fails it-is dropped on every Spark and the prompt is prefilled. With `PARALLEL` above 1, prompts with images or video are-stored too, under their pictures' content: a request resumes one only with the same pictures in the same places.--Files: one per stored prompt, about 6.7 KB a token a Spark (1.34 GB at 200k tokens), owned by you and readable only by-you (they hold your prompts' tokens); the oldest go first past `SPILL_GIB`, and also when a write would leave less-than `SPILL_MIN_FREE_GIB` (50) GiB free (if dropping old files cannot make that room, the write is skipped). Prompts-under `SPILL_MIN_TOKENS` (8,192) are not written. Its counters are in `/health` (`spill`) and `/metrics`. Design and credits: `NOTICE`,-`CREDITS.md`; the tier's core (`tensorfold/cuda/spill.py`) is model-agnostic and is offered to TensorFold itself.+| All six answered (wall) | 47.0 s / 45.7 s | 14.7 s / 15.0 s |+| Slowest first token | 46.2 s / 45.0 s | 13.5 s / 13.8 s |+| System-prompt tokens prefilled again | 60,160 | 0 |++Its counters: `/health` `prefix_waits` and `prefix_wait_tokens` (requests that waited, prompt tokens they did not+prefill again), `/metrics` `prefix_waits_total` and `prefix_wait_tokens_total`.## Worker weights over NFS@@ -548,7 +622,10 @@ sets a value wins: the environment, then `scripts/local.sh`, then `.env`, then t| `COPY` / `COPY_MAX` | `1` / `15` | copy drafts: when the reply's last 8 tokens occurred before, the tokens that followed are verified ahead of DFlash2's, up to 15 a round || `COPY_CODE` | `1` | 16-row verify windows as CUDA graphs, and copies from the reply itself only after a 16-token match || `SHARED_PREFIX` | `1` | conversations that share a system prompt reuse its prompt state |-| `SPILL_GIB` / `SPILL_DIR` / `SPILL_HIGHWATER` | `0` / `~/.cache/tensorfold-spill` / `0.70` | the spill tier: kept prompt states on local disk, up to `SPILL_GIB` GiB a Spark (0: off), written early past `SPILL_HIGHWATER` of the pool ([Spill tier](#spill-tier-optional)) |+| `SPILL_GIB` / `SPILL_DIR` | `0` / `~/.cache/tensorfold-spill` | the spill tier: kept prompt states on local disk, written when kept, up to `SPILL_GIB` GiB a Spark (0: off) ([Spill tier](#spill-tier-optional)) |+| `SPILL_QUOTA` / `SPILL_TURNS` | `0` / `4` | the spill tier's share of `SPILL_GIB` one conversation may hold before it trims its own old turns and forks (0: no quota), and the newest states kept on a conversation's path, older turns trimmed as each one is written (2: heavy agent loops or a small disk; 8+: chats with deep edits; 0: every turn until room is needed) |+| `SPILL_RELEASE_MIB` | an eighth of `MEMORY_RESERVE_GIB` | the most MiB of rows the spill tier copies to host memory while they wait to be written (rows freed or overwritten first); a state past it is not stored |+| `PREFIX_WAIT` | `0` | a request whose prompt starts with what another request is still prefilling (a shared system prompt) waits for that state instead of prefilling it too ([A system prompt prefilled once](#a-system-prompt-prefilled-once-for-every-agent)) || `MAX_TOKENS` | `32768` | the reply budget (reasoning and answer) of a request that sets no `max_tokens`; TensorFold's own default is 4,096 || `THINKING` | `1` (`0` with `ABLIT=1`) | think before answering by default; `0` answers directly unless a request asks to think || `VISION` / `VISION_URLS` | `1` / `0` | image and video input; `1` also accepts public `https://` URLs |@@ -566,6 +643,9 @@ 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), 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_SPILL_READ_BLOCKS` | `16` | the blocks restores read ahead into pinned host memory (12.1 MiB each on two Sparks; printed at start). The first ten go in the two 64 MiB read buffers `spill.preallocate` pins at start; the rest is pinned before the pool is sized, in power-of-two pieces, and the pool pays for those. Measured on two Sparks at `PARALLEL=4` (the next turn of a 260k-token conversation restored beside a decoding stream: pool tokens given up, the read, the whole turn): 9 blocks 0, 1.33 s, 7.28 s; 16 14,336, 0.85 s, 6.80 s; 21 24,576, 0.67 s, 6.59 s; 32 49,152, 0.47 s, 6.48 s. 9 is the free setting; above 16 each block buys about half as much per pool token or less ([Spill tier](#spill-tier-optional)) |+| `TF_GLM_SPILL_STAGE_MIB` | `256` | the pinned ring writes go through, in MiB. Writes come at prefill's pace (~14 MB/s a Spark), far below the disk's: 64 to 512 MiB measured the same (four 30k-token prompts beside a decoding stream: every state on disk within 0.5 s, the stream's pace unchanged) |+| `TF_GLM_SPILL_LOAD_MS` | `40` | the longest the restores' copies may pause the other requests between two decode rounds (every restore in flight shares it, each first in turn; an idle server copies at once). On GB10 the copy, within unified memory, outruns the NVMe reads feeding it, so the limit is rarely reached: 10 to 160 ms gave the same restore times (a 260k-token conversation's next turn beside a decoding stream: 1.7-1.8 s; two at once 2.1-2.9 s) and the same stalls (at most 50-58 ms for one, 67-100 for two: the resumed turns' own prompt passes, not the copies). It matters when blocks come faster than they are copied (a state still in the page cache): lower means shorter pauses and slower restores || `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. |@@ -715,7 +795,8 @@ 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) on GitHub, [@rwojo](https://x.com/rwojo) on X), #78) | [Spill tier](#spill-tier-optional) |+| Spill tier | `0088-glm-spill-tier` | kept prompt states on local disk on every Spark, read back beside decoding streams, also after a restart; the one-stream engine (`PARALLEL=1`) writes one file a state when memory drops it (`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) |+| Spill tier, blocks | `0128-glm-spill-blocks` | with `PARALLEL` above 1: every kept state written when kept, in 2,048-token blocks later turns share (equal bytes linked), so it survives a crash; room by conversation (old turns, forks, whole conversations, shared prefixes last), `SPILL_QUOTA`; a request can wait for a prefix another one is prefilling (`PREFIX_WAIT=1`, off by default) (block layout, lineage, write-at-keep ring, release and fsync order from #118 by [BadAd84](https://github.com/BadAd84); eviction by conversation for #122, reported by [xiepengqi](https://github.com/xiepengqi); the rest by Robert Wojciechowski ([wojo](https://github.com/wojo) on GitHub, [@rwojo](https://x.com/rwojo) on X)) | [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 |diff --git a/patches/0128-glm-spill-blocks.patch b/patches/0128-glm-spill-blocks.patchnew file mode 100644index 0000000..3ec11eb--- /dev/null+++ b/patches/0128-glm-spill-blocks.patch@@ -0,0 +1,2838 @@+# Spill tier, blocks (--spill-gib with --parallel above 1; SPILL_GIB, off by default): every kept prompt state of+# --spill-min-tokens or more is written to local disk when it is kept, in blocks of 2048 tokens that later turns and+# forks share (named by a hash chained over the ids and salted with the lineage; equal bytes linked), through a+# pinned ring between rounds, so it survives an eviction, a restart and a crash. Room goes by conversation: old turns,+# abandoned forks, whole conversations, shared prefixes last; an optional per-conversation quota; the free-disk+# floor. Reads beside decoding, after every rank says it holds the state (HAS): reader threads read and check blocks+# into pinned slots, the engine copies them between rounds (TF_GLM_SPILL_LOAD_MS; LOADPART takes rank 1 as far). Rows+# copied to host memory before they go have their own cap (TF_GLM_SPILL_RELEASE_MIB); one engine a folder and rank+# (a flock: a second runs without the tier, the one-stream store's too); temporary files O_EXCL | O_NOFOLLOW. A+# request whose prefix another one is still prefilling can wait for that state (TF_GLM_PREFIX_WAIT=1, off by+# default). New tensorfold/cuda/spill_blocks.py (no model code).+# Block layout, lineage, write-at-keep ring, release and fsync order: PR #118 by @BadAd84; eviction by conversation+# for issue #122, reported by @xiepengqi; the rest by Robert Wojciechowski (GitHub @wojo, X @rwojo). Builds on+# 0088-glm-spill-tier. Apache-2.0.+diff --git tensorfold/cuda/spill.py tensorfold/cuda/spill.py+index 40ed4e6..a1c471e 100644+--- tensorfold/cuda/spill.py++++ tensorfold/cuda/spill.py+@@ -71,6 +71,47 @@ def _up(x: int) -> int:+ return -(-x // ALIGN) * ALIGN++++class Busy(RuntimeError):++ """``--snapshot-dir`` is in use by another engine for this rank (``hold``): this one runs without the tier."""++++++def hold(root: str, rank: int) -> int:++ """An exclusive lock on ``root`` for ``rank``: ``.lock-rank<rank>`` in it, flock'ed for as long as the engine runs++ (the kernel lets it go when the process ends, ``kill -9`` too). Two engines on one folder would write the same++ files and prune each other's builds (``_prune_builds``), so the second gets ``Busy``. Its descriptor, for++ ``unhold``."""++++ import fcntl++++ path = os.path.join(root, f".lock-rank{int(rank)}")++ fd = os.open(path, os.O_RDWR | os.O_CREAT | getattr(os, "O_NOFOLLOW", 0), 0o600)++ try:++ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)++ except BlockingIOError:++ try:++ who = os.pread(fd, 64, 0).decode(errors="replace").strip() or "?"++ except OSError:++ who = "?"++ os.close(fd)++ raise Busy(f"{root} is in use by another engine as rank {rank} (pid {who}; {path})") from None++ except BaseException:++ os.close(fd)++ raise++ with contextlib.suppress(OSError):++ st = os.stat(root)++ if os.geteuid() == 0 and st.st_uid != 0: # (the folder's owner's, like every file in it)++ os.fchown(fd, st.st_uid, st.st_gid)++ os.ftruncate(fd, 0)++ os.pwrite(fd, f"{os.getpid()}\n".encode(), 0)++ return fd++++++def unhold(fd: int | None) -> None:++ if fd is not None and fd >= 0:++ with contextlib.suppress(OSError):++ os.close(fd) # (closing the descriptor drops the flock)+++++ @dataclass+ class SpillConfig:+ """``tensorfold serve`` flags of the tier (every rank must be started with the same values)."""+@@ -484,17 +525,28 @@ class SpillStore:+ self._dirty = False+ self._last_dir_sync = 0.0+ self._dir_lock = threading.Lock()+- problem, pruned_builds = "", 0++ problem, pruned_builds, busy = "", 0, ""++ self._held = None # the folder's lock for this rank (``hold``)+ try:++ os.makedirs(cfg.root, exist_ok=True)++ self._held = hold(cfg.root, self.rank)+ for d in (self.top, self.dir): # prompts' token ids: this user's only+ os.makedirs(d, mode=0o700, exist_ok=True)+ os.chmod(d, 0o700)+ self._own(d)+ pruned_builds = self._prune_builds()+ self._scan()++ except Busy as exc:++ busy = str(exc)+ except OSError as exc:+ problem = repr(exc)+- flags = gather([int(bool(problem))]) if self.world > 1 and gather is not None else [[int(bool(problem))]]++ code = 2 if busy else int(bool(problem))++ flags = gather([code]) if self.world > 1 and gather is not None else [[code]]++ held = [r for r, row in enumerate(flags) if row[0] == 2]++ if held: # every rank alike: the tier off on all of them++ unhold(self._held)++ self._held = None++ raise Busy(busy or f"{cfg.root}: rank(s) {held} found it in use by another engine")+ bad = [r for r, row in enumerate(flags) if row[0]]+ if bad: # every rank stops alike: none waits on another+ raise RuntimeError(f"--snapshot-dir {cfg.root}: rank(s) {bad} cannot use it"+diff --git tensorfold/cuda/spill_blocks.py tensorfold/cuda/spill_blocks.py+new file mode 100644+index 0000000..fd866fa+--- /dev/null++++ tensorfold/cuda/spill_blocks.py+@@ -0,0 +1,1804 @@++"""The spill tier's block store for a shared pool of cache rows (``tensorfold serve --spill-gib`` with several streams):++every kept prompt state is written to this rank's disk when it is kept, so it survives an eviction, a restart and a++crash, and a later request that extends the same tokens reads it back instead of prefilling them.++++A state is its rows in the pool (one tensor a cache plane, ``div`` tokens a row) plus a small state (the family's++snapshot fields: recurrences, windows, a head row; ``spill.encode``). On disk:++++- the rows, in blocks of ``block`` tokens (the pool's extent alignment). A block is named by a hash chained over the++ ids up to its end and salted with the state's lineage (the computation its rows belong to: a stream that resumed++ from a state forks that state's lineage at the resume point, ``fork``: the same names before the block holding it,++ its own from there; a fresh prefill starts its own), so a later turn of a conversation, or a fork that resumed from++ it, names the blocks its earlier turns wrote and writes only its new ones. States of the same ids computed apart++ (another prompt chunking: other bits) never share a block by name; a block whose bytes equal one already on disk is++ linked to it instead of written again (content dedup: two streams that prefilled the same system prompt at once++ store it once);++- a point a state: ``points/<key>.ids`` (its ids; with pictures its keyed ids and its tokens), ``points/<key>.st``++ (its small state, safetensors), then ``points/<key>.json`` naming its blocks with a CRC-32 of each, written LAST, so++ a point with its json is complete. Every file goes to a temporary name, is fsynced and renamed; the folders are++ fsynced before a point's json is. Blocks are written with O_DIRECT where the file system takes it (the page cache++ shares a unified-memory GPU's memory).++++Writes go through a bounded ring of pinned host slots: when a state is kept only its small state, and the block its++end cuts (a pooled-key row there is still filling), are copied to the host; its other rows stay in the pool until++written. Between rounds the engine calls ``pump`` (a few blocks a call, one gather and one copy each), the writer++thread writes each slot, then frees it; at idle ``drain`` writes the rest. Rows about to be freed or overwritten while++still waiting are copied to the host at once (``release``). Reads run on a reader thread (blocks read ahead into++pinned slots on several threads, each checked against its CRC-32); the engine copies the blocks read into the pool++between rounds (``step``), so other streams keep decoding and no CUDA work is issued off the engine's thread (a reader++issuing copies beside a decoding stream waited for the engine on every call, ~0.25 ms each); rows a memcpy may not++reach (patch 0072's display span) go by kernel.++++Every rank keeps its own disk and decides alone what to keep there; the engine asks every rank before a read++(``has``) and drops a state everywhere when any rank's read fails its checks.++++One engine a folder and rank: the store holds ``spill.hold``'s lock on ``<root>/.lock-rank<rank>`` while it runs; a++second engine there (any build) gets ``spill.Busy`` before it reads, prunes or writes anything, and runs without the++tier. Temporary files are opened O_EXCL | O_NOFOLLOW (``_open_new``). Rows ``release`` copies to pageable host memory++(and the block a keep cuts) count against ``release_cap`` (TF_GLM_SPILL_RELEASE_MIB): on a unified-memory GPU that++memory is the pool's and the reserve's, so past it a state whose rows go before they are written is not stored.++++Room. The tier holds at most ``--spill-gib`` a rank and never leaves less than ``--spill-min-free-gib`` free on its++file system. When either needs room, points go in this order (blocks go once no point names them):++++1. old turns: points a later point of the same conversation extends, beyond the newest ``turns`` on the path of the++ conversation's most recently used state (they free only their small state: the later turn names their blocks);++2. abandoned forks: a conversation's states other than its most recently used one and its path, least recently++ used first (they free the blocks only they name);++3. whole conversations, least recently used first;++4. shared-prefix states (a system prompt other conversations resume from), last.++++A conversation is the branch below the deepest shared-prefix state its ids extend (not the lineage: every++conversation that resumed from the same system prompt shares that prompt's lineage). With ``quota`` (a fraction of the++cap) a conversation holding more than its share trims its own old turns and forks before a write of its own goes on.++++Credits: the block layout, the lineage, writing a state when it is kept through a pinned staging ring, ``release`` and++the fsync order are the NVMe KV tier of MiaAI-Lab/GLM-5.3-Flash-EXL3-2x-DGX-Sparks-TensorFold pull request #118,++authored by BadAd84 (https://github.com/BadAd84), carried over here. The spill tier around it (``spill.py``, patch++0088), lineage forks at each resume point, eviction by conversation and the quota (issue #122, reported by xiepengqi,++https://github.com/xiepengqi), the free-disk floor making room in that order, content dedup by hard link, reads beside++decoding after every rank's HAS (copied between rounds, as #118 does), and pictures by content keys are by++Robert Wojciechowski (GitHub @wojo, X @rwojo)."""++++from __future__ import annotations++++import concurrent.futures++import contextlib++import errno++import hashlib++import json++import os++import queue++import shutil++import struct++import threading++import time++import zlib++from collections.abc import Sequence++from concurrent.futures import ThreadPoolExecutor++from typing import Any++++import numpy as np++import torch++++from . import spill as _sp++++FORMAT = "tensorfold-cuda-spill-blocks-1"++READERS = 8 # blocks read at once on a load (cold NVMe reads scale with the reads in flight)++READ_BLOCKS = 16 # TF_GLM_SPILL_READ_BLOCKS: blocks loads read ahead into pinned slots (GLM on two++ # Sparks: 12.1 MiB a block; spill.preallocate's read buffers hold the first ten, the rest++ # comes out of the pool, about 14k tokens at PARALLEL=4; 9 costs it nothing): a slot is++ # free again only once the engine copied it out, so beside a decoding stream a load moves++ # at most this many a round (pin_read_ahead)++STAGE_MIB = 256 # TF_GLM_SPILL_STAGE_MIB: the pinned ring writes go through (at least two blocks)++++++def read_blocks() -> int:++ """TF_GLM_SPILL_READ_BLOCKS: the blocks a load reads ahead into (at least one a reader thread)."""++++ return max(READERS, _count("TF_GLM_SPILL_READ_BLOCKS", READ_BLOCKS, "blocks"))++++++def pin_read_ahead(block_bytes: int) -> int:++ """The engine, before it sizes its pool from the memory left: room for ``read_blocks()`` blocks of ``block_bytes``++ (the engine's bytes a pool block, at least a stored block's) read ahead. ``spill.preallocate``'s read buffers,++ pinned before the engine read its free memory, hold the first of them; the rest is pinned now in pieces of a power++ of two bytes, at most ``spill.CHUNK`` each: torch's pinned allocator rounds every allocation up to a power of two,++ so a 12.1 MiB slot alone would hold 16 MiB, and eleven in one allocation 256 MiB. ``ring`` carves every whole++ stored block out of them. The bytes pinned now, which the pool pays for (the preallocated ones came out of the++ margin, as the write buffers do)."""++++ per = _up(block_bytes)++ bufs = _sp._PINNED.setdefault("read", [])++ want = read_blocks() * per - sum(b.numel() for b in bufs)++ pin = torch.cuda.is_available()++ took = 0++ while want > 0:++ size = 1 << (max(min(want, _sp.CHUNK), per) - 1).bit_length()++ bufs.append(torch.empty(size, dtype=torch.uint8, pin_memory=pin))++ took += size++ want -= size++ return took++++++def _count(name: str, default: int, unit: str) -> int:++ raw = str(os.environ.get(name, "") or "").strip() or str(default)++ try:++ n = int(raw)++ except ValueError:++ n = 0++ if n < 1:++ raise ValueError(f"{name}: whole {unit} >= 1, not {raw!r}")++ return n++PUMP_BLOCKS = 4 # at most this many blocks a pump (one call between two rounds, on the engine loop)++BACKLOG = 16 << 30 # bytes of rows waiting to be written past which a new state is not queued++TURNS = 4 # newest states kept on a conversation's path; older turns go once a newer one is written++LOAD_WAIT_S = 60.0 # a read of a point still being written waits this long for it++RELEASE_SHARE = 8 # TF_GLM_SPILL_RELEASE_MIB unset: rows ``release`` may hold in host memory, this share of++ # the memory reserve the start-up budget leaves free (14.5 GiB on two Sparks: 1.8 GiB)++++++def release_cap() -> int:++ """TF_GLM_SPILL_RELEASE_MIB: the most bytes of rows copied to pageable host memory that wait for the writer++ (``release``, and the block a kept state's end cuts). On a unified-memory GPU that memory is the pool's and the++ reserve's, so by default an eighth of ``capacity.reserve_bytes`` (``TENSORFOLD_MEMORY_RESERVE_GIB``, else a tenth of++ the memory, at least 4 GiB). 0: ``release`` copies nothing (a state whose rows go before they are written is not++ stored)."""++++ raw = str(os.environ.get("TF_GLM_SPILL_RELEASE_MIB", "") or "").strip()++ if raw:++ try:++ mib = float(raw)++ except ValueError:++ mib = -1.0++ if not mib >= 0:++ raise ValueError(f"TF_GLM_SPILL_RELEASE_MIB: MiB >= 0, not {raw!r}")++ return int(mib * (1 << 20))++ from .capacity import reserve_bytes++++ try:++ total = int(os.sysconf("SC_PAGE_SIZE") * os.sysconf("SC_PHYS_PAGES"))++ except (ValueError, OSError, AttributeError):++ total = 128 << 30++ try:++ reserve = reserve_bytes(total, host=True)++ except ValueError: # (a reserve the start-up budget refuses: its own default)++ reserve = max(4 << 30, total // 10)++ return reserve // RELEASE_SHARE++++++def _up(x: int) -> int:++ return -(-x // _sp.ALIGN) * _sp.ALIGN++++++def _host(t: torch.Tensor) -> torch.Tensor:++ """``t`` on the host, into touched pages (a copy from the GPU into fresh pageable memory faults every page in on++ the way: ~0.1 GiB/s against ~35 GiB/s into touched pages, on the engine loop)."""++++ if t.device.type == "cpu":++ return t.clone()++ out = torch.empty(t.shape, dtype=t.dtype, device="cpu")++ if out.numel():++ out.view(-1).view(torch.uint8).fill_(0)++ out.copy_(t)++ return out++++++def _crc(mv) -> int:++ return zlib.crc32(mv)++++++def _digest(mv) -> bytes:++ return hashlib.blake2b(mv, digest_size=16).digest()++++++def fork(lineage: str, name: str, at: int) -> str:++ """The lineage of a request that resumed from a state of ``lineage`` at token ``at`` and computes its own rows from++ there: the same names for the blocks before ``at``, its own from the block holding ``at`` on."""++++ return f"{lineage}|{name}@{int(at)}"++++++def _segments(lineage: str) -> tuple[bytes, list[tuple[int, bytes]]]:++ head, *rest = (lineage or "").split("|")++ forks = []++ for part in rest:++ name, _, at = part.rpartition("@")++ forks.append((int(at), f"|{name}@{at}".encode()))++ return head.encode(), forks++++++def block_hashes(ids: np.ndarray, block: int, lineage: str = "") -> list[tuple[int, int, str]]:++ """(start, end, name) of each block of ``ids``: whole blocks, then the tail [k * block, n) if any. A name covers++ the lineage (its first computation, then each fork that holds or precedes the block) and every id up to its++ block's end (chained), the tail's also its length, so equal names mean equal prefixes of one computation."""++++ h, forks = _segments(lineage)++ out, n = [], len(ids)++ a = np.asarray(ids, dtype=np.int64)++ for s in range(0, n, block):++ e = min(n, s + block)++ salt = b"".join(f for at, f in forks if s <= at < e)++ d = hashlib.sha256(h + salt + a[s:e].tobytes() + (b"" if e - s == block else str(e).encode()))++ out.append((s, e, d.hexdigest()[:32]))++ if e - s == block:++ h = d.digest()++ return out++++++def point_key(ids: Sequence[int]) -> str:++ """A state's name: its ids alone (whichever computation), 16 hex digits and its length."""++++ a = np.asarray(ids, dtype=np.int64)++ return f"{hashlib.sha256(a.tobytes()).hexdigest()[:16]}-{len(a)}"++++++def key_ints(key: str) -> list[int]:++ """A key as three int32s for an op payload."""++++ h, n = key.split("-")++ v = int(h, 16)++ hi, lo = (v >> 32) & 0xFFFFFFFF, v & 0xFFFFFFFF++ return [hi - (1 << 32) if hi >= 1 << 31 else hi, lo - (1 << 32) if lo >= 1 << 31 else lo, int(n)]++++++def ints_key(hi: int, lo: int, n: int) -> str:++ return f"{((hi & 0xFFFFFFFF) << 32) | (lo & 0xFFFFFFFF):016x}-{n}"++++++def _rows(p, s: int, e: int) -> tuple[int, int]:++ """Rows of plane ``p`` (relative to an extent's base) that tokens [s, e) occupy: every row holding one of them,++ rounded up (a row still filling at a state's end holds its tokens so far), never the row past them."""++++ return s // p.div, -(-e // p.div)++++++def _span_bytes(planes, s: int, e: int) -> int:++ out = 0++ for p in planes:++ a, b = _rows(p, s, e)++ out += (b - a) * p.tensor[0].numel() * p.tensor.element_size()++ return out++++++class Corrupt(Exception):++ """A file that does not match its point (a CRC-32, a size): the read fails, the point goes."""++++++# -- small files -----------------------------------------------------------------------------------------------------++def _fsync_dir(path) -> None:++ fd = os.open(path, os.O_RDONLY | _NOFOLLOW)++ try:++ os.fsync(fd)++ finally:++ os.close(fd)++++++def _small_parts(items: list, layer: dict) -> list:++ """A small state as a safetensors file (``spill.encode``'s items and layer, no pickle): its pieces in order, the++ header then each tensor's bytes (views of the host tensors: nothing copied)."""++++ header, _ = _sp._header(items, {"format": FORMAT, "layer": json.dumps(layer)})++ return [memoryview(header)] + [memoryview(t.contiguous().view(-1).view(torch.uint8).numpy()) for _, t in items++ if t.numel()]++++++def _small_read(raw: bytearray, classes: Sequence[str]) -> Any:++ """A small state from its file's bytes: its tensors are views of ``raw`` (no copy; the caller keeps ``raw``)."""++++ header, at = _sp._parse_header(bytes(raw[:8 + struct.unpack("<Q", raw[:8])[0]]))++ meta = header.get("__metadata__") or {}++ if meta.get("format") != FORMAT:++ raise Corrupt("a small state of another format")++ tensors = {}++ for name, d in header.items():++ if name == "__metadata__":++ continue++ a, b = d["data_offsets"]++ dt = _sp._TD[d["dtype"]]++ if b > a:++ tensors[name] = torch.frombuffer(raw, dtype=torch.uint8, count=b - a, offset=at + a).view(dt).reshape(++ d["shape"])++ else:++ tensors[name] = torch.empty(d["shape"], dtype=dt)++ return _sp.decode(json.loads(meta["layer"]), tensors, classes)++++++def _aligned_buffer(n: int) -> np.ndarray:++ """``n`` bytes (rounded up to 4 KiB) at a 4 KiB-aligned address: what O_DIRECT reads and writes."""++++ raw = np.empty(_up(n) + _sp.ALIGN, dtype=np.uint8)++ at = (-raw.ctypes.data) % _sp.ALIGN++ return raw[at:at + _up(n)]++++++_NOFOLLOW = getattr(os, "O_NOFOLLOW", 0)++_NEW = os.O_WRONLY | os.O_CREAT | os.O_EXCL | _NOFOLLOW++++++def _open_new(tmp: str, extra: int = 0) -> int:++ """A temporary file made new: O_EXCL never opens one already at that name, so never through a symlink planted++ there either (O_NOFOLLOW besides). A leftover at the name (an earlier write a crash cut short; an O_DIRECT open the++ file system refused after creating it) is removed first, the name itself, never what it points to."""++++ try:++ return os.open(tmp, _NEW | extra, 0o600)++ except FileExistsError:++ os.unlink(tmp)++ return os.open(tmp, _NEW | extra, 0o600)++++++def _drop_cache(fd: int) -> None:++ try:++ os.posix_fadvise(fd, 0, 0, os.POSIX_FADV_DONTNEED)++ except (AttributeError, OSError):++ pass++++++def _put(path: str, data, owner, direct: bool = False) -> int:++ """``data`` (bytes, or a list of pieces written in order) to ``path`` through a temporary name, fsynced, renamed;++ its CRC-32. ``direct``: through one 4 KiB-aligned buffer with O_DIRECT (where the file system takes it), so the++ page cache, which on a unified-memory GPU is the GPU's memory, keeps no copy; else written and its pages dropped++ after the fsync. A failed write (a full disk) leaves no temporary file."""++++ tmp = os.path.join(os.path.dirname(path), "." + os.path.basename(path))++ parts = [m.cast("B") if m.format != "B" or m.ndim != 1 else m++ for m in (data if isinstance(data, list) else [memoryview(data)])]++ total = sum(len(m) for m in parts)++ crc = 0++ try:++ fd = -1++ if direct and hasattr(os, "O_DIRECT"):++ try:++ fd = _open_new(tmp, os.O_DIRECT)++ except OSError as exc:++ if exc.errno != errno.EINVAL:++ raise++ try:++ if fd >= 0: # one aligned buffer, written whole, then cut to size++ buf = _aligned_buffer(total)++ at = 0++ for m in parts:++ buf[at:at + len(m)] = np.frombuffer(m, dtype=np.uint8)++ at += len(m)++ buf[at:] = 0++ crc = zlib.crc32(memoryview(buf)[:total])++ out = memoryview(buf)++ while len(out):++ k = os.write(fd, out)++ if k != len(out) and k % _sp.ALIGN: # (a partial O_DIRECT write: the rest, buffered)++ os.close(fd)++ fd = os.open(tmp, os.O_WRONLY | _NOFOLLOW)++ os.lseek(fd, k - k % _sp.ALIGN, os.SEEK_SET)++ out = out[k - k % _sp.ALIGN:]++ continue++ out = out[k:]++ os.ftruncate(fd, total)++ else:++ fd = _open_new(tmp)++ for mv in parts:++ crc = zlib.crc32(mv, crc)++ while len(mv):++ mv = mv[os.write(fd, mv):]++ os.fsync(fd)++ _drop_cache(fd) # (clean now: nothing of it stays in memory)++ finally:++ if fd >= 0:++ os.close(fd)++ _chown(tmp, owner)++ os.replace(tmp, path)++ except BaseException:++ try:++ os.remove(tmp)++ except OSError:++ pass++ raise++ return crc++++++def _chown(path: str, owner) -> None:++ if owner is not None:++ try:++ os.chown(path, *owner)++ except OSError:++ pass++++++# -- the index ---------------------------------------------------------------------------------------------------------++class Point:++ """A complete state on this rank's disk."""++++ __slots__ = ("blocks", "chain", "crcs", "digests", "fields", "head", "ids", "key", "lineage", "n", "shared",++ "small_bytes", "small_crc", "tokens", "used")++++ def __init__(self, key, n, ids, tokens, lineage, blocks, crcs, digests, small_crc, small_bytes, shared, head,++ used, chain, fields=None) -> None:++ self.key, self.n, self.ids, self.tokens, self.lineage = key, n, ids, tokens, lineage++ self.blocks, self.crcs, self.digests = blocks, crcs, digests++ self.small_crc, self.small_bytes, self.shared, self.head = small_crc, small_bytes, shared, head++ self.used, self.chain, self.fields = used, chain, fields or {}++++++def _chain(ids: np.ndarray, block: int) -> list[str]:++ """Hashes of ``ids`` (no lineage) at each whole block's end: two states' ids share a prefix of k whole blocks++ exactly when their first k hashes agree."""++++ return [h for s, e, h in block_hashes(ids, block) if e - s == block]++++++class Job:++ """A kept state waiting to be written: its new rows' blocks still in the pool at ``where.base`` (its extent, which++ may move), the next one to stage, its small state's host bytes."""++++ def __init__(self, point: Point, new: list, small: tuple, size: int, where, ids_bytes: bytes) -> None:++ self.point, self.new, self.size, self.where = point, new, size, where++ self.small = small # (items, layer): its tensors on the host++ self.ids_bytes = ids_bytes++ self.cut: list[str] = [] # its tail block, copied to the host at keep (``persist``)++ self.next = 0++ self.failed: BaseException | None = None++ self.done = threading.Event()++++++class LoadJob:++ """A read: the reader thread reads its blocks into pinned slots (checked against their CRC-32) and its small state;++ the engine copies each block read into ``where`` at its base then (``step``: between rounds, on the engine's++ stream; the extent may move between two steps). ``queued``: block index -> (slot, bytes, its read's future, its++ tokens, its name); ``next``: the blocks copied. ``done`` once the reader is through, or the read failed++ (``error``; ``bad`` / ``lost``: the blocks that failed here, damaged or missing); ``stop``: the engine gave up on++ it, the reader stops."""++++ def __init__(self, point: Point, where) -> None:++ self.point, self.where = point, where++ self.cond = threading.Condition()++ self.queued: dict[int, tuple] = {}++ self.next = 0++ self.total = len(point.blocks) if point is not None else 0++ self.stop = False++ self.done = threading.Event()++ self.error: BaseException | None = None++ self.bad: set[str] = set() # blocks whose bytes failed (every name of them)++ self.lost: set[str] = set() # blocks whose file is gone (that name)++ self.small = None++ self.stage = None++ self.t0 = time.perf_counter()++++++class BlockStore:++ """This rank's points and blocks, a writer thread, a reader thread."""++++ def __init__(self, cfg, *, planes, block: int, rank: int = 0, world: int = 1, device: Any = "cuda",++ signature: str = "", weights: str = "", model_id: str = "", gather=None, classes: Sequence[str] = (),++ quiet: bool = False, turns: int = TURNS, quota: float = 0.0) -> None:++ self.cfg, self.planes, self.block = cfg, list(planes), int(block)++ self.read_blocks = read_blocks()++ self.stage_mib = _count("TF_GLM_SPILL_STAGE_MIB", STAGE_MIB, "MiB")++ for p in self.planes:++ if self.block % p.div:++ raise ValueError(f"--spill-gib: a cache plane of {p.div} tokens a row does not divide {self.block}")++ self.rank, self.world, self.device = int(rank), int(world), device++ self.model_id, self.classes = model_id, list(classes)++ self.cap = int(cfg.gib * (1 << 30))++ self.floor = int(cfg.min_free_gib * (1 << 30))++ self.turns, self.quota = max(0, int(turns)), float(quota) # turns 0: every turn kept until room is needed++ self.block_bytes = _span_bytes(self.planes, 0, self.block)++ shared = hashlib.sha256(f"{FORMAT}|{signature}|block={self.block}".encode()).digest()++ own = hashlib.sha256(weights.encode()).digest()++ words = [int.from_bytes(h[i:i + 4], "big", signed=True) for h in (shared, own) for i in range(0, 16, 4)]++ if self.world > 1 and gather is not None: # one directory name on every rank++ rows = gather(words)++ differ = [r for r, row in enumerate(rows) if list(row[:4]) != list(rows[0][:4])]++ if differ:++ print(f"[tensorfold] spill rank {self.rank}: rank(s) {differ} run another build or settings than "++ "rank 0, so no rank can resume another's stored prompts until they match", flush=True)++ words = [w for row in rows for w in row[:8]]++ self.compat = hashlib.sha256(np.asarray(words, dtype=np.int32).tobytes()).hexdigest()[:16]++ self.top = os.path.join(cfg.root, f"spill-{self.compat}")++ self.dir = os.path.join(self.top, f"rank{self.rank}")++ self.points_dir, self.blocks_dir = os.path.join(self.dir, "points"), os.path.join(self.dir, "blocks")++ try:++ st = os.stat(cfg.root)++ self.owner = (st.st_uid, st.st_gid) if os.geteuid() == 0 and st.st_uid != 0 else None++ except OSError:++ self.owner = None++ self.lock = threading.RLock()++ self.index: dict[str, Point] = {}++ self.have: dict[str, tuple[int, int, bytes]] = {} # block on disk -> (its CRC-32, its inode, its digest)++ self.content: dict[bytes, str] = {} # a block's bytes' digest -> a block on disk with them++ self.inodes: dict[int, list] = {} # inode -> [bytes, names on disk]++ self.small_on_disk = 0 # bytes of the points' files++ self.inflight: set[str] = set() # points and blocks queued, not yet complete++ self.reading: set[str] = set() # points being read (never evicted meanwhile)++ self.pinned: set[str] = set() # blocks a persist deciding now counts on (never collected)++ self.parent: dict[str, str | None] = {} # point -> the longest other point its ids extend++ self.refs: dict[str, int] = {} # block -> points and waiting states naming it++ self.version = 0 # bumped whenever a point comes or goes (the summary's key)++ self._summary_cache: tuple | None = None++ self.block_bytes_on_disk = 0 # bytes of the blocks' inodes (each counted once)++ self.waiting: dict[str, Job] = {} # point key -> its job until written++ self.pending: list[Job] = [] # jobs whose rows wait in the pool (the engine loop's)++ self.jobs: queue.Queue = queue.Queue() # the writer's work++ self.reads: queue.Queue = queue.Queue()++ self.backlog = 0++ self.release_cap = release_cap() # host bytes of rows waiting for the writer, at most++ self.host_bytes = 0 # host bytes of rows waiting for the writer now++ self.stats = {k: 0 for k in (++ "written", "written_blocks", "written_bytes", "dedup_blocks", "dedup_bytes", "skipped", "no_space",++ "backlog_skipped", "write_failed", "pruned_turns", "pruned_forks", "pruned_conversations",++ "pruned_shared", "quota_trims", "loaded", "loaded_tokens", "loaded_bytes", "load_failed", "crc_failed",++ "load_unfit", "staged_blocks", "released_blocks", "unwritten_evicted", "dropped", "trimmed_turns",++ "written_small_bytes", "disk_lookups", "disk_hits", "has_refused", "release_dropped")}++ self.stats.update(write_s=0.0, load_s=0.0, keep_s=0.0, pump_s=0.0, load_small_s=0.0)++ self.unwritten_by: dict[str, int] = {}++ self.restore_ms: list[float] = []++ self.direct = bool(getattr(cfg, "direct", True)) and hasattr(os, "O_DIRECT")++ self.small_direct = self.direct # small states: O_DIRECT through their own aligned buffer++ problem, pruned_builds, busy = "", 0, ""++ self._held = None # the folder's lock for this rank (``spill.hold``)++ try:++ os.makedirs(cfg.root, exist_ok=True)++ self._held = _sp.hold(cfg.root, self.rank) # (before any file of it is read, pruned or written)++ for d in (self.top, self.dir, self.points_dir, self.blocks_dir):++ os.makedirs(d, mode=0o700, exist_ok=True)++ os.chmod(d, 0o700)++ _chown(d, self.owner)++ pruned_builds = self._prune_builds()++ self._scan()++ except _sp.Busy as exc:++ busy = str(exc)++ except OSError as exc:++ problem = repr(exc)++ code = 2 if busy else int(bool(problem))++ flags = gather([code]) if self.world > 1 and gather is not None else [[code]]++ held = [r for r, row in enumerate(flags) if row[0] == 2]++ if held: # every rank alike: the tier off on all of them++ _sp.unhold(self._held)++ self._held = None++ raise _sp.Busy(busy or f"{cfg.root}: rank(s) {held} found it in use by another engine")++ bad = [r for r, row in enumerate(flags) if row[0]]++ if bad: # every rank stops alike: none waits on another++ raise RuntimeError(f"--snapshot-dir {cfg.root}: rank(s) {bad} cannot use it"++ + (f": {problem}" if problem else ""))++ self.slots: list[torch.Tensor] = []++ self.free_slots: queue.Queue = queue.Queue()++ self.dev_slot: torch.Tensor | None = None++ self.slot_events: list = [] # a write slot's event, reused by every block it stages++ self.read_slots: list[torch.Tensor] = []++ self._hasher = ThreadPoolExecutor(2, thread_name_prefix=f"spill-hash-{self.rank}")++ self._readers = ThreadPoolExecutor(READERS, thread_name_prefix=f"spill-read-{self.rank}")++ threading.Thread(target=self._writer, name=f"spill-writer-{self.rank}", daemon=True).start()++ threading.Thread(target=self._read_loop, name=f"spill-reader-{self.rank}", daemon=True).start()++ if self.rank == 0 and not quiet:++ print(f"[tensorfold] spill: {self.top} ({cfg.gib:g} GiB a rank, blocks of {self.block} tokens, written "++ f"when kept, from {cfg.min_tokens} tokens{', O_DIRECT' if self.direct else ''}, floor "++ f"{cfg.min_free_gib:g} GiB free, {self.read_blocks} blocks read ahead "++ f"({self.read_blocks * _span_bytes(self.planes, 0, self.block) / (1 << 20):.0f} MiB), a "++ f"{self.stage_mib} MiB write ring): {len(self.index)} stored prompts from before this start, "++ f"{self.stored() / (1 << 30):.1f} GiB"++ + (f"; pruned {pruned_builds} older builds" if pruned_builds else ""), flush=True)++++ # -- housekeeping --------------------------------------------------------------------------------------------------++ def close(self) -> None:++ """Let the folder go (``spill.hold``): another engine may use it now. Only once nothing is written or read."""++++ _sp.unhold(self._held)++ self._held = None++++ def _prune_builds(self) -> int:++ """Folders of other compatibility hashes (other builds, formats, layouts): the newest ``keep_builds`` stay."""++++ try:++ others = [os.path.join(self.cfg.root, d) for d in os.listdir(self.cfg.root)++ if d.startswith("spill-") and os.path.join(self.cfg.root, d) != self.top]++ except OSError:++ return 0++ others = [d for d in others if os.path.isdir(d)]++ others.sort(key=lambda d: os.stat(d).st_mtime, reverse=True)++ gone = 0++ for d in others[max(0, int(getattr(self.cfg, "keep_builds", 1))):]:++ mine = os.path.join(d, f"rank{self.rank}")++ if os.path.isdir(mine):++ shutil.rmtree(mine, ignore_errors=True)++ gone += 1++ try:++ os.rmdir(d)++ except OSError:++ pass++ return gone++++ def disk_free(self) -> int:++ try:++ st = os.statvfs(self.dir)++ return st.f_bavail * st.f_frsize++ except OSError:++ return 0++++ def stored(self) -> int:++ with self.lock:++ return self.block_bytes_on_disk + self.small_on_disk++++ def _block_path(self, h: str) -> str:++ return os.path.join(self.blocks_dir, f"{h}.bin")++++ def _point_path(self, key: str, suffix: str) -> str:++ return os.path.join(self.points_dir, f"{key}{suffix}")++++ def _add_block(self, h: str, crc: int, digest: bytes | None) -> None:++ """Lock held: block ``h`` is on disk (its inode counted once whatever names it)."""++++ st = os.stat(self._block_path(h))++ self.have[h] = (crc, st.st_ino, digest or bytes(16))++ if st.st_ino not in self.inodes:++ self.inodes[st.st_ino] = [st.st_size, set()]++ self.block_bytes_on_disk += st.st_size++ self.inodes[st.st_ino][1].add(h)++ if digest is not None:++ self.content.setdefault(digest, h)++++ def _drop_block(self, h: str) -> None:++ """Lock held: block ``h``'s name goes (its bytes once no name holds its inode)."""++++ got = self.have.pop(h, None)++ if got is None:++ return++ ent = self.inodes.get(got[1])++ if ent is not None:++ ent[1].discard(h)++ if not ent[1]:++ self.inodes.pop(got[1], None)++ self.block_bytes_on_disk -= ent[0]++ if self.content.get(got[2]) == h: # its bytes under another name, or gone++ other = next(iter(ent[1]), None) if ent is not None else None++ if other is not None:++ self.content[got[2]] = other++ else:++ self.content.pop(got[2], None)++ try:++ os.remove(self._block_path(h))++ except OSError:++ pass++++ def _scan(self) -> None:++ """Points whose json, ids, small state and every block are on disk; the rest (a write a crash cut short, a++ damaged point) go, and so do blocks no point names."""++++ for d in (self.points_dir, self.blocks_dir):++ for f in os.listdir(d):++ if f.startswith("."): # a write cut off before its rename++ try:++ os.remove(os.path.join(d, f))++ except OSError:++ pass++ present = {f[:-4] for f in os.listdir(self.blocks_dir) if f.endswith(".bin")}++ metas = []++ for f in os.listdir(self.points_dir):++ if f.endswith(".json"):++ p = os.path.join(self.points_dir, f)++ try:++ metas.append((os.stat(p).st_mtime, f[:-5]))++ except OSError:++ pass++ for used, key in sorted(metas):++ try:++ with open(self._point_path(key, ".json")) as fh:++ m = json.load(fh)++ if m.get("format") != FORMAT or m["key"] != key:++ raise ValueError("another format")++ with open(self._point_path(key, ".ids"), "rb") as fh:++ raw = fh.read()++ if zlib.crc32(raw) != m["ids_crc"] or not os.path.exists(self._point_path(key, ".st")):++ raise ValueError("ids or small state")++ arr = np.frombuffer(raw, dtype=np.int64)++ n = int(m["n"])++ ids, tokens = arr[:n].copy(), (arr[n:].copy() if len(arr) > n else None)++ blocks = list(m["blocks"])++ if (len(ids) != n or point_key(ids) != key or not all(b in present for b in blocks)++ or [h for _, _, h in block_hashes(ids, self.block, m["lineage"])] != blocks):++ raise ValueError("blocks")++ pt = Point(key, n, ids, tokens, m["lineage"], blocks, [int(c) for c in m["crcs"]],++ [bytes.fromhex(x) for x in m["digests"]], int(m["small_crc"]), int(m["small_bytes"]),++ bool(m["shared"]), bool(m["head"]), float(used), _chain(ids, self.block),++ m.get("fields") or {})++ self.index[key] = pt++ for b, c, dg in zip(blocks, pt.crcs, pt.digests):++ if b not in self.have:++ self._add_block(b, c, dg)++ self.small_on_disk += pt.small_bytes++ except Exception: # noqa: BLE001, S112 (torn, damaged or foreign: gone below)++ continue++ for f in os.listdir(self.points_dir):++ if f.split(".")[0] not in self.index:++ try:++ os.remove(os.path.join(self.points_dir, f))++ except OSError:++ pass++ for b in present - self.have.keys():++ try:++ os.remove(self._block_path(b))++ except OSError:++ pass++ for pt in sorted(self.index.values(), key=lambda p: p.n):++ self.parent[pt.key] = self._parent_of(pt)++ self._ref(pt.blocks, 1)++++ # -- the staging ring and read buffers ---------------------------------------------------------------------------++ def ring(self) -> None:++ """Pinned host slots of one block each for writes (carved from ``spill.preallocate``'s write buffers, else++ allocated now), and as many for reads, all touched now; a device buffer a block is gathered in; an event a++ write slot, made here: making or dropping one later (the writer dropped one a block) waits for the engine's++ round to end whenever it decodes (CUDA holds every other thread's call while the round's readback waits on the++ default stream), ~27 ms a block beside a decoding stream."""++++ if self.slots:++ return++ per = _up(self.block_bytes)++ dev = self.planes[0].tensor.device++ pin = dev.type == "cuda"++++ def carve(bufs, count_min):++ out = []++ for b in bufs:++ for i in range(0, b.numel() - per + 1, per):++ out.append(b[i:i + per])++ while len(out) < count_min:++ out.append(torch.empty(per, dtype=torch.uint8, pin_memory=pin))++ return out++++ self.slots = carve(_sp._PINNED.get("write") or [], max(2, (self.stage_mib << 20) // per))++ early = sum(b.numel() // per for b in _sp._PINNED.get("read") or [])++ self.read_slots = carve(_sp._PINNED.get("read") or [], self.read_blocks)++ if early < self.read_blocks and self.rank == 0:++ print(f"[tensorfold] spill: {self.read_blocks - early} of {self.read_blocks} read-ahead slots pinned after "++ "the pool was sized (from the margin it keeps)", flush=True)++ self.free_reads: queue.Queue = queue.Queue()++ for i in range(len(self.read_slots)):++ self.free_reads.put(i)++ self.read_events: list = [] # (slot, the engine's event after its copy out of it)++ for s in self.slots + self.read_slots:++ s.fill_(0)++ if any(s.data_ptr() % _sp.ALIGN for s in self.slots + self.read_slots):++ self.direct = False++ self.dev_slot = torch.empty(per, dtype=torch.uint8, device=dev)++ if dev.type == "cuda":++ for _ in self.slots:++ ev = torch.cuda.Event()++ ev.record() # (an event is made at its first record)++ self.slot_events.append(ev)++ for i in range(len(self.slots)):++ self.free_slots.put(i)++++ # -- write ---------------------------------------------------------------------------------------------------------++ def wants(self, n: int) -> bool:++ return n >= self.cfg.min_tokens++++ def has(self, key: str) -> bool:++ """Whether this rank holds ``key`` complete (its json, ids, small state and every block)."""++++ with self.lock:++ pt = self.index.get(key)++ return pt is not None and all(b in self.have for b in pt.blocks)++++ def touch(self, key: str) -> None:++ with self.lock:++ pt = self.index.get(key)++ if pt is not None:++ pt.used = time.time()++ try:++ os.utime(self._point_path(key, ".json"), None)++ except OSError:++ pass++++ def persist(self, ids: Sequence[int], obj, *, extent, lineage: str, tokens: Sequence[int] | None = None,++ shared: bool = False, head: bool = False, skip: Sequence[str] = (), fields: dict | None = None) -> str:++ """Every rank, when a state of ``ids`` (keyed ids with pictures; ``tokens`` then its ids) is kept with its rows++ at its extent's rows [base, base + n): its small state (``obj``'s fields, ``spill.encode``) and the block its++ end cuts copied to the host now, its other blocks this disk lacks left in the pool and queued (``pump`` stages++ them, the writer writes them). Ids stored or on their way already are not written again; kept again as a++ shared prefix, their point becomes one (its json rewritten on the writer). Returns what happened ("queued",++ "stored", "no_space", "backlog")."""++++ t0 = time.perf_counter()++ ids = np.asarray(ids, dtype=np.int64)++ n = len(ids)++ key = point_key(ids)++ with self.lock:++ if key in self.index or key in self.inflight:++ pt = self.index.get(key)++ if pt is not None:++ pt.used = time.time()++ elif key in self.waiting: # still being written: its json takes the flag then++ pt = self.waiting[key].point++ if shared and pt is not None and not pt.shared: # the same ids kept again as a shared prefix++ pt.shared = True++ self.version += 1++ if key in self.index: # its json again, on the writer (``_mark_shared``)++ self.jobs.put(("shared", None, key, None))++ self.stats["skipped"] += 1++ return "stored"++ hashes = block_hashes(ids, self.block, lineage)++ pins = {h for _, _, h in hashes}++ with self.lock: # (making room below never takes a block this state names)++ self.pinned |= pins++ try:++ return self._persist(key, n, ids, obj, extent, lineage, tokens, shared, head, skip, fields, hashes, t0)++ finally:++ with self.lock:++ self.pinned -= pins++ self._gc(pins)++++ def _persist(self, key, n, ids, obj, extent, lineage, tokens, shared, head, skip, fields, hashes, t0) -> str:++ with self.lock:++ new = [(s, e, h) for s, e, h in hashes if h not in self.have and h not in self.inflight]++ items, layer = _sp.encode(obj, skip=skip)++ items = [(k, _host(t)) for k, t in items] # (serialized on the writer thread)++ small_n = sum(t.numel() * t.element_size() for _, t in items) + 4096++ size = sum(_span_bytes(self.planes, s, e) for s, e, _ in new)++ need = size + small_n + 8 * n * (2 if tokens is not None else 1)++ pt = Point(key, n, ids, None if tokens is None else np.asarray(tokens, dtype=np.int64), lineage,++ [h for _, _, h in hashes], [], [], 0, small_n, bool(shared), bool(head), time.time(), None,++ fields)++ if self.quota > 0:++ self._trim_own(pt, need)++ short = self.floor + need + self.backlog - self.disk_free()++ over = self.stored() + self.backlog + need - self.cap++ if max(short, over) > self.stored(): # (the disk is full of other things): nothing to evict for++ self.stats["no_space"] += 1++ return "no_space"++ if short > 0 or over > 0:++ self._make_room(max(short, over), protect={key})++ short = self.floor + need + self.backlog - self.disk_free()++ if short > 0 or self.stored() + self.backlog + need > self.cap:++ self.stats["no_space"] += 1++ return "no_space"++ # the block the state's end cuts (a tail): its last pooled-key row is still filling, and the stream goes on++ # writing it in place, so its rows are copied to the host now, as they are at the keep (at most one block)++ cut = [(h, _host(torch.cat(self._parts(extent, s, e)))) for s, e, h in new[-1:] if e - s < self.block]++ with self.lock:++ if self.backlog + size > BACKLOG:++ self.stats["backlog_skipped"] += 1++ return "backlog"++ self.backlog += size++ self.host_bytes += sum(t.numel() * t.element_size() for _, t in cut) # (at most a block a state)++ self.inflight.add(key)++ self.inflight.update(h for _, _, h in new)++ ids_bytes = ids.tobytes() + (b"" if tokens is None else np.asarray(tokens, dtype=np.int64).tobytes())++ job = Job(pt, new[:len(new) - len(cut)], (items, layer), size, extent, ids_bytes)++ job.cut = [h for h, _ in cut]++ self.waiting[key] = job++ self._ref(pt.blocks, 1)++ for h, data in cut: # (written before the blocks the pumps stage)++ self.jobs.put(("rows", job, h, data))++ self.pending.append(job)++ self.stats["keep_s"] += time.perf_counter() - t0++ return "queued"++++ def _parts(self, where, s: int, e: int) -> list[torch.Tensor]:++ """Tokens [s, e) as each plane's rows, where the extent is NOW (it may have moved)."""++++ base = where.base++ out = []++ for p in self.planes:++ a, b = _rows(p, s, e)++ t = p.tensor[base // p.div + a:base // p.div + b]++ out.append(t.reshape(-1).view(torch.uint8))++ return out++++ def pump(self, limit: int | None = PUMP_BLOCKS) -> None:++ """Between rounds (the engine loop, every rank): the waiting states' next blocks, oldest first, into free slots++ - one device gather (a kernel: display-span rows too) and one copy to pinned memory each, on the current stream++ after whatever wrote the rows - handed to the writer with the slot's event (made at start, ``ring``). A state++ whose blocks are all handed goes to the writer whole. Never waits; at most ``limit`` blocks (None: as many as++ the slots allow)."""++++ if not self.pending:++ return++ t0 = time.perf_counter()++ self.ring()++ limit = 1 << 62 if limit is None else limit++ while self.pending:++ job = self.pending[0]++ while job.next < len(job.new):++ if limit <= 0:++ self.stats["pump_s"] += time.perf_counter() - t0++ return++ try:++ slot = self.free_slots.get_nowait()++ except queue.Empty:++ self.stats["pump_s"] += time.perf_counter() - t0++ return++ limit -= 1++ s, e, h = job.new[job.next]++ try:++ parts = self._parts(job.where, s, e)++ nb = sum(t.numel() for t in parts)++ torch.cat(parts, out=self.dev_slot[:nb])++ self.slots[slot][:nb].copy_(self.dev_slot[:nb], non_blocking=True)++ ev = self.slot_events[slot] if self.slot_events else None # (made at start: a GPU's only)++ if ev is not None:++ ev.record()++ except Exception as exc: # noqa: BLE001 (never the engine's: this state is not kept)++ self.free_slots.put(slot)++ job.failed = exc++ job.next = len(job.new)++ print(f"[tensorfold] spill rank {self.rank}: staging {job.point.key} failed: {exc!r}", flush=True)++ break++ job.next += 1++ self.jobs.put(("block", job, h, (slot, nb, ev)))++ self.stats["staged_blocks"] += 1++ self.pending.pop(0)++ self.jobs.put(("point", job, None, None))++ self.stats["pump_s"] += time.perf_counter() - t0++++ def stage_all(self, timeout: float = 10.0) -> None:++ """Every waiting block through the ring now (an engine about to idle: nothing pumps meanwhile), for at most++ ``timeout`` seconds (slots come back as the writer writes); what is left goes at the next pumps."""++++ end = time.monotonic() + timeout++ while self.pending and time.monotonic() < end:++ self.pump(None)++ if self.pending:++ time.sleep(0.001)++++ def drain(self, timeout: float | None = None) -> bool:++ """Every waiting state to the writer and on disk, and the json rewrites queued before (``_mark_shared``) too++ (an idle engine, a shutdown). True when done in time."""++++ end = None if timeout is None else time.monotonic() + timeout++ while self.pending:++ self.pump(None)++ if self.pending:++ time.sleep(0.001)++ if end is not None and time.monotonic() > end:++ return False++ with self.lock:++ jobs = list(self.waiting.values())++ for job in jobs:++ left = None if end is None else max(0.0, end - time.monotonic())++ if not job.done.wait(left):++ return False++ synced = threading.Event() # (behind every rewrite those jobs or a keep queued)++ self.jobs.put(("sync", None, None, synced))++ return synced.wait(None if end is None else max(0.0, end - time.monotonic()))++++ def release(self, extent, keep: int) -> None:++ """``extent``'s rows from ``keep`` on are about to be freed or overwritten: waiting states there reaching past++ ``keep`` get the rest of their blocks copied to the host now, queued for the writer."""++++ for job in self.pending:++ if job.where is not extent or job.point.n <= keep or job.next >= len(job.new):++ continue++ left = job.new[job.next:]++ need = sum(_span_bytes(self.planes, s, e) for s, e, _ in left)++ with self.lock:++ fits = self.host_bytes + need <= self.release_cap++ if fits:++ self.host_bytes += need++ if not fits: # (host memory past TF_GLM_SPILL_RELEASE_MIB): not stored++ job.failed = RuntimeError(f"its {need / (1 << 20):.1f} MiB of rows were to go before they were written, "++ f"past the {self.release_cap / (1 << 20):.1f} MiB of host memory "++ "TF_GLM_SPILL_RELEASE_MIB allows")++ job.next = len(job.new)++ self.stats["release_dropped"] += 1++ continue++ for s, e, h in left:++ data = _host(torch.cat(self._parts(job.where, s, e)))++ self.jobs.put(("rows", job, h, data))++ self.stats["released_blocks"] += 1++ job.next = len(job.new)++++ def _write_block(self, h: str, mv: memoryview, nb: int, room: bool) -> None:++ """The writer: a block (its CRC-32 and digest computed beside the write), or a link to a block on disk with the++ same bytes. Through a temporary name, fsynced, renamed; a failure leaves no temporary file."""++++ data = mv[:nb] # ``room``: mv runs on to a 4 KiB multiple (O_DIRECT)++ crc_f = self._hasher.submit(_crc, data)++ dig_f = self._hasher.submit(_digest, data)++ dig = dig_f.result()++ crc = crc_f.result()++ path, tmp = self._block_path(h), os.path.join(self.blocks_dir, f".{h}.bin")++ with self.lock:++ same = self.content.get(dig)++ same = same if same is not None and same in self.have and self.have[same][0] == crc else None++ try:++ if same is not None: # the same bytes on disk: a second name for them++ try:++ os.link(self._block_path(same), tmp)++ os.replace(tmp, path)++ except OSError: # (gone meanwhile: written below instead)++ same = None++ try:++ os.remove(tmp)++ except OSError:++ pass++ if same is not None:++ with self.lock:++ self._add_block(h, crc, dig)++ self.stats["dedup_blocks"] += 1++ self.stats["dedup_bytes"] += nb++ return++ fd, direct = -1, False++ if self.direct and room:++ try:++ fd, direct = _open_new(tmp, os.O_DIRECT), True++ except OSError as exc:++ if exc.errno != errno.EINVAL:++ raise++ self.direct = False++ if fd < 0:++ fd = _open_new(tmp)++ try:++ out = mv[:_up(nb)] if direct else data++ while len(out):++ k = os.write(fd, out)++ if direct and k != len(out): # (a partial O_DIRECT write: the rest, buffered)++ os.close(fd)++ fd = os.open(tmp, os.O_WRONLY | os.O_TRUNC | _NOFOLLOW)++ out, direct = data, False++ continue++ out = out[k:]++ if direct:++ os.ftruncate(fd, nb)++ os.fsync(fd)++ try:++ os.posix_fadvise(fd, 0, 0, os.POSIX_FADV_DONTNEED)++ except (AttributeError, OSError):++ pass++ finally:++ os.close(fd)++ _chown(tmp, self.owner)++ os.replace(tmp, path)++ with self.lock:++ self._add_block(h, crc, dig)++ self.stats["written_blocks"] += 1++ self.stats["written_bytes"] += nb++ except BaseException:++ try:++ os.remove(tmp)++ except OSError:++ pass++ raise++++ def _writer(self) -> None:++ while True:++ kind, job, h, item = self.jobs.get()++ t0 = time.perf_counter()++ if kind == "block":++ slot, nb, ev = item++ try:++ if ev is not None:++ ev.synchronize()++ if job.failed is None:++ self._write_block(h, memoryview(self.slots[slot].numpy()), nb, True)++ except Exception as exc: # noqa: BLE001 (a full or failing disk: not kept on disk)++ job.failed = exc++ finally:++ self.free_slots.put(slot)++ self.stats["write_s"] += time.perf_counter() - t0++ continue++ if kind == "sync": # (``drain``: everything queued before it is done)++ item.set()++ continue++ if kind == "shared":++ try:++ self._mark_shared(h)++ except Exception as exc: # noqa: BLE001 (the flag holds in memory until a restart)++ print(f"[tensorfold] spill rank {self.rank}: marking {h} shared failed: {exc!r}", flush=True)++ continue++ if kind == "rows":++ try:++ if job.failed is None:++ raw = item.view(-1).view(torch.uint8)++ self._write_block(h, memoryview(raw.numpy()), raw.numel(), False)++ except Exception as exc: # noqa: BLE001++ job.failed = exc++ finally:++ with self.lock:++ self.host_bytes -= item.numel() * item.element_size()++ del item++ self.stats["write_s"] += time.perf_counter() - t0++ continue++ self._write_point(job)++ self.stats["write_s"] += time.perf_counter() - t0++++ def _mark_shared(self, key: str) -> None:++ """The writer: point ``key``'s json again with ``"shared": true`` (its ids kept again as a shared prefix), the++ way it was first written (a temporary name, fsynced, renamed, then the points' folder fsynced). A point dropped++ before is left alone; one dropped while this ran loses the json this wrote back."""++++ with self.lock:++ pt = self.index.get(key)++ if pt is None:++ return++ path = self._point_path(key, ".json")++ try:++ with open(path, "rb") as fh:++ meta = json.loads(fh.read())++ except FileNotFoundError: # (dropped meanwhile)++ return++ meta["shared"] = True++ _put(path, json.dumps(meta).encode(), self.owner)++ _fsync_dir(self.points_dir)++ with self.lock:++ gone = self.index.get(key) is not pt++ if gone:++ try:++ os.remove(path)++ except OSError:++ pass++++ def _write_point(self, job: Job) -> None:++ pt = job.point++ try:++ if job.failed is not None:++ raise job.failed++ with self.lock:++ got = [self.have.get(b) for b in pt.blocks]++ if None in got:++ raise RuntimeError(f"{got.count(None)} of its blocks are no longer on disk")++ pt.crcs = [c for c, _, _ in got]++ pt.digests = [d for _, _, d in got]++ shared = pt.shared # (kept again as shared after this: rewritten below)++ _fsync_dir(self.blocks_dir) # the blocks' renames before the point naming them++ ids_crc = _put(self._point_path(pt.key, ".ids"), job.ids_bytes, self.owner)++ parts = _small_parts(*job.small)++ pt.small_crc = _put(self._point_path(pt.key, ".st"), parts, self.owner, direct=self.small_direct)++ _fsync_dir(self.points_dir)++ meta = {"format": FORMAT, "key": pt.key, "n": pt.n, "lineage": pt.lineage, "blocks": pt.blocks,++ "crcs": pt.crcs, "digests": [d.hex() for d in pt.digests], "ids_crc": ids_crc,++ "small_crc": pt.small_crc, "small_bytes": sum(len(m) for m in parts) + len(job.ids_bytes),++ "shared": shared, "head": pt.head, "fields": pt.fields}++ pt.chain = _chain(pt.ids, self.block)++ _put(self._point_path(pt.key, ".json"), json.dumps(meta).encode(), self.owner)++ _fsync_dir(self.points_dir)++ pt.small_bytes = meta["small_bytes"]++ with self.lock:++ if any(b not in self.have for b in pt.blocks):++ for suffix in (".json", ".st", ".ids"):++ try:++ os.remove(self._point_path(pt.key, suffix))++ except OSError:++ pass++ raise RuntimeError("a block it names was dropped while it was written")++ self.index[pt.key] = pt++ self._ref(pt.blocks, 1) # (its own reference; the waiting one goes below)++ self._adopt(pt)++ self.small_on_disk += pt.small_bytes++ self.stats["written"] += 1++ self.stats["written_small_bytes"] += pt.small_bytes++ self.version += 1++ self._trim_path(pt)++ if pt.shared and not shared:++ self.jobs.put(("shared", None, pt.key, None))++ except Exception as exc: # noqa: BLE001 (only this state is not kept on disk)++ self.stats["write_failed"] += 1++ print(f"[tensorfold] spill rank {self.rank}: writing {pt.key} failed: {exc!r}", flush=True)++ finally:++ job.small = None++ with self.lock:++ self.backlog -= job.size++ self.inflight.discard(pt.key)++ self.inflight.difference_update([h for _, _, h in job.new] + job.cut)++ self.waiting.pop(pt.key, None)++ self._ref(pt.blocks, -1)++ self._gc(pt.blocks)++ job.done.set()++++ # -- room ----------------------------------------------------------------------------------------------------------++ def _ref(self, names, k: int) -> None:++ """Lock held: points or waiting states naming ``names`` (+1 each, or -1)."""++++ for b in names:++ v = self.refs.get(b, 0) + k++ if v > 0:++ self.refs[b] = v++ else:++ self.refs.pop(b, None)++++ def _gc(self, names) -> None:++ """Lock held: of ``names``, the blocks nothing names any more (no point, waiting state, write in flight or++ persist deciding) go."""++++ for b in set(names):++ if b in self.have and b not in self.refs and b not in self.inflight and b not in self.pinned:++ self._drop_block(b)++++ def _remove(self, key: str, why: str) -> None:++ """Lock held: a point goes (its files), then the blocks only it named."""++++ pt = self.index.pop(key, None)++ if pt is None:++ return++ self.version += 1++ self._ref(pt.blocks, -1)++ up = self.parent.pop(key, None) # its children's longest ancestor is now its parent++ for k, v in self.parent.items():++ if v == key:++ self.parent[k] = up++ self.small_on_disk -= pt.small_bytes++ for suffix in (".json", ".st", ".ids"):++ try:++ os.remove(self._point_path(key, suffix))++ except OSError:++ pass++ self.stats[why] += 1++ self._gc(pt.blocks)++++ def _extends(self, p: Point, q: Point) -> bool:++ """Whether ``p``'s ids extend ``q``'s (a strict prefix), by their block chains and q's tail."""++++ if q.n >= p.n:++ return False++ for x in (p, q):++ if x.chain is None:++ x.chain = _chain(x.ids, self.block)++ k = len(q.chain)++ return q.chain == p.chain[:k] and np.array_equal(p.ids[k * self.block:q.n], q.ids[k * self.block:])++++ def _parent_of(self, p: Point) -> str | None:++ """Lock held: the longest point in the index ``p``'s ids extend."""++++ best = None++ for q in self.index.values():++ if q is not p and (best is None or q.n > best.n) and self._extends(p, q):++ best = q++ return None if best is None else best.key++++ def _adopt(self, pt: Point) -> None:++ """Lock held: ``pt`` just entered the index: its parent, and the points it now stands between."""++++ self.parent[pt.key] = self._parent_of(pt)++ for q in self.index.values():++ if q is not pt and self._extends(q, pt):++ cur = self.parent.get(q.key)++ if cur is None or self.index[cur].n < pt.n:++ self.parent[q.key] = pt.key++++ def _trim_path(self, pt: Point) -> None:++ """Lock held, after ``pt`` is written: on its conversation's path (its ancestors below a shared-prefix state)++ the newest ``turns`` states stay, older ones go now (``trimmed_turns``). They free their small states only:++ the states kept still name every block. Never a state being read or written; never a fork off the path."""++++ if self.turns <= 0 or pt.shared:++ return++ path, cur = [], pt.key++ while cur is not None and cur in self.index and not self.index[cur].shared:++ path.append(cur)++ cur = self.parent.get(cur)++ for k in path[self.turns:]:++ if k not in self.reading and k not in self.inflight:++ self._remove(k, "trimmed_turns")++++ def _conv(self, key: str, parent: dict) -> str | None:++ """Lock held: the conversation of point ``key``: the topmost non-shared point on its path below a++ shared-prefix one (None for a shared one)."""++++ if self.index[key].shared:++ return None++ top, cur = key, parent.get(key)++ while cur is not None and not self.index[cur].shared:++ top, cur = cur, parent.get(cur)++ return top++++ def _tree(self) -> tuple[dict, dict]:++ """Lock held: each point's parent (kept as points come and go) and its conversation."""++++ parent = dict(self.parent)++ return parent, {k: self._conv(k, parent) for k in self.index}++++ def _victims(self, only: str | None = None) -> list[tuple[str, str]]:++ """Lock held: (point, why) in eviction order (the module's docstring); ``only``: a conversation's own old turns++ and forks (its quota)."""++++ parent, conv = self._tree()++ children: dict[str, list[str]] = {}++ for k, p in parent.items():++ if p is not None:++ children.setdefault(p, []).append(k)++ groups: dict[str, list[str]] = {}++ for k, c in conv.items():++ if c is not None:++ groups.setdefault(c, []).append(k)++ turns, forks, whole = [], [], []++ for c, keys in groups.items():++ if only is not None and c != only:++ continue++ leaves = [k for k in keys if not [x for x in children.get(k, []) if conv.get(x) == c]]++ newest = max(leaves or keys, key=lambda k: self.index[k].used)++ path, cur = [], newest++ while cur is not None and conv.get(cur) == c:++ path.append(cur)++ cur = parent[cur]++ keep = set(path[:max(1, self.turns)])++ on_path = set(path)++ for k in keys:++ if k in keep:++ continue++ if k in on_path or k not in leaves:++ turns.append(k)++ else:++ forks.append(k)++ whole.append((max(self.index[k].used for k in keys), keys, newest, path))++ by_used = lambda k: self.index[k].used++ out = [(k, "pruned_turns") for k in sorted(turns, key=by_used)]++ out += [(k, "pruned_forks") for k in sorted(forks, key=by_used)]++ if only is not None:++ return out++ for _, keys, _, path in sorted(whole, key=lambda g: g[0]):++ rest = [k for k in keys if k not in set(turns) | set(forks)]++ out += [(k, "pruned_conversations") for k in sorted(rest, key=lambda k: -self.index[k].n)]++ shared = [k for k, c in conv.items() if c is None]++ out += [(k, "pruned_shared") for k in sorted(shared, key=lambda k: (self.index[k].used, -self.index[k].n))]++ return out++++ def _make_room(self, nbytes: int, protect=frozenset()) -> None:++ """Free at least ``nbytes`` (the cap's or the floor's shortfall), in the eviction order, never ``protect``."""++++ with self.lock:++ target = self.stored() - nbytes++ for key, why in self._victims():++ if self.stored() <= target:++ return++ if key in protect or key not in self.index or key in self.reading:++ continue++ self._remove(key, why)++++ def _conv_bytes(self, keys) -> int:++ """Lock held: bytes only ``keys``' points hold (their files, and blocks no other point names)."""++++ mine = set(keys)++ others = {b for k, pt in self.index.items() if k not in mine for b in pt.blocks}++ blocks = {b for k in mine for b in self.index[k].blocks if b not in others and b in self.have}++ inos = {self.have[b][1] for b in blocks}++ own = sum(self.inodes[i][0] for i in inos if i in self.inodes and self.inodes[i][1] <= blocks)++ return own + sum(self.index[k].small_bytes for k in mine)++++ def _trim_own(self, pt: Point, need: int) -> None:++ """A write of ``pt`` whose conversation holds more than its quota: its own old turns and forks go first."""++++ with self.lock:++ if not self.index or pt.shared:++ return++ parent, conv = self._tree()++ up = self._parent_of(pt)++ c = None++ while up is not None and not self.index[up].shared:++ c, up = up, parent.get(up)++ if c is None: # its own conversation's first state: nothing to trim++ return++ c = conv.get(c)++ keys = [k for k, v in conv.items() if v == c]++ over = self._conv_bytes(keys) + need - int(self.quota * self.cap)++ if over <= 0:++ return++ self.stats["quota_trims"] += 1++ target = self.stored() - over++ for key, why in self._victims(only=c):++ if self.stored() <= target:++ break++ if key in self.inflight or key in self.reading:++ continue++ self._remove(key, why)++++ # -- read ----------------------------------------------------------------------------------------------------------++ def best(self, prompt: Sequence[int], longer_than: int = 0, grid: int = 0, usable=None) -> Point | None:++ """Rank 0: the longest complete point ``prompt`` extends (or equals, when it kept its head's row), longer than++ ``longer_than`` tokens, on the grid when there is one."""++++ arr = np.asarray(prompt, dtype=np.int64)++ with self.lock:++ cands = sorted(self.index.values(), key=lambda p: -p.n)++ for pt in cands:++ if pt.n <= longer_than:++ return None++ if pt.n > len(arr) or (grid and pt.n % grid) or (pt.n == len(arr) and not pt.head):++ continue++ if usable is not None and not usable(pt):++ continue++ if np.array_equal(arr[:pt.n], pt.ids):++ return pt++ return None++++ def load_async(self, key: str, where) -> LoadJob:++ """Start reading point ``key``'s blocks and small state on the reader thread; the engine copies them into extent++ ``where`` (``step``, ``finish_load``). A point this rank lacks fails the read."""++++ with self.lock:++ pt = self.index.get(key)++ lj = LoadJob(pt, where)++ if pt is None:++ lj.error = FileNotFoundError(f"rank {self.rank} has no stored prompt {key}")++ lj.done.set()++ return lj++ self.touch(key)++ with self.lock:++ self.reading.add(key)++ self.reads.put(lj)++ return lj++++ @staticmethod++ @contextlib.contextmanager++ def moving(lj: LoadJob):++ """The engine, around a move of the extent ``lj`` reads into. Nothing to hold: its blocks are copied on the++ engine's own stream between rounds (``step``), so the move's copy comes after the copies before it and before++ the ones after it, which find the extent at its new base."""++++ yield++++ def _read_block(self, h: str, crc: int, buf: torch.Tensor, nb: int) -> None:++ """A reader thread: block ``h`` into pinned ``buf`` (O_DIRECT where it works), checked against its CRC-32."""++++ path = self._block_path(h)++ direct = self.direct++ fd = -1++ if direct:++ try:++ fd = os.open(path, os.O_RDONLY | _NOFOLLOW | os.O_DIRECT)++ except OSError as exc:++ if exc.errno != errno.EINVAL:++ raise++ direct = False++ if fd < 0:++ fd = os.open(path, os.O_RDONLY | _NOFOLLOW)++ try:++ if os.fstat(fd).st_size != nb:++ raise Corrupt(f"{h}: {os.fstat(fd).st_size} bytes, the planes take {nb}")++ mv = memoryview(buf.numpy())[:_up(nb) if direct else nb]++ got = 0++ while got < nb:++ k = os.preadv(fd, [mv[got:]], got)++ if k <= 0:++ raise EOFError(f"{h}: short read")++ got += k++ if direct and got < nb and got % _sp.ALIGN: # (a partial O_DIRECT read: the rest, buffered)++ os.close(fd)++ fd = os.open(path, os.O_RDONLY | _NOFOLLOW)++ direct = False++ mv = mv[:nb]++ if zlib.crc32(mv[:nb]) != crc:++ raise Corrupt(f"{h}: its CRC-32 does not match its point")++ try:++ os.posix_fadvise(fd, 0, 0, os.POSIX_FADV_DONTNEED)++ except (AttributeError, OSError):++ pass++ finally:++ os.close(fd)++++ def _read_loop(self) -> None:++ while True:++ lj = self.reads.get()++ try:++ self._read(lj)++ except BaseException as exc: # noqa: BLE001 (the reader never dies)++ lj.error = exc++ with self.lock:++ self.reading.discard(lj.point.key)++ with lj.cond:++ lj.done.set()++ lj.cond.notify_all()++ lj = None++++ def _slot(self, lj: LoadJob) -> int | None:++ """The reader: a free pinned slot for ``lj``'s next block (the engine frees one once its copy out of it ended),++ or None once the engine gave up on ``lj``."""++++ while not lj.stop:++ try:++ return self.free_reads.get(timeout=0.2)++ except queue.Empty:++ continue++ return None++++ def _read(self, lj: LoadJob) -> None:++ """The reader: ``lj``'s blocks into pinned slots, in order, as slots come free (several read at once on the++ reader pool, each checked against its CRC-32), then its small state. Issues no CUDA work."""++++ pt = lj.point++ job = self.waiting.get(pt.key)++ if job is not None and not job.done.wait(LOAD_WAIT_S): # (a point is only read once complete; safety)++ raise OSError(f"{pt.key}: its write did not end in time")++ self.ring()++ spans = list(block_hashes(pt.ids, self.block, pt.lineage))++ if [h for _, _, h in spans] != pt.blocks:++ raise Corrupt(f"{pt.key}: its block list does not match its ids and lineage")++ for i, (s, e, h) in enumerate(spans):++ b = self._slot(lj)++ if b is None:++ return++ nb = _span_bytes(self.planes, s, e)++ fut = self._readers.submit(self._read_block, h, pt.crcs[i], self.read_slots[b], nb)++ with lj.cond:++ lj.queued[i] = (b, nb, fut, s, e, h)++ lj.cond.notify_all()++ if not lj.stop:++ self._read_small(lj)++++ def _read_small(self, lj) -> None:++ pt = lj.point++ t1 = time.perf_counter()++ path = self._point_path(pt.key, ".st")++ size = os.path.getsize(path)++ raw, got = self._read_file(path, size)++ if got != size or zlib.crc32(raw) != pt.small_crc:++ self.stats["crc_failed"] += 1++ raise Corrupt(f"{pt.key}: its small state does not match its CRC-32")++ lj.small = _small_read(raw, self.classes)++ lj.raw = raw # (the small state's tensors are views of it)++ self.stats["load_small_s"] += time.perf_counter() - t1++++ # -- the engine's side of a read ---------------------------------------------------------------------------------++ def _recycle(self, wait: bool = False) -> None:++ """The engine: slots whose copy out ended go back to the reader (``wait``: every one, waiting for them)."""++++ keep = []++ for b, ev in self.read_events:++ if ev is None or wait or ev.query():++ if ev is not None and wait:++ ev.synchronize()++ self.free_reads.put(b)++ else:++ keep.append((b, ev))++ self.read_events = keep++++ def settle(self) -> None:++ """The engine (every rank), in a decode round once its verify pass is queued: every read slot copied out by++ the last step (on this stream, before the round's work) back to the reader, waiting for the newest of those++ copies while the GPU runs the queued pass. Without it a step frees only the slots the step before copied out,++ so beside a decoding stream a slot turns every second round."""++++ evs = getattr(self, "read_events", None) # (made with the slots, at the first read or write)++ if not evs:++ return++ last = next((ev for _, ev in reversed(evs) if ev is not None), None)++ if last is not None:++ last.synchronize() # (one stream: the copies before it are done too)++ for b, _ in evs:++ self.free_reads.put(b)++ self.read_events = []++++ def step(self, lj: LoadJob, upto: int | None = None, budget: float | None = None) -> int:++ """The engine, between rounds (either rank): ``lj``'s next blocks into its extent, at its base now, on the++ current stream, in order. Without ``upto``: only blocks read already, for at most ``budget`` seconds; with it:++ every block before ``upto``, waiting for their reads. A block whose read failed fails the read (``error``) and++ stops it. The blocks copied."""++++ self._recycle()++ end = lj.total if upto is None else min(int(upto), lj.total)++ t, n = time.perf_counter(), 0++ while lj.next < end and lj.error is None:++ i = lj.next++ with lj.cond:++ if upto is None and not (i in lj.queued and lj.queued[i][2].done()):++ break++ while i not in lj.queued and lj.error is None and not lj.done.is_set():++ if self.read_events: # the slots this step's own copies used: back to the reader,++ self._recycle(wait=True) # or it waits for one and block i is never read++ lj.cond.wait(1.0)++ item = lj.queued.pop(i, None)++ if item is None:++ if lj.error is None:++ lj.error = OSError(f"{lj.point.key}: its read ended before block {i}")++ break++ b, nb, fut, s, e, h = item++ try:++ fut.result()++ except Exception as exc:++ if isinstance(exc, FileNotFoundError): # this name is gone: its links' bytes are not in question++ lj.lost.add(h)++ elif isinstance(exc, (Corrupt, EOFError)): # damaged bytes, not a passing I/O error++ lj.bad.add(h)++ if isinstance(exc, Corrupt):++ self.stats["crc_failed"] += 1++ lj.error = exc++ self.free_reads.put(b)++ break++ self._copy_in(lj, self.read_slots[b], s, e)++ ev = None++ if torch.cuda.is_available() and self.read_slots[b].is_pinned():++ ev = torch.cuda.Event()++ ev.record(torch.cuda.current_stream())++ self.read_events.append((b, ev))++ lj.next += 1++ n += 1++ self.stats["loaded_bytes"] += nb++ if upto is None and budget is not None and time.perf_counter() - t >= budget:++ break++ if lj.error is not None:++ lj.stop = True++ return n++++ def _copy_in(self, lj: LoadJob, src: torch.Tensor, s: int, e: int) -> None:++ """The engine: one block's rows from pinned ``src`` into ``lj``'s extent at its base now (current stream)."""++++ stream = torch.cuda.current_stream() if torch.cuda.is_available() and src.is_pinned() else None++ base = lj.where.base++ at = 0++ for p in self.planes:++ a, z = _rows(p, s, e)++ dst = p.tensor[base // p.div + a:base // p.div + z]++ k = dst.numel() * dst.element_size()++ v = dst.reshape(-1).view(torch.uint8)++ if p.spanned:++ if lj.stage is None:++ lj.stage = _sp._stage(self.planes[0].tensor.device, stream)++ _sp._by_kernel(v, src[at:at + k], lj.stage, stream)++ else:++ v.copy_(src[at:at + k], non_blocking=stream is not None)++ at += k++++ def stop_load(self, lj: LoadJob, why: str) -> None:++ """The engine: ``lj``'s extent is shrinking past rows it still has to fill: no more of its blocks are copied,++ and it fails (every rank prefills). Its reads end first, their slots back to the reader."""++++ if lj.error is None:++ lj.error = OSError(f"{lj.point.key if lj.point is not None else '?'}: {why}")++ lj.stop = True++ lj.done.wait()++ self._settle(lj)++++ def _settle(self, lj: LoadJob) -> None:++ """The engine, after the reader is through with ``lj``: blocks it read but nobody copied give their slots back++ (their reads ended first)."""++++ with lj.cond:++ left, lj.queued = list(lj.queued.values()), {}++ concurrent.futures.wait([it[2] for it in left])++ for it in left:++ self.free_reads.put(it[0])++++ def _read_file(self, path: str, size: int):++ """A whole file: O_DIRECT into an aligned buffer where it works, else buffered; its pages dropped after. (The++ bytes, as a buffer the small state's tensors view, and how many were read.)"""++++ fd, direct = -1, False++ if self.small_direct:++ try:++ fd, direct = os.open(path, os.O_RDONLY | _NOFOLLOW | os.O_DIRECT), True++ except OSError as exc:++ if exc.errno != errno.EINVAL:++ raise++ if fd < 0:++ fd = os.open(path, os.O_RDONLY | _NOFOLLOW)++ try:++ buf = _aligned_buffer(size) if direct else np.empty(size, dtype=np.uint8)++ mv = memoryview(buf)++ got = 0++ while got < size:++ k = os.preadv(fd, [mv[got:]], got)++ if k <= 0:++ break++ got += k++ if direct and got < size and got % _sp.ALIGN: # (a partial O_DIRECT read: the rest, buffered)++ os.close(fd)++ fd, direct = os.open(path, os.O_RDONLY | _NOFOLLOW), False++ _drop_cache(fd)++ finally:++ os.close(fd)++ return buf[:size], min(got, size)++++ def finish_load(self, lj: LoadJob):++ """The engine, when every rank is to end ``lj``: its blocks not copied yet into its extent (waiting for their++ reads: an idle server copies them all here), then the small state's object (its tensors on the host) and the++ point. The copies are on the current stream. Raises the read's error. Counts the restore."""++++ if lj.error is None:++ self.step(lj, upto=lj.total)++ if lj.error is not None:++ lj.stop = True++ lj.done.wait()++ self._settle(lj)++ if lj.error is None and (lj.next < lj.total or lj.small is None):++ lj.error = OSError(f"{lj.point.key}: {lj.next} of {lj.total} blocks copied")++ if lj.error is not None:++ self.stats["load_failed"] += 1++ raise lj.error++ dt = time.perf_counter() - lj.t0++ self.stats["loaded"] += 1++ self.stats["loaded_tokens"] += lj.point.n++ self.stats["load_s"] += dt++ self.restore_ms.append(dt * 1000.0)++ if len(self.restore_ms) > 4096:++ del self.restore_ms[:2048]++ return lj.small, lj.point++++ def forget(self, key: str, bad: Sequence[str] = (), lost: Sequence[str] = ()) -> None:++ """Every rank, when a read of ``key`` failed on some rank: the point goes, so do the blocks in ``bad`` (damaged++ bytes: every name linked to them too) and in ``lost`` (a name whose file is gone: that name only), and every++ point naming one of them."""++++ with self.lock:++ bad = set(bad)++ for b in list(bad): # (linked names hold the same bytes)++ if b in self.have and self.have[b][1] in self.inodes:++ bad |= self.inodes[self.have[b][1]][1]++ gone = bad | set(lost)++ drop = {key} | {k for k, pt in self.index.items() if any(b in gone for b in pt.blocks)}++ for k in drop:++ self._remove(k, "dropped")++ for b in gone:++ self._drop_block(b)++++ def unwritten(self, why: str) -> None:++ self.stats["unwritten_evicted"] += 1++ self.unwritten_by[why] = self.unwritten_by.get(why, 0) + 1++++ def summary(self) -> dict:++ """What the store holds, by conversation (recomputed when a point comes or goes, at most every 2 s): how many++ conversations and shared-prefix states, the largest conversation's own bytes, share of the cap and length,++ abandoned forks and their own bytes, the most states kept on one conversation's path, and the five largest++ conversations. A conversation's own bytes: its small parts and the blocks no other conversation names."""++++ with self.lock:++ now = time.monotonic()++ c = self._summary_cache++ if c is not None and (c[0] == self.version or now - c[1] < 2.0):++ return c[2]++ parent, conv = self._tree()++ groups: dict[str, list[str]] = {}++ for k, g in conv.items():++ if g is not None:++ groups.setdefault(g, []).append(k)++ label: dict[str, set] = {} # block -> the conversations (or shared states) naming it++ for k, pt in self.index.items():++ lab = conv[k] if conv[k] is not None else "shared:" + k++ for b in pt.blocks:++ label.setdefault(b, set()).add(lab)++++ def own(keys, lab) -> int:++ inos = {self.have[b][1] for k in keys for b in self.index[k].blocks++ if b in self.have and label.get(b) == {lab}}++ return sum(self.inodes[i][0] for i in inos if i in self.inodes) + sum(++ self.index[k].small_bytes for k in keys)++++ rows, forks, fork_bytes, turns_max = [], 0, 0, 0++ for g, keys in groups.items():++ kids = {}++ for k in keys:++ up = parent.get(k)++ if up is not None and conv.get(up) == g:++ kids.setdefault(up, []).append(k)++ leaves = [k for k in keys if k not in kids]++ newest = max(leaves or keys, key=lambda k: self.index[k].used)++ path, cur = set(), newest++ while cur is not None and conv.get(cur) == g:++ path.add(cur)++ cur = parent.get(cur)++ turns_max = max(turns_max, len(path))++ for leaf in leaves:++ if leaf not in path:++ forks += 1++ fork_bytes += self.index[leaf].small_bytes + sum(++ self.inodes[self.have[b][1]][0] for b in self.index[leaf].blocks++ if b in self.have and self.refs.get(b, 0) == 1 and self.have[b][1] in self.inodes)++ rows.append((own(keys, g), len(keys), max(self.index[k].n for k in keys)))++ shared = [k for k, g in conv.items() if g is None]++ rows.sort(reverse=True)++ big = rows[0] if rows else (0, 0, 0)++ out = {"conversations": len(groups), "conversation_bytes_max": big[0],++ "conversation_share_max": round(big[0] / self.cap, 4) if self.cap else 0.0,++ "conversation_tokens_max": max((r[2] for r in rows), default=0),++ "shared_states": len(shared), "shared_bytes": sum(own([k], "shared:" + k) for k in shared),++ "forks": forks, "fork_bytes": fork_bytes, "turns_kept_max": turns_max,++ "top_conversations": [{"bytes": b, "states": n, "tokens": t} for b, n, t in rows[:5]]}++ self._summary_cache = (self.version, now, out)++ return out++++ def info(self) -> dict:++ s = self.stats++ with self.lock:++ points, blocks, waiting = len(self.index), len(self.have), len(self.waiting)++ stored = self.stored()++ lat = sorted(self.restore_ms)++ p = (lambda q: round(lat[min(len(lat) - 1, int(q * len(lat)))], 1)) if lat else (lambda q: 0.0)++ return {"format": "blocks", "block_tokens": self.block, "direct": self.direct, "entries": points,++ "blocks": blocks, "pending": waiting, "backlog_mb": self.backlog >> 20,++ "host_mb": self.host_bytes >> 20, "release_cap_mb": self.release_cap >> 20,++ "stored_gib": round(stored / (1 << 30), 2), "stored_bytes": stored,++ "disk_free_bytes": self.disk_free(),++ **{k: (round(v, 2) if isinstance(v, float) else v) for k, v in s.items()},++ "written_gib": round(s["written_bytes"] / (1 << 30), 2),++ "written_total_bytes": s["written_bytes"] + s["written_small_bytes"],++ "written_total_gib": round((s["written_bytes"] + s["written_small_bytes"]) / (1 << 30), 2),++ "cap_bytes": self.cap, "turns": self.turns, "quota": self.quota, **self.summary(),++ "loaded_gib": round(s["loaded_bytes"] / (1 << 30), 2),++ "restore_ms_p50": p(0.5), "restore_ms_p95": p(0.95),++ **{f"unwritten_{k}": v for k, v in sorted(self.unwritten_by.items())}}+diff --git tensorfold/families/glm5_next/cuda/engine.py tensorfold/families/glm5_next/cuda/engine.py+index 4fab28d..84bcf63 100644+--- tensorfold/families/glm5_next/cuda/engine.py++++ tensorfold/families/glm5_next/cuda/engine.py+@@ -741,6 +741,10 @@ class GlmEngine:+ text = read_config(model_dir)+ g = geometry(text)+ per_token = max(1, -(-(g.bytes_at(capacity + 65536) - g.bytes_at(capacity)) // 65536))++ if self.spill_cfg is not None: # the spill tier's read-ahead, pinned now: the pool gets what it leaves++ from tensorfold.cuda.spill_blocks import pin_read_ahead++++ self.cache_bytes = max(0, self.cache_bytes - pin_read_ahead(per_token * ALIGN))+ # 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+@@ -1064,7 +1068,7 @@ class GlmEngine:+ _SPILL_SKIP = ("ids", "ids_array", "nbytes", "key", "kid", "extent", "images", "shared")++ def _spill_store(self):+- from tensorfold.cuda.spill import SpillStore, build_id, weights_id++ from tensorfold.cuda.spill import Busy, SpillStore, build_id, weights_id++ from .decode import _row_views++@@ -1072,11 +1076,16 @@ class GlmEngine:+ sig = "|".join(["single", build_id(self.model_dir, self.drafter_dir), os.environ.get("TF_GLM_KV", ""),+ os.environ.get("TF_GLM_DENSE", ""), f"tp{self.w.world}", repr(shapes), repr(self.agreed)])+ self.spill_jobs: list = []+- return SpillStore(self.spill_cfg, rank=self.rank, world=self.w.world, device=self.w.device, signature=sig,+- weights=weights_id(self.model_dir, self.drafter_dir),+- classes=["tensorfold.families.glm5_next.cuda.decode:Snapshot"],+- model_id=os.path.basename(str(self.model_dir)), share=self._share,+- gather=self._gather_ints)++ try:++ return SpillStore(self.spill_cfg, rank=self.rank, world=self.w.world, device=self.w.device,++ signature=sig, weights=weights_id(self.model_dir, self.drafter_dir),++ classes=["tensorfold.families.glm5_next.cuda.decode:Snapshot"],++ model_id=os.path.basename(str(self.model_dir)), share=self._share,++ gather=self._gather_ints)++ except Busy as exc: # (raised on every rank alike: the tier is off on all of them)++ print(f"[tensorfold] spill rank {self.rank}: {exc}: the spill tier is off for this engine (give each "++ "engine its own SPILL_DIR)", flush=True)++ return None++ def _spill_rows(self, snap) -> None:+ """Materialize: a snapshot without saved rows gets views of the live caches it owns (``_saved_views``)."""+diff --git tensorfold/families/glm5_next/cuda/multi.py tensorfold/families/glm5_next/cuda/multi.py+index 46df2bd..ef76005 100644+--- tensorfold/families/glm5_next/cuda/multi.py++++ tensorfold/families/glm5_next/cuda/multi.py+@@ -34,6 +34,7 @@ Multi-stream mode drafts with DFlash2 only: MTP policies are remapped to DFlash2++ from __future__ import annotations+++import contextlib+ import hashlib+ import json+ import os+@@ -55,11 +56,13 @@ from .multi_tune import MultiSettings, RoundProfile, allocate, reach_of, sample_+ from .pool import ALIGN, Pool, align_up+ from .verify import BatchedVerify, Segment, SerialVerify, Verified++-ADMIT, EVICT, MOVE, GROW, FILL, ROUND, FINISH, IDLE, SLOT, MFILL, FILLPART, MFILLPART, LOAD, FLUSH, SPILL, LOADED, \+- TOUCH = range(1, 18)++ADMIT, EVICT, MOVE, GROW, FILL, ROUND, FINISH, IDLE, SLOT, MFILL, FILLPART, MFILLPART, LOAD, FLUSH, LOADED, \++ HAS, LOADPART = range(1, 18)+ OPS = {ADMIT: "ADMIT", EVICT: "EVICT", MOVE: "MOVE", GROW: "GROW", FILL: "FILL", ROUND: "ROUND", FINISH: "FINISH",+ IDLE: "IDLE", SLOT: "SLOT", MFILL: "MFILL", FILLPART: "FILLPART", MFILLPART: "MFILLPART", LOAD: "LOAD",+- FLUSH: "FLUSH", SPILL: "SPILL", LOADED: "LOADED", TOUCH: "TOUCH"}++ FLUSH: "FLUSH", LOADED: "LOADED", HAS: "HAS", LOADPART: "LOADPART"}++# TF_GLM_SPILL_LOAD_MS (default 40): the most a step of the reads in flight copies between two rounds (rank 0's time)++LOAD_MS_DEFAULT = 40.0+++ def watchdog_seconds(value: str | None = None) -> float:+@@ -515,6 +518,7 @@ class Lane:+ key: list[int] | None = None # rank 0: the prompt's ids with its pictures' keys in their rows (kept states)+ images: bool = False # both ranks: the prompt has pictures (its kept states are told apart by key)+ chat: int = 0 # the conversation this stream belongs to (its kept states are capped together)++ lineage: str = "" # the computation its rows belong to (the spill tier's block names)+ decoding: bool = False+ paused: bool = False+ t0: float = 0.0+@@ -524,6 +528,9 @@ class Lane:+ next_copy: Any = None # ((copies length, room), proposal, proposed) the round's end worked out++++PREFIX_WAIT = os.environ.get("TF_GLM_PREFIX_WAIT", "0") not in ("", "0") # off unless 1+++++ class NoRoom(RuntimeError):+ """The pool cannot place a stream now (it waits for others to finish)."""++@@ -618,6 +625,10 @@ class MultiDecoder:+ self.sent = self.received = 0 # messages sealed on rank 0, unsealed on rank 1+ self.lanes: dict[int, Lane] = {} # by sid, in admission order+ self.kept: list = [] # kept prompts (decode.Snapshot + kid, extent), oldest first++ self.load_turn = 0 # which read in flight ``step_loads`` serves first++ self.boot = os.urandom(6).hex() # this process's lineages (a fresh prefill's) are its own++ self.prefix_waits = 0 # requests that waited for a prefix another one prefilled++ self.prefix_wait_tokens = 0 # the prompt tokens they did not prefill again+ 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+@@ -674,6 +685,7 @@ class MultiDecoder:+ },+ **({"multi_prefill": dict(self.grouped)} if self.group else {}),+ **({"spill": self.disk.info()} if self.disk is not None else {}),++ "prefix_waits": self.prefix_waits, "prefix_wait_tokens": self.prefix_wait_tokens,+ # how long rank 0's current iteration has run (0 between iterations): a stalled server keeps growing it+ "iteration_s": round(time.monotonic() - since, 1)+ if (since := getattr(self, "iteration_since", None)) is not None else 0.0}+@@ -1095,6 +1107,12 @@ class MultiDecoder:+ 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+ lane.key = a["keyed"]++ # the computation its rows belong to: its kept state's up to the resume point (rows copied or taken over are++ # those bits), its own from there; a new one for a fresh prefill++ from tensorfold.cuda.spill_blocks import fork++++ own = f"{self.boot}-{a['sid']}"++ lane.lineage = fork(hit.lineage, own, cut) if getattr(hit, "lineage", "") else own+ self.next_sid = max(self.next_sid, a["sid"] + 1)+ self.next_order += 1+ s.sid, s.cached = a["sid"], cut+@@ -1211,14 +1229,17 @@ class MultiDecoder:+ 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)++ snap.lineage = getattr(lane, "lineage", "")+ lane.extent.kept.append(snap)+ self.kept.append(snap)++ if self.disk is not None: # --spill-gib: on this rank's disk too, while its rows are in place++ self._persist(snap)+ if own and KEEP_PER_CHAT:+ # this conversation's older turn states: a replay of a prompt that far back is all they serve, and holding+ # every one of them is how one long conversation fills the whole cache by itself. Least recently used+ # first (self.kept's order, a resumed state moved last), so an edited or retried branch -- whose states+- # are shorter than the line it left -- keeps its own. Superseded turns are not worth the disk tier:+- # dropped without a spill (the same on both ranks).++ # are shorter than the line it left -- keeps its own (the same on both ranks; the spill tier wrote each++ # one when it was kept and trims old turns on its own).+ mine = [c for c in self.kept if getattr(c, "own", False) and getattr(c, "chat", 0) == snap.chat]+ for c in mine[:-KEEP_PER_CHAT]:+ self._drop(c, spill=False)+@@ -1228,7 +1249,7 @@ class MultiDecoder:+ # the pool (copies of the DFlash2 window), so 64 entries reached tens of GiB on the hosts (free memory to+ # 0.1 GB) and never came back. With TF_GLM_KEPT_BYTES_GIB set, rank 0 drops states past it, by the cap's+ # victim order, and tells rank 1 with EVICT (the same rank-0-decides path the takeover uses); the freed blocks+- # go back to the driver in _drop. A state dropped for its bytes is not written to the spill tier.++ # go back to the driver in _drop.+ if self.rank == 0 and self.kept_bytes_cap:+ while len(self.kept) > 1 and self._held_bytes() > self.kept_bytes_cap:+ victim = cap_victim(self.kept)+@@ -1261,11 +1282,9 @@ class MultiDecoder:+ return sum(snapshot_bytes(c) for c in self.kept)++ def _drop(self, c, spill: bool = True) -> None:+- """Forget a kept prompt; its extent goes when nothing else holds it, else shrinks to what is kept. With the+- spill tier on it goes to disk first (its rows are still in place), unless ``spill`` is False or it is there."""++ """Forget a kept prompt; its extent goes when nothing else holds it, else shrinks to what is kept. (With the++ spill tier on it was written when it was kept; ``spill`` is kept for the EVICT op's payload.)"""++- if spill and self.disk is not None:+- self._spill(c, leaving=True)+ held = 0+ if self.kept_bytes_cap:+ from .decode import snapshot_bytes+@@ -1297,23 +1316,67 @@ class MultiDecoder:+ self._emit(EVICT, [c.kid, int(spill)])+ self._drop(c, spill=spill)++- # -- the spill tier (``tensorfold serve --spill-gib``; cuda/spill.py) ----------------------------------------------+- # Every call below runs on both ranks in the same order (rank 0 decides, rank 1 follows its ops); rank 0 sends what+- # it has queued before each of the tier's all-gathers (``_sync``). Rows a pending write reads, or a read is filling,+- # never move or go before the copy ends: the pool's remove / move / resize are wrapped (``_guard_pool``). A kept+- # prompt's fields go through ``spill.encode``; its pool rows go as named row tensors into a new extent's rows.++ # -- a prefix another request is prefilling --------------------------------------------------------------------++ # Requests that start together on a system prompt nobody has kept yet would each prefill it, side by side, each at++ # a share of the GPU. A request whose prompt starts with a shared-prefix point another one still prefilling keeps++ # on its way (its system block's end) waits for that state instead (the scheduler holds it apart, the queue goes++ # on), then resumes from it like any kept prompt: one prefill of the shared tokens for all of them, and every first++ # token sooner. Off by default; TF_GLM_PREFIX_WAIT=1 turns it on (it changes admission with the spill tier off++ # too).++ def prefix_wait(self, s: Stream):++ """Rank 0, before ``s`` is admitted: (sid, position) of a shared-prefix point a stream still prefilling keeps on++ the way (its system block's end, where it stops sharing a kept prompt) that ``s``'s prompt starts with and that++ adds at least the shared-prefix minimum past what is kept now (the longest), or None."""++++ from .engine import common_prefix++++ if not PREFIX_WAIT or not s.draft or s.vision is not None or not self.g.shared or self.g.serial_only:++ return None++ prompt = [int(t) for t in s.prompt]++ hit = self._resume(prompt)++ have = len(hit.ids) if hit is not None else 0++ best = None++ for lane in self.lanes.values():++ if lane.decoding or lane.s.done or lane.key is None or lane.images:++ continue++ if self.drafts is not None and not lane.dflash: # its states keep no DFlash2 window: none would resume++ continue++ ahead = {p for p in lane.shared if p > lane.st.pos} # shared points: no other conversation's own turn++ if not ahead:++ continue++ m = common_prefix(prompt, lane.key)++ for p in ahead:++ if p <= m and p < len(prompt) and p - have >= self.g.shared and (best is None or p > best[1]):++ best = (lane.sid, p)++ if best is not None:++ self.prefix_waits += 1++ self.prefix_wait_tokens += best[1] - have++ return best++++ def prefix_ready(self, w) -> bool:++ """Rank 0: the waited-for point is kept, or never will be (its stream left the prompt, ended or went)."""++++ sid, p = w++ lane = self.lanes.get(sid)++ return lane is None or lane.decoding or lane.s.done or lane.st.pos >= p++++ # -- the spill tier (``tensorfold serve --spill-gib``; cuda/spill_blocks.py) ---------------------------------------++ # Every kept prompt of ``--spill-min-tokens`` or more is written to this rank's disk when it is kept (``_persist``):++ # its small state now, its rows in blocks through the store's ring between rounds (``pump``), so it survives an++ # eviction, a restart and a crash. Rows that are about to be freed or overwritten while still waiting are copied to++ # the host first (``_guard_pool``, ``_rewrites``); rows a read is filling never move or go before it ends. Each rank++ # keeps its own disk; rank 0 asks every rank (HAS) before a read and every rank drops a state whose read failed on++ # any of them.+ _SPILL_SKIP = ("ids", "rows", "nbytes", "pending", "mtp_len", "kid", "extent", "key", "images", "shared",+- "spill_key", "superseded", "own", "chat")++ "spill_key", "superseded", "own", "chat", "lineage")++ def _spill_store(self):+ cfg = getattr(self.g, "spill_cfg", None)+ if cfg is None:+ return None+- from tensorfold.cuda.spill import SpillStore, build_id, weights_id++ from tensorfold.cuda.spill import Busy, build_id, weights_id++ from tensorfold.cuda.spill_blocks import BlockStore++- for p in self.arena.planes:+- if ALIGN % p.div:+- raise ValueError(f"--spill-gib: a cache plane of {p.div} tokens a row does not divide {ALIGN}")+ planes = [(tuple(p.tensor.shape[1:]), str(p.tensor.dtype), p.div, p.pad) for p in self.arena.planes]+ drafter = getattr(self.g, "drafter", None)+ model = os.path.basename(str(getattr(self.g, "model_dir", "")).rstrip("/"))+@@ -1324,14 +1387,22 @@ class MultiDecoder:+ os.environ.get("TF_GLM_KV", ""), os.environ.get("TF_GLM_DENSE", ""),+ f"tp{self.w.world}", repr(planes), str(self.grid), str(self.drafts is not None),+ repr(self.g.agreed)])+- self.spill_jobs: list = [] # (job, extent, rows it reads up to), both ranks alike+ self.loads: dict = {} # load id -> a stored prompt being read into a new extent+ self.next_lid = 0+- store = SpillStore(cfg, rank=self.rank, world=self.w.world, device=self.w.device, signature=signature,+- weights=weights_id(self.g.model_dir, self.g.drafter_dir),+- classes=["tensorfold.families.glm5_next.cuda.decode:Snapshot"],+- model_id=model, share=self.g._share, gather=self.g._gather_ints,+- spanned=[f"p{i}" for i, p in enumerate(self.arena.planes) if p.spanned])++ self.load_budget = float(os.environ.get("TF_GLM_SPILL_LOAD_MS") or LOAD_MS_DEFAULT) / 1000.0++ quota = float(os.environ.get("TF_GLM_SPILL_QUOTA", "0") or 0)++ turns = int(os.environ.get("TF_GLM_SPILL_TURNS") or 4) # (0: every turn kept until room is needed)++ try:++ store = BlockStore(cfg, planes=self.arena.planes, block=ALIGN, rank=self.rank, world=self.w.world,++ device=self.w.device, signature=signature,++ weights=weights_id(self.g.model_dir, self.g.drafter_dir), model_id=model,++ gather=self.g._gather_ints,++ classes=["tensorfold.families.glm5_next.cuda.decode:Snapshot"], turns=turns, quota=quota)++ except Busy as exc: # (raised on every rank alike: the tier is off on all of them)++ print(f"[tensorfold] spill rank {self.rank}: {exc}: the spill tier is off for this engine (give each "++ "engine its own SPILL_DIR)", flush=True)++ return None++ store.ring() # the pinned ring now, not on the engine loop later+ self._guard_pool()+ return store++@@ -1350,7 +1421,7 @@ class MultiDecoder:+ return remove(x)++ def g_move(x, base, size=None):+- self._release_rows(x, 0)++ self._release_rows(x, None)+ return move(x, base, size)++ def g_resize(x, size):+@@ -1359,75 +1430,40 @@ class MultiDecoder:++ pool.remove, pool.move, pool.resize = g_remove, g_move, g_resize++- def _release_rows(self, x, keep: int) -> None:+- """Both ranks, each on its own: rows of extent x past ``keep`` are about to move or go; a pending write that+- reads them first finishes its copy off the device, a read filling them first ends (no message: every rank+- waits for its own)."""++ def _release_rows(self, x, keep: int | None) -> None:++ """Both ranks, each on its own: extent x's rows past ``keep`` are about to go or be overwritten (None: the++ extent moves, its rows with it): a read still to fill them stops (it fails: every rank prefills); waiting writes++ there get their rows copied to the host. A move waits for neither: a write reads the extent where it is when its++ blocks are staged, and a read copies each block where the extent is then (between rounds, on this stream)."""++- h = getattr(x, "loading", None)+- if h is not None and h.lj is not None:+- h.lj.done.wait()+- if self.disk is None or not self.spill_jobs:++ if keep is None:+ return+- self.spill_jobs = [j for j in self.spill_jobs if not j[0].copied.is_set()]+- for job, y, upto in self.spill_jobs:+- if y is x and upto > keep:+- self.disk.release(job)++ h = getattr(x, "loading", None)++ if h is not None and h.lj is not None and keep < h.n:++ self.disk.stop_load(h.lj, "its extent shrank under the read")++ if self.disk is not None:++ self.disk.release(x, keep)++ def _rewrites(self, x, cut: int) -> None:+- """Both ranks: a stream takes extent x over and writes its rows from ``cut`` on. A longer kept prompt there,+- evicted for it (``admit``), may still be on its way to disk: its copy off the device ends first."""++ """Both ranks: a stream takes extent x over and writes its rows from ``cut`` on. Longer kept prompts there,++ evicted for it (``admit``), may still wait to be written: their rows go to the host first."""++ div = max(p.div for p in self.arena.planes)+ self._release_rows(x, cut - cut % div)++- def _planes(self, base: int, n: int) -> list:+- out = []+- for i, p in enumerate(self.arena.planes):+- a = base // p.div+- out.append((f"p{i}", p.tensor[a:a + -(-n // p.div)]))+- return out+-+- def _key(self, c) -> tuple[int, int]:+- """Kept prompt ``c``'s ``ids_key``, hashed once (its ids never change while kept; ``_behind`` asks every+- iteration)."""+-+- k = getattr(c, "spill_key", None)+- if k is None:+- from tensorfold.cuda.spill import ids_key+- k = c.spill_key = ids_key(self._ident(c))+- return k+-+ @staticmethod+ def _ident(c) -> list[int]:+ """What the tier stores and matches a kept prompt by: its ids, or its keyed ids when it has pictures."""++ return c.key if c.images else c.ids++- def _superseded(self, c) -> bool:+- """A longer kept prompt of the same conversation (the same extent, it extends c) that can be written itself:+- c need not be. Never a shared-prefix state (other conversations resume from it, not from the longer one). The+- answer holds while the extent keeps the same prompts, so it is remembered against their kids."""+-+- x = getattr(c, "extent", None)+- if x is None or getattr(c, "shared", False):+- return False+- held = tuple(k.kid for k in x.kept)+- memo = getattr(c, "superseded", None)+- if memo is not None and memo[0] == held:+- return memo[1]+- n = len(c.ids)+- out = any(k is not c and len(k.ids) > n and k.ids[:n] == c.ids and self._spillable(k) for k in x.kept)+- c.superseded = (held, out)+- return out+-+ def _unspillable(self, c) -> str | None:+- """Why kept prompt ``c`` cannot be written (None: it can)."""++ """Why kept prompt ``c`` is not written (None: it is)."""++ if c.images and c.key is None:+ return "images" # pictures without content keys: nothing tells them apart+ n = len(c.ids)+- if n < self.disk.cfg.min_tokens:++ if not self.disk.wants(n):+ return "short"+ if self.grid and n % self.grid:+ return "off_grid"+@@ -1437,97 +1473,37 @@ class MultiDecoder:+ return "no_draft_window"+ return None++- def _spillable(self, c) -> bool:+- return self._unspillable(c) is None+-+- def _unwritten(self, why: str) -> None:+- st = self.disk.stats+- st.unwritten_evicted += 1+- st.unwritten[why] = st.unwritten.get(why, 0) + 1+-+- def _spill(self, c, leaving: bool = False, keep: frozenset = frozenset()) -> bool:+- """Both ranks, in lockstep: write kept prompt ``c`` (its rows still in place) to the spill tier, unless it is+- there or on its way, superseded, off grid, too short, or lacks the DFlash2 window a stream resuming from it+- needs. ``leaving``: its rows go right after (an eviction). ``keep``: stored entries no room is made from. True+- when a write was queued."""++ def _persist(self, c) -> None:++ """Both ranks, as ``c`` is kept: its state to this rank's disk (``BlockStore.persist``; a failure only leaves it++ off disk)."""++- d = self.disk+- why = self._unspillable(c) or ("superseded" if self._superseded(c) else None)++ why = self._unspillable(c)+ if why is not None:+- if leaving:+- self._unwritten(why)+- return False+- if d.has(self._ident(c), self._key(c)):+- return False+- self._sync()++ self.disk.unwritten(why)++ return+ try:+- job = d.save(self._ident(c), c, self._planes(c.extent.base, len(c.ids)), skip=self._SPILL_SKIP,+- head=c.head is not None, tokens=c.ids if c.images else None, keep=keep)+- except Exception as exc: # noqa: BLE001 (a spill never fails the engine: the prompt is lost)++ self.disk.persist(self._ident(c), c, extent=c.extent, lineage=c.lineage,++ tokens=c.ids if c.images else None, shared=bool(c.shared), head=c.head is not None,++ skip=self._SPILL_SKIP)++ except Exception as exc: # noqa: BLE001 (a spill never fails the engine)+ print(f"[tensorfold] spill rank {self.rank}: not written: {exc!r}", flush=True)+- job = None+- if job is None:+- if leaving:+- self._unwritten("not_saved")+- return False+- self.spill_jobs.append((job, c.extent, len(c.ids))) # its rows stay put until copied (``_guard_pool``)+- return True+-+- def _kept_keys(self) -> frozenset:+- """Both ranks alike: the stored copies an early write never evicts, those of the prompts still kept (else+- they evict each other in turn under a small cap)."""+-+- return frozenset(self._key(k) for k in self.kept if self._spillable(k))++ self.disk.unwritten("failed")++- def _behind(self) -> None:+- """Rank 0: past the pool's high-water mark (``--spill-highwater``), or near the kept-prompt cap, the kept+- prompts eviction would take next are written in the background (SPILL), so an eviction usually finds them on+- disk and frees their rows at once. A writer's worth at a time; more wait for the next iteration (deferred)."""++ def _pump(self) -> None:++ """Both ranks, between iterations: waiting writes' next blocks through the ring (never the engine's failure:++ rank 1 raising here would leave rank 0 waiting in its next collective)."""++- d = self.disk+- rows = self.pool.rows+- used = rows - self.pool.free_rows()+- hw = d.cfg.highwater+- near_cap = len(self.kept) >= max(1, self.g.cache_entries) - 2+- if used < hw * rows and not near_cap:+- return+- token = (d.generation, tuple(k.kid for k in self.kept)) # what decides whether an early write finds room+- if getattr(self, "behind_skip", (None,))[0] != token:+- self.behind_skip = (token, set())+- skip = self.behind_skip[1] # kept prompts that found no room: not tried again until then+- keep = None+- order = self._victims(())+- if near_cap and self.kept:+- v = cap_victim(self.kept)+- order = [v] + [c for c in order if c is not v]+- want = (used - hw * rows) + 2 * (1.0 - hw) * rows+- covered = 0+- for c in order:+- if covered >= want and not (near_cap and c is order[0]):+- break+- if (c.images and c.key is None) or c.kid in skip: # (pictures without content keys: never written)+- continue+- if d.has(self._ident(c), self._key(c)) or self._superseded(c):+- covered += len(c.ids)+- continue+- if not self._spillable(c):+- continue+- if d.pending_jobs() >= d.cfg.writers:+- d.stats.deferred += 1+- break+- self._emit(SPILL, [c.kid])+- keep = self._kept_keys() if keep is None else keep+- refused = d.stats.full + d.stats.no_space+- if self._spill(c, keep=keep):+- d.stats.behind += 1+- elif d.stats.full + d.stats.no_space > refused: # no room under the cap or above the free-disk floor+- skip.add(c.kid)+- continue+- covered += len(c.ids)++ if self.disk is not None and self.disk.pending:++ try:++ self.disk.pump()++ except Exception as exc: # noqa: BLE001++ print(f"[tensorfold] spill rank {self.rank}: pump failed: {exc!r}", flush=True)++ # reads: rank 0 sends LOAD when a request's prompt extends a stored prompt longer than any kept one; both ranks+ # add an extent for it and start their reads (other streams keep decoding meanwhile); when rank 0's read is done+ # it sends LOADED and both agree, in one all-gather, that every read worked: the extent then holds a kept prompt++ # (the reads only read: between rounds rank 0 copies its blocks read so far and sends LOADPART, and rank 1 copies++ # as far; LOADED copies the rest on each rank)+ # the request resumes from; else it goes, the entry is forgotten, and the request prefills.+ def prestage(self, s: Stream):+ """Rank 0, before a request is admitted: a read of the stored prompt its prompt extends, or None (nothing to+@@ -1550,22 +1526,29 @@ class MultiDecoder:+ if len(prompt) >= h.n and prompt[:h.n] == h.ids:+ return h+ hit = self._resume(prompt)+- e = self.disk.find(prompt, grid=self.grid)+- if e is None or (hit is not None and len(hit.ids) >= e.n):++ self.disk.stats["disk_lookups"] += 1++ pt = self.disk.best(prompt, len(hit.ids) if hit is not None else 0, self.grid)++ if pt is None:++ return None++ from tensorfold.cuda.spill_blocks import key_ints++++ hi, lo, n = key_ints(pt.key)++ self._emit(HAS, [hi, lo, n]) # every rank holds it complete, or nobody reads it++ self._flush()++ if not all(r[0] for r in self.g._gather_ints([int(self.disk.has(pt.key))])):++ self.disk.stats["has_refused"] += 1 # a rank lacks it (lost, damaged, evicted there)+ return None+- size = align_up(e.n)+- self._emit(TOUCH, list(e.key)) # both ranks: the newest entry now, so no save made for room evicts it+- self.disk.touch_key(e.key)++ size = align_up(pt.n)+ base = self._room(size, [hit.extent] if hit is not None else [])+ if base is None:+ self._sync()+ return None+- hi, lo = e.key+ lid = self.next_lid+- self._emit(LOAD, [hi, lo, e.n, base, size, lid])++ self.disk.stats["disk_hits"] += 1++ self._emit(LOAD, [hi, lo, n, base, size, lid])+ self._flush()+- h = self._start_load(hi, lo, e.n, base, size, lid)+- h.ids = [int(t) for t in e.ids]++ h = self._start_load(hi, lo, n, base, size, lid)++ h.ids = [int(t) for t in pt.ids]+ return h++ def _start_load(self, hi: int, lo: int, n: int, base: int, size: int, lid: int):+@@ -1578,32 +1561,76 @@ class MultiDecoder:+ h = types.SimpleNamespace(lid=lid, key=(hi, lo), n=n, x=x, lj=None, err=None, done=False, ids=None)+ x.loading = h++- def dst(name, shape, dt):+- if name.startswith("rows.p"):+- p = self.arena.planes[int(name[6:])]+- a = base // p.div+- return p.tensor[a:a + shape[0]]+- return None++ from tensorfold.cuda.spill_blocks import ints_key+++ h.key = ints_key(hi, lo, n)+ try:+- h.lj = self.disk.load_async((hi, lo), dst)++ h.lj = self.disk.load_async(h.key, x)+ except Exception as exc: # noqa: BLE001 (the read fails at LOADED, on every rank)+ h.err = exc+ self.loads[lid] = h+ return h+++ def step_loads(self) -> None:++ """Rank 0, between iterations: each read's blocks read so far into its extent (on this thread, never beside a++ decoding stream), at most TF_GLM_SPILL_LOAD_MS; LOADPART has rank 1 copy as far (waiting for its own reads)."""++++ if self.disk is None or not self.loads:++ return++ budget = getattr(self, "load_budget", LOAD_MS_DEFAULT / 1000.0)++ deadline = time.perf_counter() + budget # one budget for every read in flight, not one each++ live = [h for h in self.loads.values()++ if not (h.done or h.err is not None or h.lj is None or h.lj.error is not None)]++ if live:++ k = self.load_turn % len(live) # each pause starts with the next read, so none waits behind++ self.load_turn += 1 # the others for its turn++ for h in live[k:] + live[:k]:++ left = deadline - time.perf_counter()++ if left <= 0:++ break++ if self.disk.step(h.lj, budget=left):++ self._emit(LOADPART, [h.lid, h.lj.next])++ if self.outbox and self.idle: # rank 1 waits for the bell between requests (``finish`` rings IDLE)++ self._flush()++++ def _load_part(self, lid: int, upto: int) -> None:++ """Rank 1 (LOADPART): read ``lid``'s blocks before ``upto`` into its extent, waiting for its own reads. A++ failure only fails the read (LOADED says so on every rank)."""++++ h = self.loads.get(lid)++ if h is None or h.err is not None or h.lj is None or h.lj.error is not None:++ return++ try:++ self.disk.step(h.lj, upto=upto)++ except Exception as exc: # noqa: BLE001++ h.lj.error = exc+++ def load_ready(self, h) -> bool:+- """Rank 0: this rank's read is over (or never started)."""++ """Rank 0: this rank's read is over (or never started) and, while other streams decode, every block it read is++ in the pool (``step_loads``, within TF_GLM_SPILL_LOAD_MS a pause): LOADED then copies nothing beside them. Reads++ run ahead of those copies by up to the read-ahead, which LOADED would otherwise copy in one pause. With no++ stream decoding, LOADED copies the rest at once."""++- return h.done or h.err is not None or (h.lj is not None and h.lj.done.is_set())++ if h.done or h.err is not None:++ return True++ lj = h.lj++ if lj is None or not lj.done.is_set():++ return False++ if lj.error is not None or lj.next >= lj.total:++ return True++ return not any(l.decoding and not l.s.done and not l.paused for l in self.lanes.values())++ def complete_load(self, h) -> bool:+- """Rank 0: LOADED to rank 1, then both agree (``_finish_load``). True when the stored prompt is kept now."""++ """Rank 0: LOADED to rank 1, then both agree (``_finish_load``). True when the stored prompt is kept now.++ LOADED carries rank 0's shared-prefix flag of the point: each rank wrote its own point, so theirs may differ,++ and ``cap_victim`` must drop the same state on every rank."""++ if h.done:+ return getattr(h, "ok", False)+ self._check()+- self._emit(LOADED, [h.lid])++ shared = int(h.lj is not None and h.lj.point is not None and bool(h.lj.point.shared))++ self._emit(LOADED, [h.lid, shared])++ h.shared = shared+ self._flush()+ try:+ return self._finish_load(h.lid)+@@ -1613,14 +1640,16 @@ class MultiDecoder:++ def _finish_load(self, lid: int) -> bool:+ """Both ranks: wait for this rank's read, agree through one all-gather that every read worked, then the+- extent holds a kept prompt; else the extent goes and the entry is forgotten on both."""++ extent holds a kept prompt (a shared-prefix one when rank 0's point is: ``h.shared``, LOADED's flag); else the++ extent goes and the entry is forgotten on both."""++ h = self.loads.pop(lid)+- ok, snap, meta = 0, None, None++ shared = getattr(h, "shared", 0)++ ok, snap, pt = 0, None, None+ if h.err is None:+ try:+- snap, _, meta = self.disk.finish_load(h.lj)+- ok = int(snap is not None and int(meta["n"]) == h.n)++ snap, pt = self.disk.finish_load(h.lj)++ ok = int(snap is not None and pt.n == h.n)+ except Exception as exc: # noqa: BLE001 (a failed read: every rank prefills)+ print(f"[tensorfold] spill rank {self.rank}: restore failed: {exc!r}", flush=True)+ else:+@@ -1631,19 +1660,28 @@ class MultiDecoder:+ h.done = True+ h.ok = all(r[0] for r in every)+ if not h.ok:+- self.disk.stats.load_failed += 1+- self.disk.forget(h.key)++ if ok: # read here, but not on every rank: a failed restore here too++ self.disk.stats["loaded"] -= 1++ self.disk.stats["load_failed"] += 1++ lj = h.lj++ self.disk.forget(h.key, lj.bad if lj is not None else (), lj.lost if lj is not None else ())+ self.pool.remove(x)+ return False+- ids = [int(t) for t in json.loads(meta["tokens"])]+- keyed = json.loads(meta["keyed"]) if meta.get("keyed") else None++ dev = self.w.device++ snap.rec, snap.conv = snap.rec.to(dev), snap.conv.to(dev)++ snap.tail = [(sl.to(dev), r.to(dev)) for sl, r in (snap.tail or [])] or None++ snap.head = snap.head.to(dev) if snap.head is not None else None++ snap.drafter_rows = [r.to(dev) for r in snap.drafter_rows] if snap.drafter_rows is not None else None++ ids = [int(t) for t in (pt.tokens if pt.tokens is not None else pt.ids)]++ keyed = [int(t) for t in pt.ids] if pt.tokens is not None else None++ snap.lineage = pt.lineage+ snap.ids = ids+ snap.pending, snap.mtp_len, snap.rows, snap.nbytes = None, -1, None, 0+ snap.kid = self.next_kid+ self.next_kid += 1+ snap.key = keyed if keyed is not None else ids if self.rank == 0 else None+ snap.images = keyed is not None+- snap.shared = False++ snap.shared = bool(shared) # rank 0's (LOADED): cap_victim keeps a system prompt on every rank+ snap.own, snap.chat = False, 0 # a restored state counts against no conversation's quota+ snap.extent = x+ x.kept.append(snap)+@@ -1653,50 +1691,32 @@ class MultiDecoder:+ return True++ def flush_spill(self, budget: float | None = None) -> None:+- """Rank 0 (the scheduler's worker), a clean shutdown: the kept prompts not yet on disk, newest first, as many+- as the flush budget's time allows at the writers' rate so far (FLUSH carries the list), then both ranks wait+- for their writes."""++ """Rank 0 (the scheduler's worker), a clean shutdown: every kept prompt is on its way to disk already (written++ when kept); both ranks write what still waits (FLUSH), within the flush budget."""++ if self.disk is None:+ return+- d = self.disk+- budget = d.cfg.flush_s if budget is None else budget+- s = d.stats+- rate = s.written_bytes / s.write_s if s.write_s > 1 and s.written_bytes else 0.5 * (1 << 30)+- rate *= d.cfg.writers+- kids, t = [], 0.0+- for c in reversed(self.kept):+- if not self._spillable(c) or d.has(self._ident(c), self._key(c)) or self._superseded(c):+- continue+- nb = sum(t2.numel() * t2.element_size() for _, t2 in self._planes(c.extent.base, len(c.ids)))+- t += nb / rate+- if t > 0.8 * budget:+- break+- kids.append(c.kid)+- self._emit(FLUSH, kids)++ self._emit(FLUSH, [])+ if not self.lanes: # rank 1 goes back to the doorbell after the FLUSH+ self._emit(IDLE, [])+ self._flush()+ if not self.lanes:+ self.idle = True+- self._do_flush(kids, budget)++ self._do_flush([])++ def _do_flush(self, kids, budget: float | None = None) -> None:+ t = time.perf_counter()+ budget = self.disk.cfg.flush_s if budget is None else budget+- done: list = []+- for kid in kids:+- c = next((k for k in self.kept if k.kid == kid), None)+- if c is not None: # newest first: the flush's own earlier (newer) picks stay+- self._spill(c, keep=frozenset(self._key(k) for k in done))+- done.append(c)+- ok = self.disk.drain(max(1.0, budget - (time.perf_counter() - t)))+- print(f"[tensorfold] spill rank {self.rank}: flushed {len(done)} kept prompts in "++ waiting = len(self.disk.waiting)++ ok = self.disk.drain(budget)++ print(f"[tensorfold] spill rank {self.rank}: wrote the {waiting} kept prompts still waiting in "+ f"{time.perf_counter() - t:.1f}s{'' if ok else ' (not finished)'}", flush=True)++ # -- room --------------------------------------------------------------------------------------------------------------+ def _used(self, x) -> int:+ used = max([len(k.ids) for k in x.kept], default=0)++ if self.disk is not None: # rows a waiting write still reads move with the extent++ used = max([used] + [j.point.n for j in self.disk.pending if j.where is x and j.next < len(j.new)])+ if getattr(x, "loading", None) is not None: # a stored prompt being read into it (``_start_load``)+ used = max(used, x.loading.n)+ if x.owner is not None:+@@ -1706,11 +1726,14 @@ class MultiDecoder:+ return used++ def _move(self, x, base: int, size: int) -> None:+- """Both ranks: relocate extent x (its used rows copied) to [base, base + size)."""++ """Both ranks: relocate extent x (its used rows copied) to [base, base + size). A stored prompt being read into++ it goes on: its next blocks land at the new base, after the rows' copy (``BlockStore.moving``)."""++ used = self._used(x)+- old = self.pool.move(x, base, size)+- self.arena.copy(old, base, used)++ h = getattr(x, "loading", None)++ with self.disk.moving(h.lj) if h is not None and h.lj is not None else contextlib.nullcontext():++ old = self.pool.move(x, base, size)++ self.arena.copy(old, base, used)+ if x.owner is not None:+ self.lanes[x.owner].st.bind(x.base, x.size)++@@ -1800,10 +1823,7 @@ class MultiDecoder:+ _watch(self.watchdog, "iteration") # cancelled at the end of ``finish``+ self.iteration_since = time.monotonic() # /health's iteration_s+ try:+- if self.disk is not None and self.disk.cfg.highwater < 1.0:+- t0 = time.perf_counter()+- self._behind()+- self.disk.stats.behind_s += time.perf_counter() - t0++ self._pump()+ return self._iterate()+ except Exception as exc:+ self._break(exc)+@@ -2236,6 +2256,11 @@ class MultiDecoder:+ if prof is not None:+ prof.gpu_start()+ v = forward_streams(verify, segments)++ if self.disk is not None and self.loads:++ try:++ self.disk.settle() # (reads' slots back beside the queued pass: a slot turns every round)++ except Exception as exc: # noqa: BLE001 (never the engine's failure: the read ends at LOADED)++ print(f"[tensorfold] spill rank {self.rank}: read settle failed: {exc!r}", flush=True)+ if prof is not None:+ prof.gpu_stop()+ prof.mark("verify")+@@ -2378,6 +2403,8 @@ class MultiDecoder:+ self._emit(IDLE, [])+ self._flush()+ self.idle = True++ if self.disk is not None: # nothing pumps while idle: every waiting block through the ring now++ self.disk.stage_all()+ _unwatch(self.watchdog)+ self.iteration_since = None++@@ -2458,6 +2485,7 @@ class MultiDecoder:+ _watch(self.watchdog, f"rank {self.rank} message") # busy: rank 0's next message is due within a round+ self.apply(unseal(self.g._share(None), self.received, self.rank))+ self.received = (self.received + 1) % SEAL_MOD++ self._pump()+ _unwatch(self.watchdog)+ if once:+ return+@@ -2489,14 +2517,18 @@ class MultiDecoder:+ self._drop(self._kept_by_id(p[0]), spill=bool(p[1]) if len(p) > 1 else True)+ elif op == LOAD:+ self._start_load(*p)+- elif op == LOADED:+- self._finish_load(*p)+- elif op == TOUCH:+- self.disk.touch_key((p[0], p[1]))++ elif op == LOADED: # (rank 0's shared-prefix flag of the point: ``_finish_load``)++ if len(p) > 1 and p[0] in self.loads:++ self.loads[p[0]].shared = int(p[1])++ self._finish_load(p[0])++ elif op == LOADPART:++ self._load_part(*p)++ elif op == HAS:++ from tensorfold.cuda.spill_blocks import ints_key++++ self.g._gather_ints([int(self.disk is not None and self.disk.has(ints_key(*p[:3])))])+ elif op == FLUSH:+ self._do_flush(p)+- elif op == SPILL:+- self._spill(self._kept_by_id(p[0]), keep=self._kept_keys())+ elif op == MOVE:+ self._move(self.pool.get(p[0]), p[1], p[2])+ elif op == GROW:+@@ -2539,6 +2571,8 @@ class MultiDecoder:+ if self.lanes:+ raise RuntimeError(f"rank 1 holds {len(self.lanes)} streams rank 0 has finished")+ self.idle = True++ if self.disk is not None: # nothing pumps while idle: every waiting block through the ring now++ self.disk.stage_all()+ else:+ raise RuntimeError(f"rank 1: unknown op {op}")++@@ -2565,6 +2599,7 @@ class GlmScheduler(Scheduler):+ self.flush_lock = threading.Lock()+ self.loading: list = [] # (read, item): requests waiting for a stored prompt read (--spill-gib)+ self.ready: list = [] # items whose read ended: admitted before the queue++ self.prefix: list = [] # (point, item): requests waiting for a prefix another one is prefilling+ self.staged: set = set() # streams a read was looked for already+ # TF_GLM_MULTI_PREFILL_WAIT_MS: an idle server's wait for requests arriving with the first (their prompts then+ # share its first chunk); only with TF_GLM_MULTI_PREFILL=1+@@ -2646,7 +2681,7 @@ class GlmScheduler(Scheduler):++ if background or self.max_in_system is None:+ return+- held = self.decoder.live() + self._reading() + len(self.ready)++ held = self.decoder.live() + self._reading() + len(self.ready) + len(self.prefix)+ if held + self.waiting.foreground_count() >= self.max_in_system:+ raise CapacityError("all serving lanes are busy; retry shortly")++@@ -2660,6 +2695,7 @@ class GlmScheduler(Scheduler):+ import heapq++ self.ready = [it for it in self.ready if not self._cancel_item(it)] # their stored prompts read (--spill-gib)++ self.prefix = [(w, it) for w, it in self.prefix if not self._cancel_item(it)]+ self.loading = [(read, None if it is None or self._cancel_item(it) else it) for read, it in self.loading]+ if self.held is not None and self._cancel_item(self.held):+ self.held = None+@@ -2690,6 +2726,11 @@ class GlmScheduler(Scheduler):+ self.decoder.flush_spill()+ finally:+ flush.set()++ for w, it in [p for p in self.prefix if self.decoder.prefix_ready(p[0])]:++ self.prefix.remove((w, it))++ self.ready.append(it) # (admitted before the queue, resuming from that point)++ if self.loading:++ self.decoder.step_loads() # reads' blocks into the pool, between rounds (this thread)+ for it in [it for it in self.loading if self.decoder.load_ready(it[0])]:+ self.loading.remove(it)+ try:+@@ -2722,6 +2763,13 @@ class GlmScheduler(Scheduler):+ if not self.decoder.fits(stream):+ self.held = item # waits, first in line, for room+ break++ waiter = getattr(self.decoder, "prefix_wait", None)++ if waiter is not None and not getattr(stream, "prefix_waited", False):++ w = waiter(stream)++ if w is not None: # another stream is prefilling its prefix: wait for that state++ stream.prefix_waited = True++ self.prefix.append((w, item))++ continue+ prestage = getattr(self.decoder, "prestage", None)+ if prestage is not None and id(stream) not in self.staged:+ self.staged.add(id(stream))+@@ -2803,7 +2851,7 @@ class GlmScheduler(Scheduler):+ def _iteration(self) -> None:+ self._cancel_waiting()+ self._yield()+- reading = bool(self.loading or self.ready)++ reading = bool(self.loading or self.ready or self.prefix)+ idle = not self.decoder.live() and self.held is None and not reading+ if reading and not self.decoder.live():+ time.sleep(0.002) # only reads in flight: poll them+diff --git tensorfold/server/metrics.py tensorfold/server/metrics.py+index cb260c4..6b13428 100644+--- tensorfold/server/metrics.py++++ tensorfold/server/metrics.py+@@ -175,7 +175,8 @@ def send(handler: Any, app: Any) -> None:+ handler.close_connection = True+++-# /health's fields under HEALTH: (field, type, help); the totals are the finished requests' engine stats++# /health's fields under HEALTH: (field, type, help); the totals are the finished requests' engine stats, then the GLM++# engine's prefix-wait counters (/health names them without the suffix: _HEALTH_RENAMED)+ _HEALTH_TOTALS = (+ ("requests_total", "counter", "Finished requests (as /health's requests_total)."),+ ("completion_tokens_total", "counter", "Reply tokens, the running replies' tokens so far included."),+@@ -183,8 +184,16 @@ _HEALTH_TOTALS = (+ ("rounds_total", "counter", "Decode rounds of finished requests."),+ ("prefill_seconds_total", "counter", "Engine prefill seconds of finished requests."),+ ("decode_seconds_total", "counter", "Engine decode seconds of finished requests."),++ ("prefix_waits_total", "counter", "Requests that waited for a prefix another request was prefilling."),++ ("prefix_wait_tokens_total", "counter", "Prompt tokens those requests did not prefill again."),+ )+-_SPILL_GAUGES = {"entries", "pending", "stored_bytes", "disk_free_bytes", "highwater", "writers"}++_HEALTH_RENAMED = {"prefix_waits": "prefix_waits_total", "prefix_wait_tokens": "prefix_wait_tokens_total"}++# the spill tier's gauges in /health's spill (highwater, writers: the one-stream engine's SpillStore; the rest from++# entries on: either store, or the block store alone); its other numbers are counters++_SPILL_GAUGES = {"entries", "pending", "stored_bytes", "disk_free_bytes", "highwater", "writers", "blocks",++ "backlog_mb", "block_tokens", "stored_gib", "cap_bytes", "turns", "quota", "conversations",++ "conversation_bytes_max", "conversation_share_max", "conversation_tokens_max", "shared_states",++ "shared_bytes", "forks", "fork_bytes", "turns_kept_max", "host_mb", "release_cap_mb"}+ _HEALTH_GAUGES = (+ ("ok", "Engine health: 1 healthy, 0 broken (see /health for the reason)."),+ ("context_length", "Tokens a request's prompt and reply may hold (the server's effective window)."),+@@ -210,6 +219,9 @@ def _health(lines: list[str], app: Any) -> None:+ body = _read(lambda: snapshot(app), None) if callable(snapshot) else None+ if not isinstance(body, dict):+ return++ for field, name in _HEALTH_RENAMED.items(): # (counters /health names without the suffix)++ if field in body:++ body.setdefault(name, body[field])+ for name, kind, help_text in _HEALTH_TOTALS:+ if isinstance(body.get(name), (int, float)):+ _family(lines, name, kind, help_text, [f"{HEALTH}{name} {_num(body[name])}"], HEALTH)diff --git a/scripts/config.sh b/scripts/config.shindex d735971..21c876d 100644--- a/scripts/config.sh+++ b/scripts/config.sh@@ -439,17 +439,37 @@ prepared_state() {echo "$line"}-# Spill tier (patch 0088-glm-spill-tier, off by default): kept prompt states go to local disk on each Spark and come-# back instead of a new prefill, also after a clean restart. SPILL_GIB: the cap per Spark (0: off). SPILL_DIR: the same-# absolute path on every Spark (mounted at /spill; files owned by your user). SPILL_HIGHWATER: past this fraction of-# the KV pool, the kept prompts eviction would take next are written in the background (1.0: only when evicted).-# A clean stop writes what is kept within SPILL_FLUSH_S seconds; STOP_TIMEOUT gives it the time. README: Spill tier.+# Spill tier (patches 0088-glm-spill-tier and 0128-glm-spill-blocks, off by default): kept prompt states go to local+# disk on each Spark when they are kept (PARALLEL above 1) and come back instead of a new prefill, also after a+# restart or a crash. SPILL_GIB: the cap per Spark (0: off). SPILL_DIR: the same absolute path on every Spark (mounted+# at /spill; files owned by your user). SPILL_QUOTA: the share of SPILL_GIB one conversation may hold before its own+# old turns and forks go first (0: none). SPILL_TURNS: the newest states kept on a conversation's path; older turns+# go as each one is written (each keeps a ~91 MB small part; 2 for heavy agent loops or a small disk, 8+ for chats with+# deep edits, 0: every turn kept until room is needed). SPILL_RELEASE_MIB: the most MiB of rows copied to host memory+# while they wait to be written (rows freed or overwritten before their write: on a GB10 that memory is the pool's and+# the reserve's); unset, an eighth of MEMORY_RESERVE_GIB (1.8 GiB at 14.5); a state past it is not stored. One engine a+# SPILL_DIR on each Spark: a second one finds it locked and runs without the tier.+# SPILL_HIGHWATER: no longer used (states are written when kept). A clean stop writes what still waits within+# SPILL_FLUSH_S seconds; STOP_TIMEOUT gives it the time. README: Spill tier.SPILL_GIB="${SPILL_GIB:-0}"SPILL_DIR="${SPILL_DIR:-$HOME/.cache/tensorfold-spill}"SPILL_HIGHWATER="${SPILL_HIGHWATER:-0.70}"SPILL_MIN_TOKENS="${SPILL_MIN_TOKENS:-8192}"SPILL_MIN_FREE_GIB="${SPILL_MIN_FREE_GIB:-50}"SPILL_FLUSH_S="${SPILL_FLUSH_S:-60}"+# (each also taken from its TF_GLM_ name when only that is set: exporting the TF_GLM_ name alone was overwritten)+SPILL_QUOTA="${SPILL_QUOTA:-${TF_GLM_SPILL_QUOTA:-0}}"+export TF_GLM_SPILL_QUOTA="$SPILL_QUOTA"+SPILL_TURNS="${SPILL_TURNS:-${TF_GLM_SPILL_TURNS:-4}}"+export TF_GLM_SPILL_TURNS="$SPILL_TURNS"+SPILL_RELEASE_MIB="${SPILL_RELEASE_MIB:-${TF_GLM_SPILL_RELEASE_MIB:-}}"+[[ -z "$SPILL_RELEASE_MIB" ]] || export TF_GLM_SPILL_RELEASE_MIB="$SPILL_RELEASE_MIB"+# A request whose prompt starts with what another request is still prefilling (a system prompt several agents share)+# waits for that state instead of prefilling it beside it (patch 0128): six agents at once on a fresh 12k-token system+# prompt answered in 15 s instead of 47 s. Same replies. Off by default: it changes admission (with SPILL_GIB=0 too).+# PREFIX_WAIT=1 turns it on. README: A system prompt prefilled once.+PREFIX_WAIT="${PREFIX_WAIT:-0}"+export TF_GLM_PREFIX_WAIT="$PREFIX_WAIT"if [[ "$SPILL_GIB" != 0 ]]; thenSTOP_TIMEOUT="${STOP_TIMEOUT:-$(( ${SPILL_FLUSH_S%.*} + 30 ))}"fidiff --git a/tools/kept_state_check.py b/tools/kept_state_check.pyindex 459ec66..48bbe62 100644--- a/tools/kept_state_check.py+++ b/tools/kept_state_check.py@@ -5,9 +5,9 @@ scripts/prepare.sh built:docker run --rm --entrypoint python -v "$PWD/tools/kept_state_check.py:/c.py" tensorfold-glm53:v0.6.0 /c.pyMultiDecoder'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.+default (nothing dropped), 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; with the spill tier on, every kept state written when it is kept+and none at a drop (the quota's, the byte budget's, the entry cap's or rank 1's EVICT). Exit code 1 when a check fails."""from types import SimpleNamespace as NS@@ -43,8 +43,8 @@ def dec(entries=32, size=100, cap=0):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.disk = object() # the spill tier "on": _persist records what it is asked+ m._persist = lambda c: m.spilled.append(c.kid)m._emit = lambda op, p: m.ops.append((op, list(p)))m._ctx = lambda lane: Nonereturn m@@ -64,7 +64,8 @@ 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)+check("off: all six of one chat kept and written when kept, nothing evicted", len(m.kept) == 6 and not m.ops+ and len(m.spilled) == 6)M.KEEP_PER_CHAT = 2m = dec()@@ -73,7 +74,7 @@ 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)+check("quota drops write nothing (each state was written when kept)", len(m.spilled) == 5)sh = lane(m, 2, 64)m._keep(sh, 64)m._keep(sh, 66)@@ -93,13 +94,13 @@ for i, l in enumerate(ls):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)+check("byte cap: its drops write nothing (each state was written when kept)", len(m.spilled) == 6)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)+check("entry cap: every state written when kept, none at its drop", len(m.kept) == 2 and len(m.spilled) == 4)# rank 1 applies the EVICT: the same drop, no spillr = dec(cap=250 * MB)@@ -108,7 +109,7 @@ 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)+check("rank 1: EVICT drops and writes nothing more", not r.kept and len(r.spilled) == 1)print("all passed" if not fails else f"FAILED: {fails}")raise SystemExit(1 if fails else 0)diff --git a/tools/spill_blocks_check.py b/tools/spill_blocks_check.pynew file mode 100644index 0000000..97197bb--- /dev/null+++ b/tools/spill_blocks_check.py@@ -0,0 +1,1396 @@+#!/usr/bin/env python3+"""Checks for patch 0128 (the spill tier's block store, tensorfold/cuda/spill_blocks.py, and its hooks in multi.py),+CPU only, run inside the image that scripts/prepare.sh built (no GPU, no model, no server); its files go to a scratch+folder under $TMPDIR:++ docker run --rm --entrypoint python -e CUDA_VISIBLE_DEVICES= -v "$PWD/tools/spill_blocks_check.py:/c.py" \+ tensorfold-glm53:v0.6.0 /c.py++A real BlockStore over a real Arena on the host (a latents plane, div 1, and a pooled-key plane, div 4 with 2 pad+rows), with a stand-in small state, and MultiDecoder's own load and move paths on a real Pool:+- the block a kept state's end cuts holds the rows of the keep, not what the stream writes after it (its pooled-key+ row still filling at the keep);+- a read only reads: its reader copies no row (no CUDA work off the engine's thread); the engine copies the blocks+ read so far between rounds (rank 0's step, LOADPART to rank 1 copying as far, the rest at LOADED), on its own thread;+- compaction moving an extent a stored prompt is being read into goes on without waiting for the disk, and the read's+ later blocks land at the new base and none at the old one;+- a restored state keeps its point's shared-prefix flag, rank 0's on every rank (LOADED carries it);+- the same ids kept again as a shared prefix make the stored point shared, its json rewritten through a temporary+ name and the folder fsynced (a restart reads it so), also when they were still waiting or being written; a point+ dropped during the rewrite does not get its json back, and a drain (a clean stop) waits for the rewrite;+- a read that fails on a missing block file drops that name and the points naming it, not the points whose blocks+ are links to the same bytes (they still read back); one that fails on damaged bytes drops every name of them;+- every op in multi's table has a sender, and /metrics carries the prefix wait's counters;+- each of a point's files (.ids, .st, .json) has its pages dropped from the page cache after its fsync;+- a decode round settles the reads once its verify pass is queued (every slot the last step copied out back to the+ reader, after the newest copy only), so beside a decoding stream a read slot turns every round;+- a staged block records its write slot's own event (made at start), and the writer waits on that one;+- LOADED on a rank with more blocks left than read slots returns: the wait for a block frees the slots the step's+ own copies hold (a rank 1 whose rank 0 failed early hung there for ever);+- the read-ahead (16 blocks unless TF_GLM_SPILL_READ_BLOCKS says otherwise; on two Sparks the preallocated read+ buffers hold the first ten and 9 fits them, so the pool pays nothing for 9) keeps spill.preallocate's read buffers+ and pins only the rest before the pool is sized, in power-of-two pieces of at most spill.CHUNK (torch's pinned+ allocator rounds an allocation up to one), the bytes it returns (the pool's cost) those pieces only; ring carves+ at least that many stored blocks out of them and pins none later;+- the room, files first: each eviction step deletes the files it should (an old turn its point files only, a fork+ and a whole conversation their own blocks too, never a block another point names) and goes in the order old turns,+ abandoned forks, whole conversations least recently used, shared prefixes last; a point being read is never taken,+ nor a block the state being written names;+- old turns trimmed as newer ones are written (SPILL_TURNS: the newest on the path stay, forks off it and shared+ prefixes untouched, a turn being read kept; 0 keeps every turn), the quota (a conversation over its share trims its+ own old turns and forks, no other's), the free-disk floor (a disk full of other things refuses without evicting;+ short of the floor, room made in the eviction order);+- a restart: temporary names, points without their json, with damaged ids or a missing block, blocks no point names+ and foreign files go, the complete point reads back; older builds lose this rank's folder (the newest other stays);+ a failed write leaves no temporary file;+- temporary files are opened O_EXCL | O_NOFOLLOW (a symlink planted at the name is not written through, a leftover+ file replaced); one engine a folder and rank (``spill.hold``: a second engine, of any build, the one-stream store+ too, gets ``Busy`` before it prunes anything, the engine then runs with the tier off; a kill -9 lets it go);+- release has its own cap (TF_GLM_SPILL_RELEASE_MIB, by default an eighth of the memory reserve): past it a state's+ rows are not copied and it is not stored; the host copies (and the block a keep cuts) are let go once written;+- the prefix wait is off unless TF_GLM_PREFIX_WAIT=1; what it waits for and what not, when it lets go, and the+ scheduler (the spill tier off) holding the request apart while the queue goes on.+Exit code 1 when a check fails; tools/spill_blocks_mutants.sh runs it on faithful mutants of each fix.+"""+import inspect+import json+import os+import queue+import subprocess+import sys+import tempfile+import threading+import time+from types import SimpleNamespace as NS++import numpy as np+import torch++from tensorfold.cuda import health as H+from tensorfold.cuda import spill as SP+from tensorfold.cuda import spill_blocks as S+from tensorfold.cuda.scheduler import Waiting+from tensorfold.families.glm5_next.cuda import multi as M+from tensorfold.families.glm5_next.cuda.pool import ALIGN, Arena, Plane, Pool, align_up+from tensorfold.server import metrics as MT++ROWS = 8 * ALIGN+# TEST_TIMEOUT_S: the whole run's watchdog (a hang prints a FAIL and exits), and the longest single wait is half of it.+# 900 s by default: one run takes ~15-60 s, and a slower CPU went past the old 60 s (tools/spill_blocks_mutants.sh+# sets 120 for its runs).+TIMEOUT = float(os.environ.get("TEST_TIMEOUT_S", "900"))+fails: list[str] = []+ROOT = tempfile.mkdtemp(prefix="spill-blocks-check-")+++def check(name: str, ok: bool) -> None:+ print(("ok " if ok else "FAIL ") + name, flush=True)+ if not ok:+ fails.append(name)+++def _hung() -> None:+ print(f"FAIL timed out after {TIMEOUT:g} s", flush=True)+ os._exit(1)+++_watchdog = threading.Timer(TIMEOUT, _hung)+_watchdog.daemon = True # (a crash ends the run at once)+_watchdog.start()+++class Snap:+ """A stand-in for decode.Snapshot: the fields ``_finish_load`` moves to the device, and the multi-stream ones+ ``_SPILL_SKIP`` leaves out."""+++CLASSES = [f"{Snap.__module__}:{Snap.__qualname__}"]+++def snap(ids, shared=False) -> Snap:+ s = Snap()+ s.ids, s.shared, s.lineage = list(ids), shared, ""+ s.rec, s.conv = torch.arange(64, dtype=torch.float32) + len(ids), torch.ones(8)+ s.tail, s.head, s.drafter_rows = None, None, None+ return s+++def arena(seed: int) -> Arena:+ g = torch.Generator().manual_seed(seed)+ lat = torch.randint(-2**31, 2**31 - 1, (ROWS, 4), generator=g, dtype=torch.int32)+ pk = torch.randint(-2**15, 2**15 - 1, (ROWS // 4 + 2, 8), generator=g, dtype=torch.int16)+ return Arena(ROWS, [Plane(lat, 1), Plane(pk, 4, 2)])+++OPEN: dict = {} # (folder, rank) -> the store holding it (``spill.hold``)+++def store(ar: Arena, name: str, rank: int = 0, gib: float = 1.0, floor: float = 0.0, **kw) -> S.BlockStore:+ """A store on ``ROOT/name``; one already open there for ``rank`` is closed first (the engine before it ended: a+ restart)."""++ cfg = SP.SpillConfig(root=os.path.join(ROOT, name), gib=gib, min_tokens=1, min_free_gib=floor)+ os.makedirs(cfg.root, exist_ok=True)+ old = OPEN.pop((cfg.root, rank), None)+ if old is not None:+ old.close()+ st = S.BlockStore(cfg, planes=ar.planes, block=ALIGN, rank=rank, device="cpu", classes=CLASSES, quiet=True, **kw)+ OPEN[(cfg.root, rank)] = st+ return st+++def rows(ar: Arena, base: int, n: int) -> list[torch.Tensor]:+ """The rows tokens [0, n) of an extent at ``base`` occupy, each plane (a pooled-key row still filling included)."""++ return [p.tensor[base // p.div:base // p.div + -(-n // p.div)].clone() for p in ar.planes]+++def span(ar: Arena, a: int, b: int) -> list[torch.Tensor]:+ """Every plane's rows of tokens [a, b) (both multiples of 4)."""++ return [p.tensor[a // p.div:b // p.div].clone() for p in ar.planes]+++def same(a: list, b: list) -> bool:+ return all(torch.equal(x, y) for x, y in zip(a, b))+++def ids_of(n: int, seed: int = 0) -> list[int]:+ return [int(v) for v in np.random.default_rng(seed).integers(1, 150000, n)]+++def until(cond, timeout: float = 10.0) -> bool:+ end = time.monotonic() + timeout+ while not cond():+ if time.monotonic() > end:+ return False+ time.sleep(0.005)+ return True+++def load_rows(st: S.BlockStore, ar: Arena, key: str, x, n: int):+ """A read of point ``key`` into extent ``x`` (the store's own reader), then its rows; Nones when the read fails."""++ try:+ small, pt = st.finish_load(st.load_async(key, x))+ except Exception as exc: # noqa: BLE001 (a failed read: the checks below say so)+ print(f" (read of {key} failed: {exc!r})")+ return None, None, None+ return small, pt, rows(ar, x.base, n)+++def stored(st: S.BlockStore, ar: Arena, n: int, seed: int, base: int = 0, shared: bool = False):+ """A state of ``n`` tokens kept at ``base`` and written: (its ids, its rows as kept)."""++ ids = ids_of(n, seed)+ x = Pool(ROWS).add(base, align_up(n))+ st.persist(ids, snap(ids), extent=x, lineage=f"s{seed}", shared=shared, skip=M.MultiDecoder._SPILL_SKIP)+ if not st.drain(TIMEOUT / 2):+ print(" (a write did not end)")+ return ids, rows(ar, base, n)+++def decoder(ar: Arena, st: S.BlockStore, rank: int = 0) -> M.MultiDecoder:+ """A MultiDecoder with only what its spill-tier paths use: a real Pool over ``ar`` guarded by ``_guard_pool``,+ ``st`` as its disk, one rank's view (no collectives), its ops left in ``outbox``."""++ m = object.__new__(M.MultiDecoder)+ m.pool, m.arena, m.disk, m.rank = Pool(ROWS), ar, st, rank+ m.w = NS(world=1, device="cpu")+ m.g = NS(cache_entries=8)+ m.kept, m.lanes, m.partial, m.loads, m.outbox = [], {}, None, {}, []+ m.next_lid = m.next_kid = 0+ m.load_turn = 0+ m.broken, m.idle = None, False+ m._flush = lambda: None+ m._guard_pool()+ return m+++def gate_reads(st: S.BlockStore, hold) -> threading.Event:+ """Reads of the blocks ``hold(name)`` names wait for the returned event (the disk slow)."""++ gate, orig = threading.Event(), st._read_block++ def gated(h, crc, buf, nb):+ if hold(h):+ gate.wait(TIMEOUT)+ return orig(h, crc, buf, nb)++ st._read_block = gated+ return gate+++# -- review 1: the block a state's end cuts is frozen at the keep ---------------------------------------------------+ar = arena(1)+pool = Pool(ROWS)+st = store(ar, "tail")+n = 2 * ALIGN + 6 # a tail of 6 tokens: its last pooled-key row holds 2 of 4+x = pool.add(0, align_up(n))+ids = ids_of(n)+kept = rows(ar, x.base, n)+check("tail: a state with a tail is queued", st.persist(ids, snap(ids), extent=x, lineage="a",+ skip=M.MultiDecoder._SPILL_SKIP) == "queued")+g = torch.Generator().manual_seed(9)+for p in ar.planes: # the stream goes on decoding in its extent past the keep+ a = n // p.div+ p.tensor[a:a + 8] = torch.randint(-100, 100, tuple(p.tensor[a:a + 8].shape), generator=g, dtype=p.tensor.dtype)+check("tail: the stream's next pooled-key row is the one the keep ended in", not same(rows(ar, x.base, n), kept))+check("tail: drained", st.drain(TIMEOUT / 2))+y = pool.add(4 * ALIGN, align_up(n))+_, pt, got = load_rows(st, ar, S.point_key(ids), y, n)+check("tail: the stored rows are those of the keep (the filling row as it was)", got is not None and same(got, kept))+check("tail: the tail block is not staged from the pool later", st.stats["staged_blocks"] == 2)++# -- review 2: compaction moves an extent being read without waiting for the read ----------------------------------+n = 3 * ALIGN+ar = arena(2)+st = store(ar, "move")+m = decoder(ar, st)+ids, kept = stored(st, ar, n, 21)+pt = st.index[S.point_key(ids)]+gate = gate_reads(st, lambda h: h != pt.blocks[0]) # the first block comes, the disk holds the rest+below = m.pool.add(0, 2 * ALIGN) # an extent below the read's, gone before the compaction+hi, lo, _ = S.key_ints(pt.key)+h = m._start_load(hi, lo, n, 2 * ALIGN, align_up(n), 0)+x = h.x+check("move: the read's first block is in the pool", until(lambda: (m.step_loads(), st.stats["loaded_bytes"] > 0)[1]))+m.pool.remove(below)+t = threading.Thread(target=m._compact, daemon=True)+t.start()+t.join(3.0)+check("move: compaction moves the extent being read without waiting for the disk", not t.is_alive() and x.base == 0)+left = (align_up(n), 2 * ALIGN + align_up(n)) # the rows it left (past its new end)+for p in ar.planes:+ p.tensor[left[0] // p.div:left[1] // p.div] = 7+before = span(ar, *left)+gate.set()+t.join(TIMEOUT / 2)+check("move: the read ends", until(lambda: h.lj.done.is_set()))+check("move: the stored prompt is kept after its read", m.complete_load(h) and len(x.kept) == 1)+check("move: its rows are at the extent's new base, as they were kept", same(rows(ar, x.base, n), kept))+check("move: no block of the read landed at the old base", same(span(ar, *left), before))+++# -- the reader reads, the engine copies (between rounds, on its thread; LOADPART takes rank 1 as far) ------------------+ar = arena(3)+st = store(ar, "engine")+m = decoder(ar, st)+ids, kept = stored(st, ar, n, 31)+pt = st.index[S.point_key(ids)]+hi, lo, _ = S.key_ints(pt.key)+h = m._start_load(hi, lo, n, 2 * ALIGN, align_up(n), 0)+x = h.x+for p in ar.planes:+ p.tensor[x.base // p.div:(x.base + align_up(n)) // p.div] = 5+before = rows(ar, x.base, n)+check("engine: the reader reads every block and copies none", until(lambda: h.lj.done.is_set())+ and len(h.lj.queued) == h.lj.total and st.stats["loaded_bytes"] == 0 and same(rows(ar, x.base, n), before))+threads, copy_in = set(), st._copy_in+st._copy_in = lambda *a: (threads.add(threading.get_ident()), copy_in(*a))[1]+m.step_loads()+check("engine: a step copies the blocks read, on the engine's own thread",+ h.lj.next == h.lj.total and threads == {threading.get_ident()})+check("engine: LOADPART tells rank 1 how far", [p for op, p in m.parse(m.outbox) if op == M.LOADPART] == [[0, h.lj.total]])+check("engine: the stored prompt is kept after its read", m.complete_load(h) and len(x.kept) == 1)+check("engine: its rows as they were kept", same(rows(ar, x.base, n), kept))+ar = arena(4)+st = store(ar, "engine1", 1)+m1 = decoder(ar, st, 1)+ids, kept = stored(st, ar, n, 31)+hi, lo, _ = S.key_ints(S.point_key(ids))+m1.apply([M.LOAD, 6, hi, lo, n, 2 * ALIGN, align_up(n), 0])+h = m1.loads[0]+m1.apply([M.LOADPART, 2, 0, 2])+check("engine: rank 1 copies as far as LOADPART says (waiting for its reads), no further", h.lj.next == 2)+m1.apply([M.LOADED, 2, 0, 0])+check("engine: rank 1 copies the rest at LOADED, its rows as kept", len(m1.kept) == 1 and same(rows(ar, h.x.base, n), kept))+++# -- review 3, shared-flag 1 and 2: a restore keeps the shared-prefix flag, rank 0's on every rank -----------------+def two_ranks(flags: tuple[bool, bool], name: str):+ """Rank 0 and rank 1 (each its arena, disk and pool), rank 0's ops applied by rank 1's own ``apply``; the same+ state stored on each with its own shared flag (``flags``), then read back through LOAD and LOADED."""++ ms = []+ for rank, flag in enumerate(flags):+ a = arena(40 + rank)+ s = store(a, f"{name}{rank}", rank)+ ids, _ = stored(s, a, n, 41, shared=flag)+ ms.append(decoder(a, s, rank))+ m0, m1 = ms+ sent = []++ def flush():+ msg, m0.outbox = m0.outbox, []+ sent.extend(m1.parse(msg))+ m1.apply(msg)++ m0._flush = flush+ hi, lo, _ = S.key_ints(S.point_key(ids))+ m0._emit(M.LOAD, [hi, lo, n, 0, align_up(n), 0]) # as ``prestage`` sends it+ m0._flush()+ h = m0._start_load(hi, lo, n, 0, align_up(n), 0)+ until(lambda: h.lj.done.is_set() and m1.loads[0].lj.done.is_set())+ ok = m0.complete_load(h)+ return ok, m0, m1, [p for op, p in sent if op == M.LOADED]+++ok, m0, m1, loaded = two_ranks((True, False), "shared")+check("shared: a point rank 0 holds as shared is restored on both ranks",+ ok and len(m0.kept) == 1 and len(m1.kept) == 1)+check("shared: LOADED carries rank 0's flag", loaded == [[0, 1]])+check("shared: rank 0 restores it as a shared-prefix state", ok and m0.kept[0].shared is True)+check("shared: rank 1 too, though its own point says otherwise", ok and m1.kept[0].shared is True)+ok, m0, m1, loaded = two_ranks((False, True), "own")+check("shared: a point rank 0 holds as not shared is restored unshared on both ranks",+ ok and not m0.kept[0].shared and not m1.kept[0].shared and loaded == [[0, 0]])+++# -- shared-flag 3: the same ids kept again as a shared prefix make the stored point shared, on disk too ------------+def json_of(st: S.BlockStore, key: str) -> dict:+ try:+ with open(st._point_path(key, ".json")) as fh:+ return json.load(fh)+ except (OSError, ValueError):+ return {}+++def keep(st: S.BlockStore, ids: list, shared: bool, lineage: str) -> str:+ x = Pool(ROWS).add(0, align_up(len(ids)))+ return st.persist(ids, snap(ids, shared), extent=x, lineage=lineage, shared=shared,+ skip=M.MultiDecoder._SPILL_SKIP)+++log: list = [] # (what, path) of the writer's puts and folder fsyncs+_put, _fsync_dir, hooks = S._put, S._fsync_dir, {}+++def put_logged(path, data, owner, direct=False):+ log.append(("put", os.path.basename(path)))+ for suffix, fn in list(hooks.items()): # (before the file is written)+ if path.endswith(suffix):+ hooks.pop(suffix)+ fn()+ return _put(path, data, owner, direct)+++def fsync_dir_logged(path):+ log.append(("fsync_dir", os.path.basename(path)))+ return _fsync_dir(path)+++S._put, S._fsync_dir = put_logged, fsync_dir_logged+n2 = ALIGN + 100+ar = arena(5)+st = store(ar, "upgrade")+ids, _ = stored(st, ar, n2, 51) # written as a conversation's own turn+key = S.point_key(ids)+log.clear()+check("upgrade: the same ids kept again as shared are not written again", keep(st, ids, True, "s51") == "stored")+check("upgrade: the point is shared now", st.index[key].shared is True)+check("upgrade: its json says so", until(lambda: json_of(st, key).get("shared") is True, 5))+check("upgrade: the json goes through a temporary name, fsynced, renamed, then the folder is fsynced",+ until(lambda: log[-2:] == [("put", f"{key}.json"), ("fsync_dir", "points")], 5))+check("upgrade: a restart reads it shared", store(ar, "upgrade").index.get(key, NS(shared=None)).shared is True)++ids = ids_of(n2, 52)+key = S.point_key(ids)+check("upgrade: a state waiting to be written", keep(st, ids, False, "s52") == "queued")+check("upgrade: kept again as shared meanwhile", keep(st, ids, True, "s52") == "stored")+st.drain(TIMEOUT / 4)+check("upgrade: it is written as shared", st.index[key].shared is True+ and until(lambda: json_of(st, key).get("shared") is True, 5))++ids = ids_of(n2, 53)+key = S.point_key(ids)+hooks[f"{key}.ids"] = lambda: keep(st, ids, True, "s53") # kept again as shared while its files are written+check("upgrade: a state written as its own", keep(st, ids, False, "s53") == "queued")+st.drain(TIMEOUT / 4)+check("upgrade: kept again as shared during its write, its json is rewritten shared",+ st.index[key].shared is True and until(lambda: json_of(st, key).get("shared") is True, 5))++ids, _ = stored(st, ar, n2, 54)+key = S.point_key(ids)+++def drop():+ with st.lock:+ st._remove(key, "dropped")+++hooks[f"{key}.json"] = drop # dropped while its json is rewritten+keep(st, ids, True, "s54")+check("upgrade: a point dropped during the rewrite", until(lambda: not hooks, 5) and key not in st.index)+time.sleep(0.2)+check("upgrade: ... loses the json the rewrite put back", not os.path.exists(st._point_path(key, ".json")))++ids, _ = stored(st, ar, n2, 55)+key = S.point_key(ids)+hooks[f"{key}.json"] = lambda: time.sleep(0.3) # a slow rewrite+keep(st, ids, True, "s55")+check("upgrade: a drain (a clean stop) waits for the rewrite", st.drain(TIMEOUT / 4)+ and json_of(st, key).get("shared") is True)+S._put, S._fsync_dir = _put, _fsync_dir+++# -- review 4: a missing block file drops that name, a damaged one every name linked to its bytes -----------------+def linked(name: str):+ """A (2 blocks), B (other ids, the same rows: its blocks linked to A's) and C (A's ids and one block more, A's+ lineage: it names A's blocks), written; a decoder over the store."""++ a = arena(60)+ s = store(a, name)+ ia, ib = ids_of(2 * ALIGN, 61), ids_of(2 * ALIGN, 62)+ ic = ia + ids_of(ALIGN, 63)+ kept = rows(a, 0, 2 * ALIGN)+ for ids, lineage in ((ia, "a"), (ib, "b"), (ic, "a")):+ keep(s, ids, False, lineage)+ s.drain(TIMEOUT / 4)+ return a, s, decoder(a, s), [S.point_key(i) for i in (ia, ib, ic)], kept+++def read_fails(m: M.MultiDecoder, key: str, n: int) -> bool:+ """A read of ``key`` through LOAD / LOADED (``_finish_load`` forgets it): True when it failed."""++ hi, lo, _ = S.key_ints(key)+ h = m._start_load(hi, lo, n, 4 * ALIGN, align_up(n), m.next_lid)+ until(lambda: m.load_ready(h))+ return not m.complete_load(h)+++ar, st, m, (ka, kb, kc), kept = linked("lost")+pa, pb = st.index[ka], st.index[kb]+check("forget: B's blocks are links to A's (the same bytes)", st.stats["dedup_blocks"] == 2+ and [st.have[b][1] for b in pa.blocks] == [st.have[b][1] for b in pb.blocks])+os.remove(st._block_path(pa.blocks[0])) # one name of the bytes gone+check("forget: the read of A fails", read_fails(m, ka, 2 * ALIGN))+check("forget: A goes, and C, which names the missing block", ka not in st.index and kc not in st.index)+check("forget: B, linked to the missing name's bytes, stays with its files",+ kb in st.index and all(os.path.exists(st._block_path(b)) for b in pb.blocks))+y = Pool(ROWS).add(4 * ALIGN, 2 * ALIGN)+_, _, got = load_rows(st, ar, kb, y, 2 * ALIGN)+check("forget: B still reads back whole", got is not None and same(got, kept))++ar, st, m, (ka, kb, kc), kept = linked("damaged")+pa, pb = st.index[ka], st.index[kb]+with open(st._block_path(pa.blocks[0]), "r+b") as fh: # the bytes of every name linked to them+ fh.write(b"\xff" * 64)+check("forget: the read of a damaged A fails", read_fails(m, ka, 2 * ALIGN))+check("forget: damaged bytes drop every point naming any of their names (A, B, C)",+ ka not in st.index and kb not in st.index and kc not in st.index)+check("forget: ... and those names' files", not any(os.path.exists(st._block_path(b)) for b in pb.blocks[:1]))+++# -- review 5: every op has a sender; the prefix wait's counters reach /metrics ------------------------------------+src = inspect.getsource(M)+unsent = [name for name in M.OPS.values() if f"self._emit({name}," not in src]+check("ops: every op in the table has a sender", not unsent)+of = H.of+H.of = lambda app: NS(snapshot=lambda app: {"prefix_waits": 6, "prefix_wait_tokens": 98688})+lines: list = []+MT._health(lines, object())+H.of = of+check("metrics: the prefix wait's counters", f"{MT.HEALTH}prefix_waits_total 6" in lines+ and f"{MT.HEALTH}prefix_wait_tokens_total 98688" in lines+ and f"# TYPE {MT.HEALTH}prefix_waits_total counter" in lines)+++# -- a point's small files leave no pages behind: each one's pages are dropped after its fsync ---------------------+events: list = [] # (what, file name) in order, on the writer thread+++def fname(fd: int) -> str:+ try:+ return os.path.basename(os.readlink(f"/proc/self/fd/{fd}"))+ except OSError:+ return "?"+++fsync, drop_cache = os.fsync, S._drop_cache+os.fsync = lambda fd: (events.append(("fsync", fname(fd))), fsync(fd))[1]+S._drop_cache = lambda fd: (events.append(("drop", fname(fd))), drop_cache(fd))[1]+ar = arena(7)+st = store(ar, "pages")+ids, _ = stored(st, ar, ALIGN + 100, 71)+os.fsync, S._drop_cache = fsync, drop_cache+key = S.point_key(ids)+for suffix in (".ids", ".st", ".json"):+ mine = [what for what, f in events if f == f".{key}{suffix}"]+ check(f"pages: {suffix} dropped from the page cache after its fsync", mine == ["fsync", "drop"])++# -- a read slot turns every round: beside a decoding stream the step between rounds frees only the slots the step+# before copied out, so a slot turned every second round (profiled on GPU: the reader waited for slots 80% of a 226k+# read, 14-18 blocks copied a round through 32 slots).+class Stop(Exception):+ pass+++def round_order(loading: bool) -> list:+ """What a decode round does, in order, up to its sampling: its verify pass queued, the reads settled, sampled."""++ a = arena(100)+ s = store(a, f"round{int(loading)}")+ m = decoder(a, s)+ order: list = []+ lane = NS(copies=None, dflash=False, depth=0, s=NS(out=[7], sampling=None, stop_eos=False), constraint=None,+ st=NS(pos=0), window=None)+ m.profile, m.tune, m.drafts, m.window, m.verify = None, NS(depth="", sampler=""), None, 64, NS()++ def forward(verify, segments):+ order.append("forward")+ return NS(logits=[torch.zeros(1, 4)])++ def sample(w, parts):+ order.append("sample")+ raise Stop++ fwd, smp = M.forward_streams, M.sample_streams+ M.forward_streams, M.sample_streams = forward, sample+ s.settle = lambda: order.append("settle")+ if loading:+ m.loads[0] = NS()+ try:+ m._round([lane])+ except Stop:+ pass+ finally:+ M.forward_streams, M.sample_streams = fwd, smp+ return order+++check("round: a decode round settles the reads once its verify pass is queued, before its readback",+ round_order(True) == ["forward", "settle", "sample"])+check("round: with no read under way a round settles nothing", round_order(False) == ["forward", "sample"])+++class StreamEv:+ """A copy's event on one stream: waiting for it means every event recorded before it is done too."""++ def __init__(self, line: list) -> None:+ self.line, self.done, self.synced = line, False, 0+ line.append(self)++ def query(self) -> bool:+ return self.done++ def synchronize(self) -> None:+ self.synced += 1+ for e in self.line[:self.line.index(self) + 1]:+ e.done = True+++def drained(q) -> list:+ out = []+ while not q.empty():+ out.append(q.get_nowait())+ return sorted(out)+++st = store(arena(104), "settle")+try:+ st.settle()+ early = True+except Exception as exc: # noqa: BLE001+ print(f" (settle before the slots: {exc!r})")+ early = False+check("settle: before the read slots exist it does nothing", early)+st.ring()+drained(st.free_reads)+line: list = []+evs = [StreamEv(line) for _ in range(3)]+st.read_events = list(zip((4, 5, 6), evs))+st._recycle()+check("settle: a step's recycling between rounds waits for no copy", not drained(st.free_reads)+ and all(e.synced == 0 for e in evs) and len(st.read_events) == 3)+st.settle()+check("settle: it waits for the newest copy only, and every slot copied out comes back",+ drained(st.free_reads) == [4, 5, 6] and not st.read_events and [e.synced for e in evs] == [0, 0, 1])+++class Rec:+ """A slot's event: counts its records and the writer's waits on it."""++ def __init__(self) -> None:+ self.records = self.syncs = 0++ def record(self, stream=None) -> None:+ self.records += 1++ def synchronize(self) -> None:+ self.syncs += 1+++ar = arena(102)+st = store(ar, "wevents")+st.ring()+st.slot_events = [Rec() for _ in st.slots] # (made at start on a GPU; none on the host)+ids, kept = stored(st, ar, 3 * ALIGN - 6, 103) # two blocks staged by the pumps, the tail copied at keep+staged = st.stats["staged_blocks"]+check("write: a staged block records its slot's own event, made at start, and the writer waits on that one (no event "+ "made or dropped a block)", staged == 2 and sum(r.records for r in st.slot_events) == staged+ and sum(r.syncs for r in st.slot_events) == staged)+_, _, back = load_rows(st, ar, S.point_key(ids), Pool(ROWS).add(0, align_up(3 * ALIGN - 6)), 3 * ALIGN - 6)+check("write: its rows read back as kept", back is not None and same(back, kept))++# -- review (wojo#2): the reads in flight share one TF_GLM_SPILL_LOAD_MS pause between rounds, each first in turn ----+class SlowDisk:+ """A disk whose every step copies for as long as it may, 30 ms at most."""++ def __init__(self) -> None:+ self.calls: list = []++ def step(self, lj, upto=None, budget=None):+ self.calls.append(lj.name)+ time.sleep(min(budget, 0.03))+ return 1+++ar = arena(9)+m = decoder(ar, store(ar, "budget"))+m.disk, m.load_budget = SlowDisk(), 0.04+m.loads = {i: NS(done=False, err=None, lid=i, lj=NS(error=None, next=0, name=i)) for i in range(3)}+t = time.perf_counter()+m.step_loads()+took = time.perf_counter() - t+check(f"budget: three reads in flight share one 40 ms pause (took {took * 1000:.0f} ms)", took < 0.06)+first = []+for _ in range(3):+ m.disk.calls.clear()+ m.step_loads()+ first.append(m.disk.calls[0])+check(f"budget: each pause starts with the next read ({first})", sorted(first) == [0, 1, 2])++# -- a restore beside decoding streams ends only once its budgeted copies are done (LOADED copies nothing then) ---------+ar = arena(10)+m = decoder(ar, store(ar, "ready"))+done = threading.Event()+done.set()+h = NS(done=False, err=None, lj=NS(done=done, error=None, next=3, total=10))+m.lanes = {1: NS(decoding=True, paused=False, s=NS(done=False))}+check("ready: a read done with blocks left to copy waits while a stream decodes", not m.load_ready(h))+h.lj.next = 10+check("ready: every block copied, the restore ends", m.load_ready(h))+h.lj.next = 3+m.lanes = {}+check("ready: nothing decoding, the rest is copied at once", m.load_ready(h))++# -- LOADED on a rank that copied little: the wait for a block frees the read slots the step's own copies hold ---------+# Rank 0's read failed early (LOADED came with no LOADPART before it) and rank 1 has more blocks left than read slots:+# its step copies a slot's worth, and the reader needs those slots back to read the next block. They went back only at+# the top of the next step, so the wait for that block starved the reader for ever (the rank-1 watchdog then exits).+saved, ROWS = ROWS, 22 * ALIGN+os.environ.update(TF_GLM_SPILL_READ_BLOCKS="8", TF_GLM_SPILL_STAGE_MIB="1")+try:+ ar = arena(500)+ st = store(ar, "hang", 1)+ nt = 20 * ALIGN+ ids, kept = stored(st, ar, nt, 501)+ m1 = decoder(ar, st, 1)+finally:+ ROWS = saved+ for k in ("TF_GLM_SPILL_READ_BLOCKS", "TF_GLM_SPILL_STAGE_MIB"):+ os.environ.pop(k, None)+hi, lo, _ = S.key_ints(S.point_key(ids))+m1.apply([M.LOAD, 6, hi, lo, nt, 0, align_up(nt), 0])+h = m1.loads[0]+check("hang: 20 blocks through 8 read slots", len(st.read_slots) == 8 and h.lj.total == 20)+until(lambda: len(h.lj.queued) >= 8)+t = threading.Thread(target=lambda: m1.apply([M.LOADED, 2, 0, 0]), daemon=True)+t.start()+t.join(8.0)+check("hang: LOADED on a rank that copied nothing before returns (the wait frees the slots its copies hold)",+ not t.is_alive())+check("hang: the state is kept, its rows as stored", not t.is_alive() and len(m1.kept) == 1+ and same(rows(ar, h.x.base, nt), kept))++# The same with the read slots carved as pin_read_ahead leaves them: a preallocated buffer that holds two and a half+# blocks, the rest in one power-of-two piece, so the ring holds more slots than the 7 asked and some sit in each buffer.+pinned, per = dict(SP._PINNED), S._up(st.block_bytes)+saved, ROWS = ROWS, 22 * ALIGN+os.environ.update(TF_GLM_SPILL_READ_BLOCKS="7", TF_GLM_SPILL_STAGE_MIB="1")+try:+ SP._PINNED.clear()+ SP._PINNED["read"] = [torch.zeros(2 * per + per // 2, dtype=torch.uint8)]+ took = S.pin_read_ahead(per)+ ar = arena(510)+ st = store(ar, "hangC", 1)+ ids, kept = stored(st, ar, nt, 511)+ m1 = decoder(ar, st, 1)+finally:+ ROWS = saved+ for k in ("TF_GLM_SPILL_READ_BLOCKS", "TF_GLM_SPILL_STAGE_MIB"):+ os.environ.pop(k, None)+hi, lo, _ = S.key_ints(S.point_key(ids))+m1.apply([M.LOAD, 6, hi, lo, nt, 0, align_up(nt), 0])+h = m1.loads[0]+check("hang, carved slots: 20 blocks through more than the 7 slots asked, carved from the preallocated buffer and one "+ "piece", took > 0 and 7 < len(st.read_slots) < 20 and h.lj.total == 20)+until(lambda: len(h.lj.queued) >= len(st.read_slots))+t = threading.Thread(target=lambda: m1.apply([M.LOADED, 2, 0, 0]), daemon=True)+t.start()+t.join(8.0)+check("hang, carved slots: LOADED on a rank that copied nothing before returns", not t.is_alive())+check("hang, carved slots: the state is kept, its rows as stored", not t.is_alive() and len(m1.kept) == 1+ and same(rows(ar, h.x.base, nt), kept))+SP._PINNED.clear()+SP._PINNED.update(pinned)++saved, chunk, env = dict(SP._PINNED), SP.CHUNK, os.environ.pop("TF_GLM_SPILL_READ_BLOCKS", None)+check("read-ahead: 16 blocks by default", S.read_blocks() == 16)+SP._PINNED.clear()+SP._PINNED["read"] = [torch.empty(SP.CHUNK, dtype=torch.uint8) for _ in range(2)] # (preallocate's, 2 x 64 MiB)+check("read-ahead: the default at two Sparks' block size keeps preallocate's read buffers and pins 64 + 32 MiB more, "+ "what the pool pays (the engine's bytes a pool block there: 13.6-14.0 MB, a stored block 12.7 MB)",+ S.pin_read_ahead(14_029_224) == 96 << 20 and len(SP._PINNED["read"]) == 4)+os.environ["TF_GLM_SPILL_READ_BLOCKS"] = "9"+SP._PINNED["read"] = [torch.empty(SP.CHUNK, dtype=torch.uint8) for _ in range(2)]+check("read-ahead: 9 blocks fit preallocate's read buffers on two Sparks, so the pool pays nothing for them",+ S.pin_read_ahead(14_029_224) == 0 and len(SP._PINNED["read"]) == 2)+os.environ["TF_GLM_SPILL_READ_BLOCKS"] = "21"+st = store(arena(105), "readahead")+pe = 3 * S._up(st.block_bytes) # (the engine's bytes a pool block, more than a stored block's, as on the Sparks)+SP.CHUNK = 1 << (4 * pe - 1).bit_length() # (small pieces, a power of two as 64 MiB is)+pre = [torch.zeros(SP.CHUNK, dtype=torch.uint8) for _ in range(2)] # (preallocate's two read buffers)+SP._PINNED.clear()+SP._PINNED["read"] = list(pre)+took = S.pin_read_ahead(pe)+new = SP._PINNED["read"][2:]+check("read-ahead: preallocate's read buffers kept, only the rest pinned before the pool, and only that charged",+ len(SP._PINNED["read"]) > 2 and all(a is b for a, b in zip(SP._PINNED["read"], pre))+ and took == sum(b.numel() for b in new)+ and took + 2 * SP.CHUNK >= 21 * pe > took + 2 * SP.CHUNK - max(b.numel() for b in new))+check("read-ahead: the rest in power-of-two pieces of at most spill.CHUNK",+ bool(new) and all(b.numel() & (b.numel() - 1) == 0 and b.numel() <= SP.CHUNK for b in new))+st.ring()+check("read-ahead: ring carves at least the blocks asked from them and pins none later",+ len(st.read_slots) >= 21 and {x.untyped_storage().data_ptr() for x in st.read_slots}+ == {b.untyped_storage().data_ptr() for b in SP._PINNED["read"]})+SP._PINNED.clear()+SP._PINNED.update(saved)+SP.CHUNK = chunk+os.environ.pop("TF_GLM_SPILL_READ_BLOCKS", None)+if env is not None:+ os.environ["TF_GLM_SPILL_READ_BLOCKS"] = env+++# == the store's room, files and settings (review 2026-10-24): files deleted first, then the order, quota, turns, floor+os.environ["TF_GLM_SPILL_STAGE_MIB"] = "2" # (a small write ring a store: these make many stores)+def fill(ar: Arena, base: int, n: int, seed: int) -> None:+ """Rows of their own for tokens [base, base + n) (no two states' blocks the same bytes: no dedup links)."""++ g = torch.Generator().manual_seed(1000 + seed)+ for p in ar.planes:+ a, b = base // p.div, (base + align_up(n)) // p.div+ p.tensor[a:b] = torch.randint(-2**15, 2**15 - 1, tuple(p.tensor[a:b].shape), generator=g,+ dtype=torch.int32).to(p.tensor.dtype)+++SEEDS = iter(range(10_000))+BANK: dict = {} # a block's name -> its rows (one computation: the same rows)+++def put(st: S.BlockStore, ar: Arena, ids: list, lineage: str, shared: bool = False, used: float | None = None):+ """A state of ``ids`` kept at base 0 and written: rows of their own for blocks no state named before, the same+ rows for a block named before (what a later turn or a fork computes there); its key, its rows as kept, what+ persist said."""++ fill(ar, 0, len(ids), next(SEEDS))+ for s0, e0, h in S.block_hashes(np.asarray(ids, dtype=np.int64), B, lineage):+ for p, t in zip(ar.planes, BANK.setdefault(h, span(ar, s0, e0))):+ p.tensor[s0 // p.div:e0 // p.div] = t+ x = Pool(ROWS).add(0, align_up(len(ids)))+ kept = rows(ar, 0, len(ids))+ r = st.persist(ids, snap(ids, shared), extent=x, lineage=lineage, shared=shared, skip=M.MultiDecoder._SPILL_SKIP)+ st.drain(TIMEOUT / 4)+ key = S.point_key(ids)+ if used is not None and key in st.index:+ st.index[key].used = used+ return key, kept, r+++def files_of(st: S.BlockStore, key: str) -> list[str]:+ return [sfx for sfx in (".ids", ".st", ".json") if os.path.exists(st._point_path(key, sfx))]+++def block_files(st: S.BlockStore) -> set[str]:+ return {f[:-4] for f in os.listdir(st.blocks_dir) if f.endswith(".bin")}+++def reads_back(st: S.BlockStore, ar: Arena, key: str, ids: list, kept) -> bool:+ st.ring() # (the engine makes it at start)+ fill(ar, 0, len(ids), 9999) # (other rows there first)+ y = Pool(ROWS).add(0, align_up(len(ids)))+ _, _, got = load_rows(st, ar, key, y, len(ids))+ return got is not None and same(got, kept)+++B = ALIGN+SYS = ids_of(B, 500) # a shared system prompt, one block+LA, LB = S.fork("sys", "a", B), S.fork("sys", "b", B) # two conversations that resumed from it+TA = [SYS + ids_of(k * B, 501) for k in (1, 2, 3)] # conversation A: three turns, one block more each+FA = TA[1] + ids_of(B, 502) # a fork of A's second turn (an edited last message)+TB = [SYS + ids_of(k * B, 503) for k in (1, 2)] # conversation B: two turns+++def tree(name: str, **kw):+ """S (shared), A1-A3, A2f (a fork off A2), B1, B2 written, each its own rows; used: S, B1, B2, A1, A2, A2f, A3."""++ ar = arena(200)+ st = store(ar, name, **kw)+ k = {}+ k["S"], _, _ = put(st, ar, SYS, "sys", shared=True, used=1.0)+ k["B1"], _, _ = put(st, ar, TB[0], LB, used=2.0)+ k["B2"], _, _ = put(st, ar, TB[1], LB, used=3.0)+ k["A1"], _, _ = put(st, ar, TA[0], LA, used=4.0)+ k["A2"], _, _ = put(st, ar, TA[1], LA, used=5.0)+ k["A2f"], _, _ = put(st, ar, FA, S.fork(LA, "f", 3 * B), used=6.0)+ k["A3"], _, _ = put(st, ar, TA[2], LA, used=7.0)+ return ar, st, k+++# -- eviction: one victim at a time, each one's files gone, the blocks another point names kept ---------------------+ar, st, k = tree("order", turns=0)+name = {v: n for n, v in k.items()}+check("room: seven points written, nothing trimmed (turns 0)", len(st.index) == 7 and st.stats["trimmed_turns"] == 0)+check("room: the victims in order: old turns (least recently used first), the abandoned fork, whole conversations "+ "(least recently used first), the shared prefix last",+ [(name[key], why) for key, why in st._victims()] ==+ [("B1", "pruned_turns"), ("A1", "pruned_turns"), ("A2", "pruned_turns"), ("A2f", "pruned_forks"),+ ("B2", "pruned_conversations"), ("A3", "pruned_conversations"), ("S", "pruned_shared")])+blk = {n: set(st.index[key].blocks) for n, key in k.items()}+gone: list = []+for step in range(7):+ before = set(st.index)+ st._make_room(1) # (any shortfall: the next victim alone goes)+ gone += [name[key] for key in before - set(st.index)]+check("room: _make_room takes one at a time; once A1 and A2 are gone the fork is a conversation of its own (B2, "+ "least recently used, goes before it)", gone == ["B1", "A1", "A2", "B2", "A2f", "A3", "S"])+ar, st, k = tree("files", turns=0)+st._make_room(1)+check("files: an old turn's files go (.ids, .st, .json)", not files_of(st, k["B1"]))+check("files: ... its blocks stay (the newer turn names them all)", blk["B1"] <= block_files(st))+st._make_room(1)+st._make_room(1)+check("files: two more old turns' files go, no block", not files_of(st, k["A1"]) and not files_of(st, k["A2"])+ and blk["A2"] <= block_files(st))+st._make_room(1)+check("files: a whole conversation's files and own blocks go", not files_of(st, k["B2"])+ and not (blk["B2"] - blk["S"]) & block_files(st))+check("files: ... the shared prefix's block stays", blk["S"] <= block_files(st))+st._make_room(1)+check("files: the fork goes with its own block", not (blk["A2f"] - blk["A2"]) & block_files(st)+ and not files_of(st, k["A2f"]))+check("files: ... the blocks it shared with the newest turn stay", blk["A2"] <= block_files(st)+ and len(files_of(st, k["A3"])) == 3)+check("files: the counters say why", (st.stats["pruned_turns"], st.stats["pruned_conversations"]) == (3, 2))+check("files: stored bytes match the blocks left on disk",+ st.block_bytes_on_disk == sum(os.stat(st._block_path(b)).st_size for b in block_files(st)))++# -- a point being read is never evicted; making room never takes a block a state being written names ------------+ar, st, k = tree("reading", turns=0)+st.reading.add(k["B1"])+st._make_room(st.stored()) # (more than everything)+check("reading: a point being read stays while everything else goes", set(st.index) == {k["B1"]}+ and len(files_of(st, k["B1"])) == 3 and blk["B1"] <= block_files(st))+st.reading.clear()+ar = arena(201)+st = store(ar, "pinned", gib=1.0, turns=0)+ka, kept_a, _ = put(st, ar, TA[2], LA, used=1.0) # conversation A's state (older)+kb, _, _ = put(st, ar, TB[1], LB, used=2.0) # conversation B's (newer)+st.cap = st.stored() + st.block_bytes # room for one block more, not for C's block and small part+ids_c = TA[2] + ids_of(B, 504) # C extends A's state (its lineage: names A's four blocks)+wrote = st.stats["written_blocks"]+kc, kept_c, r = put(st, ar, ids_c, LA)+check("pinned: C is written once room is made", r == "queued" and kc in st.index)+check("pinned: A's point went first (least recently used conversation)", ka not in st.index)+check("pinned: ... but not the blocks C names", all(b in block_files(st) for b in st.index[kc].blocks))+check("pinned: C wrote only its new block", st.stats["written_blocks"] == wrote + 1)+check("pinned: C reads back whole", reads_back(st, ar, kc, ids_c, kept_c))++# -- old turns trimmed as newer ones are written (SPILL_TURNS) -------------------------------------------------------+ar = arena(202)+st = store(ar, "turns", turns=2)+ks, _, _ = put(st, ar, SYS, "sys", shared=True)+k1, _, _ = put(st, ar, TA[0], LA)+k2, kept2, _ = put(st, ar, TA[1], LA)+kf, keptf, _ = put(st, ar, FA, S.fork(LA, "f", 3 * B))+check("turns: a fork's own path counts too (A2f, A2 kept: A1 trimmed)", k1 not in st.index and k2 in st.index+ and st.stats["trimmed_turns"] == 1)+k3, _, _ = put(st, ar, TA[2], LA)+check("turns: A3 written, A2 still among the newest two of its path", k2 in st.index)+before_blocks = block_files(st)+ids4 = TA[2] + ids_of(B, 505)+k4, kept4, _ = put(st, ar, ids4, LA)+check("turns: A4 written, A2 trimmed (the newest 2 on the path stay: A4, A3)", k2 not in st.index+ and k3 in st.index and k4 in st.index and st.stats["trimmed_turns"] == 2)+check("turns: a trimmed turn's files go", not files_of(st, k1) and not files_of(st, k2))+check("turns: ... and no block (the newest turn names them)", before_blocks <= block_files(st))+check("turns: the fork off the path is untouched, and still reads back", kf in st.index+ and reads_back(st, ar, kf, FA, keptf))+check("turns: the shared prefix is never trimmed", ks in st.index)+check("turns: the newest turn reads back whole", reads_back(st, ar, k4, ids4, kept4))+check("turns: a restart finds the same points", set(store(ar, "turns", turns=2).index) == {ks, kf, k3, k4})+ar = arena(203)+st = store(ar, "turns0", turns=0)+for ids in [SYS] + TA:+ put(st, ar, ids, "sys" if ids is SYS else LA, shared=ids is SYS)+check("turns: SPILL_TURNS 0 keeps every turn until room is needed", len(st.index) == 4+ and st.stats["trimmed_turns"] == 0)+ar = arena(204)+st = store(ar, "turnsread", turns=1)+put(st, ar, SYS, "sys", shared=True)+k1, _, _ = put(st, ar, TA[0], LA)+st.reading.add(k1)+put(st, ar, TA[1], LA)+check("turns: a turn being read is not trimmed", k1 in st.index)+st.reading.clear()+env = os.environ.pop("TF_GLM_SPILL_TURNS", None)+for raw, want in (("0", 0), ("2", 2), (None, 4)):+ if raw is None:+ os.environ.pop("TF_GLM_SPILL_TURNS", None)+ else:+ os.environ["TF_GLM_SPILL_TURNS"] = raw+ got = int(os.environ.get("TF_GLM_SPILL_TURNS") or 4) # (multi._spill_store's reading of it)+ check(f"turns: TF_GLM_SPILL_TURNS={raw} reads as {want}", got == want)+os.environ.pop("TF_GLM_SPILL_TURNS", None)+if env is not None:+ os.environ["TF_GLM_SPILL_TURNS"] = env+check("turns: multi reads TF_GLM_SPILL_TURNS that way", 'int(os.environ.get("TF_GLM_SPILL_TURNS") or 4)'+ in inspect.getsource(M.MultiDecoder._spill_store))++# -- the quota: a conversation over its share trims its own old turns and forks first -------------------------------+ar, st, k = tree("quota", turns=0, quota=0.0)+own_a = st._conv_bytes([k["A1"], k["A2"], k["A2f"], k["A3"]])+st.quota = (own_a - 1) / st.cap # A holds just over its share, B well under+ids4 = TA[2] + ids_of(B, 506)+k4, _, r = put(st, ar, ids4, LA, used=8.0)+check("quota: A's next turn is written", r == "queued" and k4 in st.index)+check("quota: A's own old turns and its fork went first", st.stats["quota_trims"] == 1+ and not {k["A1"], k["A2"], k["A2f"]} & set(st.index))+check("quota: A's newest state before the write stays", k["A3"] in st.index)+check("quota: the other conversation and the shared prefix are untouched",+ {k["B1"], k["B2"], k["S"]} <= set(st.index))+ar, st, k = tree("quota-under", turns=0)+st.quota = 0.9+put(st, ar, TA[2] + ids_of(B, 507), LA)+check("quota: under its share nothing is trimmed", st.stats["quota_trims"] == 0 and len(st.index) == 8)++# -- the free-disk floor ----------------------------------------------------------------------------------------------+ar = arena(205)+st = store(ar, "floor", floor=1.0 / 1024) # 1 MiB floor+k1, _, _ = put(st, ar, TA[0], LA)+files0 = set(os.listdir(st.points_dir)), block_files(st)+st.disk_free = lambda: 0 # the disk full of other things+k2, _, r = put(st, ar, TB[0], LB)+check("floor: a disk full of other things refuses the write", r == "no_space" and st.stats["no_space"] == 1)+check("floor: ... without evicting anything", set(st.index) == {k1})+check("floor: ... and leaves no file behind", (set(os.listdir(st.points_dir)), block_files(st)) == files0)+ar, st, k = tree("floor-room", turns=0, floor=1.0 / 1024)+start = st.stored()+need = 2 * st.block_bytes # what a write of one new block needs, about+st.disk_free = lambda: st.floor + need - 4096 + (start - st.stored()) # (what goes comes back as free space)+k4, _, r = put(st, ar, TA[2] + ids_of(B, 508), LA)+check("floor: short of the floor, room is made in the eviction order and the write goes on", r == "queued"+ and k4 in st.index and st.stats["no_space"] == 0)+check("floor: ... the first victim went, the rest stayed", k["B1"] not in st.index+ and {k["A3"], k["B2"], k["S"]} <= set(st.index))++# -- a restart with torn, orphaned and foreign files: only complete points stay ------------------------------------------+ar = arena(206)+st = store(ar, "torn", turns=0)+ks, kept_s, _ = put(st, ar, SYS, "sys", shared=True)+k1, _, _ = put(st, ar, TA[0], LA)+k2, _, _ = put(st, ar, TB[0], LB)+k3, _, _ = put(st, ar, TB[0] + ids_of(B, 509), LB)+ids_p = ids_of(B, 530) # a picture prompt: its ids are keyed, its tokens after them+fill(ar, 0, B, 531)+st.persist(ids_p, snap(ids_p), extent=Pool(ROWS).add(0, B), lineage="pic", tokens=ids_of(B, 532),+ skip=M.MultiDecoder._SPILL_SKIP)+st.drain(TIMEOUT / 4)+kp = S.point_key(ids_p)+own1 = set(st.index[k1].blocks) - set(st.index[ks].blocks)+own3 = set(st.index[k3].blocks) - set(st.index[k2].blocks)+os.remove(st._point_path(k1, ".json")) # a write cut before its json: incomplete+with open(st._point_path(k2, ".ids"), "r+b") as fh: # its ids damaged (their CRC-32 in its json)+ fh.write(b"\x00" * 8)+with open(st._point_path(kp, ".ids"), "r+b") as fh: # a picture point's tokens damaged (its keyed ids intact):+ fh.seek(8 * B) # only the CRC-32 tells+ fh.write(b"\x01" * 8)+os.remove(st._block_path(sorted(own3)[0])) # a block of k3 gone+for d in (st.points_dir, st.blocks_dir):+ open(os.path.join(d, ".left-over.tmp"), "wb").write(b"x") # temporary names a crash left+orphan = st._block_path("0" * 32)+open(orphan, "wb").write(b"y" * 100) # a block no point names+foreign = st._point_path("feedfacefeedface-7", ".json")+open(foreign, "w").write(json.dumps({"format": "another", "key": "feedfacefeedface-7"}))+st = store(ar, "torn", turns=0)+check("torn: only the complete point stays", set(st.index) == {ks})+check("torn: a point without its json loses its other files", not files_of(st, k1))+check("torn: ... and the blocks only it named", not own1 & block_files(st))+check("torn: a point whose ids fail their CRC goes with its files", not files_of(st, k2))+check("torn: ... also when only a picture point's tokens are damaged (its key still matches)", kp not in st.index+ and not files_of(st, kp))+check("torn: a point missing a block goes with its files and its other blocks", not files_of(st, k3)+ and not own3 & block_files(st))+check("torn: temporary names left by a crash go", not [f for d in (st.points_dir, st.blocks_dir)+ for f in os.listdir(d) if f.startswith(".")])+check("torn: a block no point names goes", not os.path.exists(orphan))+check("torn: a json of another format goes", not os.path.exists(foreign))+check("torn: the counts match what is left", len(st.have) == len(st.index[ks].blocks) == len(block_files(st)))+check("torn: the complete point reads back", reads_back(st, ar, ks, SYS, kept_s))++# -- older builds' folders pruned (this rank's only), the newest other kept -------------------------------------------+ar = arena(207)+root = os.path.join(ROOT, "builds")+for i, (age, ranks) in enumerate(((300, (0, 1)), (200, (0,)), (100, (0,)))):+ for r in ranks:+ os.makedirs(os.path.join(root, f"spill-{i:016x}", f"rank{r}"), exist_ok=True)+ open(os.path.join(root, f"spill-{i:016x}", f"rank{r}", "f"), "wb").write(b"z")+ t = time.time() - age+ os.utime(os.path.join(root, f"spill-{i:016x}"), (t, t))+st = store(ar, "builds")+check("builds: the newest other build stays", os.path.isdir(os.path.join(root, f"spill-{2:016x}", "rank0")))+check("builds: older builds lose this rank's folder", not os.path.exists(os.path.join(root, f"spill-{1:016x}"))+ and not os.path.exists(os.path.join(root, f"spill-{0:016x}", "rank0")))+check("builds: ... not another rank's", os.path.exists(os.path.join(root, f"spill-{0:016x}", "rank1", "f")))++# -- a failed write leaves no temporary file ------------------------------------------------------------------------------+d = os.path.join(ROOT, "failed")+os.makedirs(d, exist_ok=True)+fsync = S.os.fsync+++def full(fd):+ raise OSError(28, "No space left on device")+++S.os.fsync = full+try:+ S._put(os.path.join(d, "x.json"), b"{}" * 100, None)+ raised = False+except OSError:+ raised = True+finally:+ S.os.fsync = fsync+check("failed write: raises, and leaves neither the file nor its temporary name", raised and not os.listdir(d))++# -- temporary files: made new (O_EXCL), never through a symlink (O_NOFOLLOW) ----------------------------------------------+check("tmp: temporary files are opened O_CREAT | O_EXCL | O_NOFOLLOW",+ bool(S._NEW & os.O_EXCL and S._NEW & os.O_CREAT and S._NEW & os.O_NOFOLLOW))+d = os.path.join(ROOT, "symlink")+os.makedirs(d, exist_ok=True)+victim = os.path.join(ROOT, "victim.txt")+open(victim, "w").write("not yours")+for direct in (False, True):+ path = os.path.join(d, f"p{int(direct)}.json")+ os.symlink(victim, os.path.join(d, f".p{int(direct)}.json")) # planted at the temporary name+ S._put(path, b"mine", None, direct=direct)+ check(f"tmp: a symlink planted at the temporary name is not written through (direct={direct})",+ open(victim).read() == "not yours" and open(path, "rb").read() == b"mine"+ and not os.path.islink(path) and not os.path.lexists(os.path.join(d, f".p{int(direct)}.json")))+open(os.path.join(d, ".left.json"), "wb").write(b"old bytes, longer than the new ones")+S._put(os.path.join(d, "left.json"), b"new", None)+check("tmp: a temporary file left at the name is replaced, not appended to or reused",+ open(os.path.join(d, "left.json"), "rb").read() == b"new")+ar = arena(208)+st = store(ar, "symlink-block")+ids = ids_of(B, 510)+h0 = S.block_hashes(np.asarray(ids), B, "sl")[0][2]+os.symlink(victim, os.path.join(st.blocks_dir, f".{h0}.bin"))+fill(ar, 0, B, 511)+kept = rows(ar, 0, B)+st.persist(ids, snap(ids), extent=Pool(ROWS).add(0, B), lineage="sl", skip=M.MultiDecoder._SPILL_SKIP)+st.drain(TIMEOUT / 4)+check("tmp: a block written over a symlink planted at its temporary name leaves the target alone",+ open(victim).read() == "not yours" and not os.path.islink(st._block_path(h0)))+check("tmp: ... and the block reads back", reads_back(st, ar, S.point_key(ids), ids, kept))++# -- one engine a folder (and rank): flock on .lock-rank<r> --------------------------------------------------------------+ar = arena(209)+st = store(ar, "lock")+ids_l = ids_of(B, 512)+kl, _, _ = put(st, ar, ids_l, "l")+cfg = SP.SpillConfig(root=os.path.join(ROOT, "lock"), gib=1.0, min_tokens=1, min_free_gib=0.0)+try:+ S.BlockStore(cfg, planes=ar.planes, block=ALIGN, rank=0, device="cpu", classes=CLASSES, quiet=True)+ msg = ""+except SP.Busy as exc:+ msg = str(exc)+check("lock: a second engine on the folder, same rank, is refused (Busy)", bool(msg))+check("lock: ... saying which folder and which process holds it", cfg.root in msg and f"pid {os.getpid()}" in msg)+old_build = os.path.join(cfg.root, "spill-00000000000000ab", "rank0") # an older build's folder the other+os.makedirs(old_build, exist_ok=True) # engine would prune (it keeps the newest:+open(os.path.join(old_build, "f"), "wb").write(b"z") # this engine's)+t = time.time() - 1000+os.utime(os.path.dirname(old_build), (t, t))+try:+ S.BlockStore(cfg, planes=ar.planes, block=ALIGN, rank=0, device="cpu", classes=CLASSES, quiet=True,+ signature="another build")+ other = False+except SP.Busy:+ other = True+check("lock: an engine of another build is refused too, before it prunes anything", other+ and st.has(kl) and os.path.isdir(st.dir) and len(files_of(st, kl)) == 3+ and os.path.exists(os.path.join(old_build, "f")))+r1 = S.BlockStore(cfg, planes=ar.planes, block=ALIGN, rank=1, device="cpu", classes=CLASSES, quiet=True)+check("lock: another rank on the same folder is not", r1 is not None)+r1.close()+try:+ SP.SpillStore(SP.SpillConfig(root=cfg.root, gib=1.0, min_tokens=1, min_free_gib=0.0), device="cpu", quiet=True)+ one = False+except SP.Busy:+ one = True+check("lock: the one-stream store (PARALLEL=1) is refused on a folder in use", one)+st = store(ar, "lock") # (the first closed: a restart)+check("lock: once the first engine ended, the folder opens again with its points", kl in st.index)+code = ("import sys, time; from tensorfold.cuda import spill as SP; SP.hold(sys.argv[1], 0); "+ "print('held', flush=True); time.sleep(60)")+st.close()+OPEN.pop((cfg.root, 0), None)+proc = subprocess.Popen([sys.executable, "-c", code, cfg.root], stdout=subprocess.PIPE, text=True)+line = proc.stdout.readline().strip()+try:+ store(ar, "lock")+ held = False+except SP.Busy as exc:+ held = f"pid {proc.pid}" in str(exc)+proc.kill()+proc.wait()+check("lock: held by another process (its pid named)", line == "held" and held)+check("lock: a kill -9 of that process lets it go", kl in store(ar, "lock").index)+++class _BusyStore:+ def __init__(self, *a, **kw):+ raise SP.Busy("/spill is in use by another engine as rank 0 (pid 1)")+++dec = object.__new__(M.MultiDecoder)+dec.g = NS(spill_cfg=cfg, model_dir=ROOT, drafter_dir=None, drafter=None, agreed=(), _gather_ints=None)+dec.arena, dec.w, dec.grid, dec.drafts, dec.rank, dec.pool = ar, NS(world=1, device="cpu"), 0, None, 0, Pool(ROWS)+saved = S.BlockStore, SP.build_id, SP.weights_id+S.BlockStore, SP.build_id, SP.weights_id = _BusyStore, (lambda *a: "b"), (lambda *a: "w")+try:+ off = dec._spill_store()+except SP.Busy:+ off = "raised"+finally:+ S.BlockStore, SP.build_id, SP.weights_id = saved+check("lock: the engine runs with the tier off (Busy on every rank alike)", off is None)++# -- release: rows copied to host memory have their own cap (TF_GLM_SPILL_RELEASE_MIB) ----------------------------------+env = {k: os.environ.pop(k, None) for k in ("TF_GLM_SPILL_RELEASE_MIB", "TENSORFOLD_MEMORY_RESERVE_GIB")}+os.environ["TENSORFOLD_MEMORY_RESERVE_GIB"] = "4" # (two Sparks: 14.5, so 1.8 GiB; 4 fits any test machine)+check("release cap: by default an eighth of the memory reserve (4 GiB: 512 MiB)", S.release_cap() == 512 << 20)+os.environ.pop("TENSORFOLD_MEMORY_RESERVE_GIB")+check("release cap: without a reserve set, an eighth of TensorFold's (at least 4 GiB: 512 MiB or more)",+ S.release_cap() >= 512 << 20 and S.release_cap() < S.BACKLOG)+os.environ["TENSORFOLD_MEMORY_RESERVE_GIB"] = "100000"+check("release cap: a reserve TensorFold would refuse falls back to its default, not an error at start",+ S.release_cap() >= 512 << 20)+os.environ.pop("TENSORFOLD_MEMORY_RESERVE_GIB")+os.environ["TF_GLM_SPILL_RELEASE_MIB"] = "64"+check("release cap: TF_GLM_SPILL_RELEASE_MIB=64 is 64 MiB", S.release_cap() == 64 << 20)+os.environ["TF_GLM_SPILL_RELEASE_MIB"] = "0"+check("release cap: 0 is allowed (release copies nothing)", S.release_cap() == 0)+bad = []+for raw in ("-1", "lots"):+ os.environ["TF_GLM_SPILL_RELEASE_MIB"] = raw+ try:+ S.release_cap()+ except ValueError:+ bad.append(raw)+check("release cap: a negative or non-number value is refused", bad == ["-1", "lots"])+for kk, v in env.items():+ os.environ.pop(kk, None)+ if v is not None:+ os.environ[kk] = v+++def stalled(st: S.BlockStore):+ """The writer held at its next block until the returned event (a slow disk)."""++ gate, orig = threading.Event(), st._write_block++ def slow(*a):+ gate.wait(TIMEOUT)+ return orig(*a)++ st._write_block = slow+ return gate+++ar = arena(210)+st = store(ar, "release")+st.release_cap = 4 * st.block_bytes # room for four blocks+gate = stalled(st)+m = decoder(ar, st)+ids1, ids2 = ids_of(3 * B, 513), ids_of(2 * B, 514)+x1 = m.pool.add(0, 3 * B)+fill(ar, 0, 3 * B, 515)+kept1 = rows(ar, 0, 3 * B)+st.persist(ids1, snap(ids1), extent=x1, lineage="r1", skip=M.MultiDecoder._SPILL_SKIP)+x2 = m.pool.add(3 * B, 2 * B)+fill(ar, 3 * B, 2 * B, 516)+st.persist(ids2, snap(ids2), extent=x2, lineage="r2", skip=M.MultiDecoder._SPILL_SKIP)+m.pool.remove(x1) # (its rows go before they are written: the pool's guard)+check("release: rows within the cap are copied to the host", st.stats["released_blocks"] == 3+ and st.host_bytes == 3 * st.block_bytes)+m.pool.remove(x2)+check("release: past the cap a state's rows are not copied, the state is dropped", st.stats["released_blocks"] == 3+ and st.stats["release_dropped"] == 1 and st.host_bytes == 3 * st.block_bytes)+fill(ar, 0, 5 * B, 517) # (other streams write those rows now)+gate.set()+st.drain(TIMEOUT / 4)+check("release: the copied state is stored as it was kept", reads_back(st, ar, S.point_key(ids1), ids1, kept1))+check("release: the dropped one is not stored, and wrote nothing", S.point_key(ids2) not in st.index+ and st.stats["write_failed"] == 1 and len(block_files(st)) == 3)+check("release: the host copies are let go once written", st.host_bytes == 0 and st.backlog == 0)+check("release: /health shows the cap and what it holds", st.info()["release_cap_mb"] == (4 * st.block_bytes) >> 20+ and "host_mb" in st.info() and "release_dropped" in st.info())+ar = arena(211)+st = store(ar, "release-tail")+gate = stalled(st)+n = B + 6+fill(ar, 0, n, 518)+st.persist(ids_of(n, 519), snap(ids_of(n, 519)), extent=Pool(ROWS).add(0, align_up(n)), lineage="t",+ skip=M.MultiDecoder._SPILL_SKIP)+tail = S._span_bytes(ar.planes, B, n)+check("release: the block a kept state's end cuts counts in the same host bytes", st.host_bytes == tail)+gate.set()+st.drain(TIMEOUT / 4)+check("release: ... until it is written", st.host_bytes == 0)++# -- the prefix wait: off by default (it changes admission with the spill tier off too) ---------------------------------+probe = "from tensorfold.families.glm5_next.cuda import multi as M; print(M.PREFIX_WAIT)"+seen = {}+for raw in (None, "0", "1"):+ e = {kk: v for kk, v in os.environ.items() if kk != "TF_GLM_PREFIX_WAIT"}+ if raw is not None:+ e["TF_GLM_PREFIX_WAIT"] = raw+ seen[raw] = subprocess.run([sys.executable, "-c", probe], env=e, capture_output=True, text=True).stdout.strip()+check("prefix wait: off unless TF_GLM_PREFIX_WAIT=1", seen == {None: "False", "0": "False", "1": "True"})+++def waiter(lanes, hit=0):+ d = object.__new__(M.MultiDecoder)+ d.g = NS(shared=B, serial_only=False)+ d.drafts, d.prefix_waits, d.prefix_wait_tokens = None, 0, 0+ d._resume = lambda prompt: NS(ids=prompt[:hit]) if hit else None+ d.lanes = {ln.sid: ln for ln in lanes}+ return d+++def lane(sid, key, shared, pos, **kw):+ return NS(sid=sid, decoding=False, s=NS(done=False), key=list(key), images=None, dflash=True, shared=set(shared),+ st=NS(pos=pos), **kw)+++sysp = ids_of(3 * B, 520) # a 6k-token system prompt another request is prefilling+prompt = sysp + ids_of(B, 521)+req = NS(prompt=prompt, draft=True, vision=None)+filling = lane(1, sysp + ids_of(B, 522), {3 * B}, B) # at token 2048 of 6144, its shared point ahead+saved_pw = M.PREFIX_WAIT+M.PREFIX_WAIT = False+check("prefix wait: off, a request never waits", waiter([filling]).prefix_wait(req) is None)+M.PREFIX_WAIT = True+d = waiter([filling])+check("prefix wait: on, it waits for the shared point another request is still prefilling",+ d.prefix_wait(req) == (1, 3 * B) and d.prefix_waits == 1 and d.prefix_wait_tokens == 3 * B)+check("prefix wait: not for a point already kept (what it adds is under the shared-prefix minimum)",+ waiter([filling], hit=3 * B - 100).prefix_wait(req) is None)+check("prefix wait: not when its prompt leaves the other's before the point",+ waiter([filling]).prefix_wait(NS(prompt=sysp[:2 * B] + ids_of(2 * B, 523), draft=True, vision=None)) is None)+check("prefix wait: not when its prompt ends at the point (nothing left to prefill)",+ waiter([filling]).prefix_wait(NS(prompt=sysp, draft=True, vision=None)) is None)+past, pics = lane(1, filling.key, {3 * B}, B), lane(1, filling.key, {3 * B}, B)+past.decoding, pics.images = True, [1]+check("prefix wait: not for a stream past its prompt (decoding) or with pictures",+ waiter([past]).prefix_wait(req) is None and waiter([pics]).prefix_wait(req) is None)+done = lane(1, filling.key, {3 * B}, B)+done.s.done = True+check("prefix wait: not for a stream that ended", waiter([done]).prefix_wait(req) is None)+check("prefix wait: not for a point it has passed", waiter([lane(1, filling.key, {3 * B}, 3 * B)]).prefix_wait(req)+ is None)+check("prefix wait: not for a request without drafts or with pictures",+ waiter([filling]).prefix_wait(NS(prompt=prompt, draft=False, vision=None)) is None+ and waiter([filling]).prefix_wait(NS(prompt=prompt, draft=True, vision=object())) is None)+nodf = waiter([lane(1, filling.key, {3 * B}, B)])+nodf.drafts = object()+nodf.lanes[1].dflash = False+check("prefix wait: not for a stream whose states keep no DFlash2 window", nodf.prefix_wait(req) is None)+d = waiter([filling])+w = (1, 3 * B)+check("prefix wait: not released while the point is still ahead", not d.prefix_ready(w))+filling.st.pos = 3 * B+check("prefix wait: released once the point is kept", d.prefix_ready(w))+filling.st.pos = B+filling.decoding = True+check("prefix wait: released when the stream left its prompt", d.prefix_ready(w))+filling.decoding = False+check("prefix wait: released when the stream went", waiter([]).prefix_ready(w))++# the scheduler with the spill tier off (no prestage): a waiting request is held apart while the queue goes on++class SchedDecoder:+ def __init__(self, w):+ self.w, self.admitted, self.streams = w, [], {}++ def live(self):+ return len(self.streams)++ def fits(self, s):+ return True++ def admit(self, s):+ self.admitted.append(s)+ self.streams[id(s)] = s++ def prefix_wait(self, s):+ return self.w.prefix_wait(s)++ def prefix_ready(self, p):+ return self.w.prefix_ready(p)+++def sched(w):+ o = object.__new__(M.GlmScheduler)+ o.decoder, o.max_streams = SchedDecoder(w), 4+ o.waiting, o.held, o.boxes, o.yields, o.gather_s = Waiting(), None, {}, 0, 0+ o.flushing, o.flush_lock, o.loading, o.ready, o.staged, o.prefix = None, threading.Lock(), [], [], set(), []+ o.max_in_system = None+ return o+++def item(p):+ return (NS(prompt=p, draft=True, vision=None, background=False, done=False, emit=NS()), queue.Queue())+++filling = lane(1, sysp + ids_of(B, 522), {3 * B}, B)+for on in (False, True):+ M.PREFIX_WAIT = on+ o = sched(waiter([filling]))+ a, b = item(prompt), item(ids_of(2 * B, 524))+ o.waiting.put(a)+ o.waiting.put(b)+ o._admit()+ if not on:+ check("prefix wait off: both requests admitted at once (admission as without the patch)",+ o.decoder.admitted == [a[0], b[0]] and not o.prefix)+ continue+ check("prefix wait on: the request sharing the prefix is held apart, the next one admitted",+ o.decoder.admitted == [b[0]] and [it for _, it in o.prefix] == [a])+ o._admit()+ check("prefix wait on: still held while the point is ahead", o.decoder.admitted == [b[0]])+ filling.st.pos = 3 * B+ o._admit()+ check("prefix wait on: admitted once the point is kept, before the queue", o.decoder.admitted == [b[0], a[0]]+ and not o.prefix and getattr(a[0], "prefix_waited", False))+M.PREFIX_WAIT = saved_pw+conf = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "scripts", "config.sh")+if os.path.exists(conf): # (the recipe's tree; not when the check is run alone)+ check("prefix wait: config.sh defaults PREFIX_WAIT to 0", 'PREFIX_WAIT="${PREFIX_WAIT:-0}"' in open(conf).read())++print("all passed" if not fails else f"FAILED: {fails}", flush=True)+os._exit(1 if fails else 0)diff --git a/tools/spill_blocks_mutants.sh b/tools/spill_blocks_mutants.shnew file mode 100755index 0000000..7ba782f--- /dev/null+++ b/tools/spill_blocks_mutants.sh@@ -0,0 +1,165 @@+#!/bin/bash+# spill_blocks_mutants.sh <dir> [names] CPU only: tools/spill_blocks_check.py must pass on patch 0128 as it is and+# FAIL on each faithful mutant of its fixes (the code before the fix, or one of its parts taken out). <dir> holds the+# patched tensorfold/ package; each run works on a copy of it with $PYTHON (default python3). In the image+# scripts/prepare.sh built:+# docker run --rm --network none -e CUDA_VISIBLE_DEVICES= -v "$PWD/tools:/t:ro" --entrypoint bash \+# tensorfold-glm53:v0.6.0 /t/spill_blocks_mutants.sh /usr/local/lib/python3.12/dist-packages+# Each run applies one mutant (one or more edits, python escapes; an anchor that does not match exactly once is an+# ERROR, never a pass); a kill needs the check's non-zero exit AND a FAIL line. names: a bash regex, only the runs it+# matches. Exit 0 only when the unmutated check passes and every mutant is killed. Not mutated (no CPU check reaches+# them): the CUDA events that keep a read's pinned slot from being read into again before the engine's copy out of it+# ended (``_recycle``).+set -u+TARGET=$1; ONLY=${2:-.}+HERE=$(cd "$(dirname "$0")" && pwd)+C="$HERE/spill_blocks_check.py"+PYTHON=${PYTHON:-python3}+OUT=$(mktemp)+SCRATCH=$(mktemp -d)+trap 'rm -rf "$SCRATCH" "$OUT"' EXIT+MUTATE='+import os, sys+for i in range(int(os.environ["EDITS"])):+ old = os.environ[f"OLD{i}"].encode().decode("unicode_escape")+ p = os.path.join(os.environ["TREE"], os.environ[f"FILE{i}"])+ s = open(p).read()+ n = s.count(old)+ if n != 1:+ sys.exit(f"ANCHOR {n} (edit {i})")+ open(p, "w").write(s.replace(old, os.environ[f"NEW{i}"].encode().decode("unicode_escape")))+'+bad=0+run() { # name, then (file under tensorfold/, old, new) for each edit (name "patched": none)+ local name=$1 i=0+ shift+ [[ "$name" =~ $ONLY ]] || return 0+ local env=()+ while [ $# -ge 3 ]; do env+=("FILE$i=$1" "OLD$i=$2" "NEW$i=$3"); i=$((i + 1)); shift 3; done+ env+=("EDITS=$i")+ rm -rf "$SCRATCH/t" && mkdir -p "$SCRATCH/t" && cp -r "$TARGET/tensorfold" "$SCRATCH/t/" &&+ find "$SCRATCH/t" -name __pycache__ -type d -prune -exec rm -rf {} + &&+ env "${env[@]}" TREE="$SCRATCH/t/tensorfold" "$PYTHON" -c "$MUTATE" > "$OUT" 2>&1 &&+ (cd "$SCRATCH" && PYTHONPATH="$SCRATCH/t" CUDA_VISIBLE_DEVICES= TEST_TIMEOUT_S=${TEST_TIMEOUT_S:-120} timeout 300 "$PYTHON" "$C") \+ >> "$OUT" 2>&1+ rc=$?+ set -- "$name"+ if grep -q "^ANCHOR" "$OUT"; then echo "ERROR $1: $(grep ANCHOR "$OUT")"; bad=1+ elif [ "$1" = patched ]; then+ if [ $rc = 0 ] && grep -q "^all passed" "$OUT" && ! grep -q "^FAIL" "$OUT"; then+ echo "patched: all passed ($(grep -c '^ok' "$OUT") checks)"+ else echo "patched: FAILS, exit $rc ($(grep -m3 -E '^FAIL|Error' "$OUT" | tr '\n' ' '))"; bad=1; fi+ elif [ $rc != 0 ] && grep -q "^FAIL " "$OUT"; then+ echo "KILLED $1 ($(grep -c '^FAIL ' "$OUT") FAIL lines, e.g. $(grep -m1 '^FAIL ' "$OUT" | cut -c1-110))"+ elif [ $rc = 0 ]; then echo "SURVIVED $1"; bad=1+ else echo "CRASHED $1, exit $rc: $(grep -E 'Error|error' "$OUT" | tail -1)"; bad=1; fi+}+B=cuda/spill_blocks.py; MU=families/glm5_next/cuda/multi.py+run patched+# review 1: the tail block copied at keep+run tail-staged-later $B " cut = [(h, _host(torch.cat(self._parts(extent, s, e)))) for s, e, h in new[-1:] if e - s < self.block]" " cut = []"+run tail-copied-and-staged $B " job = Job(pt, new[:len(new) - len(cut)], (items, layer)" " job = Job(pt, new, (items, layer)"+run tail-not-queued $B " for h, data in cut: # (written before the blocks the pumps stage)\n self.jobs.put((\"rows\", job, h, data))\n" ""+# review 2: a move of an extent being read waits for neither the read nor the disk+run move-waits-for-read $MU " if keep is None:\n return\n h = getattr(x, \"loading\", None)\n if h is not None and h.lj is not None and keep < h.n:\n self.disk.stop_load(h.lj, \"its extent shrank under the read\")\n" " h = getattr(x, \"loading\", None)\n while h is not None and h.lj is not None and not all(it[2].done() for it in list(h.lj.queued.values())):\n time.sleep(0.01)\n if keep is None:\n return\n"+run read-at-first-base $B " self.point, self.where = point, where\n" " self.point, self.where = point, where\n self.base0 = where.base\n" \+ $B " base = lj.where.base\n" " base = lj.base0\n"+# the reader reads, the engine copies between rounds; LOADPART takes rank 1 as far+run reader-copies $B " fut = self._readers.submit(self._read_block, h, pt.crcs[i], self.read_slots[b], nb)\n" " fut = self._readers.submit(self._read_block, h, pt.crcs[i], self.read_slots[b], nb)\n fut.result()\n self._copy_in(lj, self.read_slots[b], s, e)\n self.stats[\"loaded_bytes\"] += nb\n"+run no-step $MU " if self.disk.step(h.lj, budget=left):\n" " if False:\n"+# review (wojo#2): one budget a pause for every read in flight, and each read first in turn+run budget-each-read $MU " left = deadline - time.perf_counter()\n" " left = budget\n"+run ready-before-copies $MU " if lj.error is not None or lj.next >= lj.total:\n return True\n" " return True\n"+run budget-same-first $MU " k = self.load_turn % len(live)" " k = 0"+run loadpart-not-sent $MU " self._emit(LOADPART, [h.lid, h.lj.next])\n" " pass\n"+run loadpart-not-applied $MU " elif op == LOADPART:\n self._load_part(*p)" " elif op == LOADPART:\n pass"+run loadpart-past-upto $B " end = lj.total if upto is None else min(int(upto), lj.total)\n" " end = lj.total\n"+run loaded-without-rest $B " if lj.error is None:\n self.step(lj, upto=lj.total)\n" ""+# review 3, shared flag 1 and 2: a restore keeps rank 0's shared-prefix flag on every rank+run restore-unshared $MU " snap.shared = bool(shared)" " snap.shared = False" \+ $MU " self._emit(LOADED, [h.lid, shared])" " self._emit(LOADED, [h.lid])"+run each-rank-own-flag $MU " snap.shared = bool(shared)" " snap.shared = bool(pt.shared)"+run loaded-without-flag $MU " self._emit(LOADED, [h.lid, shared])" " self._emit(LOADED, [h.lid])"+# shared flag 3: ids kept again as shared make their point shared, durably+run no-upgrade $B " pt = self.index.get(key)\n if pt is not None:\n pt.used = time.time()\n elif key in self.waiting:" " pt = None\n if key in self.index:\n self.index[key].used = time.time()\n elif False:"+run upgrade-not-durable $B " if key in self.index: # its json again, on the writer (\`\`_mark_shared\`\`)\n self.jobs.put((\"shared\", None, key, None))\n" ""+run waiting-not-flagged $B " elif key in self.waiting: # still being written: its json takes the flag then\n pt = self.waiting[key].point\n" ""+run written-no-rewrite $B " if pt.shared and not shared:\n self.jobs.put((\"shared\", None, pt.key, None))\n" ""+run rewrite-resurrects $B " if gone:\n try:\n os.remove(path)" " if False:\n try:\n os.remove(path)"+run rewrite-not-put $B " _put(path, json.dumps(meta).encode(), self.owner)\n" " open(path, \"wb\").write(json.dumps(meta).encode())\n"+run rewrite-no-dir-fsync $B " _put(path, json.dumps(meta).encode(), self.owner)\n _fsync_dir(self.points_dir)\n" " _put(path, json.dumps(meta).encode(), self.owner)\n"+run drain-skips-rewrites $B " synced = threading.Event() # (behind every rewrite those jobs or a keep queued)\n self.jobs.put((\"sync\", None, None, synced))\n return synced.wait(None if end is None else max(0.0, end - time.monotonic()))\n" " return True\n"+# review 4: a missing name is not damage to the names linked to its bytes+run lost-is-damage $B " if isinstance(exc, FileNotFoundError): # this name is gone: its links' bytes are not in question\n lj.lost.add(h)\n elif isinstance(exc, (Corrupt, EOFError)): # damaged bytes, not a passing I/O error\n" " if isinstance(exc, (Corrupt, FileNotFoundError, EOFError)): # damage, not a passing I/O error\n"+run lost-names-kept $B " gone = bad | set(lost)\n" " gone = bad\n"+run damage-not-widened $B " if b in self.have and self.have[b][1] in self.inodes:\n bad |= self.inodes[self.have[b][1]][1]\n" " pass\n"+run finish-load-drops-lost $MU " self.disk.forget(h.key, lj.bad if lj is not None else (), lj.lost if lj is not None else ())" " self.disk.forget(h.key, lj.bad if lj is not None else ())"+# review 5: no op without a sender; the prefix wait's counters in /metrics+run ops-unsent $MU "LOAD, FLUSH, LOADED, \\\\\n HAS, LOADPART = range(1, 18)" "LOAD, FLUSH, SPILL, LOADED, \\\\\n TOUCH, HAS, LOADPART = range(1, 20)" \+ $MU " FLUSH: \"FLUSH\", LOADED: \"LOADED\", HAS: \"HAS\", LOADPART: \"LOADPART\"}" " FLUSH: \"FLUSH\", SPILL: \"SPILL\", LOADED: \"LOADED\", TOUCH: \"TOUCH\", HAS: \"HAS\", LOADPART: \"LOADPART\"}"+run prefix-not-exported server/metrics.py " if field in body:\n body.setdefault(name, body[field])\n" " pass\n"+# the page cache: every point file's pages dropped after its fsync (already so in the patch; pinned here)+run small-files-keep-pages $B " os.fsync(fd)\n _drop_cache(fd) # (clean now" " os.fsync(fd)\n pass # (clean now"+run pages-dropped-before-fsync $B " os.fsync(fd)\n _drop_cache(fd) # (clean now" " _drop_cache(fd)\n os.fsync(fd) # (clean now"+# a read slot turns every round: the round settles the reads once its verify pass is queued+run round-no-settle $MU " if self.disk is not None and self.loads:\n try:\n self.disk.settle()" " if False:\n try:\n self.disk.settle()"+run round-settle-always $MU " if self.disk is not None and self.loads:\n try:\n self.disk.settle()" " if self.disk is not None:\n try:\n self.disk.settle()"+run settle-oldest-only $B " last = next((ev for _, ev in reversed(evs) if ev is not None), None)" " last = next((ev for _, ev in evs if ev is not None), None)"+run settle-frees-none $B " for b, _ in evs:\n self.free_reads.put(b)\n self.read_events = []\n" " pass\n"+run settle-before-slots $B " evs = getattr(self, \"read_events\", None)" " evs = self.read_events"+# the writer: a write slot's event made at start and reused (wojo#2's pump made one a block, the writer dropped it)+run write-event-per-block $B " ev = self.slot_events[slot] if self.slot_events else None # (made at start: a GPU's only)\n if ev is not None:\n ev.record()\n" " ev = None\n if self.dev_slot.device.type == \"cuda\":\n ev = torch.cuda.Event()\n ev.record()\n"+# LOADED on a rank with more blocks left than read slots: the wait frees the slots its copies hold+run hang-no-recycle-in-wait $B " if self.read_events: # the slots this step's own copies used: back to the reader,\n self._recycle(wait=True) # or it waits for one and block i is never read\n" ""+# the read-ahead: 16 blocks by default (ten in the preallocated buffers), those buffers kept, the rest in power-of-two pieces+run read-ahead-default-9 $B "READ_BLOCKS = 16 #" "READ_BLOCKS = 9 #"+run read-ahead-default-32 $B "READ_BLOCKS = 16 #" "READ_BLOCKS = 32 #"+run read-ahead-default-17 $B "READ_BLOCKS = 16 #" "READ_BLOCKS = 17 #"+run read-ahead-replaces-preallocate $B " bufs = _sp._PINNED.setdefault(\"read\", [])\n want = read_blocks() * per - sum(b.numel() for b in bufs)\n" " bufs = _sp._PINNED[\"read\"] = []\n want = read_blocks() * per\n"+run read-ahead-charges-preallocate $B " want = read_blocks() * per - sum(b.numel() for b in bufs)\n" " want = read_blocks() * per\n"+run read-ahead-one-piece $B " size = 1 << (max(min(want, _sp.CHUNK), per) - 1).bit_length()\n" " size = max(want, per)\n"+run read-ahead-per-slot $B " size = 1 << (max(min(want, _sp.CHUNK), per) - 1).bit_length()\n" " size = per\n"+# the room (review 2026-10-24): the eviction order, what goes with a point, the quota, the turns, the floor, a restart+run victims-forks-first $B " out = [(k, \"pruned_turns\") for k in sorted(turns, key=by_used)]\n out += [(k, \"pruned_forks\") for k in sorted(forks, key=by_used)]\n" " out = [(k, \"pruned_forks\") for k in sorted(forks, key=by_used)]\n out += [(k, \"pruned_turns\") for k in sorted(turns, key=by_used)]\n"+run victims-shared-early $B " for _, keys, _, path in sorted(whole, key=lambda g: g[0]):\n" " out += [(k, \"pruned_shared\") for k, c in conv.items() if c is None]\n for _, keys, _, path in sorted(whole, key=lambda g: g[0]):\n"+run remove-keeps-files $B " self.small_on_disk -= pt.small_bytes\n for suffix in (\".json\", \".st\", \".ids\"):\n try:\n os.remove(self._point_path(key, suffix))\n" " self.small_on_disk -= pt.small_bytes\n for suffix in ():\n try:\n os.remove(self._point_path(key, suffix))\n"+run remove-keeps-blocks $B " self.stats[why] += 1\n self._gc(pt.blocks)\n" " self.stats[why] += 1\n"+run room-takes-read $B " if key in protect or key not in self.index or key in self.reading:\n" " if key in protect or key not in self.index:\n"+run room-takes-pinned $B " if b in self.have and b not in self.refs and b not in self.inflight and b not in self.pinned:\n" " if b in self.have and b not in self.refs and b not in self.inflight:\n"+run no-trim $B " for k in path[self.turns:]:\n" " for k in path[len(path):]:\n"+run trim-reading $B " if k not in self.reading and k not in self.inflight:\n self._remove(k, \"trimmed_turns\")\n" " if k not in self.inflight:\n self._remove(k, \"trimmed_turns\")\n"+run trim-shared $B " while cur is not None and cur in self.index and not self.index[cur].shared:\n" " while cur is not None and cur in self.index:\n"+run no-quota $B " if self.quota > 0:\n self._trim_own(pt, need)\n" ""+run quota-takes-others $B " for key, why in self._victims(only=c):\n" " for key, why in self._victims():\n"+run floor-evicts-for-nothing $B " if max(short, over) > self.stored(): # (the disk is full of other things): nothing to evict for\n" " if False:\n"+run floor-ignored $B " short = self.floor + need + self.backlog - self.disk_free()\n over =" " short = 0\n over ="+run scan-keeps-temporary $B " if f.startswith(\".\"): # a write cut off before its rename\n" " if False:\n"+run scan-keeps-orphans $B " for b in present - self.have.keys():\n" " for b in ():\n"+run scan-keeps-incomplete-files $B " for f in os.listdir(self.points_dir):\n if f.split(\".\")[0] not in self.index:\n" " for f in ():\n if f.split(\".\")[0] not in self.index:\n"+run scan-no-ids-crc $B " if zlib.crc32(raw) != m[\"ids_crc\"] or not os.path.exists(self._point_path(key, \".st\")):\n" " if not os.path.exists(self._point_path(key, \".st\")):\n"+run prune-other-ranks $B " mine = os.path.join(d, f\"rank{self.rank}\")\n if os.path.isdir(mine):\n shutil.rmtree(mine, ignore_errors=True)\n" " if os.path.isdir(d):\n shutil.rmtree(d, ignore_errors=True)\n"+run failed-put-leaves-tmp $B " except BaseException:\n try:\n os.remove(tmp)\n except OSError:\n pass\n raise\n return crc\n" " except BaseException:\n raise\n return crc\n"+# hardening: temporary files made new, never through a symlink; one engine a folder+run tmp-truncates $B "_NEW = os.O_WRONLY | os.O_CREAT | os.O_EXCL | _NOFOLLOW\n" "_NEW = os.O_WRONLY | os.O_CREAT | os.O_TRUNC\n" \+ $B " except FileExistsError:\n os.unlink(tmp)\n" " except FileExistsError:\n pass\n"+run tmp-no-excl $B "_NEW = os.O_WRONLY | os.O_CREAT | os.O_EXCL | _NOFOLLOW\n" "_NEW = os.O_WRONLY | os.O_CREAT | os.O_TRUNC | _NOFOLLOW\n"+run no-lock cuda/spill.py " fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)\n" " pass\n"+run lock-after-prune $B " self._held = _sp.hold(cfg.root, self.rank) # (before any file of it is read, pruned or written)\n" "" \+ $B " pruned_builds = self._prune_builds()\n self._scan()\n except _sp.Busy" " pruned_builds = self._prune_builds()\n self._scan()\n self._held = _sp.hold(cfg.root, self.rank)\n except _sp.Busy"+run busy-stops-engine $MU " except Busy as exc: # (raised on every rank alike: the tier is off on all of them)\n print(f\"[tensorfold] spill rank {self.rank}: {exc}: the spill tier is off" " except KeyError as exc:\n print(f\"[tensorfold] spill rank {self.rank}: {exc}: the spill tier is off"+run one-stream-unlocked cuda/spill.py " self._held = hold(cfg.root, self.rank)\n" ""+# release: its own cap on the rows it copies to host memory+run release-uncapped $B " fits = self.host_bytes + need <= self.release_cap\n" " fits = True\n"+run release-not-counted $B " if fits:\n self.host_bytes += need\n" ""+run release-never-let-go $B " with self.lock:\n self.host_bytes -= item.numel() * item.element_size()\n" " pass\n"+run release-cap-backlog $B " return reserve // RELEASE_SHARE\n" " return BACKLOG\n"+run cut-not-counted $B " self.host_bytes += sum(t.numel() * t.element_size() for _, t in cut) # (at most a block a state)\n" ""+# the prefix wait: off by default+run prefix-wait-default-on $MU "PREFIX_WAIT = os.environ.get(\"TF_GLM_PREFIX_WAIT\", \"0\") not in (\"\", \"0\")" "PREFIX_WAIT = os.environ.get(\"TF_GLM_PREFIX_WAIT\", \"1\") != \"0\""+run prefix-wait-ignores-flag $MU " if not PREFIX_WAIT or not s.draft" " if not s.draft"+run prefix-wait-no-minimum $MU " if p <= m and p < len(prompt) and p - have >= self.g.shared and" " if p <= m and p < len(prompt) and"+run prefix-never-ready $MU " return lane is None or lane.decoding or lane.s.done or lane.st.pos >= p\n" " return lane is None or lane.s.done\n"+run prefix-wait-blocks-queue $MU " stream.prefix_waited = True\n self.prefix.append((w, item))\n continue\n" " stream.prefix_waited = True\n self.prefix.append((w, item))\n break\n"+rm -f "$OUT"+echo "exit $bad"+exit $baddiff --git a/tools/test_broken_health_exit.py b/tools/test_broken_health_exit.pyindex d593eb1..4c2576a 100644--- a/tools/test_broken_health_exit.py+++ b/tools/test_broken_health_exit.py@@ -31,7 +31,7 @@ def decoder_type(root):calls.append(method.name)assert sorted(writes) == ['__init__', '_break'], writesassert sorted(calls) == ['admit', 'complete_load', 'drop', 'round'], calls- names = {'_break', '_check', 'round', 'drop', 'complete_load'}+ names = {'_break', '_check', '_pump', 'round', 'drop', 'complete_load'}methods = [n for n in cls.body if isinstance(n, ast.FunctionDef) and n.name in names]assert len(methods) == len(names)for n in methods:@@ -90,7 +90,7 @@ def main():d.lanes = {}d.partial = Nonetry:- getattr(d, path)(SimpleNamespace(lid=1, done=False)) if path == 'complete_load' else getattr(d, path)()+ getattr(d, path)(SimpleNamespace(lid=1, done=False, lj=None)) if path == 'complete_load' else getattr(d, path)()except RuntimeError:passassert d.broken is not None, pathdiff --git a/tools/test_queued_cancellation.py b/tools/test_queued_cancellation.pyindex 59e6551..dfb8468 100644--- a/tools/test_queued_cancellation.py+++ b/tools/test_queued_cancellation.py@@ -95,6 +95,7 @@ def main():obj.waiting, obj.held, obj.boxes, obj.yields, obj.gather_s = ns["Waiting"](), None, {}, 0, 0# patch 0088's spill tier (off): its scheduler stateobj.flushing, obj.flush_lock, obj.loading, obj.ready, obj.staged = None, threading.Lock(), [], [], set()+ obj.prefix = []obj.max_in_system = None # patch 0082's admission cap: offfor _ in range(holders):stream = Stream([1], 100)@@ -180,6 +181,9 @@ def main():self.reads += 1return object()+ def step_loads(self):+ pass # (0128's block reads move their rows between rounds)+def load_ready(self, handle):return True