Skip to content

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

Python

Patch 0129: KV sharding, each conversation's latent cache once on its owner Spark (net diff of PR #152)

Robert Wojciechowskibce0895c7a93
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ceff1ba..31a65e5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,36 @@ Every change to this recipe, newest first. Each release names the image it serve
## Unreleased
+- **KV sharding** (patch `0129-glm-kv-shard`, `TF_GLM_KV_SHARD=1`, off by default, by
+ Robert Wojciechowski ([wojo](https://github.com/wojo) on GitHub, [@rwojo](https://x.com/rwojo) on X)): each
+ conversation's MLA latent cache is stored once, on the Spark that owns it,
+ instead of on every Spark (tensor parallelism splits the heads, but every head reads the whole latent). The owner
+ computes the decode attention of its rows; a prompt chunk on the other Sparks gets only the history rows its sparse
+ attention selects, or borrows free rows and attends locally. Two Sparks, `PARALLEL=8`: the pool holds 1.87x the tokens
+ (1.51M -> 2.83M; 1.85M -> 3.47M with `DISPLAY_KV_MIB=1792`), every reply byte-equal to the unsharded engine's, decode
+ within 1%, prompts within noise when rows can be borrowed and +1.8-3.5% when they are sent. A borrowed row is pinned
+ while its prompt fills (a compaction moving it gave wrong replies under concurrent load; found in review, fixed, and
+ a forced-compaction run on two Sparks is byte-equal). A cache hit whose part has no room no longer drops the cache
+ or evicts kept conversations while another part has room: its rows are carried there (`TF_GLM_KV_SHARD_CARRY`,
+ on; only when it saves a recompute, an eviction or a pause, never to even out the parts). The same shard code serves
+ the tp4 branch (own-row front, microbatching, a carry relayed over a switchless ring's neighbour links); two Sparks
+ and four (tp4, on a ring) tested, three untested. The staging buffers a prompt's history fetch keeps (`shard._grown`) are outside the start-up
+ estimate. Builds on `0128` and `0119` (renumbered from `0118`, which #216 uses). CPU checks: `tools/kv_shard_check.py`, `tools/kv_shard_mutants.sh`.
+
+- **A rewound conversation keeps its id** (patch `0119-glm-chat-continued`, by
+ Robert Wojciechowski ([wojo](https://github.com/wojo) on GitHub, [@rwojo](https://x.com/rwojo) on X)): patch
+ `0089` gave a stream a new conversation id unless it resumed from one of that conversation's own turn states, so a
+ client rewinding before the kept turns (issue #104, @danielbanu), a state read back from the spill tier, or dropped
+ states split one session into several ids, and `TF_GLM_KEEP_PER_CHAT` counted each piece on its own: one session
+ held more states than the quota. Now the stream joins the conversation whose own kept state its prompt repeats past
+ that conversation's first prompt and the first 32 tokens of the reply to it. On two Sparks (PARALLEL=8,
+ `TF_GLM_KEEP_PER_CHAT=2`, `TF_GLM_CACHE_ENTRIES=16`), a ~110k-token session rewinding three rounds every fifth of 16
+ while six chats fill the cache: before, its states went under 3 ids; after, 1, holding 2 states as asked; replies
+ the same drafted and with `draft:false`. New counters `chats_continued`, `chats_continued_prefill_tokens` (`/health`,
+ `/metrics`) and a rank-0 log line for one prefilling 4096 tokens or more, with where the prompt left the kept state
+ and what it resumed from. Two sessions with the same opening message and the same first reply (temperature 0)
+ cannot be told apart by this match and share an id. CPU check: `tools/chat_continued_check.py` (fails on the
+ unpatched engine; also runs `_admitted` itself and the `chat_roots` pruning).
- **`prepare.sh` warns when a node's NVIDIA CDI device cannot be confirmed** (by
[SvangenStudios](https://github.com/SvangenStudios), [pull request #207](https://github.com/MiaAI-Lab/GLM-5.3-Flash-EXL3-2x-DGX-Sparks-TensorFold/pull/207),
issue #150): without the host's CDI spec, a `systemctl daemon-reload` can remove the GPU from a running container's
diff --git a/CREDITS.md b/CREDITS.md
index 5bcb7a7..6098268 100644
--- a/CREDITS.md
+++ b/CREDITS.md
@@ -188,6 +188,11 @@ checkpoint's ShapleyMcg attribution and the drafter's license).
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.
+- `0129-glm-kv-shard` (KV sharding, `TF_GLM_KV_SHARD`; its checks `tools/kv_shard_check.py` and
+ `tools/kv_shard_mutants.sh`): authored by Robert Wojciechowski ([wojo](https://github.com/wojo) on GitHub,
+ [@rwojo](https://x.com/rwojo) on X) in [PR #152](https://github.com/MiaAI-Lab/GLM-5.3-Flash-EXL3-2x-DGX-Sparks-TensorFold/pull/152),
+ from [issue #151](https://github.com/MiaAI-Lab/GLM-5.3-Flash-EXL3-2x-DGX-Sparks-TensorFold/issues/151). It builds on
+ `0128-glm-spill-blocks` and `0119-glm-chat-continued`, whose credits are above.
- `0089-glm-kept-state` (a byte budget for the kept states and a per-conversation quota, `TF_GLM_KEPT_BYTES_GIB` and
`TF_GLM_KEEP_PER_CHAT`): authored by Thomas Wade ([ThomasWadeZ](https://github.com/ThomasWadeZ)) in
[PR #65](https://github.com/MiaAI-Lab/GLM-5.3-Flash-EXL3-2x-DGX-Sparks-TensorFold/pull/65) (Apache 2.0); rebased
diff --git a/README.md b/README.md
index 699c63c..72138b9 100644
--- a/README.md
+++ b/README.md
@@ -335,6 +335,68 @@ with that window and says so (free memory on both Sparks for the full one). Othe
| `KV=bf16 DRAFTER=mtp` | 524,288 | one request at a time |
| `CONTEXT=0` | the largest that fits | no memory is left to keep other conversations' prompts |
+### KV sharding (optional)
+
+`TF_GLM_KV_SHARD=1` (patch `0129`, `PARALLEL` above 1) stores each conversation's latent cache once instead of on
+every Spark. Tensor parallelism splits the attention heads, but every head reads the whole MLA latent, so each Spark
+held a full copy: 11 DSA layers x (528 bytes of fp8 latent + 36 of pooled keys) = 6,204 bytes a token a Spark. With
+the shard the pool is split in parts, one a Spark; a conversation lives in one part, and only that Spark (its owner)
+keeps its latents, the pooled keys staying on every Spark: 3,300 bytes a token at two Sparks, so the same memory holds
+1.87x the tokens (computed: 2.66x at three, untested there). The same shard code serves the tp4 branch (four Sparks):
+there its own-row prompt front and microbatching run with it, and on a switchless ring a carry is relayed over the
+neighbour links; four Sparks on a ring measured 3.4x the pool with byte-equal replies (#152). On this branch a carry
+always goes straight from owner to owner.
+
+- **Decode**: the queries are all-gathered and each row's owner computes all 64 heads over its latents, sending the
+ other Sparks their heads' outputs (64 heads at once give the same bits as 32 + 32).
+- **Prompts**: the other Sparks keep their own heads; the owner sends only the history rows a chunk's sparse attention
+ selects (90% of the history under 50k tokens, ~43% at 250k), deduplicated and renumbered with marks and prefix sums.
+ When the other parts have free rows, a new prompt borrows them instead: every Spark writes its own copy while the
+ prompt fills and attends locally, and the rows go back at the first reply token, at the end, or as soon as anything
+ else needs them (a borrow never evicts a kept prompt).
+- **Pool**: evictions happen in one part only, the one whose newest needed eviction is the oldest; a new conversation
+ goes to the part with fewer live streams. The spill tier and the display reservation work with it (each Spark stores
+ what it holds; a restore goes back into its part). Not with `TF_GLM_MULTI_LONE`.
+- **Carry** (`TF_GLM_KV_SHARD_CARRY`, on; `0` turns it off): a resumed conversation, or a request starting from a
+ kept shared system prompt, uses rows its own part holds, so it lands in that part. With agents resuming all the time
+ one part fills while the other has room. When that would cost something, the cached rows go to the other part
+ instead (the owner sends the latents, ~5.8 KB a token over the Sparks' link; every Spark copies its pooled keys):
+ - *the cache would be dropped*: no room beside the kept rows, so the whole prompt was computed again (~93 s at 205k
+ tokens), now a carry of ~70 ms;
+ - *its part would evict kept conversations* to fit it, while the other part has the room free (with room to grow);
+ - *a live stream cannot grow* in its part and would pause: it moves whole, or a smaller stream of its part moves so
+ it grows in place; the target must keep room for its own streams, a moved stream stays put for 256 rounds and
+ never goes straight back; if no move is safe, it pauses as before.
+
+ Never to even out the parts (that would buy ~0.7% decode): when the request fits where it is without evicting,
+ nothing moves. Same replies (rows copied byte for byte). Nothing changes until a carry is due (one host-side check a
+ cache hit); a carry pauses every stream once for its transfer (two Sparks: 14-17 GB/s, at most 69 ms in a test of
+ 124 carries, 3.38M tokens). Spill blocks of a sharded run name their part (a carried conversation's later blocks
+ are written by another owner); stores from before still restore.
+- **Refused at start**, with the reason: `TF_GLM_MULTI_VERIFY=serial`, and a part under 131,072 tokens or a quarter
+ of the window. A part a little short of the window (a first start of a new image) caps a request at what a part
+ holds, logged once at start.
+- **Outside the start-up estimate**: the staging buffers a prompt's history fetch keeps (`shard._grown`), each the
+ next power of two of the largest fetch so far, kept once grown: on a Spark receiving another Spark's rows, the rows
+ received (528 bytes a row with the FP8 KV cache, 1,024 with bf16: 0.5-1 GiB once a ~1M-token prompt has sent its
+ whole history), and on the owner its send piece (at most 64 MiB). They grow with the longest prompt served, so the
+ memory reserve, not the pool, has to cover them.
+
+Measured on two Sparks (`PARALLEL=8`, default reserve), every reply byte-equal to the unsharded engine's (concurrent
+streams, 60k to ~1M-token prompts, real text, multi-turn, borrows taken back mid-prompt, spill restores, prefix waits):
+
+| | unsharded | sharded |
+|---|---|---|
+| Pool | 1,505,280-1,531,904 tokens | 2,813,952-2,842,624 |
+| Pool with `DISPLAY_KV_MIB=1792` | 1,849,344 | 3,465,216 |
+| Decode, 8 streams | 103.1 tok/s | 102.4 (101.7 with every stream on one Spark) |
+| 205k-token prompt (real text) | 113.4 s | 113.7 borrowing rows; 116.0 sending them |
+| ~1M-token prompt, sending rows | 900.9 s | 932.0 |
+| Lowest free memory, 1M prompt + 7 decoding | rank 0 12.1 GiB | 10.6 GiB (rank 1 unchanged) |
+
+Open items being measured: the ~1 GiB of extra worst-case memory on the owner, the decode stalls beside two restores
+at once, and TP3 (the code handles N Sparks; a part a Spark, the prompt rows broadcast from the owner).
+
## Spill tier (optional)
The KV pool keeps a few conversations' prompt states (`TF_GLM_CACHE_ENTRIES`, and what the pool holds); one that
@@ -645,6 +707,7 @@ sets a value wins: the environment, then `scripts/local.sh`, then `.env`, then t
| `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_KV_SHARD` | `0` (off) | `1`: each conversation's latent cache stored once, on its owner Spark, instead of on every Spark: 1.87x the pool's tokens at two Sparks, same replies (patch `0129`, `PARALLEL` above 1, not with `TF_GLM_MULTI_LONE`; [KV sharding](#kv-sharding-optional-in-testing)). Set the same on every Spark |
| `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 |
@@ -760,6 +823,7 @@ applied with `patch -p0` in filename order); `start.sh` rebuilds or re-pulls the
| Weights | `0002-glm-dense-fp8`, `0005-glm-dense-q4` | the checkpoint's BF16 dense weights in FP8, or 4-bit with MSE-searched ranges (`DENSE`) | q4 over fp8: prose 38.9 -> 44.4 tok/s, code 44.2 -> 48.7, prefill ~1,090 -> ~1,260 tok/s |
| KV cache | `0038-glm-kv-fp8` | the DSA latent cache and the indexer's pooled keys as FP8 rows (`KV=fp8`) | the 1M window with 4 requests fits |
| KV pool | `0072-glm-display-kv` | the first DSA latent planes in a span ending in the GPU's display reservation, which `MemAvailable` does not count; the pool's row copies of those planes by a kernel (a memcpy may not cross the span's two registrations) (`DISPLAY_KV_MIB`, by ezoushen) | 1792 MiB: ~277k more tokens at `PARALLEL=8`; the same bits, decode and prefill |
+| KV pool, sharded | `0129-glm-kv-shard` | each conversation's latent cache once, on its owner Spark (`TF_GLM_KV_SHARD=1`): owner-computed decode attention, prompts fetching only the rows their sparse attention selects or borrowing free rows, part-aware eviction and placement, with the spill tier and the display reservation (by Robert Wojciechowski ([wojo](https://github.com/wojo) on GitHub, [@rwojo](https://x.com/rwojo) on X)) | [KV sharding](#kv-sharding-optional-in-testing) |
| Loads, kindling | `0098-glm-mmap-uploads` | the DFlash2 drafter's and the vision tower's loaders copy each tensor out of the safetensors mmap before it goes to the GPU: on kindling spark-os's 64 KiB-page kernel a pageable copy straight from a file mmap hangs in the driver once the process holds GPU memory (by [BadAd84](https://github.com/BadAd84)) | kindling: the server starts (it stopped after the drafter timings); elsewhere the same bytes, one host copy a tensor at start |
| KV pool, kindling | `0087-glm-display-kv-dispram` | `0072`'s span with its reservation half from kindling spark-os's `dispramd` instead of a DRM dumb buffer, which kindling's `nvidia_drm` (no modeset) cannot make; the rest of `0072` runs unchanged (`DISPLAY_KV_BACKEND=dispram`) (by [BadAd84](https://github.com/BadAd84)) | 2032 MiB: +317,440 tokens at `PARALLEL=4` on three Sparks; the display check 53/53 |
| Prompt | `0001-glm-exl3-prompt-experts`, `0004-glm-prompt-kernels`, `0009-glm-prefill-kernels`, `0020-glm-prompt-experts-order`, `0024-glm-prompt-select-rows`, `0028-glm-lean-prompt-scratch` | EXL3 expert kernels that keep a prompt chunk's rows in L2, launched in a better order; each row's input rotated once; dense attention only where the sparse pass needs it; token selection in blocks of 512 rows; smaller prompt scratch | faster prefill, less memory at 1M |
@@ -799,7 +863,7 @@ applied with `patch -p0` in filename order); `start.sh` rebuilds or re-pulls the
| 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 |
+| 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; two sessions with an identical opening message and an identical (temperature 0) first reply cannot be told apart by this match and share one id (by Robert Wojciechowski ([wojo](https://github.com/wojo) on GitHub, [@rwojo](https://x.com/rwojo) on X)) | with `TF_GLM_KEEP_PER_CHAT=0` (the default) only the counters and the log line |
| Responses `include` | `0093-responses-include` | `/v1/responses` accepts OpenAI's `include` values and ignores them (reasoning already comes as text, nothing is encrypted); an unknown value or a non-list is still a 400 (issue #73) | the AI SDK's `include: ["reasoning.encrypted_content"]` no longer fails every request |
| Broken engine | `0118-glm-broken-health-exit` | `/health` reports `ok: false` with its first broken cause, `/metrics` exposes `tensorfold_health:ok`, and opt-in `TF_GLM_EXIT_ON_BROKEN=1` exits non-zero on the latch | broken state is visible; default process lifetime unchanged |
| Chunked request bodies | `0094-chunked-request-bodies` | a `Transfer-Encoding: chunked` request body (AI SDK clients, Chatbox, proxies) is read like a `Content-Length` one on the chat, completions, tokenizer and Responses routes and the MLX-style server, each route keeping its own size limit (96 MiB for chat); a refused request's body is consumed so it cannot reach the next one. The reader is `request_body.read_body` from TensorFold's 977f2cc by Jordi Posthumus (@JordiPosthumus), which `0084` adds; this patch uses it at the remaining sites (issues #67, #74) | no dechunking proxy; a validation 400 no longer leaves HTML after the JSON on a keep-alive connection |
@@ -869,6 +933,8 @@ with [sparkDash](https://github.com/MiaAI-Lab/sparkDash) ([Performance](#perform
| `tools/display_kv_check.py [--gpu]` | patch 0072's checks, run in the image (`docker run ... --entrypoint python`, see the file): the setting, the span's mapping and unwinding through a fake driver, the carved planes and the pool's copies; with `--gpu`, the real span on a Spark whose display reservation is free |
| `tools/qmm_noclusters_check.py [--time]` | patch 0103's checks: the installed 4-bit matmul against a build of the same sources with the old cluster rule, bit for bit at every decode shape of TP=4, TP=3 and TP=2 and at the 28 Mi edge, the path each call takes (and with `TF_GLM_QMM_CLUSTERS=1`), and a CUDA graph on side streams; run in the image on one GPU (`docker run --gpus all ... --entrypoint python`, see the file); `--time` prints the old and new paths' times |
| `tools/pool_pressure.py [size]` | on a fresh server with nothing else sending requests: two conversations of ~`size` tokens (default 30000) take a turn each, others fill the pool, then each takes another turn; exit 1 when a turn resumes less than 90% of its previous prompt, 2 when the kept-prompt cap stops the fill first (a smaller pool runs it faster: `CONTEXT=131072 KV_POOL_GIB=0.5`) |
+| `tools/kv_shard_check.py` | patch 0129's checks, run in the image (`docker run ... --entrypoint python`, CPU only): the pool in parts at two, three and four ranks, eviction in one part only (the one losing the oldest states), placement by live streams, the sharded pool's size, and the carry: when it runs and when it must not, its op order, the rows sent byte for byte (display span, bf16, a partial row, a bystander at three ranks), moves that do not bounce, spill names by part, `TF_GLM_KV_SHARD_CARRY=0` as before; fails on the unpatched placement |
+| `tools/kv_shard_mutants.sh` | the shard check must fail on each faithful mutant of the carry (a guard, rule or step taken out or turned the wrong way): 63, all killed |
| `tools/pool_room_check.py` | patch 0074's checks, run in the image (`docker run ... --entrypoint python`, see the file): the pool's room-making on a CPU arena, what it evicts and moves, and rank 1 replaying the same ops |
| `tools/test_broken_health_exit.py --source-root DIR` | CPU-only broken-state checks against patched TensorFold: settings, first cause, request refusal, round/load/drop errors, health and metrics, subprocess exit (no Torch/GPU) |
| `tools/parked_pages_check.py` | patch 0122's checks, run in the image (`docker run ... --entrypoint python`, see the file) or against the patched source with `PYTHONPATH`: the start-up budget's count of the pages parked on the kernel's per-CPU free lists beyond their resting level, on synthetic zoneinfo / meminfo files (several CPUs, zones and nodes, a warm start, no `high_min`, no page lists, unreadable and garbled files) and the `available_bytes` / `page_room` figures that include them; no GPU, no model |
diff --git a/patches/0129-glm-kv-shard.patch b/patches/0129-glm-kv-shard.patch
new file mode 100644
index 0000000..2215dbf
--- /dev/null
+++ b/patches/0129-glm-kv-shard.patch
@@ -0,0 +1,2635 @@
+# KV sharding (TF_GLM_KV_SHARD=1, --parallel above 1, two ranks or more): each conversation's latent cache stored
+# once, on its owner, instead of on every rank (~1.88x the tokens in the same memory at two ranks). Decode: the owner
+# computes every head of its rows (queries gathered, the other ranks' heads sent back). Prompts: the owner sends only
+# the history rows the chunk's sparse attention selects, or the other ranks borrow free rows of their part and
+# attend locally (taken back when needed). Same bits as unsharded. Spill tier and display reservation supported.
+# A cache hit whose part has no room is carried to another part (its latents sent by the owner) when that saves a
+# recompute, an eviction or a pause (TF_GLM_KV_SHARD_CARRY, on), never to even out the parts.
+# Builds on 0128 (the spill tier's blocks) and 0119 (chat-continued). By Robert Wojciechowski (GitHub @wojo, X @rwojo). Apache-2.0.
+diff --git tensorfold/cuda/spill_blocks.py tensorfold/cuda/spill_blocks.py
+index fd866fa..ab22614 100644
+--- tensorfold/cuda/spill_blocks.py
++++ tensorfold/cuda/spill_blocks.py
+@@ -12,7 +12,8 @@ snapshot fields: recurrences, windows, a head row; ``spill.encode``). On disk:
+ 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);
++ store it once); with TF_GLM_KV_SHARD the lineage also names the part the rows lie in (``in_part``: a rank holds the
++ latents of its own part only, so the same ids in another part are other bytes there);
+ - 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
+@@ -199,6 +200,18 @@ def fork(lineage: str, name: str, at: int) -> str:
+ return f"{lineage}|{name}@{int(at)}"
+
+
++def in_part(lineage: str, part: int) -> str:
++ """``lineage`` for rows that live in part ``part`` of a sharded pool (TF_GLM_KV_SHARD): the first computation's name
++ carries the part (``#<part>``), so every block name of the state does. The rank that owns a part writes its
++ latent rows, the others only its pooled keys, so the same ids in another part are other bytes on a rank: a state
++ carried to another part must not skip, by name, the blocks it wrote there before. Idempotent (a lineage read back
++ from disk, or forked from a kept state, already has one: it is replaced, never stacked), and the fork segments
++ after the first computation are untouched. An unsharded store never calls it, so its names are unchanged."""
++
++ head, bar, rest = (lineage or "").partition("|")
++ return f"{head.partition('#')[0]}#{int(part)}{bar}{rest}"
++
++
+ def _segments(lineage: str) -> tuple[bytes, list[tuple[int, bytes]]]:
+ head, *rest = (lineage or "").split("|")
+ forks = []
+@@ -832,7 +845,7 @@ class BlockStore:
+ 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)
++ size = sum(self._span(extent.base, 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,
+@@ -872,6 +885,24 @@ class BlockStore:
+ self.stats["keep_s"] += time.perf_counter() - t0
+ return "queued"
+
++ def _present(self, base: int) -> list:
++ """The planes holding the rows of the extent at ``base`` on this rank: every plane, but one sharded over the
++ ranks (``shard``: TF_GLM_KV_SHARD's latent planes) only on the rank whose half the extent is in."""
++
++ return [p for p in self.planes if not getattr(p, "shard", False) or p.view(base, 0) is not None]
++
++ def _span(self, base: int, s: int, e: int) -> int:
++ return _span_bytes(self._present(base), s, e)
++
++ @staticmethod
++ def _rows_of(p, base: int, a: int, b: int):
++ """Rows [a, b) of plane ``p`` in the extent at ``base`` (None: a sharded plane without that extent here)."""
++
++ if getattr(p, "shard", False):
++ v = p.view(base, b * p.div)
++ return None if v is None else v[a:b]
++ return p.tensor[base // p.div + a:base // p.div + b]
++
+ 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)."""
+
+@@ -879,8 +910,9 @@ class BlockStore:
+ 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))
++ t = self._rows_of(p, base, a, b)
++ if t is not None:
++ out.append(t.reshape(-1).view(torch.uint8))
+ return out
+
+ def pump(self, limit: int | None = PUMP_BLOCKS) -> None:
+@@ -1504,7 +1536,7 @@ class BlockStore:
+ b = self._slot(lj)
+ if b is None:
+ return
+- nb = _span_bytes(self.planes, s, e)
++ nb = self._span(lj.where.base, 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)
+@@ -1614,7 +1646,9 @@ class BlockStore:
+ at = 0
+ for p in self.planes:
+ a, z = _rows(p, s, e)
+- dst = p.tensor[base // p.div + a:base // p.div + z]
++ dst = self._rows_of(p, base, a, z)
++ if dst is None:
++ continue
+ k = dst.numel() * dst.element_size()
+ v = dst.reshape(-1).view(torch.uint8)
+ if p.spanned:
+diff --git tensorfold/families/glm5_next/cuda/engine.py tensorfold/families/glm5_next/cuda/engine.py
+index 84bcf63..a263996 100644
+--- tensorfold/families/glm5_next/cuda/engine.py
++++ tensorfold/families/glm5_next/cuda/engine.py
+@@ -599,6 +599,14 @@ class GlmEngine:
+ if kv != "bf16" and not LATENT:
+ raise ValueError("TF_GLM_KV=fp8 holds the latent cache: it needs TF_GLM_LATENT=1")
+ self.kv = kv
++ from . import shard
++
++ if shard.ON and parallel > 1: # settings the shard cannot serve, refused now rather than at a request
++ from .multi import verify_kind
++
++ why = shard.unsupported(verify_kind(), world)
++ if why:
++ raise ValueError(why)
+ # TF_GLM_MTP off: the MTP layer's tensors, caches and buffers are neither loaded nor estimated
+ self.mtp_on = mtp_head(drafter is not None, serial_only, cfg.mtp_layers) and parallel == 1 # multi: DFlash2
+ if not self.mtp_on:
+@@ -703,7 +711,8 @@ class GlmEngine:
+ self.agreed = mine[:1] + mine[2:] # the spill tier's folders are keyed on these (not the window's slots)
+ from .multi import PRELAUNCH # TF_GLM_DRAFT_PRELAUNCH: every rank alike
+
+- mine = mine + [int(PRELAUNCH)] # checked alike, not in the spill tier's key (``agreed``)
++ # checked alike, not in the spill tier's key (``agreed``; the shard's is in its store's signature, multi.py)
++ mine = mine + [int(PRELAUNCH), int(shard.ON)]
+ rows = self._gather_ints(mine + [spare >> 20])
+ odd = [r for r, row in enumerate(rows) if row[:-1] != rows[0][:-1]]
+ if odd:
+@@ -713,7 +722,7 @@ class GlmEngine:
+ "TF_GLM_DRAFT_QUANT, TF_GLM_SHARED_PREFIX, TF_GLM_DRAFT_RING, TF_GLM_MTP, --parallel, "
+ "TF_GLM_MULTI_VERIFY, TF_GLM_MULTI_SAMPLER / _DEPTH / _OVERHEAD_MS / _ASYNC / _LONE / _PROFILE / _WINDOW, "
+ "TENSORFOLD_NUCLEUS_UNION, TF_GLM_MAX_ROWS, TF_GLM_WIDE_GRAPHS, TF_GLM_KV, TF_GLM_ASSISTANT_ENDS, "
+- "TF_GLM_DRAFT_PRELAUNCH): "
++ "TF_GLM_DRAFT_PRELAUNCH, TF_GLM_KV_SHARD): "
+ f"rank 0 {rows[0][:-1]}, " + ", ".join(f"rank {r} {rows[r][:-1]}" for r in odd) +
+ "; pull the draft model on every machine (or pass --drafter none to all) and give "
+ "every rank the same flags")
+@@ -792,6 +801,34 @@ class GlmEngine:
+ print("[tensorfold] the checkpoint's MTP head is not loaded (TF_GLM_MTP=" +
+ (os.environ.get("TF_GLM_MTP", "").strip() or MTP_DEFAULT) + "): " +
+ ("DFlash2 drafts every request" if drafter is not None else "--no-drafts"), flush=True)
++ if shard.ON: # TF_GLM_KV_SHARD: the latent cache once over the ranks
++ if parallel < 2 or pool_rows is None or world < 2 or os.environ.get("TF_GLM_MULTI_LONE", "0") == "1":
++ raise ValueError("TF_GLM_KV_SHARD=1 needs --parallel above 1, two ranks or more, and no "
++ "TF_GLM_MULTI_LONE")
++ dsa = len([l for l in w.layers if l.kind == "dsa"])
++ # a part's owner is ``base // HALF``: every rank must size the parts alike, and each computed the
++ # unsharded pool from its own KDA state size (they differ at three ranks): all take the smallest
++ pool_rows, display_rows = shard.agree(self._gather_ints([pool_rows, display_rows]))
++ unsharded = pool_rows
++ pool_rows, note = shard.plan(pool_rows, dsa, kv, self.limit, world, MAX_ROWS)
++ if display: # the reservation's bytes, at a sharded token's cost (never past the pool)
++ display_rows = max(0, pool_rows - shard.budget(unsharded - display_rows, dsa, kv, world))
++ same = self._gather_ints([pool_rows, display_rows])
++ if any(r != same[0] for r in same):
++ raise RuntimeError(f"TF_GLM_KV_SHARD: the ranks sized the sharded pool differently {same}")
++ if note and rank == 0:
++ print(f"[tensorfold] TF_GLM_KV_SHARD: {note}", flush=True)
++ from . import tp
++
++ shard.setup(rank, world, pool_rows, heads=[tp.of(w).at(r).heads for r in range(world)])
++ shard.warm(self.comm, w.device) # (TP3 and up: the pairs' send/recv connections now, not at a carry)
++ self.limit = min(self.limit, shard.HALF - MAX_ROWS) # (a stream lives in one part: what plan noted)
++ self.capacity_plan["context_window"] = self.limit
++ self.capacity_plan["pool_tokens"] = pool_rows
++ if rank == 0:
++ print(f"[tensorfold] TF_GLM_KV_SHARD: the latent cache once over the {world} ranks: a pool of "
++ f"{pool_rows} tokens in {world} parts of {shard.HALF} (unsharded {unsharded}), the same memory",
++ flush=True)
+ self.drafter = None
+ self.drafter_dir = drafter
+ if drafter is not None:
+diff --git tensorfold/families/glm5_next/cuda/forward.py tensorfold/families/glm5_next/cuda/forward.py
+index bbae712..e86b556 100644
+--- tensorfold/families/glm5_next/cuda/forward.py
++++ tensorfold/families/glm5_next/cuda/forward.py
+@@ -12,7 +12,7 @@ from tensorfold.cuda import experts as grouped
+ from tensorfold.cuda.geometry import MLA_PROMPT_ATT_ROWS as PROMPT_ATT_ROWS # a dense latent call's prompt rows
+ from tensorfold.cuda.kernels import prefill_attention, qmm as shared
+
+-from . import glue, kda as kda_mod, kv8, l2pf, latent, prof, qmm, sparse, tp
++from . import glue, kda as kda_mod, kv8, l2pf, latent, prof, qmm, shard, sparse, tp
+ from .attention import AttnScratch, attention, kv_write
+ from .weights import LayerW, Weights
+
+@@ -202,23 +202,28 @@ class Caches:
+ self.kv = kv
+ planes: list[Plane] = []
+ spanned: list[torch.Tensor] = []
++ sharded = shard.ON and shard.HALF > 0 # TF_GLM_KV_SHARD: the latent planes hold this rank's half
++ if sharded and not self.latent:
++ raise ValueError("TF_GLM_KV_SHARD=1 needs the latent cache")
+ if display:
+ if not self.latent:
+ raise ValueError("TF_GLM_DISPLAY_KV_MIB needs the latent cache (TF_GLM_LATENT=1)")
+ from . import display_kv
+
+- spanned = display_kv.latent_planes(dsa, rows, c.kv_lora, kv, dev, display)
++ # (sharded: the planes are a half and its trash rows long, the span the same bytes of the reservation)
++ spanned = display_kv.latent_planes(dsa, shard.HALF + shard.TRASH if sharded else rows, c.kv_lora, kv, dev,
++ display)
+
+- def add(shape, div: int = 1, pad: int = 0, fmt: str = "bf16", tensor=None) -> int:
+- n = rows // div + pad
++ def add(shape, div: int = 1, pad: int = 0, fmt: str = "bf16", tensor=None, half: bool = False) -> int:
++ n = shard.HALF + shard.TRASH if half else rows // div + pad
+ t = tensor if tensor is not None else (kv8.zeros(n, shape[0], fmt, dev) if fmt != "bf16" else
+ torch.zeros((n, *shape), dtype=torch.bfloat16, device=dev))
+- planes.append(Plane(t, div, pad, spanned=tensor is not None))
++ planes.append(Plane(t, div, pad, spanned=tensor is not None, shard=half))
+ return len(planes) - 1
+
+ def attention_planes() -> tuple[int, int | None]:
+ if self.latent: # one 512-wide latent a token and layer (kc), no separate values (vc)
+- return add((c.kv_lora,), fmt=kv, tensor=spanned.pop(0) if spanned else None), None
++ return add((c.kv_lora,), fmt=kv, tensor=spanned.pop(0) if spanned else None, half=sharded), None
+ return add((HL, c.qk_dim)), add((HL, c.v_dim))
+
+ self.kc, self.vc = [], []
+@@ -246,6 +251,9 @@ class Caches:
+ for _ in range(2)) for _ in range(n_idx)]
+ self.arena = Arena(rows, planes)
+ self.rows = rows
++ if sharded:
++ shard.ROW = kv8.row_bytes(c.kv_lora, kv)
++ shard.DTYPE = torch.uint8 if kv == "fp8" else torch.bfloat16
+
+ def index_tensors(self, i: int) -> tuple:
+ """Indexed layer i's (keys, gates, pooled keys) over every stream: the rings (or planes) and the pool plane."""
+@@ -267,7 +275,12 @@ class Caches:
+ """Point ``st``'s caches at tokens [base, base + size) of the pool."""
+
+ view = lambda i: None if i is None else self.arena.view(i, base, size) # noqa: E731
+- st.kc = [view(i) for i in self.kc]
++ tb = getattr(st, "twin_base", None) # TF_GLM_KV_SHARD: a filling prompt's rows in this rank's half
++ if tb is not None and getattr(st, "twin_size", size) != size: # (its twin has the extent's size: both
++ raise ValueError(f"a filling prompt's extent of {size} rows with a twin of {st.twin_size}") # hold it)
++ lat = view if tb is None or shard.owns(base) else (
++ lambda i: None if i is None else self.arena.view(i, tb, size)) # noqa: E731
++ st.kc = [lat(i) for i in self.kc]
+ st.vc = [view(i) for i in self.vc]
+ if self.mtp is not None:
+ st.mtp_kc, st.mtp_vc = view(self.mtp[0]), view(self.mtp[1])
+@@ -593,8 +606,9 @@ def dsa_front(layer: LayerW, w: Weights, b: Buffers, lo: int, hi: int) -> None:
+
+ def dsa_block(layer: LayerW, w: Weights, kc: torch.Tensor, vc: torch.Tensor, pos_dev: torch.Tensor, b: Buffers,
+ R: int, nch: int | None, index=None, host_pos: int | None = None,
+- sparse_np: int | None = None, done: tuple[int, int] | None = None) -> torch.Tensor:
+- """Write every index key and pool; rows past the dense limit attend to their top-512 pools (host_pos eager, or sparse_np in a captured graph). ``done``: rows ``dsa_front`` already ran on (TF_GLM_PREFILL_OVERLAP=2)."""
++ sparse_np: int | None = None, done: tuple[int, int] | None = None, twin: bool = False,
++ root: int = -1) -> torch.Tensor:
++ """Write every index key and pool; rows past the dense limit attend to their top-512 pools (host_pos eager, or sparse_np in a captured graph). ``done``: rows ``dsa_front`` already ran on (TF_GLM_PREFILL_OVERLAP=2). ``twin``: the stream's latents are on every rank (TF_GLM_KV_SHARD's twins); ``root``: the rank that owns them (sharded)."""
+
+ c = w.cfg
+ a = layer.dsa
+@@ -602,7 +616,8 @@ def dsa_block(layer: LayerW, w: Weights, kc: torch.Tensor, vc: torch.Tensor, pos
+ dsa_front(layer, w, b, lo, hi)
+ HL = a.heads
+ if a.absorb is not None:
+- return _dsa_latent(a, w, kc, pos_dev, b, R, nch, index, host_pos, sparse_np, layer=layer.index)
++ return _dsa_latent(a, w, kc, pos_dev, b, R, nch, index, host_pos, sparse_np, layer=layer.index, twin=twin,
++ root=root)
+ if sparse_np is not None:
+ raise ValueError("sparse CUDA graphs need the latent cache (TF_GLM_LATENT=1)")
+ mm(b, b.lat[:R], a.kv_k, b.xs_lat[:R], b.kn[:R].view(R, HL * c.qk_dim))
+@@ -660,15 +675,111 @@ def dense_attention(qa: torch.Tensor, lc: torch.Tensor, pos_dev: torch.Tensor, s
+
+
+ def _dsa_latent(a, w: Weights, lc: torch.Tensor, pos_dev: torch.Tensor, b: Buffers, R: int, nch: int | None,
+- index, host_pos: int | None, sparse_np: int | None = None, layer: int = -1) -> torch.Tensor:
++ index, host_pos: int | None, sparse_np: int | None = None, layer: int = -1,
++ twin: bool = False, root: int = -1) -> torch.Tensor:
+ """DSA on the latent cache: the same indexer and selection, attention over latents with kv_b's key blocks absorbed into the query."""
+
+- o = dsa_rows(a, w, lc, pos_dev, b, R, nch, index, host_pos, sparse_np, layer)
++ o = dsa_rows(a, w, lc, pos_dev, b, R, nch, index, host_pos, sparse_np, layer, twin=twin, root=root)
+ return out_proj(w, b, o, a.o, qmm.group_sums(o, b.xs_ao[:R]), R, site=(layer, "a"))
+
+
++def _sharded_rows(a, w, lc, pos_dev, b, R, nch, index, host_pos, sparse_np, rs, qa, ol, scale, all_sparse,
++ sparse_rows, root: int = -1) -> None:
++ """``dsa_rows``' attention with the latent cache sharded (TF_GLM_KV_SHARD): the owner of the stream (``lc`` its
++ view; None on the other rank) sends the history rows the chunk reads, and the other rank attends over a compact
++ copy of them and of the chunk's own rows (their token ids renumbered in order: the same keys in the same order,
++ so the same bits). Rows before the dense limit read the whole history at its positions."""
++
++ c = w.cfg
++ if host_pos is None:
++ raise RuntimeError("TF_GLM_KV_SHARD=1: a prompt chunk's position must be known on the host")
++ tokens = counts = None
++ if sparse_rows:
++ ix = a.index
++ with prof.timed("dsa: select tokens"):
++ mm(b, b.qr[rs], ix.qb, b.xs_qr[rs], b.qi[rs])
++ tokens, counts = sparse.select_tokens(b.qi[rs], b.ikr[rs, c.index_dim:], index[2], host_pos, R,
++ index[2].shape[0] - 2, pos_dev, bucket=sparse_np)
++ _sharded_attend(a, w, lc, pos_dev, b, R, nch, host_pos, rs, qa, ol, scale, all_sparse, sparse_rows, tokens, counts,
++ root)
++
++
++def _side_stream(b):
++ """The row split's side stream (its exchanges, and microbatching's other half's chain), if any."""
++
++ sp = getattr(b, "split", None)
++ return getattr(sp, "stream", None) if sp is not None else None
++
++
++def _sharded_attend(a, w, lc, pos_dev, b, R, nch, host_pos, rs, qa, ol, scale, all_sparse, sparse_rows, tokens,
++ counts, root: int = -1) -> None:
++ """``_sharded_rows`` after the token selection (``tokens`` / ``counts``: every row's, None without sparse rows),
++ shared with the own-row front (``own_front.rest``): the owner's history rows fetched, the chunk's own written into
++ the copy on the other ranks, the attention over it. The fetch is the only collective a prompt chunk runs on the
++ current stream: with a row split's side stream (its exchanges; with microbatching the other half's chain) it waits
++ for that stream and that stream for it, so two communicators never run at once (a deadlock risk on the ring, where
++ the side stream's exchanges use the neighbour links). Same bits: only the order of the streams changes."""
++
++ c = w.cfg
++ dev = qa.device
++ identity = not all_sparse
++ tok = tokens
++ if identity:
++ hist = torch.arange(host_pos, device=dev)
++ elif lc is not None:
++ hist, _ = shard.history(tokens[:R], host_pos, owner=True)
++ else: # the count (what arrives) and the tokens renumbered into the copy
++ hist, tok = shard.history(tokens[:R], host_pos, owner=False)
++ # (rows travel as bytes: a bf16 plane's row is 1,024 of them, an FP8 plane's 528, and the receiver views its copy
++ # back as the cache's type)
++ lcb = shard.as_bytes(lc)
++ rb = lcb.shape[1] if lcb is not None else shard.ROW
++ side = _side_stream(b) if torch.cuda.is_available() else None
++ if side is not None:
++ torch.cuda.current_stream().wait_stream(side)
++ with prof.timed("dsa: shard fetch"):
++ got = shard.fetch(w.comm, lcb, hist, rb, dev, extra=R, root=root)
++ if side is not None:
++ side.wait_stream(torch.cuda.current_stream())
++ att = lc
++ if lc is None: # the fetched rows, then the chunk's own (identity: at their positions)
++ n = hist if isinstance(hist, int) else int(hist.numel())
++ att = shard.as_cache(got)
++ if identity:
++ latent.latent_write(b.lat[rs], att, pos_dev)
++ else:
++ latent.latent_write(b.lat[rs], att[n:], torch.zeros_like(pos_dev))
++ if not all_sparse:
++ dense = dense_rows(c, R, host_pos) if sparse_rows else R
++ s = b.lat_s
++ with prof.timed("dsa: dense attention"):
++ dense_attention(qa[:dense], att, pos_dev, s, scale=scale, nch=min(nch or s.nch, s.nch), out=ol[:dense],
++ hb=latent.head_block(R), starts=b.att_starts if b.prefill else None)
++ if sparse_rows:
++ with prof.timed("dsa: sparse attention"):
++ _shard_sparse(qa, att, tok, counts, ol, scale, b.prefill)
++
++
++def _shard_sparse(qa, att, tok, counts, ol, scale, prefill: bool) -> None:
++ """The sharded rows' sparse attention with the unsharded path's kernel choice, so both give the same bits: a prompt
++ chunk through ``sparse_prompt`` where the base has it (tp4: TF_GLM_MSA, else sparse_onepass), else sparse_onepass
++ with TF_GLM_SPARSE_ONEPASS (main); a decode window through sparse_attention. A row's bits depend on its query, its
++ tokens and the keys only, so the owner's cache and the other ranks' compact copy agree."""
++
++ if prefill:
++ f = globals().get("sparse_prompt")
++ if f is not None:
++ f(qa, att, tok, counts, ol, scale)
++ return
++ if latent.SPARSE_ONEPASS:
++ latent.sparse_onepass(qa, att, tok, counts, ol, scale)
++ return
++ latent.sparse_attention(qa, att, tok, counts, ol, scale)
++
++
+ def dsa_rows(a, w: Weights, lc: torch.Tensor, pos_dev: torch.Tensor, b: Buffers, R: int, nch: int | None,
+- index, host_pos: int | None, sparse_np: int | None = None, layer: int = -1, lo: int = 0) -> torch.Tensor:
++ index, host_pos: int | None, sparse_np: int | None = None, layer: int = -1, lo: int = 0,
++ twin: bool = False, root: int = -1) -> torch.Tensor:
+ """``_dsa_latent`` up to its output projection, for rows lo .. lo + R of the buffers (their front done) on one
+ stream's caches (``lc``, ``index``, ``pos_dev``, ``host_pos``: its first row's position): the latent write,
+ indexer update, absorb, attention and expand; returns the rows' attention output [R, heads * v_dim] (b.vn's rows).
+@@ -679,8 +790,10 @@ def dsa_rows(a, w: Weights, lc: torch.Tensor, pos_dev: torch.Tensor, b: Buffers,
+ HL = a.heads
+ s = b.lat_s
+ rs = slice(lo, lo + R)
+- with prof.timed("dsa: latent write"):
+- latent.latent_write(b.lat[rs], lc, pos_dev)
++ sharded = shard.ON and w.comm is not None and not twin # (a twin: this rank's own copy, as unsharded)
++ if not sharded or lc is not None: # (sharded, not the owner: into its copy of the chunk's keys below)
++ with prof.timed("dsa: latent write"):
++ latent.latent_write(b.lat[rs], lc, pos_dev)
+ # sparse_np: every row is past the dense limit (a captured graph); else the host position decides
+ all_sparse = sparse_np is not None or (host_pos is not None and host_pos >= c.dense_limit)
+ sparse_rows = index is not None and (all_sparse or (host_pos is not None and host_pos + R - 1 >= c.dense_limit))
+@@ -696,6 +809,14 @@ def dsa_rows(a, w: Weights, lc: torch.Tensor, pos_dev: torch.Tensor, b: Buffers,
+ l2pf.site(layer, "o")
+ ol = s.ol[rs]
+ scale = c.qk_dim ** -0.5
++ if sharded and (host_pos is not None or lc is None):
++ if host_pos is not None:
++ _sharded_rows(a, w, lc, pos_dev, b, R, nch, index, host_pos, sparse_np, rs, qa, ol, scale, all_sparse,
++ sparse_rows, root)
++ else: # the one-stream graphs captured at start (served only by TF_GLM_MULTI_LONE, refused with the
++ ol.zero_() # shard): the rank without the rows captures no attention; its owner runs it as before
++ with prof.timed("dsa: expand"):
++ return latent.expand_v(ol, a.absorb, b.vn[rs], prompt=b.prefill and latent.PROMPT_MMA).view(R, HL * c.v_dim)
+ if not all_sparse:
+ # Rows past the dense limit are recomputed sparsely below, so the dense pass needs only the chunks up to it
+ # and only the rows before it (a row's dense bits do not depend on the rows after it: latent.attention).
+@@ -717,6 +838,13 @@ def dsa_rows(a, w: Weights, lc: torch.Tensor, pos_dev: torch.Tensor, b: Buffers,
+ return latent.expand_v(ol, a.absorb, b.vn[rs], prompt=b.prefill and latent.PROMPT_MMA).view(R, HL * c.v_dim)
+
+
++class _Lat:
++ """A decode window's latent write targets (``latent.seg_latent_write`` reads ``pos`` and ``base``)."""
++
++ def __init__(self, pos, base) -> None:
++ self.pos, self.base = pos, base
++
++
+ def dsa_segments(layer: LayerW, w: Weights, lc: torch.Tensor, b: Buffers, R: int, rows, sel=None, index=None, *,
+ select: bool = True) -> torch.Tensor | None:
+ """dsa_block on the latent cache for a multi-stream window (``rows``: segments.SegRows, already set): several
+@@ -736,8 +864,9 @@ def dsa_segments(layer: LayerW, w: Weights, lc: torch.Tensor, b: Buffers, R: int
+ HL = a.heads
+ mm(b, b.qr[:R], a.q_b, b.xs_qr[:R], b.q[:R].view(R, HL * c.qk_dim))
+ s = b.lat_s
+- with prof.timed("dsa: latent write"):
+- latent.seg_latent_write(b.lat[:R], lc, rows)
++ sharded = shard.ON and w.comm is not None
++ with prof.timed("dsa: latent write"): # (sharded: this rank's rows; the others' into its trash rows)
++ latent.seg_latent_write(b.lat[:R], lc, _Lat(rows.wpos, rows.lbase) if sharded else rows)
+ tokens = counts = None
+ if index is not None:
+ ik, ig, pk = index
+@@ -754,7 +883,10 @@ def dsa_segments(layer: LayerW, w: Weights, lc: torch.Tensor, b: Buffers, R: int
+ qa = latent.absorb_q(b.q[:R], a.absorb, s.qa[:R])
+ l2pf.site(layer.index, "o")
+ with prof.timed("dsa: attention"):
+- ol = latent.seg_attention(qa, lc, rows, tokens, counts, s, scale=c.qk_dim ** -0.5, out=s.ol[:R])
++ if sharded: # each row's owner computes its heads and the other rank's
++ ol = shard.attention(w.comm, qa, lc, rows, tokens, counts, s, scale=c.qk_dim ** -0.5, out=s.ol[:R], R=R)
++ else:
++ ol = latent.seg_attention(qa, lc, rows, tokens, counts, s, scale=c.qk_dim ** -0.5, out=s.ol[:R])
+ with prof.timed("dsa: expand"):
+ o = latent.expand_v(ol, a.absorb, b.vn[:R]).view(R, HL * c.v_dim)
+ return out_proj(w, b, o, a.o, qmm.group_sums(o, b.xs_ao[:R]), R, site=(layer.index, "a"))
+@@ -840,7 +972,9 @@ def _mixer(layer: LayerW, w: Weights, st: State, b: Buffers, R: int, nch: int |
+ di = st.dsa_index[layer.index]
+ with prof.timed("dsa (total)"):
+ return dsa_block(layer, w, st.kc[di], st.vc[di], st.pos_dev, b, R, nch,
+- st.index[di] if st.index is not None else None, host_pos, sparse_np, done)
++ st.index[di] if st.index is not None else None, host_pos, sparse_np, done,
++ twin=getattr(st, "twin_base", None) is not None,
++ root=shard.owner(st.base) if shard.ON and shard.HALF else -1)
+
+
+ def _ffn(layer: LayerW, w: Weights, b: Buffers, R: int, done: tuple[int, int] | None = None) -> torch.Tensor | None:
+diff --git tensorfold/families/glm5_next/cuda/multi.py tensorfold/families/glm5_next/cuda/multi.py
+index ef76005..26244ba 100644
+--- tensorfold/families/glm5_next/cuda/multi.py
++++ tensorfold/families/glm5_next/cuda/multi.py
+@@ -25,7 +25,7 @@ are balanced within the budget without adding rounds; GPU layer cost, finalizati
+ learned separately so extra slices cannot inflate every layer cost.
+
+ Rank 0 decides everything that depends on time, clients or placement; rank 1 applies it. Each iteration rank 0 sends
+-ONE message (``GlmEngine._share``): ops ADMIT, EVICT, MOVE, GROW, FILL, MFILL, FILLPART, MFILLPART, ROUND, FINISH, IDLE, which both ranks apply
++ONE message (``GlmEngine._share``): ops ADMIT, EVICT, MOVE, XMOVE, GROW, FILL, MFILL, FILLPART, MFILLPART, ROUND, FINISH, IDLE, which both ranks apply
+ in order through the same code (rank 0 as it decides them). Rank 1 derives drafts itself and checks the depths rank 0
+ sent. An idle rank 1 waits on the doorbell (``GlmEngine._await_bell``), not in an all-gather. After an error the two
+ ranks cannot be trusted to agree: ``broken`` latches and every later call fails until both restart.
+@@ -51,16 +51,16 @@ from tensorfold.cuda.scheduler import Scheduler
+ from tensorfold.server.errors import CapacityError # TFCAP-0075
+ from tensorfold.cuda.streams import Stream, next_fill
+
+-from . import multi_prefill, sliced_fill
++from . import multi_prefill, shard, sliced_fill
+ from .multi_tune import MultiSettings, RoundProfile, allocate, reach_of, sample_packed, scaled_confidence
+ 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, LOADED, \
+- HAS, LOADPART = range(1, 18)
++ HAS, LOADPART, UNTWIN, XMOVE = range(1, 20)
+ 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", LOADED: "LOADED", HAS: "HAS", LOADPART: "LOADPART"}
++ FLUSH: "FLUSH", LOADED: "LOADED", HAS: "HAS", LOADPART: "LOADPART", UNTWIN: "UNTWIN", XMOVE: "XMOVE"}
+ # 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
+
+@@ -231,6 +231,62 @@ def kept_bytes_cap() -> int:
+ KEPT_BYTES_CAP = kept_bytes_cap()
+
+
++def kv_carry(value: str | None = None) -> bool:
++ """TF_GLM_KV_SHARD_CARRY (default 1; 0 = off, every decision as before the carry existed): with TF_GLM_KV_SHARD, a
++ request that resumes from a kept state may have the state's rows carried into another part (``Arena.carry``)
++ instead of being forced into the state's part, but only to avoid a real cost, never to even the parts out: when
++ that part has no room beside the state (the hit used to be dropped and the whole prompt prefilled again), when
++ fitting the request there would evict kept states while another part has the room free, or when the other parts'
++ free rows spare evicting other conversations' states from the shared rows (``MultiDecoder._place_hit``); and a
++ live stream that cannot grow in its part moves whole to one that has room (XMOVE) instead of pausing. Rank 0
++ decides, so only its setting matters; every rank applies a carry it is sent."""
++
++ raw = (os.environ.get("TF_GLM_KV_SHARD_CARRY", "") if value is None else value).strip() or "1"
++ if raw not in ("0", "1"):
++ raise ValueError(f"TF_GLM_KV_SHARD_CARRY: 0 or 1, not {raw!r}")
++ return raw == "1"
++
++
++KV_CARRY = kv_carry()
++# A hit of at least this many tokens (one pool block) is carried, a smaller one never: a smaller one saves under a second of prefill
++# (~0.45 ms a token measured at 205k) and a carry has costs a small state does not repay -- the flush, a send and a
++# receive per sharded plane and the wait for them, during which no lane decodes. (A fixed number, not a setting.)
++CARRY_MIN = 2048
++CARRY_LOG = 8192 # rank 0 logs a carry of this many tokens or more, one line each
++# a live stream that has moved is not moved again, nor back into the part it left, and no stream leaves a part another
++# one entered, for this many decode rounds. A round is a token or so a stream (~20-40 ms), so 256 rounds are ~5-10 s:
++# an order of magnitude over what a carry costs (~0.1-0.5 s at 200k tokens), so a stream that moves pays for itself
++# before it can move again, and the headroom a move needs in its target (a block for each stream the part holds) is
++# hundreds of rounds of growth. (A fixed number, not a setting.)
++RELOCATE_HOLD = 256
++
++
++def shard_tune(tune):
++ """The settings the decoder runs with: TF_GLM_MULTI_LONE is on by default (``MultiSettings``), but a lone stream
++ moves home to the pool's first rows and its one-stream graphs bake the extent's base, which the shard refuses (an
++ explicit LONE=1 is refused at start), so with the shard on it is off, whatever the default says. Left on, it also
++ switched off the shared-rows copy and the carry beside it (``_place``)."""
++
++ if not shard.ON or not tune.lone or not KV_CARRY: # (TF_GLM_KV_SHARD_CARRY=0: the decoder as before the carry)
++ return tune
++ import dataclasses
++
++ return dataclasses.replace(tune, lone=False)
++
++
++def carry_stats() -> dict:
++ """/health's ``carry`` (kv_shard): admissions that carried a kept state into another part (``hits``, by the rule
++ that chose it: ``rescued`` where its own part had no room, so the hit would have been dropped; ``pressure`` where
++ fitting the request there would have evicted kept states and another part had the room free; ``others`` where the
++ other parts' free rows spared evicting other conversations' states), live streams moved (``live``), the tokens and
++ bytes sent, the time (ms, the transfer's, of every carry and the longest), and the carries not made, by why
++ (``refused``)."""
++
++ return {"hits": 0, "rescued": 0, "pressure": 0, "others": 0, "live": 0, "tokens": 0, "bytes": 0,
++ "ms_total": 0.0, "ms_max": 0.0,
++ "refused": {"pinned": 0, "twin": 0, "loading": 0, "partial": 0, "no_target": 0, "small": 0}}
++
++
+ def known_key(c):
+ """A kept state's key as an int64 array, converted once: every admission scans all of ``kept`` for the prefix a
+ new prompt shares, and rebuilding the array each time cost O(kept states x their tokens) a request."""
+@@ -519,6 +575,10 @@ class Lane:
+ 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)
++ twin: Any = None # TF_GLM_KV_SHARD: the extents its filling prompt borrows in the other parts
++ xwhy: str | None = None # rank 0: why its last move to another part was refused (counted once a reason)
++ moved_at: int = -(1 << 30) # rank 0: the decode round (``xticks``) it last moved to another part in
++ came_from: int = -1 # ...and the part it left then
+ decoding: bool = False
+ paused: bool = False
+ t0: float = 0.0
+@@ -562,7 +622,9 @@ class MultiDecoder:
+ if self.window < streams:
+ raise ValueError(f"a verify window of {self.window} rows cannot hold {streams} streams' pending tokens")
+ self.rows_max = e.rows # a stream's window (decode.MAX_ROWS)
+- self.pool = Pool(e.caches.rows)
++ from . import shard
++
++ self.pool = Pool(e.caches.rows, half=shard.HALF if shard.ON else 0)
+ self.arena = e.caches.arena
+ self.grid = engine.grid
+ self.fill_rows = fill_rows(e.prefill_rows, self.grid)
+@@ -602,7 +664,7 @@ class MultiDecoder:
+ verify = SerialVerify(e, taps=self.drafts is not None)
+ self.verify = verify
+ # speed settings (multi_tune): the sampler's gathers, the drafts' depth, async messages, the profile
+- self.tune = tune if tune is not None else MultiSettings.from_env()
++ self.tune = shard_tune(tune if tune is not None else MultiSettings.from_env())
+ self.profiles = None
+ if self.tune.profile and self.rank == 0:
+ self.profiles = {False: RoundProfile(self.tune.profile, label="batched"),
+@@ -626,6 +688,11 @@ class MultiDecoder:
+ 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.twins = {"made": 0, "revoked": 0} # TF_GLM_KV_SHARD: prompts filled with borrowed rows
++ self.no_part = 0 # TF_GLM_KV_SHARD: placements refused (no part could make room)
++ self.carry = carry_stats() # TF_GLM_KV_SHARD_CARRY: hits and live streams moved across parts
++ self.xticks = 0 # rank 0: decode rounds decided (the moves' cooldown counts them)
++ self.entered: dict[int, int] = {} # rank 0: part -> the round a live stream last moved into it
+ 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
+@@ -657,12 +724,36 @@ class MultiDecoder:
+ def live(self) -> int:
+ return len(self.lanes)
+
++ def _shard_health(self) -> dict:
++ """TF_GLM_KV_SHARD: each part's rows (free, live streams', kept prompts', twins') and this rank's prompt-chunk
++ fetches (``shard.STATS``)."""
++
++ pool = self.pool
++ parts = []
++ for h in range(pool.parts):
++ xs = [x for x in pool.extents if pool.half_of(x) == h]
++ pin = self._pinned() # (room a request can get: free rows and revocable twins, per segment)
++ segs, room = pool.segments(h, pin), pool.segment_free(h, pin)
++ for x in xs:
++ i = pool.segment_of(segs, x.base)
++ if i >= 0 and x.twin:
++ room[i] += x.size
++ parts.append({"free": pool.free_rows(h), "gatherable": max(room, default=0),
++ "live_rows": sum(x.size for x in xs if x.owner is not None),
++ "kept_rows": sum(x.size for x in xs if x.owner is None and not x.twin),
++ "twin_rows": sum(x.size for x in xs if x.twin), "live": pool.live(h)})
++ return {"parts": parts, "fetch": dict(shard.STATS), "refused_no_part": self.no_part,
++ "carry": dict(self.carry, ms_total=round(self.carry["ms_total"], 1), ms_max=round(self.carry["ms_max"], 1),
++ refused=dict(self.carry["refused"]))}
++
+ def health(self) -> dict:
+ lanes = list(self.lanes.values())
+ return {"streams": {"decoding": sum(l.decoding and not l.paused for l in lanes),
+ "filling": sum(not l.decoding for l in lanes),
+ "paused": sum(l.decoding and l.paused for l in lanes)},
+ "pool_tokens": self.pool.rows, "pool_free_tokens": self.pool.free_rows(),
++ "kv_shard_twins": dict(self.twins, held=sum(1 for l in lanes if l.twin is not None)),
++ "kv_shard": self._shard_health() if self.pool.half else None,
+ "kept_prompts": len(self.kept),
+ # streams that continued their conversation without resuming from its own turn state (a rewind before
+ # its kept states, or they were dropped or read back from disk), and the tokens those prefilled
+@@ -869,6 +960,8 @@ class MultiDecoder:
+ if op == MFILLPART and (len(p) < 5 or p[0] < 1 or len(p) != 3 + 2 * p[0]
+ or not 0 <= p[1] < p[2]):
+ raise RuntimeError("invalid MFILLPART payload")
++ if op == XMOVE and len(p) != 4:
++ raise RuntimeError("invalid XMOVE payload")
+ ops.append((op, p))
+ i += 2 + n
+ return ops
+@@ -879,13 +972,29 @@ class MultiDecoder:
+
+ def fits(self, s: Stream) -> bool:
+ """Whether ``s`` can be placed now (else it waits, in order, for streams to finish): the free rows and the
+- kept-only extents cover its prompt, with a block of headroom for each decoding stream to grow into."""
++ kept-only extents cover its prompt, with a block of headroom for each decoding stream to grow into. With parts
++ (TF_GLM_KV_SHARD) in one of them, and in one segment of it (the rows between pinned twins: a twin is no room
++ and the extents around it do not pass it). Only the twins ``_room`` cannot give back are pinned here (a fill part
++ way through its layers); the others count as room, since ``_room`` and ``_grow`` revoke them first."""
+
+ if not self.lanes:
+ return True # everything can be evicted; a prompt past the pool fails in ``admit``
+ need = self._need(len(s.prompt))
+- room = self.pool.free_rows() + sum(x.size for x in self.pool.extents if x.owner is None)
+- return room >= need + ALIGN * sum(l.decoding for l in self.lanes.values())
++ pool, pin = self.pool, self._pinned()
++ for h in range(pool.parts) if pool.half else [None]:
++ segs = pool.segments(h, pin)
++ room, busy = pool.segment_free(h, pin), [0] * len(segs)
++ for x in pool.extents:
++ i = pool.segment_of(segs, x.base)
++ if i >= 0 and x.owner is None: # (kept prompts and revocable twins; a pinned twin is in no segment)
++ room[i] += x.size
++ for l in self.lanes.values():
++ i = pool.segment_of(segs, l.extent.base)
++ if i >= 0 and l.decoding:
++ busy[i] += 1
++ if any(r >= need + ALIGN * b for r, b in zip(room, busy)):
++ return True
++ return False
+
+ def admit(self, s: Stream) -> None:
+ """Rank 0: place a request (slot, extent; resumed from the longest kept prefix of its prompt when it drafts)
+@@ -933,36 +1042,7 @@ class MultiDecoder:
+ if s.vision is not None: # encoded before anything is sent: a failure stops here
+ feed = self._encode(s.vision, encoded_from)
+ need = self._need(len(prompt))
+- # placement: take a kept extent over in place, or copy its rows into a new one while a stream writes in it
+- copy = 0
+- base = None
+- if hit is not None and hit.extent.owner is None:
+- x = hit.extent
+- # kept prompts the stream would overwrite: another conversation's longer states in the same rows (a shared
+- # system prompt's state lives in the extent of the conversation that wrote it). Copy the shared rows into
+- # an extent of their own instead, so that conversation keeps its state. Only into free rows: evicting other
+- # conversations to make room would cost more than it saves, so then the rows are overwritten as before.
+- # Not with TF_GLM_MULTI_LONE=1: the copy, decoding alone, would move home to the pool's first rows and evict
+- # the writer's whole extent there, the shared state included.
+- others = [c for c in x.kept if len(c.ids) > len(hit.ids) and key[:len(c.ids)] != c.key]
+- if others and not self.tune.lone:
+- base = self.pool.place(need)
+- copy = int(base is not None)
+- if base is None:
+- for c in others:
+- self._evict(c)
+- if self._grow(x, need, protect=[x]):
+- base = x.base
+- else:
+- hit = None
+- if base is None:
+- base = self._room(need, [hit.extent] if hit is not None else [])
+- if base is None and hit is not None: # no room beside the kept rows: start fresh
+- hit = None
+- base = self._room(need)
+- if base is None:
+- raise NoRoom(f"no room for a {need}-token extent in the {self.pool.rows}-token pool now")
+- copy = int(hit is not None)
++ base, copy, hit = self._place_hit(hit, need, key)
+ if s.vision is not None and hit is None and encoded_from:
+ feed = None # (its rows freed before the tower runs again)
+ feed = self._encode(s.vision, 0) # the kept state was given up: every picture, from the prompt's start
+@@ -983,13 +1063,265 @@ class MultiDecoder:
+ payload += [len(packed), *packed, len(positions), *positions, int(s.vision is not None),
+ *pack_keys(vrows, vkeys, vpos)]
+ self._emit(ADMIT, payload)
++ if copy == 2 and self.carry_kind: # (counted once the ADMIT is queued: a placement that failed earlier is not)
++ self.carry[self.carry_kind] += 1
+ try:
++ if copy == 2: # a carry is a collective: the other ranks hold this ADMIT before rank 0 sends
++ self._sync()
+ self._admitted(self._parse_admit(payload), s, feed, s.constraint, info.get("spec", ""))
+ except Exception as exc: # rank 1 applies the same ADMIT: the ranks may no longer agree
+ self._break(exc)
+ raise
+ self.lanes[sid].key = key
+
++ carry_kind = None # rank 0: which rule chose the carry ``_place_hit`` just decided (counted at the ADMIT)
++
++ def _place_hit(self, hit, need: int, key) -> tuple[int, int, Any]:
++ """Rank 0: where a request's extent goes and how its rows get there -> (base, copy, hit). ``copy`` 0: the request
++ takes the kept extent over in place; 1: the hit's rows are copied into a new extent of its part while a stream
++ writes in it; 2 (TF_GLM_KV_SHARD_CARRY): they are carried into a new extent in ANOTHER part (``Arena.carry``, a
++ collective: ``admit`` flushes the ADMIT before it runs). ``hit`` comes back None when the hit was given up and
++ the whole prompt prefills (nothing to resume from, or no room for it anywhere).
++
++ Without parts, or with the carry off, every decision is the one made before the carry existed. With parts a
++ carry is made only to avoid a real cost, and never when the hit's part fits the request without evicting
++ anything, however empty another part is: (1) the hit's part has no free rows for the copy that spares other
++ conversations' longer states from being overwritten: free rows of another part take it, before those states
++ are evicted (``_free_elsewhere``); (2) fitting the request in its part would evict kept states (or cannot be
++ done), and another part has the room free, plus headroom for the streams it holds, with no eviction there
++ (``_pressed``); (3) where the hit used to be DROPPED (and the prompt recomputed -- ~93 s at 205k tokens),
++ another part's room, evicting there as the drop would have, keeps it (``_rescue``). A hit under ``CARRY_MIN``
++ tokens is never carried. Host-side arithmetic over the parts, nothing on the common path. A carry wanted and
++ refused is counted once a reason (``carry.refused``), however many of the rules asked; the rule that chose a
++ carry is left in ``carry_kind`` for ``admit`` to count once the ADMIT is queued."""
++
++ why: set[str] = set()
++ self.carry_kind = None
++ try:
++ return self._place(hit, need, key, why)
++ finally:
++ for w in sorted(why):
++ self._refused(w)
++
++ def _place(self, hit, need: int, key, why: set) -> tuple[int, int, Any]:
++ pool = self.pool
++ sharded = KV_CARRY and bool(pool.half)
++ copy = 0
++ base = None
++ others: list = []
++ if hit is not None and hit.extent.owner is None:
++ x = hit.extent
++ # kept prompts the stream would overwrite: another conversation's longer states in the same rows (a shared
++ # system prompt's state lives in the extent of the conversation that wrote it). Copy the shared rows into
++ # an extent of their own instead, so that conversation keeps its state. Only into free rows: evicting other
++ # conversations to make room would cost more than it saves, so then the rows are overwritten as before.
++ # Not with TF_GLM_MULTI_LONE=1: the copy, decoding alone, would move home to the pool's first rows and evict
++ # the writer's whole extent there, the shared state included.
++ others = [c for c in x.kept if len(c.ids) > len(hit.ids) and key[:len(c.ids)] != c.key]
++ if others and not self.tune.lone:
++ base = pool.place(need, half=pool.half_of(x) if pool.half else None)
++ copy = int(base is not None)
++ if base is None and sharded: # its part is full: free rows of another carry them instead
++ base = self._free_elsewhere(hit, need, why)
++ if base is not None:
++ copy = 2
++ self.carry_kind = "others"
++ if base is None and hit is not None and sharded:
++ base = self._pressed(hit, need, others, why)
++ if base is not None:
++ copy = 2
++ if base is None and hit is not None and hit.extent.owner is None:
++ x = hit.extent
++ # (with parts a grow that cannot work is not tried: ``_grow`` evicts every kept prompt it may before it gives
++ # up, and the rescue below keeps the hit without that)
++ grown = False
++ if not sharded or self._grow_fits(x, need):
++ for c in others:
++ self._evict(c)
++ grown = self._grow(x, need, protect=[x])
++ if grown:
++ base = x.base
++ elif not sharded:
++ hit = None
++ if base is None:
++ part = pool.half_of(hit.extent) if hit is not None and pool.half else None
++ spent = self.no_part
++ base = self._room(need, [hit.extent] if hit is not None else [], half=part)
++ if base is None and hit is not None: # no room beside the kept rows
++ refused = self.no_part
++ got = self._rescue(hit, need, why) if sharded else None
++ if sharded: # (counted as the old code did: the refusal of a part's own
++ self.no_part = spent if got is not None or hit.extent.owner is None else refused # attempt, once)
++ if got is not None: # ...but another part has it: the hit stays, its rows travel
++ return got[0], got[1], hit
++ hit = None # start fresh
++ base = self._room(need)
++ if base is None:
++ raise NoRoom(f"no room for a {need}-token extent in the {pool.rows}-token pool now")
++ copy = int(hit is not None)
++ return base, copy, hit
++
++ def _fits_unevicted(self, hit, need: int, others: list) -> bool:
++ """Rank 0, read only: whether the hit's part places the request without evicting anything, by the paths the old
++ code takes: with other conversations' longer states in the hit's extent (the shared-rows copy), a single stretch
++ of free rows ``need`` long (the copy gathers nothing; with TF_GLM_MULTI_LONE they would be overwritten, an
++ eviction); otherwise the request takes the extent over in place -- a free stretch elsewhere in the part, or the
++ extent's own segment (the rows between pinned twins, free rows gathered by compacting) with its rows counted
++ free -- or, when a live stream holds the extent, copies beside it into free rows of any segment (gathered by
++ compacting). Twins that can be given back are not in the way; pinned ones cut the part."""
++
++ pool = self.pool
++ x = hit.extent
++ p = pool.half_of(x)
++ if others:
++ return not self.tune.lone and pool.place(need, half=p) is not None
++ pin = self._pinned()
++ loose = [y for y in pool.extents if y.twin and not pin(y)]
++ inplace = x.owner is None
++ if inplace and pool.place(need, ignore=[x] + loose, half=p) is not None:
++ return True
++ for lo, hi in pool.segments(p, pin):
++ if inplace and not lo <= x.base < hi:
++ continue
++ held = sum(y.size for y in pool.extents if lo <= y.base < hi and not y.twin and not (inplace and y is x))
++ if hi - lo - held >= need:
++ return True
++ return False
++
++ def _pressed(self, hit, need: int, others: list, why: set) -> int | None:
++ """Rank 0: the hit's part cannot place the request without evicting kept states (or at all): the rows of another
++ part that has ``need`` free plus a block for each stream it holds and the one arriving (``ALIGN * (live + 1)``:
++ what ``fits`` leaves a part's decoders, so the moved conversation is not the next to find it full), found without
++ evicting anything there (free rows, or gathered by compacting that part) -> its base, ``carry_kind`` set
++ ("rescued" where the hit's part could not have placed the request even by evicting: the hit would have been
++ dropped). None when its part has the room, the hit is under ``CARRY_MIN``, something pins its rows, or no
++ other part has it (the last two counted in ``why``)."""
++
++ if self._fits_unevicted(hit, need, others):
++ return None
++ if len(hit.ids) < CARRY_MIN:
++ why.add("small")
++ return None
++ pin = self._pins(hit.extent)
++ if pin is not None:
++ why.add(pin)
++ return None
++ pool = self.pool
++ p = pool.half_of(hit.extent)
++ for q in sorted((q for q in range(pool.parts) if q != p), key=lambda q: (pool.live(q), -pool.free_rows(q), q)):
++ want = need + ALIGN * (pool.live(q) + 1)
++ if pool.place(want, half=q) is not None or pool.compactable(q) >= want:
++ base = self._room_free(want, q)
++ if base is not None:
++ self.carry_kind = "pressure" if self._placeable(hit, need) else "rescued"
++ return base
++ why.add("no_target")
++ return None
++
++ def _placeable(self, hit, need: int) -> bool:
++ """Rank 0, read only: whether the hit's part could place the request at all, evicting what it may (else the hit
++ would be dropped)."""
++
++ x = hit.extent
++ if x.owner is None:
++ return self._grow_fits(x, need)
++ pool = self.pool
++ p = pool.half_of(x)
++ return (pool.place(need, half=p) is not None or self._gathered(need, p) is not False
++ or self._eviction_cost(need, [x], p) is not None)
++
++ def _pins(self, x) -> str | None:
++ """Rank 0: why the rows of extent ``x`` cannot be carried or moved to another part now (``carry.refused``'s
++ names), or None. ``loading``: a stored prompt is being read into it; ``pinned`` / ``twin``: it is a filling
++ prompt's borrowed rows (a pinned one is the fill part way through its layers), or its stream holds some -- the
++ stream's state points at them, and they exist in the part a carry would send the rows to as well; ``partial``:
++ its stream is in a prompt slice in flight, whose later layers write the rows its earlier ones read."""
++
++ if getattr(x, "loading", None) is not None:
++ return "loading"
++ if self._pinned()(x):
++ return "pinned"
++ lane = self.lanes.get(x.owner) if x.owner is not None else None
++ if x.twin or (lane is not None and lane.twin is not None):
++ return "twin"
++ if lane is not None and self.partial is not None and self.partial.contains(lane.sid):
++ return "partial"
++ return None
++
++ def _refused(self, why: str) -> None:
++ self.carry["refused"][why] += 1
++
++ def _room_free(self, need: int, part: int) -> int | None:
++ """Rank 0: a base for ``need`` rows in ``part`` without evicting anything: free rows, or those gathered by
++ compacting the part (MOVEs within it)."""
++
++ base = self.pool.place(need, half=part)
++ if base is None and self._gathered(need, part) is not False:
++ self._compact(half=part)
++ base = self.pool.place(need, half=part)
++ return base
++
++ def _free_elsewhere(self, hit, need: int, why: set) -> int | None:
++ """Rank 0: free rows for ``need`` in a part other than the hit's, the lightest first (no eviction, no
++ compaction: the others branch carries only where the copy is cheap); None when there are none, the hit is under
++ ``CARRY_MIN`` or something pins its rows (``why`` collects the reasons)."""
++
++ pool = self.pool
++ if len(hit.ids) < CARRY_MIN:
++ why.add("small")
++ return None
++ pin = self._pins(hit.extent)
++ if pin is not None:
++ why.add(pin)
++ return None
++ p = pool.half_of(hit.extent)
++ for q in sorted((q for q in range(pool.parts) if q != p), key=lambda q: (pool.live(q), -pool.free_rows(q), q)):
++ base = pool.place(need, half=q)
++ if base is not None:
++ return base
++ why.add("no_target")
++ return None
++
++ def _grow_fits(self, x, size: int, free=()) -> bool:
++ """Rank 0, read only: whether ``_grow`` could make extent ``x`` ``size`` rows in its part, evicting every kept
++ prompt it may and giving back the twins it can: whether some stretch of the part between pinned twins has that
++ many rows once the live streams' extents and the extents it cannot evict (a stored prompt being read into one)
++ are left out; ``x`` and the rows it holds count as free, and so do the extents in ``free`` (streams about to
++ move away). Never says no to a grow that would work."""
++
++ pool = self.pool
++ half = pool.half_of(x) if pool.half else None
++ gone = {id(y) for y in free}
++ for lo, hi in pool.segments(half, self._pinned()):
++ held = sum(y.size for y in pool.extents if y is not x and lo <= y.base < hi and not y.twin
++ and id(y) not in gone and (y.owner is not None or not y.kept))
++ if hi - lo - held >= size:
++ return True
++ return False
++
++ def _rescue(self, hit, need: int, why: set) -> tuple[int, int] | None:
++ """Rank 0: the hit's part has no room for ``need`` rows beside it, so the other parts are asked (evicting
++ there as dropping the hit would have, never the hit's own extent) -> (base, copy) with copy 2 when the room is
++ in another part: its rows are carried and the prompt resumes instead of prefilling again (``carry_kind``
++ "rescued"). None (counted) when the hit is under ``CARRY_MIN``, something pins its rows, or no part has the
++ room either."""
++
++ if len(hit.ids) < CARRY_MIN:
++ why.add("small")
++ return None
++ pin = self._pins(hit.extent)
++ if pin is not None:
++ why.add(pin)
++ return None
++ base = self._room(need, [hit.extent])
++ if base is None:
++ why.add("no_target")
++ return None
++ if self.pool.half_of(base) == self.pool.half_of(hit.extent):
++ return base, 1
++ self.carry_kind = "rescued"
++ return base, 2
++
+ def _encode(self, prepared, cut: int):
+ """Rank 0: the tower's rows of the pictures a prompt resumed at ``cut`` still fills (those whose rows end past
+ it), as a VisionFeed; None when the kept state already holds them all."""
+@@ -1063,7 +1395,11 @@ class MultiDecoder:
+ self._rewrites(x, cut)
+ else:
+ x = self.pool.add(a["base"], a["size"])
+- if hit is not None:
++ if a["copy"] == 2 and hit is None:
++ raise RuntimeError(f"stream {a['sid']}: a carry (copy 2) of no kept prompt")
++ if hit is not None and a["copy"] == 2: # another part: its owner's rows travel (rank 0 flushed first)
++ self._carry(hit.extent.base, x.base, cut, "admit")
++ elif hit is not None:
+ self.arena.copy(hit.extent.base, x.base, cut)
+ x.owner = a["sid"]
+ st = State(self.w, x.size, e.rows, caches=e.caches, base=x.base, slots=e.slots, slot=a["slot"])
+@@ -1113,6 +1449,25 @@ class MultiDecoder:
+
+ own = f"{self.boot}-{a['sid']}"
+ lane.lineage = fork(hit.lineage, own, cut) if getattr(hit, "lineage", "") else own
++ if hit is None and shard.ON and self.pool.half:
++ twins = [] # one in every other part, all or none; free rows only (every rank
++ for p in range(self.pool.parts): # places alike)
++ if p == self.pool.half_of(x):
++ continue
++ tb = self.pool.place(x.size, half=p)
++ if tb is None:
++ break
++ twins.append(self.pool.add(tb, x.size, twin=True))
++ if len(twins) == self.pool.parts - 1:
++ lane.twin = twins
++ mine = [t for t in twins if self.pool.half_of(t) == shard.RANK]
++ st.twin_base = mine[0].base if mine else twins[0].base # (the owner: only a flag)
++ st.twin_size = x.size
++ st.bind(x.base, x.size)
++ self.twins["made"] += 1
++ else:
++ for t in twins:
++ self.pool.remove(t)
+ self.next_sid = max(self.next_sid, a["sid"] + 1)
+ self.next_order += 1
+ s.sid, s.cached = a["sid"], cut
+@@ -1136,7 +1491,7 @@ class MultiDecoder:
+ raise RuntimeError(f"the kept prompt {a['kid']} is the whole prompt of stream {a['sid']} but "
+ f"kept no head row")
+ lane.head = hit.head.clone()
+- self._touch(hit)
++ self._recent(hit, a["copy"])
+ # where its prompt states are kept: the grid point (or the end) and rank 0's shared-prefix points
+ if a["draft"]:
+ lane.point = grid_point(len(prompt), cut, self.grid)
+@@ -1193,6 +1548,17 @@ class MultiDecoder:
+ def _touch(self, c) -> None:
+ self.kept = [k for k in self.kept if k is not c] + [c]
+
++ def _recent(self, hit, copy: int) -> None:
++ """Both ranks: a request just resumed from ``hit``, which becomes the most recently used kept state -- except a
++ conversation's OWN turn state that the request carried into another part (``copy`` 2): the carried rows are the
++ conversation's now (its next turn resumes from the state kept where they are), so the old copy keeps its place
++ in the order and is the first the LRU reclaims in its part. A shared prefix is touched as ever: it stays for
++ the other conversations that resume from it."""
++
++ if copy == 2 and getattr(hit, "own", False):
++ return
++ self._touch(hit)
++
+ def _keep(self, lane: Lane, n: int, head=None, own: bool = False) -> None:
+ """Both ranks: the lane's state at prompt position n (== its pos) becomes a kept prompt in its extent;
+ ``head``: at the prompt's end, the logits row its first token is sampled from (kept for a replay);
+@@ -1381,12 +1747,14 @@ class MultiDecoder:
+ drafter = getattr(self.g, "drafter", None)
+ model = os.path.basename(str(getattr(self.g, "model_dir", "")).rstrip("/"))
+ # what the stored bits depend on: build and runtime, drafter, KV and dense formats, TP layout, plane shapes,
+- # grid, and the settings every rank agreed at start
++ # grid, and the settings every rank agreed at start; TF_GLM_KV_SHARD's points hold a rank's part of the
++ # latents, another layout than an unsharded run's (it would read them as corrupt and drop them), so a store
++ # of their own (appended only when on: an unsharded run keeps its store)
+ signature = "|".join(["multi", build_id(self.g.model_dir, self.g.drafter_dir),
+ "" if drafter is None else type(drafter).__name__,
+ 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)])
++ repr(self.g.agreed)] + ([f"kvshard{self.pool.parts}"] if shard.ON else []))
+ self.loads: dict = {} # load id -> a stored prompt being read into a new extent
+ self.next_lid = 0
+ self.load_budget = float(os.environ.get("TF_GLM_SPILL_LOAD_MS") or LOAD_MS_DEFAULT) / 1000.0
+@@ -1420,9 +1788,9 @@ class MultiDecoder:
+ self._release_rows(x, 0)
+ return remove(x)
+
+- def g_move(x, base, size=None):
+- self._release_rows(x, None)
+- return move(x, base, size)
++ def g_move(x, base, size=None, cross=False):
++ self._release_rows(x, 0 if cross else None) # (another part's owner would stage a waiting write's rows)
++ return move(x, base, size, cross)
+
+ def g_resize(x, size):
+ self._release_rows(x, size)
+@@ -1473,6 +1841,18 @@ class MultiDecoder:
+ return "no_draft_window"
+ return None
+
++ def _lineage(self, c) -> str:
++ """The lineage a kept state's blocks are named by: its own, and with parts (TF_GLM_KV_SHARD) the part its extent
++ lies in. A part's owner writes the latent rows and the other ranks only the pooled keys, so one name could
++ be two different blocks on a rank once a conversation can change part (``Arena.carry``): the owner of its new
++ part would find the old part's blocks, by name, already on disk and skip writing the rows it alone holds. Every
++ sharded store is named this way, carried or not (names do not depend on whether a state ever moved), and an
++ unsharded store's names are as they were."""
++
++ from tensorfold.cuda.spill_blocks import in_part
++
++ return in_part(c.lineage, self.pool.half_of(c.extent)) if self.pool.half else c.lineage
++
+ 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)."""
+@@ -1482,9 +1862,10 @@ class MultiDecoder:
+ self.disk.unwritten(why)
+ return
+ try:
+- self.disk.persist(self._ident(c), c, extent=c.extent, lineage=c.lineage,
++ self.disk.persist(self._ident(c), c, extent=c.extent, lineage=self._lineage(c),
+ tokens=c.ids if c.images else None, shared=bool(c.shared), head=c.head is not None,
+- skip=self._SPILL_SKIP)
++ skip=self._SPILL_SKIP,
++ fields={"half": self.pool.half_of(c.extent)} if self.pool.half else None)
+ 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)
+ self.disk.unwritten("failed")
+@@ -1539,7 +1920,13 @@ class MultiDecoder:
+ self.disk.stats["has_refused"] += 1 # a rank lacks it (lost, damaged, evicted there)
+ return None
+ size = align_up(pt.n)
+- base = self._room(size, [hit.extent] if hit is not None else [])
++ half = None
++ if self.pool.half: # TF_GLM_KV_SHARD: back into the half whose rank holds its latents
++ half = (pt.fields or {}).get("half")
++ if half is None: # (a point an unsharded run wrote: counted, never silent)
++ self.disk.stats["refused_half"] = self.disk.stats.get("refused_half", 0) + 1
++ return None
++ base = self._room(size, [hit.extent] if hit is not None else [], half=half)
+ if base is None:
+ self._sync()
+ return None
+@@ -1713,9 +2100,13 @@ class MultiDecoder:
+ f"{time.perf_counter() - t:.1f}s{'' if ok else ' (not finished)'}", flush=True)
+
+ # -- room --------------------------------------------------------------------------------------------------------------
+- def _used(self, x) -> int:
++ def _used(self, x, pending: bool = True) -> int:
++ """The rows of extent x in use. ``pending=False`` (XMOVE) leaves out the spill tier's waiting writes, which each
++ rank advances on its own: a cross-part move first copies their blocks to the host (``BlockStore.release``), so
++ those rows never need to travel, and what remains (kept prompts, the stream's position, a read, a pending fill)
++ is the same on every rank."""
+ 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
++ if pending and 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)
+@@ -1729,6 +2120,8 @@ class MultiDecoder:
+ """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``)."""
+
++ if x.twin: # a twin's rows are where its filling prompt's state reads them: never moved
++ raise RuntimeError(f"extent {x.eid} is a twin of a filling prompt: it is pinned, not moved")
+ used = self._used(x)
+ 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():
+@@ -1737,55 +2130,221 @@ class MultiDecoder:
+ if x.owner is not None:
+ self.lanes[x.owner].st.bind(x.base, x.size)
+
++ def _carry(self, src: int, dst: int, n: int, kind: str) -> None:
++ """Both ranks: tokens [src, src + n) of an extent in one part into [dst, dst + n) in another (``Arena.carry``:
++ the two owners send and receive, every rank copies what it holds whole), counted for /health and, from
++ ``CARRY_LOG`` tokens, logged by rank 0. ``kind`` "admit": a request resuming from a kept state (the source stays);
++ "live": a live stream's extent on its way (``_xmove``). Waits for the transfer: both ranks are in it, rank 0
++ flushed the op that names it first. The time is the transfer's: measured by the ranks that send or receive
++ (a rank owning neither part only copies pooled keys, and would report ~0), and with three ranks or more the
++ longest of them, through one all-gather every rank joins."""
++
++ pool = self.pool
++ a, b = pool.half_of(src), pool.half_of(dst)
++ if a == b:
++ raise RuntimeError(f"rank {self.rank}: a carry from pool row {src} to {dst} stays in part {a}")
++ timed = torch.cuda.is_available() and self.rank in (a, b)
++ t0 = time.perf_counter()
++ if timed:
++ e0, e1 = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
++ e0.record()
++ self.arena.carry(src, dst, n, self.g.comm)
++ if timed:
++ e1.record()
++ e1.synchronize()
++ ms = e0.elapsed_time(e1)
++ else:
++ ms = (time.perf_counter() - t0) * 1000.0 if self.rank in (a, b) else 0.0
++ if self.w.world > 2:
++ ms = max(r[0] for r in self.g._gather_ints([int(ms * 1000)])) / 1000.0
++ c = self.carry
++ c["hits" if kind == "admit" else "live"] += 1
++ c["tokens"] += n
++ c["bytes"] += self.arena.sharded_bytes(n)
++ c["ms_total"] += ms
++ c["ms_max"] = max(c["ms_max"], ms)
++ if self.rank == 0 and n >= CARRY_LOG:
++ print(f"[tensorfold] kv shard carry ({kind}): {n} tokens, part {a} -> {b}, {ms:.1f} ms", flush=True)
++
++ def _xmove(self, x, base: int, size: int, used: int) -> None:
++ """Both ranks (XMOVE): extent x, its kept prompts with it, to [base, base + size) in ANOTHER part, its ``used``
++ rows carried (``_carry``: the source rows free as the extent leaves them; stream order puts any later writer after
++ the sends). ``used`` is rank 0's (the op carries it), counted without the spill tier's waiting writes
++ (``_used(pending=False)``): the same count on every rank, so both owners send and receive the same rows. Nothing
++ here refuses after rank 0 has emitted the op (a follower that raised would leave rank 0 in its send). The spill tier
++ first: a state of x waiting to be written still reads its rows from the old part's owner, so those blocks go to the
++ host now (``BlockStore.release``, through the pool's guard on a cross move); what is written afterwards names the
++ new part (``in_part``)."""
++
++ if x.twin or getattr(x, "loading", None) is not None:
++ raise RuntimeError(f"extent {x.eid} is a twin or being read into: it is pinned, not moved across parts")
++ if used > size: # (rank 0's own arguments: checked before anything is sent)
++ raise RuntimeError(f"rank {self.rank}: XMOVE of extent {x.eid} carries {used} rows of {size}")
++ old = self.pool.move(x, base, size, cross=True)
++ self._carry(old, base, used, "live")
++ if x.owner is not None:
++ self.lanes[x.owner].st.bind(x.base, x.size)
++
++ def _untwin(self, lane: Lane) -> None:
++ """Both ranks: the lane's twin rows back to the pool; its prompt fills on as sharded (the owner holds every row
++ the twin did)."""
++
++ if lane.twin is None:
++ raise RuntimeError(f"rank {self.rank}: stream {lane.sid} has no twin to give back")
++ for t in lane.twin:
++ self.pool.remove(t)
++ lane.twin = None
++ lane.st.twin_base = lane.st.twin_size = None
++ lane.st.bind(lane.extent.base, lane.extent.size)
++
++ def _pinned(self):
++ """Which extents ``_revoke_twins`` cannot give back now: the twins of the fill part way through its layers
++ (a predicate on extents, for ``Pool.segments``)."""
++
++ pending = self.partial
++ held = {id(t) for l in self.lanes.values() if l.twin is not None and pending is not None
++ and pending.contains(l.sid) for t in l.twin}
++ return lambda x: id(x) in held
++
++ def _revoke_twins(self, half: int | None) -> bool:
++ """Rank 0: every twin in ``half`` (None: all) given back before rows there are made by evicting or moving.
++ A fill part way through its layers keeps its twin to the end (its remaining layers would read a different
++ binding than the first ones wrote; no byte-equality run covers that yet): the twin is pinned meanwhile, so
++ the extents around it move and it does not (``Extent.twin``, ``_compact``)."""
++
++ pending = self.partial
++ lanes = [l for l in self.lanes.values() if l.twin is not None and
++ (half is None or any(self.pool.half_of(t) == half for t in l.twin)) and
++ (pending is None or not pending.contains(l.sid))]
++ for l in lanes:
++ self._emit(UNTWIN, [l.sid])
++ self._untwin(l)
++ self.twins["revoked"] += 1
++ return bool(lanes)
++
+ def _resize(self, x, size: int) -> None:
+ self.pool.resize(x, size)
+ if x.owner is not None:
+ self.lanes[x.owner].st.bind(x.base, x.size)
+
+- def _victims(self, protect) -> list:
++ def _victims(self, protect, half: int | None = None) -> list:
++ """Kept prompts that may be evicted, least recently used first; with halves (TF_GLM_KV_SHARD) and ``half``,
++ only those in it (evicting in the other half frees nothing where the rows are needed)."""
++
+ keep = set(id(x) for x in protect)
+- return [c for c in self.kept if c.extent.owner is None and id(c.extent) not in keep]
++ return [c for c in self.kept if c.extent.owner is None and id(c.extent) not in keep
++ and (half is None or not self.pool.half or self.pool.half_of(c.extent) == half)]
++
++ def _eviction_cost(self, need: int, protect, half: int):
++ """Rank 0, with halves: evicting the least recently used kept prompts of ``half`` until it has ``need`` free
++ rows, the place in the kept order (the recency) of the newest one that takes: -1 when none is needed, None
++ when even all of them leave too little. An extent's rows come free as ``_settle`` frees them, in its segment
++ (the rows between pinned twins: compaction gathers no further)."""
++
++ segs, free = self.pool.segments(half), self.pool.segment_free(half)
++ if max(free, default=0) >= need:
++ return -1
++ left = {id(x): list(x.kept) for x in self.pool.extents}
++ size = {id(x): x.size for x in self.pool.extents}
++ for i, c in enumerate(self.kept):
++ x = c.extent
++ if x.owner is not None or any(x is y for y in protect) or self.pool.half_of(x) != half:
++ continue
++ ks = left[id(x)] = [k for k in left[id(x)] if k is not c]
++ new = min(size[id(x)], align_up(max(len(k.ids) for k in ks))) if ks else 0
++ i = self.pool.segment_of(segs, x.base)
++ assert i >= 0, f"kept extent {x.eid} at {x.base} lies in no segment (inside a twin?)"
++ free[i] += size[id(x)] - new
++ size[id(x)] = new
++ if max(free) >= need:
++ return i
++ return None
+
+- def _compact(self, grow=None) -> None:
++ def _cheaper_half(self, need: int, protect) -> int | None:
++ """Rank 0, with halves: the half where making ``need`` rows evicts only older kept prompts (the newest one it
++ takes less recently used), so a placement evicts as little, and as old, as one pool would."""
++
++ costs = [(c, h) for h in range(self.pool.parts) if (c := self._eviction_cost(need, protect, h)) is not None]
++ return min(costs)[1] if costs else None
++
++ def _compact(self, grow=None, half: int | None = None) -> None:
+ """Rank 0: slide every extent down to the lowest free rows (MOVEs), so the free rows are one range; with
+ ``grow``, only the extents up to it slide down and the ones after it up to the pool's end, so that range
+- follows ``grow`` (each extent moves once at most)."""
+-
+- at = 0
++ follows ``grow`` (each extent moves once at most). With halves (TF_GLM_KV_SHARD): within ``half`` (grow's),
++ around the pinned twins (a filling prompt's borrowed rows): they stay where they are, and what slides stays
++ on its side of each, so a segment's free rows are what gathers."""
++
++ if grow is not None and self.pool.half:
++ half = self.pool.half_of(grow)
++ lo = half * self.pool.half if half is not None and self.pool.half else 0
++ hi = lo + self.pool.half if half is not None and self.pool.half else self.pool.rows
++ at = lo
+ for x in list(self.pool.extents):
++ if not lo <= x.base < hi:
++ continue
+ if grow is not None and x.base > grow.base:
+ break
++ if x.twin:
++ at = x.end
++ continue
+ if x.base != at:
+ self._emit(MOVE, [x.eid, at, x.size])
+ self._move(x, at, x.size)
+ at += x.size
+ if grow is None:
+ return
+- top = self.pool.rows
++ top = hi
+ for x in reversed(list(self.pool.extents)):
++ if not lo <= x.base < hi:
++ continue
+ if x is grow:
+ break
++ if x.twin:
++ top = x.base
++ continue
+ top -= x.size
+ if x.base != top:
+ self._emit(MOVE, [x.eid, top, x.size])
+ self._move(x, top, x.size)
+
+- def _room(self, need: int, protect=()) -> int | None:
++ def _gathered(self, need: int, half: int | None):
++ """Rank 0: where ``need`` free rows exist, just not together, and compacting gathers them (around pinned
++ twins): None (the pool), a half (``half``, or either, with halves), or False."""
++
++ if not self.pool.half:
++ return None if self.pool.compactable() >= need else False
++ for h in ([half] if half is not None else range(self.pool.parts)):
++ if self.pool.compactable(h) >= need:
++ return h
++ return False
++
++ def _room(self, need: int, protect=(), half: int | None = None) -> int | None:
+ """Rank 0: a base with ``need`` free rows, evicting kept prompts (least recently used first, never
+ ``protect``'s extents) only while the free rows fall short of ``need``, then compacting if they are not
+ together: moving rows costs far less than prefilling an evicted conversation again. None if even evicting
+- every other kept prompt leaves too little."""
+-
+- base = self.pool.place(need)
++ every other kept prompt leaves too little (with halves: in any part, in which case none is evicted)."""
++
++ base = self.pool.place(need, half=half)
++ if base is None and self.pool.half and self._revoke_twins(half):
++ base = self.pool.place(need, half=half)
++ if base is None and self.pool.half and self._gathered(need, half) is False:
++ if half is None:
++ half = self._cheaper_half(need, protect) # evict in one half only, the one losing the oldest states
++ elif self._eviction_cost(need, protect, half) is None:
++ half = None
++ if half is None:
++ self.no_part += 1
++ return None # no part can make the room: evicting would only lose states
+ while base is None:
+- if self.pool.free_rows() >= need:
+- self._compact()
+- return self.pool.place(need)
+- victims = self._victims(protect)
++ h = self._gathered(need, half)
++ if h is not False:
++ self._compact(half=h)
++ return self.pool.place(need, half=h)
++ victims = self._victims(protect, half)
+ if not victims:
+ break
+ self._evict(victims[0])
+- base = self.pool.place(need)
++ base = self.pool.place(need, half=half)
+ return base
+
+ def _grow(self, x, size: int, protect=()) -> bool:
+@@ -1801,19 +2360,110 @@ class MultiDecoder:
+ self._emit(GROW, [x.eid, size])
+ self._resize(x, size)
+ return True
+- base = self.pool.place(size, ignore=[x])
++ hx = self.pool.half_of(x) if self.pool.half else None
++ base = self.pool.place(size, ignore=[x], half=hx)
++ if base is None and self.pool.half and self._revoke_twins(hx):
++ continue
+ if base is not None:
+ self._emit(MOVE, [x.eid, base, size])
+ self._move(x, base, size)
+ return True
+- if self.pool.free_rows() + x.size >= size:
++ if self.pool.segment_room(x) + x.size >= size:
+ self._compact(grow=x) # the rows are free, just not together: gathered right after x
+ continue
+- victims = self._victims(protect)
++ victims = self._victims(protect, hx)
+ if not victims:
+ return False
+ self._evict(victims[0])
+
++ def _legal(self, lane: Lane, part: int) -> bool:
++ """Rank 0: whether live stream ``lane`` (in ``part``) may move now: nothing pins its rows (``_pins``) and it has
++ not moved for ``RELOCATE_HOLD`` rounds."""
++
++ return (self._pins(lane.extent) is None and lane.decoding and not lane.s.done
++ and self.xticks - lane.moved_at >= RELOCATE_HOLD)
++
++ def _move_to(self, lane: Lane, size: int) -> int | None:
++ """Rank 0: the part a live stream of ``lane``'s part would move to, for an extent of ``size`` rows: one that has
++ them free (or gathered by compacting it) plus a block for every stream it holds and the one arriving, never the
++ part the stream just left (within ``RELOCATE_HOLD`` rounds); the lightest, then the one with more free rows."""
++
++ pool = self.pool
++ p = pool.half_of(lane.extent)
++ fit = []
++ for q in range(pool.parts):
++ if q == p or (lane.came_from == q and self.xticks - lane.moved_at < RELOCATE_HOLD):
++ continue
++ want = size + ALIGN * (pool.live(q) + 1)
++ if pool.place(want, half=q) is not None or pool.compactable(q) >= want:
++ fit.append(q)
++ return min(fit, key=lambda q: (pool.live(q), -pool.free_rows(q), q)) if fit else None
++
++ def _move_lane(self, lane: Lane, size: int, q: int) -> bool:
++ """Rank 0: XMOVE ``lane``'s extent into part ``q``, ``size`` rows with the headroom ``_move_to`` found."""
++
++ pool = self.pool
++ x = lane.extent
++ p = pool.half_of(x)
++ base = self._room_free(size + ALIGN * (pool.live(q) + 1), q)
++ if base is None:
++ return False
++ used = self._used(x, pending=False)
++ if used > size:
++ return False
++ self._emit(XMOVE, [x.eid, base, size, used])
++ self._sync() # a carry is a collective: rank 1 holds the op before rank 0 sends
++ self._xmove(x, base, size, used)
++ lane.moved_at, lane.came_from, lane.xwhy = self.xticks, p, None
++ self.entered[q] = self.xticks
++ return True
++
++ def _relocate(self, lane: Lane) -> bool:
++ """Rank 0: a decoding stream whose extent cannot grow in its part (``_grow`` failed, so every kept prompt it
++ could evict there is gone already) would pause -- and, if every stream pauses, be given back and prefilled
++ again. Instead a stream moves whole, its kept prompts with it, to a part that has the room free (XMOVE) -- the
++ cheapest way to give it the room: of this stream and the other live streams of its part whose leaving lets it
++ grow (``_grow_fits``), the one with the fewest rows to carry, if it may move (``_legal``) and a part has the
++ room for it with headroom (``_move_to``). No stream moves out of a part another entered in the last
++ ``RELOCATE_HOLD`` rounds, nor twice in that time, nor back: moves do not answer one another. When none can,
++ it pauses as before. Refused (counted once per reason a stream, not once per round it waits) when something
++ pins its rows (``_pins``) or no move is safe; True once ``lane`` can grow."""
++
++ pool = self.pool
++ if not (KV_CARRY and pool.half):
++ return False
++ x = lane.extent
++ p = pool.half_of(x)
++ size = max(align_up(lane.st.pos + self.rows_max), x.size)
++ why = self._pins(x)
++ options = [] # (rows to carry, 0: the stream itself, stream, extent size, part)
++ if self.xticks - self.entered.get(p, -(1 << 30)) >= RELOCATE_HOLD:
++ if why is None and self._legal(lane, p):
++ q = self._move_to(lane, size)
++ if q is not None:
++ options.append((self._used(x, pending=False), 0, lane, size, q))
++ for m in self.lanes.values():
++ if m is lane or pool.half_of(m.extent) != p or not self._legal(m, p):
++ continue
++ msize = max(align_up(m.st.pos + self.rows_max), m.extent.size)
++ q = self._move_to(m, msize)
++ if q is not None and self._grow_fits(x, size, free=[m.extent]):
++ options.append((self._used(m.extent, pending=False), 1, m, msize, q))
++ for _, _, m, msize, q in sorted(options, key=lambda o: o[:2]):
++ if not self._move_lane(m, msize, q):
++ continue
++ # one carry a relocation: a bystander moved, the stream grows where it is or pauses this round as before
++ # (``_grow_fits`` only promises not to refuse a grow that works, so its yes can still fail here)
++ if m is lane or self._grow(x, lane.st.pos + self.rows_max, protect=[x]):
++ lane.xwhy = None
++ return True
++ break
++ why = why or "no_target"
++ if lane.xwhy != why:
++ self._refused(why)
++ lane.xwhy = why
++ return False
++
+ # -- iterations ---------------------------------------------------------------------------------------------------------
+ @torch.no_grad()
+ def round(self) -> list[Stream]:
+@@ -1896,8 +2546,14 @@ class MultiDecoder:
+ return [lane.s] if lane.s.done else []
+ lanes = [l for l in self.lanes.values() if l.decoding and not l.s.done]
+ t_begin = time.perf_counter()
++ self.xticks += 1
+ for l in lanes: # room for this round's widest window, else paused
+- l.paused = not self._grow(l.extent, l.st.pos + self.rows_max, protect=[l.extent])
++ ok = self._grow(l.extent, l.st.pos + self.rows_max, protect=[l.extent])
++ if ok:
++ l.xwhy = None
++ elif KV_CARRY and self.pool.half:
++ ok = self._relocate(l) # (TF_GLM_KV_SHARD: another part may have the room)
++ l.paused = not ok
+ active = [l for l in lanes if not l.paused]
+ if not active:
+ done = []
+@@ -2134,6 +2790,8 @@ class MultiDecoder:
+
+ from .copy_drafts import CopyDrafts
+
++ if lane.twin is not None: # decode windows read the owner's rows only
++ self._untwin(lane)
+ s = lane.s
+ prompt = s.prompt
+ lane.decoding = True
+@@ -2423,6 +3081,8 @@ class MultiDecoder:
+ for retired in pending.retired - {sid}:
+ self._finish(retired)
+ lane = self.lanes.pop(sid)
++ if lane.twin is not None: # ended while its prompt filled
++ self._untwin(lane)
+ x = lane.extent
+ x.owner = None
+ self._settle(x)
+@@ -2531,8 +3191,16 @@ class MultiDecoder:
+ self._do_flush(p)
+ elif op == MOVE:
+ self._move(self.pool.get(p[0]), p[1], p[2])
++ elif op == XMOVE:
++ self._xmove(self.pool.get(p[0]), p[1], p[2], p[3])
+ elif op == GROW:
+ self._resize(self.pool.get(p[0]), p[1])
++ elif op == UNTWIN:
++ lane = self.lanes.get(p[0])
++ if lane is None or lane.twin is None:
++ raise RuntimeError(f"rank {self.rank}: UNTWIN of stream {p[0]}, which "
++ + ("is not live" if lane is None else "has no twin"))
++ self._untwin(lane)
+ elif op == FILL:
+ lane = self.lanes[p[0]]
+ if p[1] != self._stop_bound(lane, p[1]):
+diff --git tensorfold/families/glm5_next/cuda/multi_prefill.py tensorfold/families/glm5_next/cuda/multi_prefill.py
+index 474753d..be1112e 100644
+--- tensorfold/families/glm5_next/cuda/multi_prefill.py
++++ tensorfold/families/glm5_next/cuda/multi_prefill.py
+@@ -113,7 +113,7 @@ class PieceMixer:
+ def __call__(self, layer, done: tuple[int, int] | None = None):
+ from . import prof
+ from .forward import chunks_for, dsa_front, dsa_rows, kda_front, kda_rows, out_proj, undone
+- from . import qmm
++ from . import qmm, shard
+
+ w, b, R = self.w, self.b, self.R
+ if layer.kind == "kda":
+@@ -136,7 +136,9 @@ class PieceMixer:
+ st = p.st
+ di = st.dsa_index[layer.index]
+ dsa_rows(a, w, st.kc[di], st.pos_dev, b, p.rows, chunks_for(st, p.rows),
+- st.index[di] if st.index is not None else None, st.pos, None, layer.index, lo=p.lo)
++ st.index[di] if st.index is not None else None, st.pos, None, layer.index, lo=p.lo,
++ twin=getattr(st, "twin_base", None) is not None,
++ root=shard.owner(st.base) if shard.ON and shard.HALF else -1)
+ o = b.vn[:R].view(R, a.heads * c.v_dim)
+ return out_proj(w, b, o, a.o, qmm.group_sums(o, b.xs_ao[:R]), R, site=(layer.index, "a"))
+
+diff --git tensorfold/families/glm5_next/cuda/pool.py tensorfold/families/glm5_next/cuda/pool.py
+index 2f39307..7f04340 100644
+--- tensorfold/families/glm5_next/cuda/pool.py
++++ tensorfold/families/glm5_next/cuda/pool.py
+@@ -33,13 +33,20 @@ class Plane:
+ past the last token's. ``spanned``: in the display reservation's span (``display_kv``), whose two registrations
+ a memcpy may not cross, so its rows move by a kernel."""
+
+- def __init__(self, tensor, div: int = 1, pad: int = 0, spanned: bool = False) -> None:
++ def __init__(self, tensor, div: int = 1, pad: int = 0, spanned: bool = False, shard: bool = False) -> None:
+ self.tensor, self.div, self.pad, self.spanned = tensor, int(div), int(pad), bool(spanned)
++ self.shard = bool(shard) # TF_GLM_KV_SHARD: this rank's half of the pool only (``shard``)
+
+ def rows_for(self, tokens: int) -> int:
+ return tokens // self.div
+
+ def view(self, base: int, size: int):
++ if self.shard: # an extent of the other rank's half: no rows here
++ from . import shard
++
++ if not shard.owns(base):
++ return None
++ base = shard.local(base)
+ return self.tensor[base // self.div:(base + size) // self.div + self.pad]
+
+
+@@ -50,7 +57,12 @@ class Arena:
+ self.rows = int(rows)
+ self.planes = planes
+ for p in planes:
+- want = self.rows // p.div + p.pad
++ if p.shard:
++ from . import shard
++
++ want = shard.HALF + shard.TRASH
++ else:
++ want = self.rows // p.div + p.pad
+ if p.tensor.shape[0] != want:
+ raise ValueError(f"a plane of {p.tensor.shape[0]} rows over {self.rows} tokens (div {p.div}, pad "
+ f"{p.pad}): want {want}")
+@@ -77,44 +89,112 @@ class Arena:
+ if min(src, dst) < 0 or max(src, dst) + n > self.rows:
+ raise ValueError(f"a copy of {n} tokens from {src} to {dst} reaches outside the arena's {self.rows}")
+ for p in self.planes:
++ if p.shard: # this rank's half only; an extent never changes halves
++ from . import shard
++
++ if shard.owner(src) != shard.owner(dst):
++ raise ValueError(f"a copy from pool row {src} to {dst} crosses the halves (TF_GLM_KV_SHARD)")
++ if not shard.owns(src):
++ continue
++ a, b = shard.local(src), shard.local(dst)
++ _move(p.tensor, a, b, min(n, p.tensor.shape[0] - max(a, b)), p.spanned)
++ continue
+ a, b = src // p.div, dst // p.div
+ m = -(-n // p.div)
+ m = min(m, p.tensor.shape[0] - max(a, b))
+ _move(p.tensor, a, b, m, p.spanned)
+
++ def carry(self, src: int, dst: int, n: int, comm) -> None:
++ """``copy`` across parts (TF_GLM_KV_SHARD): tokens [src, src + n) of an extent in one part to [dst, dst + n)
++ in another, byte for byte (no conversion: the rows are viewed as bytes, a bf16 plane's included). What every
++ rank holds whole (the pooled keys, a last pool row still filling taken whole, the pad rows untouched) is
++ copied locally on every rank exactly as ``copy`` does; a sharded plane's rows live on the rank that owns
++ their part, so the source's owner sends them to the destination's (``shard.send_rows`` / ``recv_rows``: pieces
++ through the staging buffers, a plane in the display span by kernel on both sides, never a memcpy or a transport
++ on the span itself) and a rank that owns neither (TP3 and up) has nothing to do for them. A collective of the
++ two owners: every rank calls it with the same arguments in the same order (rank 0 flushes the op that names
++ it first, so the others are in it when it sends); the source's rows stay."""
++
++ if n <= 0:
++ return
++ if min(src, dst) < 0 or max(src, dst) + n > self.rows:
++ raise ValueError(f"a carry of {n} tokens from {src} to {dst} reaches outside the arena's {self.rows}")
++ from . import shard
+
+-def _move(t, a: int, b: int, m: int, spanned: bool = False) -> None:
+- """t[b:b + m] = t[a:a + m] (rows), safe when they overlap; ``spanned``: by a kernel, not a memcpy."""
++ so, do = shard.owner(src), shard.owner(dst)
++ if so == do: # one part: no rows to send
++ return self.copy(src, dst, n)
++ nc = getattr(comm, "nccl", comm)
++ relay = shard.relayed(nc) # a switchless ring: hop by hop over the neighbour links, every rank between
++ for p in self.planes: # the two owners passing each piece on (``shard.relay_rows``)
++ if not p.shard:
++ a, b = src // p.div, dst // p.div
++ _move(p.tensor, a, b, min(-(-n // p.div), p.tensor.shape[0] - max(a, b)), p.spanned)
++ elif relay:
++ rows = (_byte_rows(p, shard.local(src), n) if shard.RANK == so else
++ _byte_rows(p, shard.local(dst), n) if shard.RANK == do else None)
++ shard.relay_rows(nc, so, do, rows, n, _byte_rows(p, 0, 1).shape[1], p.tensor.device, p.spanned)
++ elif shard.RANK == so:
++ shard.send_rows(nc, do, _byte_rows(p, shard.local(src), n), p.spanned)
++ elif shard.RANK == do:
++ shard.recv_rows(nc, so, _byte_rows(p, shard.local(dst), n), p.spanned)
+
+- def put(dst, src):
+- if spanned: # the same bytes through an elementwise kernel
+- import torch
++ def sharded_bytes(self, n: int) -> int:
++ """Bytes ``carry`` of ``n`` tokens sends between the two owners (the sharded planes' rows)."""
+
+- torch.bitwise_or(src.view(torch.uint8), 0, out=dst.view(torch.uint8))
+- else:
+- dst.copy_(src)
++ return sum(n * p.tensor[0].numel() * p.tensor.element_size() for p in self.planes if p.shard)
++
++
++def _byte_rows(p: Plane, a: int, n: int):
++ """Rows [a, a + n) of sharded plane ``p`` (a row a token) as bytes [n, row bytes]: what travels, whatever the
++ cache's type (``shard.as_bytes``: a bf16 row is 1,024 bytes, an FP8 one 528)."""
++
++ import torch
++
++ if p.div != 1 or a < 0 or a + n > p.tensor.shape[0]:
++ raise ValueError(f"rows [{a}, {a + n}) of a sharded plane of {p.tensor.shape[0]} rows (div {p.div})")
++ return p.tensor[a:a + n].reshape(n, -1).view(torch.uint8)
++
++
++def put_rows(dst, src, spanned: bool = False) -> None:
++ """dst[:] = src (same shape, same bytes); ``spanned``: by a kernel, not a memcpy (the display span's two
++ registrations may not be crossed by one: rows in it never go through ``copy_`` or a transport directly)."""
++
++ if spanned: # the same bytes through an elementwise kernel
++ import torch
++
++ torch.bitwise_or(src.view(torch.uint8), 0, out=dst.view(torch.uint8))
++ else:
++ dst.copy_(src)
++
++
++def _move(t, a: int, b: int, m: int, spanned: bool = False) -> None:
++ """t[b:b + m] = t[a:a + m] (rows), safe when they overlap; ``spanned``: by a kernel, not a memcpy."""
+
+ gap = abs(a - b)
+ if gap >= m:
+- put(t[b:b + m], t[a:a + m])
++ put_rows(t[b:b + m], t[a:a + m], spanned)
+ return
+ step = gap
+ starts = range(0, m, step) if b < a else reversed(range(0, m, step))
+ for s in starts: # down: front to back; up: back to front
+ k = min(step, m - s)
+- put(t[b + s:b + s + k], t[a + s:a + s + k])
++ put_rows(t[b + s:b + s + k], t[a + s:a + s + k], spanned)
+
+
+ @dataclass(eq=False)
+ class Extent:
+ """Pool rows [base, base + size). ``owner``: the live stream writing into it (its sid), or None; ``kept``: the
+- kept prompts whose rows it holds (each a prefix of the rows)."""
++ kept prompts whose rows it holds (each a prefix of the rows). ``twin`` (TF_GLM_KV_SHARD): rows a filling prompt
++ borrows in a part that is not its own, written by that part's rank. It has no owner and keeps no prompt, but its
++ rows are live and the prompt's state points at them, so it is pinned: it never moves and never counts as room."""
+
+ base: int
+ size: int
+ eid: int = 0
+ owner: int | None = None
+ kept: list = field(default_factory=list)
++ twin: bool = False
+
+ @property
+ def end(self) -> int:
+@@ -128,10 +208,16 @@ class Pool:
+ """Extents over ``rows`` pool rows, host side only. Placement is lowest base first; every call is deterministic
+ in the calls before it, so two ranks making the same calls hold the same extents."""
+
+- def __init__(self, rows: int, align: int = ALIGN) -> None:
++ def __init__(self, rows: int, align: int = ALIGN, half: int = 0) -> None:
+ if rows <= 0 or rows % align:
+ raise ValueError(f"a pool of {rows} rows: a positive multiple of {align}")
+ self.rows, self.align = int(rows), int(align)
++ # TF_GLM_KV_SHARD: parts of ``half`` rows, one a rank (two halves at two ranks; 0: one pool); no extent
++ # crosses a part's end
++ self.half = int(half)
++ if self.half and (self.rows % self.half or self.half % align):
++ raise ValueError(f"a pool of {rows} rows in parts of {half}")
++ self.parts = self.rows // self.half if self.half else 1
+ self.extents: list[Extent] = [] # by base
+ self.next_id = 0
+
+@@ -149,24 +235,108 @@ class Pool:
+ at = max(at, x.end)
+ if at < self.rows:
+ out.append((at, self.rows - at))
+- return _merge(out)
+-
+- def free_rows(self) -> int:
+- return self.rows - sum(x.size for x in self.extents)
+-
+- def place(self, size: int, ignore: Iterable[Extent] = ()) -> int | None:
+- """The lowest base with ``size`` free rows (``ignore``'s rows free), or None."""
++ out = _merge(out)
++ if self.half: # cut at every part's end: a range of free rows lies in one part
++ cut = []
++ for base, n in out:
++ end = base + n
++ while base < end:
++ stop = min(end, (base // self.half + 1) * self.half)
++ cut.append((base, stop - base))
++ base = stop
++ out = cut
++ return out
++
++ def half_of(self, x) -> int:
++ """The half extent (or pool row) ``x`` lies in (0 without halves)."""
++ base = x if isinstance(x, int) else x.base
++ return base // self.half if self.half else 0
++
++ def live(self, half: int) -> int:
++ """Extents a live stream writes in, in ``half``."""
++ return sum(1 for x in self.extents if x.owner is not None and self.half_of(x) == half)
++
++ def free_rows(self, half: int | None = None) -> int:
++ if half is None or not self.half:
++ return self.rows - sum(x.size for x in self.extents)
++ return self.half - sum(x.size for x in self.extents if self.half_of(x) == half)
++
++ def place(self, size: int, ignore: Iterable[Extent] = (), half: int | None = None) -> int | None:
++ """The lowest base with ``size`` free rows (``ignore``'s rows free), or None. With halves: in ``half``, or
++ else in the half with fewer live streams first (each row's owner computes its decode attention, so the ranks'
++ shares of that stay even), then the one with more free rows."""
+
+ size = align_up(size, self.align)
+- for base, n in self.gaps(ignore):
+- if n >= size:
+- return base
++ gaps = self.gaps(ignore)
++ if not self.half:
++ order = [None]
++ elif half is not None:
++ order = [half]
++ else:
++ order = sorted(range(self.parts), key=lambda h: (self.live(h), -self.free_rows(h), h))
++ for h in order:
++ for base, n in gaps:
++ if n >= size and (h is None or self.half_of(base) == h):
++ return base
+ return None
+
++ def segments(self, half: int | None = None, pinned=None) -> list[tuple[int, int]]:
++ """The ranges of ``half`` (None: the pool) between its pinned twin extents, [lo, hi) by base: what compaction
++ slides extents down within (a twin never moves, so no extent passes one that way). ``pinned``: which extents
++ are (default: every twin; a caller that will give back the twins it can first passes the ones it cannot)."""
++
++ pin = pinned or (lambda x: x.twin)
++ lo, hi = (half * self.half, (half + 1) * self.half) if half is not None and self.half else (0, self.rows)
++ out, at = [], lo
++ for x in self.extents:
++ if pin(x) and lo <= x.base < hi:
++ if x.base > at:
++ out.append((at, x.base))
++ at = x.end
++ if at < hi:
++ out.append((at, hi))
++ return out
++
++ @staticmethod
++ def segment_of(segments: list[tuple[int, int]], base: int) -> int:
++ """The index in ``segments`` of the one holding pool row ``base`` (-1: none: a twin's, or another part's)."""
++
++ for i, (lo, hi) in enumerate(segments):
++ if lo <= base < hi:
++ return i
++ return -1
++
++ def segment_free(self, half: int | None = None, pinned=None) -> list[int]:
++ """The free rows of each of ``segments(half)``: what compacting gathers there into one range."""
++
++ segs = self.segments(half, pinned)
++ free = [hi - lo for lo, hi in segs]
++ for x in self.extents:
++ i = self.segment_of(segs, x.base)
++ if i >= 0:
++ free[i] -= x.size
++ return free
++
++ def compactable(self, half: int | None = None, pinned=None) -> int:
++ """The longest range of free rows ``half`` (None: the pool) can gather by compacting around its pinned twins:
++ the most free rows of any one segment (without twins, all the free rows of the half)."""
++
++ return max(self.segment_free(half, pinned), default=0)
++
++ def segment_room(self, x: Extent) -> int:
++ """The free rows of the segment ``x`` lies in: what ``x`` can grow by once compaction has gathered them after
++ it."""
++
++ half = self.half_of(x) if self.half else None
++ i = self.segment_of(self.segments(half), x.base)
++ return self.segment_free(half)[i] if i >= 0 else 0
++
+ def room_after(self, x: Extent) -> int:
+ """Free rows right after x (before the next extent or the pool's end)."""
+
+- nxt = min((y.base for y in self.extents if y.base >= x.end and y is not x), default=self.rows)
++ end = (self.half_of(x) + 1) * self.half if self.half else self.rows
++ nxt = min((y.base for y in self.extents if y.base >= x.end and y is not x), default=end)
++ nxt = min(nxt, end)
+ return nxt - x.end
+
+ def get(self, eid: int) -> Extent:
+@@ -176,15 +346,18 @@ class Pool:
+ raise KeyError(f"no extent {eid}")
+
+ # -- changes -------------------------------------------------------------------------------------------------
+- def add(self, base: int, size: int) -> Extent:
+- """A new extent at exactly [base, base + size) (rank 0's placement, applied on both ranks)."""
++ def add(self, base: int, size: int, twin: bool = False) -> Extent:
++ """A new extent at exactly [base, base + size) (rank 0's placement, applied on both ranks); ``twin``: a
++ filling prompt's borrowed rows (``Extent.twin``)."""
+
+ size = align_up(size, self.align)
+ if base % self.align or base < 0 or base + size > self.rows:
+ raise ValueError(f"extent [{base}, {base + size}) is not an aligned range of the {self.rows}-row pool")
+ if any(x.base < base + size and base < x.end for x in self.extents):
+ raise ValueError(f"extent [{base}, {base + size}) overlaps another")
+- x = Extent(base, size, self.next_id)
++ if self.half and self.half_of(base) != self.half_of(base + size - 1):
++ raise ValueError(f"extent [{base}, {base + size}) crosses the pool's halves")
++ x = Extent(base, size, self.next_id, twin=bool(twin))
+ self.next_id += 1
+ self.extents.append(x)
+ self.extents.sort(key=lambda y: y.base)
+@@ -204,15 +377,21 @@ class Pool:
+ raise ValueError("an extent keeps at least one aligned block")
+ x.size = size
+
+- def move(self, x: Extent, base: int, size: int | None = None) -> int:
++ def move(self, x: Extent, base: int, size: int | None = None, cross: bool = False) -> int:
+ """Place x at ``base`` (with ``size`` rows): the bookkeeping only (the caller copies the rows). Returns the old
+- base."""
++ base. With parts, an extent stays in its own (its rank holds its latents) unless ``cross``: the caller then
++ carries the rows to the other part's rank (``Arena.carry``; ``MultiDecoder._xmove``)."""
+
+ size = x.size if size is None else align_up(size, self.align)
++ if x.twin:
++ raise ValueError(f"extent {x.eid} is a twin: its rows are pinned, a filling prompt reads them in place")
+ if base % self.align or base < 0 or base + size > self.rows:
+ raise ValueError(f"extent [{base}, {base + size}) is not an aligned range of the pool")
+ if any(y is not x and y.base < base + size and base < y.end for y in self.extents):
+ raise ValueError(f"extent {x.eid} cannot move to [{base}, {base + size}): taken")
++ if self.half and (self.half_of(base) != self.half_of(base + size - 1) or
++ (self.half_of(base) != self.half_of(x) and not cross)):
++ raise ValueError(f"extent {x.eid} cannot move to [{base}, {base + size}): another half")
+ old = x.base
+ x.base, x.size = base, size
+ self.extents.sort(key=lambda y: y.base)
+diff --git tensorfold/families/glm5_next/cuda/segments.py tensorfold/families/glm5_next/cuda/segments.py
+index b8361aa..afea97e 100644
+--- tensorfold/families/glm5_next/cuda/segments.py
++++ tensorfold/families/glm5_next/cuda/segments.py
+@@ -55,7 +55,7 @@ class SegRows:
+ self.rows, self.max_segs = rows, max_segs
+ self.ring = ring
+ self.ring_rows = ring if ring is not None else self.NO_RING
+- n = 5 * rows + 4 * max_segs
++ n = 10 * rows + 4 * max_segs
+ pin = torch.cuda.is_available() and torch.device(device).type == "cuda"
+ self.host = torch.zeros((n,), dtype=torch.int32, pin_memory=pin)
+ self.dev = torch.zeros((n,), dtype=torch.int32, device=device)
+@@ -63,6 +63,13 @@ class SegRows:
+ o = 5 * rows
+ self.seg_start, self.seg_rows, self.seg_pbase, self.seg_pools = (
+ self.dev[o + i * max_segs:o + (i + 1) * max_segs] for i in range(4))
++ # TF_GLM_KV_SHARD (``shard``), per row: ``lbase`` (its stream in this rank's latent planes, or the trash rows
++ # past them), ``own`` (1: this rank owns its stream), ``sparse_eff`` (1 for a row it does not own: no key read),
++ # ``wpos`` (the row's position, or its index in the window for one it does not own: its trash row), ``orank``
++ # (the rank that owns it)
++ o2 = 5 * rows + 4 * max_segs
++ self.lbase, self.own, self.sparse_eff, self.wpos, self.orank = (self.dev[o2 + i * rows:o2 + (i + 1) * rows]
++ for i in range(5))
+ self.staged = torch.cuda.Event() if pin else None
+ self.R = 0
+ self.segments: list[tuple[int, int, int]] = []
+@@ -78,7 +85,13 @@ class SegRows:
+ if R > self.rows:
+ raise ValueError(f"a window of {R} rows, the tables hold {self.rows}")
+ rows, S = self.rows, self.max_segs
+- t = torch.zeros((5 * rows + 4 * S,), dtype=torch.int32).numpy()
++ t = torch.zeros((10 * rows + 4 * S,), dtype=torch.int32).numpy()
++ from . import shard
++
++ sharded = shard.ON and shard.HALF > 0
++ if sharded and R > shard.TRASH: # (a row it does not own writes to its own trash row: the window's index)
++ raise ValueError(f"a window of {R} rows, the sharded latent planes keep {shard.TRASH} trash rows")
++ o2 = 5 * rows + 4 * S
+ r = 0
+ for s, seg in enumerate(segments):
+ base, pos, n = seg[:3]
+@@ -99,6 +112,12 @@ class SegRows:
+ t[2 * rows + r + i] = s
+ t[3 * rows + r + i] = int(sparse_from is not None and q >= sparse_from)
+ t[4 * rows + r + i] = ibase
++ own = not sharded or shard.owns(base)
++ t[o2 + r + i] = (shard.local(base) if own else shard.HALF) if sharded else base
++ t[o2 + rows + r + i] = int(own)
++ t[o2 + 2 * rows + r + i] = t[3 * rows + r + i] if own else 1
++ t[o2 + 3 * rows + r + i] = q if own else r + i
++ t[o2 + 4 * rows + r + i] = shard.owner(base) if sharded else 0
+ last = pos + n - 1
+ o = 5 * rows
+ t[o + s] = r
+diff --git tensorfold/families/glm5_next/cuda/shard.py tensorfold/families/glm5_next/cuda/shard.py
+new file mode 100644
+index 0000000..9b7dcf0
+--- /dev/null
++++ tensorfold/families/glm5_next/cuda/shard.py
+@@ -0,0 +1,644 @@
++"""TF_GLM_KV_SHARD=1 (two ranks or more, --parallel above 1): the latent cache stored once instead of on every rank.
++
++The pool's rows are split in parts, one a rank (two halves at two ranks): an extent lives in one part
++(``Pool(half=...)``, a part's rows, never places one across a boundary) and the rank that part belongs to, its owner,
++holds the extent's latent rows; the other ranks hold none of them. The latent planes are sized for one half plus ``TRASH`` rows (where a non-owner's writes of a decode
++window's rows land). The pooled keys (6% of a token's bytes) stay on both ranks over the whole pool, so the token
++selection runs on both as before. A token then takes about half its bytes: the same memory holds ~1.9x the tokens.
++
++Attention reads every key of a row's stream, so it runs where the keys are:
++- a decode window (``forward.dsa_segments``): the ranks' absorbed queries are gathered, each row's owner computes all
++ 64 heads over it, and the other ranks' heads go back to them (``attention``; past two ranks one all-to-all);
++- a prompt chunk (``forward.dsa_rows``): the owner sends the history rows the chunk selects (their union, a fraction
++ of the history) and the other ranks attend over that compact copy for their own heads (``fetch``; past two ranks a
++ broadcast).
++Each head's attention is the same kernel over the same keys in the same order, so every output bit is the unsharded
++engine's (64 heads at once == 32 + 32; a compact copy, its token ids renumbered in order == the arena).
++
++A new prompt borrows rows when the other parts have them free: while it fills,
++every other rank writes its own copy of the prompt's latents into free rows of its part (twin extents, one a part,
++all or none, placed the same way on every rank when the stream is admitted), so both attend locally as unsharded and nothing is sent; the twin
++goes when the prompt is in (before the first decode round), when the stream ends, or as soon as rank 0 needs its rows
++for anything else (UNTWIN), unless the fill is part way through its layers (its remaining layers read the binding its
++first ones wrote): that twin is pinned, never moved (the prompt's state points at its rows) and never counted as room,
++and compaction goes around it. Only rows nobody holds are borrowed: a twin never evicts a kept prompt.
++
++A conversation can change part (``Arena.carry``, TF_GLM_KV_SHARD_CARRY): a request that resumes from a kept state in a
++part that is full (or busier than another) has the state's rows sent to the owner of a part with room, instead of
++recomputing the prompt (``send_rows`` / ``recv_rows``: the same pieces and staging buffers as the prompt-chunk fetch,
++point to point between the two owners), and a live stream that cannot grow in its part moves whole the same way.
++
++The spill tier stores what each rank holds: an extent's owner its latent and pooled-key rows, the other rank its
++pooled keys (and each its own small state); a point records its half, and a restore goes back into it.
++
++With the display reservation (TF_GLM_DISPLAY_KV_MIB) the first latent planes, each a half and its trash rows long, are
++carved from its span as unsharded (the pool's rows count its bytes at a sharded token's cost). Not with
++TF_GLM_MULTI_LONE, TF_GLM_MULTI_VERIFY=serial or one rank (refused at start: ``unsupported``).
++The same code serves main and the tp4 branch (#152). On tp4 its own-row prompt front and microbatching run with the
++shard (``own_front.rest`` through ``forward._sharded_attend``, the fetch ordered with the split's side stream), and on
++a switchless ring the carry is relayed hop by hop over the neighbour links (``relay_rows``); without those links
++(main) a carry goes straight from owner to owner. Tested on two Sparks (main) and on four on a ring (tp4); three are
++untested on hardware."""
++
++from __future__ import annotations
++
++import os
++from types import SimpleNamespace
++
++import torch
++import triton
++import triton.language as tl
++
++from tensorfold.cuda.comm import _DTYPES
++
++ON = os.environ.get("TF_GLM_KV_SHARD", "0") == "1"
++TRASH = 2048 # latent rows past a half: a non-owner's writes of a decode window's rows
++SEND_MIB = 64 # the owner's send buffer: fetched rows go in pieces of this many MiB
++
++RANK = 0
++WORLD = 2
++HALF = 0 # pool rows a part, one a rank: a half at two ranks (latent rows a rank: HALF + TRASH)
++HEADS: list = [] # every rank's attention heads (22/21/21 at three ranks)
++ROW = 0 # bytes of a latent row (set with the caches)
++DTYPE = torch.uint8 # the latent planes' type (set with the caches): a fetched copy is viewed as it
++STATS = {"fetches": 0, "identity": 0, "rows": 0, "bytes": 0} # this rank's prompt-chunk fetches (/health)
++_buf: dict = {}
++
++
++def setup(rank: int, world: int, pool_rows: int, heads=None) -> None:
++ """Every rank, once the pool is sized: ``pool_rows`` (every part) over ``world`` ranks; ``heads``: each rank's
++ attention heads (None: an even split)."""
++
++ global RANK, WORLD, HALF, HEADS
++ if world < 2:
++ raise ValueError(f"TF_GLM_KV_SHARD=1 shards the latent cache over two ranks or more, not {world}")
++ if pool_rows % (world * 2048):
++ raise ValueError(f"TF_GLM_KV_SHARD=1: a pool of {pool_rows} rows is not {world} parts of whole extents")
++ RANK, WORLD, HALF = int(rank), int(world), int(pool_rows) // int(world)
++ HEADS = [int(h) for h in heads] if heads is not None else []
++
++
++def owner(base: int) -> int:
++ """The rank holding the latent rows of the extent at pool row ``base``."""
++
++ return int(base) // HALF
++
++
++def owns(base: int) -> bool:
++ return owner(base) == RANK
++
++
++def local(base: int) -> int:
++ """Pool row ``base`` of an extent this rank owns, as a row of its latent planes."""
++
++ return int(base) - RANK * HALF
++
++
++def budget(pool_rows: int, dsa: int, kv: str, world: int = 2) -> int:
++ """The sharded pool's rows for the memory ``pool_rows`` unsharded rows of ``dsa`` latent planes and pooled-key
++ planes take: each token's latent once over the ``world`` ranks, its pooled keys on every one, ``TRASH`` latent
++ rows a rank (whole parts of extents; 0 when the memory does not hold the trash rows)."""
++
++ from . import kv8
++
++ align = world * 2048
++ lat, pk = kv8.row_bytes(512, kv), kv8.row_bytes(128, kv) / 4
++ mem = pool_rows * dsa * (lat + pk)
++ return max(0, int((mem - TRASH * dsa * lat) // (dsa * (lat / world + pk))) // align * align)
++
++
++def floor(capacity: int, world: int = 2) -> int:
++ """The fewest rows of a sharded pool whose parts each hold one stream's window (``capacity`` tokens)."""
++
++ align = world * 2048
++ return world * (-(-capacity // align) * align)
++
++
++def sizes(pool_rows: int, dsa: int, kv: str, capacity: int, world: int = 2) -> int:
++ """``budget``, at least ``floor`` (the rows past the memory then are the caller's to account for: ``plan`` is the
++ start-up's, which shrinks the window to a part instead)."""
++
++ return max(budget(pool_rows, dsa, kv, world), floor(capacity, world))
++
++
++MIN_PART = 131072 # tokens: a part smaller than this (or than a quarter of the window) is refused
++
++
++def plan(pool_rows: int, dsa: int, kv: str, limit: int, world: int, max_rows: int) -> tuple[int, str]:
++ """The start-up's sharded pool: (rows, a note for the log or ""). The memory ``pool_rows`` unsharded rows take
++ holds ``budget`` sharded ones, never more. A stream lives in one part, so a part smaller than the requested window
++ (``limit`` tokens) shortens what a request may use to what a part holds (``part - max_rows``: the engine's limit,
++ which admit and ``generate`` already cite): the note says so, with the numbers. That happens by a few thousand
++ tokens when the memory read at start is a little low (a first start that compiles extensions just before). A part
++ below ``MIN_PART`` (131,072: the smallest window the recipe suggests) or a quarter of the window is refused, since
++ the server would then serve a fraction of what was asked."""
++
++ rows = budget(pool_rows, dsa, kv, world)
++ part = rows // world
++ effective = min(int(limit), part - int(max_rows))
++ if effective >= limit:
++ return rows, ""
++ if effective < 1 or part < max(MIN_PART, int(limit) // 4):
++ raise ValueError(f"TF_GLM_KV_SHARD=1: the memory of a {pool_rows}-token pool holds {rows} sharded tokens "
++ f"({part} a part at {world} ranks), too little for the requested {limit}-token window "
++ f"(a part must hold at least {max(MIN_PART, int(limit) // 4)}): lower --context, or free "
++ f"memory")
++ return rows, (f"a part holds {part} tokens, less than the requested {limit}-token window: a request may use up to "
++ f"{effective} tokens ({max_rows} rows of a part are a decode window's)")
++
++
++# The tp4 branch's prompt settings: they run with the shard (the own-row front's attention through
++# ``forward._sharded_attend``); main has neither.
++PROMPT_SETTINGS = ("TF_GLM_PROMPT_OWN_FRONT", "TF_GLM_PROMPT_MICROBATCH")
++
++
++def carry_on() -> bool:
++ """TF_GLM_KV_SHARD_CARRY as ``multi.kv_carry`` reads it (default 1): whether a carry may send rows between ranks."""
++
++ return (os.environ.get("TF_GLM_KV_SHARD_CARRY", "").strip() or "1") != "0"
++
++
++def ring() -> bool:
++ """A switchless ring (TF_NCCL_RING=1): each rank reaches only its neighbours, opposite ranks have no link."""
++
++ return os.environ.get("TF_NCCL_RING", "0").strip() == "1"
++
++
++def unsupported(verify: str, world: int = 2) -> str | None:
++ """Why the shard cannot run with TF_GLM_MULTI_VERIFY=``verify`` on ``world`` ranks (None: it can)."""
++
++ if verify == "serial":
++ return ("TF_GLM_KV_SHARD=1 does not run with TF_GLM_MULTI_VERIFY=serial: the one-stream graphs it replays are "
++ "captured with the rank that does not own the rows attending nothing (the owner computes every head), "
++ "so their tokens would be wrong; use the batched verify")
++ return None
++
++
++def as_bytes(lc):
++ """A latent plane's rows as bytes [rows, row bytes] (None: this rank holds none): rows travel as bytes, whatever
++ the cache's type (a bf16 row is 1,024 of them, an FP8 row 528)."""
++
++ return lc if lc is None or lc.dtype == torch.uint8 else lc.view(torch.uint8)
++
++
++def as_cache(got):
++ """A fetched copy [rows, row bytes] as the latent planes' type, what the attention kernels read."""
++
++ return got if DTYPE == torch.uint8 else got.view(DTYPE)
++
++
++def agree(rows: list) -> tuple[int, int]:
++ """(pool rows, display rows) every rank uses, from what each computed (``rows``: one [pool, display] a rank).
++ Ranks' pools differ by a few extents (each rank's own KDA state size is in the plan), and a part's owner is
++ ``base // HALF``: the ranks must agree on HALF, so all take the smallest."""
++
++ return min(int(r[0]) for r in rows), min(int(r[1]) for r in rows)
++
++
++def _scratch(R: int, H: int, LW: int, device, nch: int):
++ """Decode windows' buffers for ``attention`` (allocated once, outside graph capture)."""
++
++ key = (R, H, LW, str(device))
++ b = _buf.get(key)
++ if b is None:
++ if torch.cuda.is_current_stream_capturing():
++ raise RuntimeError("TF_GLM_KV_SHARD: the decode window's buffers must be allocated before graph capture")
++ from . import latent
++
++ b = SimpleNamespace(
++ q2=torch.empty((2 * R * H * LW,), dtype=torch.bfloat16, device=device),
++ q64=torch.empty((R, 2 * H, LW), dtype=torch.bfloat16, device=device),
++ o64=torch.empty((R, 2 * H, LW), dtype=torch.bfloat16, device=device),
++ send=torch.empty((R, H, LW), dtype=torch.bfloat16, device=device),
++ recv=torch.empty((2 * R * H * LW,), dtype=torch.bfloat16, device=device),
++ counts=torch.zeros((R,), dtype=torch.int32, device=device),
++ zero=torch.zeros((R,), dtype=torch.int32, device=device),
++ notok=torch.full((R, 1), -1, dtype=torch.int32, device=device),
++ s64=latent.LatentScratch(R, 2 * H, nch, device, lw=LW))
++ _buf[key] = b
++ return b
++
++
++def attention(comm, qa, lc, rows, tokens, counts, s, *, scale: float, out, R: int):
++ """A decode window's latent attention, sharded: every rank's queries qa [R, H, 512] (its heads) gathered, each
++ row's owner computes all heads over its keys (``rows.lbase``: the row's stream in this rank's latent planes;
++ ``rows.own``: whether this rank owns it), and each rank keeps its own heads: its own rows' from its pass, the
++ other rows' from the owner's -> out [R, H, 512]."""
++
++ from . import latent
++
++ if WORLD > 2:
++ return _attention_n(comm, qa, lc, rows, tokens, counts, s, scale=scale, out=out, R=R)
++ H, LW = qa.shape[1], qa.shape[2]
++ b = _scratch(s.rows, H, LW, qa.device, s.nch)
++ q2 = b.q2[:2 * R * H * LW]
++ comm.all_gather(qa[:R].contiguous().view(-1), q2)
++ q64 = b.q64[:R]
++ q64.view(R, 2, H, LW).copy_(q2.view(2, R, H, LW).transpose(0, 1))
++ if tokens is None:
++ tokens, counts = b.notok[:R], b.zero[:R]
++ ce = b.counts[:R]
++ torch.mul(counts[:R], rows.own[:R], out=ce)
++ view = SimpleNamespace(pos=rows.pos, base=rows.lbase, sparse=rows.sparse_eff)
++ o64 = latent.seg_attention(q64, lc, view, tokens, ce, b.s64, scale=scale, out=b.o64[:R])
++ mine, theirs = slice(RANK * H, RANK * H + H), slice((1 - RANK) * H, (2 - RANK) * H)
++ send = b.send[:R]
++ send.copy_(o64[:, theirs])
++ recv = b.recv[:2 * R * H * LW]
++ comm.all_gather(send.reshape(-1), recv)
++ peer = recv.view(2, R, H, LW)[1 - RANK]
++ torch.where(rows.own[:R].bool()[:, None, None], o64[:, mine], peer, out=out)
++ return out
++
++
++def _scratch_n(R: int, H: int, LW: int, device, nch: int):
++ """``_scratch`` past two ranks: every rank's queries padded to the most heads a rank has, gathered; all heads'
++ outputs; one send and one receive a peer."""
++
++ key = ("n", R, H, LW, str(device))
++ b = _buf.get(key)
++ if b is None:
++ if torch.cuda.is_current_stream_capturing():
++ raise RuntimeError("TF_GLM_KV_SHARD: the decode window's buffers must be allocated before graph capture")
++ from . import latent
++
++ heads = HEADS or [H] * WORLD
++ hp = head_plan(heads, RANK)
++ Hm, T = hp.Hm, hp.T
++ send, recv = exchange_buffers(hp, R, LW, device)
++ b = SimpleNamespace(
++ heads=heads, Hm=Hm, T=T, offs=hp.offs, peers=hp.peers,
++ qp=torch.zeros((R, Hm, LW), dtype=torch.bfloat16, device=device),
++ qg=torch.empty((WORLD * R * Hm * LW,), dtype=torch.bfloat16, device=device),
++ qall=torch.empty((R, T, LW), dtype=torch.bfloat16, device=device),
++ oall=torch.empty((R, T, LW), dtype=torch.bfloat16, device=device),
++ send=send, recv=recv,
++ counts=torch.zeros((R,), dtype=torch.int32, device=device),
++ zero=torch.zeros((R,), dtype=torch.int32, device=device),
++ notok=torch.full((R, 1), -1, dtype=torch.int32, device=device),
++ s64=latent.LatentScratch(R, T, nch, device, lw=LW))
++ _buf[key] = b
++ return b
++
++
++def _attention_n(comm, qa, lc, rows, tokens, counts, s, *, scale: float, out, R: int):
++ """``attention`` past two ranks: each rank's queries (padded) gathered, each row's owner computes every head over
++ its keys, and every other rank gets its own heads of the rows it does not own in one all-to-all (``rows.orank``:
++ each row's owner); the same kernel over the same keys, so the same bits as each rank's own heads."""
++
++ from . import latent
++
++ H, LW = qa.shape[1], qa.shape[2]
++ b = _scratch_n(s.rows, H, LW, qa.device, s.nch)
++ qp = b.qp[:R]
++ qp[:, :H].copy_(qa[:R])
++ qg = b.qg[:WORLD * R * b.Hm * LW]
++ comm.all_gather(qp.reshape(-1), qg)
++ g = qg.view(WORLD, R, b.Hm, LW)
++ qall = b.qall[:R]
++ for r in range(WORLD):
++ qall[:, b.offs[r]:b.offs[r] + b.heads[r]].copy_(g[r, :, :b.heads[r]])
++ if tokens is None:
++ tokens, counts = b.notok[:R], b.zero[:R]
++ ce = b.counts[:R]
++ torch.mul(counts[:R], rows.own[:R], out=ce)
++ view = SimpleNamespace(pos=rows.pos, base=rows.lbase, sparse=rows.sparse_eff)
++ oall = latent.seg_attention(qall, lc, view, tokens, ce, b.s64, scale=scale, out=b.oall[:R])
++ sends, recvs = pack_heads(b, oall, R)
++ xa = getattr(comm, "exchange_all", None) or getattr(comm, "nccl", comm).exchange_all
++ xa(sends, recvs)
++ return unpack_heads(b, oall, rows.orank[:R], out, R)
++
++
++def head_plan(heads: list, rank: int) -> SimpleNamespace:
++ """Where each rank's heads sit among all of them (``offs``, ``T`` in all), the most any rank has (``Hm``: what a
++ queries' gather and a pair's exchange are padded to) and ``rank``'s peers."""
++
++ return SimpleNamespace(Hm=max(heads), T=sum(heads), offs=[sum(heads[:r]) for r in range(len(heads))],
++ peers=[p for p in range(len(heads)) if p != rank])
++
++
++def exchange_buffers(hp, R: int, LW: int, device):
++ """A send and a receive a peer, [R, Hm, LW] each: every pair's alike, padded to the most heads a rank has (as the
++ gathered queries are), since ``exchange_all`` refuses unequal sizes and the ranks' heads differ at three."""
++
++ mk = lambda: {p: torch.empty((R, hp.Hm, LW), dtype=torch.bfloat16, device=device) for p in hp.peers} # noqa: E731
++ return mk(), mk()
++
++
++def pack_heads(b, oall, R: int):
++ """The owner's output ``oall`` [R, all heads, LW] cut for each peer: its heads, padded to ``Hm`` -> the
++ all-to-all's {peer: [send]} and {peer: [receive]} (both [R, Hm, LW], the same size in every pair)."""
++
++ sends, recvs = {}, {}
++ for p in b.peers:
++ b.send[p][:R, :b.heads[p]].copy_(oall[:, b.offs[p]:b.offs[p] + b.heads[p]])
++ sends[p], recvs[p] = [b.send[p][:R]], [b.recv[p][:R]]
++ return sends, recvs
++
++
++def unpack_heads(b, oall, orank, out, R: int):
++ """This rank's heads of every row: its own pass's for the rows it owns, else the owner's (the receive from rank
++ ``orank[row]``, its first ``out``'s heads of the padding) -> ``out`` [R, heads, LW]."""
++
++ H = out.shape[1]
++ out.copy_(oall[:, b.offs[RANK]:b.offs[RANK] + H])
++ owner = orank[:, None, None]
++ for p in b.peers:
++ torch.where(owner == p, b.recv[p][:R, :H], out, out=out)
++ return out
++
++
++def _grown(name: str, rows: int, row_bytes: int, device) -> torch.Tensor:
++ """A staging buffer of at least ``rows`` rows, kept and grown (to the next power of two) rather than allocated a
++ layer at a time: the allocator would otherwise keep every size a long prompt's chunks asked for (~6 GiB at 1M)."""
++
++ b = _buf.get(name)
++ if b is None or b.shape[0] < rows or b.shape[1] != row_bytes:
++ _buf.pop(name, None)
++ size = 1 << max(12, (int(rows) - 1).bit_length())
++ b = torch.empty((size, row_bytes), dtype=torch.uint8, device=device)
++ _buf[name] = b
++ return b
++
++
++def _mark_kernel(tok_ptr, n, mark_ptr, limit, BLOCK: tl.constexpr):
++ offs = tl.program_id(0) * BLOCK + tl.arange(0, BLOCK)
++ m = offs < n
++ t = tl.load(tok_ptr + offs, mask=m, other=-1)
++ ok = m & (t >= 0) & (t < limit)
++ tl.store(mark_ptr + t, tl.full([BLOCK], 1, tl.int32), mask=ok)
++
++
++def _renumber_kernel(tok_ptr, out_ptr, n, cum_ptr, limit, BLOCK: tl.constexpr):
++ offs = tl.program_id(0) * BLOCK + tl.arange(0, BLOCK)
++ m = offs < n
++ t = tl.load(tok_ptr + offs, mask=m, other=-1)
++ hist = (t >= 0) & (t < limit)
++ c = tl.load(cum_ptr + t, mask=m & hist, other=0) # marked positions up to t (inclusive)
++ fetched = tl.load(cum_ptr + limit - 1) # every marked position: the fetched rows
++ r = tl.where(t < 0, -1, tl.where(hist, c - 1, fetched + t - limit))
++ tl.store(out_ptr + offs, r, mask=m)
++
++
++def _ints(name: str, n: int, device) -> torch.Tensor:
++ """A kept int32 buffer of at least ``n`` (grown to the next power of two, as ``_grown``)."""
++
++ b = _buf.get(name)
++ if b is None or b.numel() < n:
++ b = _buf[name] = torch.empty((1 << max(12, (int(n) - 1).bit_length()),), dtype=torch.int32, device=device)
++ return b[:n]
++
++
++def history(tokens: torch.Tensor, host_pos: int, owner: bool):
++ """A prompt chunk's selected history: the positions below ``host_pos`` its rows' tokens [R, width] (int32, -1
++ none) name, deduplicated in order, in time linear in the tokens (a mark a position, then its prefix sums), where a
++ sort would take ~4x the chunk's own attention work. The owner gets the positions (int64, ascending: what it sends);
++ the other rank gets their count and the tokens renumbered to rows of the compact copy (a history position to its
++ place among the fetched rows, a chunk row's own after them, -1 kept), the same ids a sorted search would give."""
++
++ dev = tokens.device
++ t = tokens.contiguous().view(-1)
++ n_tok = t.numel()
++ mark = _ints("mark", max(host_pos, 1), dev)
++ mark.zero_()
++ BLOCK = 1024
++ grid = (triton.cdiv(n_tok, BLOCK),)
++ if n_tok:
++ _mark_kernel[grid](t, n_tok, mark, host_pos, BLOCK=BLOCK)
++ if owner:
++ return torch.nonzero(mark).view(-1), None
++ cum = _ints("cum", max(host_pos, 1), dev)
++ torch.cumsum(mark, 0, dtype=torch.int32, out=cum)
++ out = _ints("renum", n_tok, dev)
++ if n_tok:
++ _renumber_kernel[grid](t, out, n_tok, cum, host_pos, BLOCK=BLOCK)
++ return int(cum[host_pos - 1]) if host_pos else 0, out.view(tokens.shape)
++
++
++def fetch(comm, lc, hist: torch.Tensor, row_bytes: int, device, extra: int = 0, root: int | None = None):
++ """A prompt chunk's history rows ``hist`` (positions, ascending; on the other ranks, their count) from their
++ owner to the other ranks, one way (past two ranks a broadcast from the owner, ``root``).
++ ``lc``: this rank's view of the stream (None: it is not the owner). The owner sends and gets None; the other rank
++ gets a staging buffer [n + extra, row_bytes] whose first n rows are the fetched ones (``extra`` rows after them
++ for the chunk's own)."""
++
++ n = hist if isinstance(hist, int) else int(hist.numel())
++ STATS["fetches"] += 1
++ STATS["rows"] += n
++ STATS["bytes"] += n * row_bytes
++ nc = getattr(comm, "nccl", comm)
++ peer = 1 - RANK
++ stream = _stream()
++ piece = _piece(row_bytes) # rows a send (both ranks cut alike: each send meets its receive)
++ if WORLD > 2:
++ return _broadcast(nc, lc, hist, n, row_bytes, device, extra, root, piece, stream)
++ if lc is not None: # gathered a piece at a time into one bounded buffer (stream order:
++ buf = _grown("send", min(n, piece), row_bytes, device) # a piece's send ends before the next gather)
++ for i in range(0, n, piece):
++ k = min(piece, n - i)
++ torch.index_select(lc, 0, hist[i:i + k], out=buf[:k])
++ _send(nc, buf[:k], peer, stream)
++ return None
++ buf = _grown("comp", n + extra, row_bytes, device)[:n + extra]
++ for i in range(0, n, piece):
++ k = min(piece, n - i)
++ _recv(nc, buf[i:i + k], peer, stream)
++ return buf
++
++
++def _stream() -> int:
++ return torch.cuda.current_stream().cuda_stream
++
++
++def _piece(row_bytes: int) -> int:
++ """Rows a send carries: ``SEND_MIB`` of them (the sender's staging buffer is bounded by it)."""
++
++ return max(1, (SEND_MIB << 20) // row_bytes)
++
++
++def _send(nc, rows: torch.Tensor, peer: int, stream: int) -> None:
++ """One ncclSend of ``rows`` [k, row bytes] (bytes, a multiple of 4 a row) to rank ``peer``."""
++
++ w = rows.view(torch.int32)
++ nc._check(nc.lib.ncclSend(w.data_ptr(), w.numel(), _DTYPES[torch.int32], peer, nc.comm, stream))
++
++
++def _recv(nc, rows: torch.Tensor, peer: int, stream: int) -> None:
++ """The matching ncclRecv into ``rows`` [k, row bytes] from rank ``peer``."""
++
++ w = rows.view(torch.int32)
++ nc._check(nc.lib.ncclRecv(w.data_ptr(), w.numel(), _DTYPES[torch.int32], peer, nc.comm, stream))
++
++
++def warm(comm, device) -> None:
++ """TP3 and up, once at start (every rank, at the same point): every pair of ranks sends 16 bytes each way, so NCCL
++ makes its point-to-point connections now and not at the first carry mid-serve (a connection's setup blocks the host
++ and allocates buffers). The pairs go in the same order on every rank (a < b, by a then b): a sends first and
++ receives, b receives first and sends, so each call meets its partner's; a rank outside a pair goes on to the next."""
++
++ nc = getattr(comm, "nccl", comm)
++ if WORLD < 3 or not carry_on() or relayed(nc): # (only the carry sends point to point past two ranks, and on a
++ return # ring it goes over the neighbour links opened at start)
++ stream = _stream()
++ out = torch.zeros((1, 16), dtype=torch.uint8, device=device)
++ got = torch.empty((1, 16), dtype=torch.uint8, device=device)
++ for a in range(WORLD):
++ for b in range(a + 1, WORLD):
++ if RANK == a:
++ _send(nc, out, b, stream)
++ _recv(nc, got, b, stream)
++ elif RANK == b:
++ _recv(nc, got, a, stream)
++ _send(nc, out, a, stream)
++ if torch.cuda.is_available():
++ torch.cuda.synchronize(device)
++
++
++def send_rows(nc, peer: int, rows: torch.Tensor, spanned: bool = False) -> None:
++ """``rows`` [n, row bytes] (a latent plane's rows of an extent, as bytes) to rank ``peer``, which calls
++ ``recv_rows`` with the same row count and size: a piece (``SEND_MIB``) at a time through the sender's staging
++ buffer (the one ``fetch`` gathers into: stream order ends a piece's send before the next copy overwrites it).
++ ``spanned``: the plane lies in the display span, whose two registrations a memcpy (or a transport reading it)
++ may not cross: the rows reach the staging buffer by kernel, as ``Arena.copy`` moves them (``pool.put_rows``);
++ only rank ``peer`` and this rank call, a rank that owns neither part does not (TP3 and up)."""
++
++ from .pool import put_rows
++
++ n, rb = rows.shape
++ piece = _piece(rb)
++ buf = _grown("send", min(n, piece), rb, rows.device)
++ stream = _stream()
++ for i in range(0, n, piece):
++ k = min(piece, n - i)
++ put_rows(buf[:k], rows[i:i + k], spanned)
++ _send(nc, buf[:k], peer, stream)
++
++
++def recv_rows(nc, peer: int, rows: torch.Tensor, spanned: bool = False) -> None:
++ """The receiving half of ``send_rows``: rank ``peer``'s rows into ``rows`` [n, row bytes] (a view of this rank's
++ plane), a piece at a time through the staging buffer ``fetch`` receives into (``comp``: a fetch's copy of the
++ history lives only inside the layer that asked for it, never across the carry that runs between iterations);
++ the rows reach the plane by kernel when ``spanned``."""
++
++ from .pool import put_rows
++
++ n, rb = rows.shape
++ piece = _piece(rb)
++ buf = _grown("comp", min(n, piece), rb, rows.device)
++ stream = _stream()
++ for i in range(0, n, piece):
++ k = min(piece, n - i)
++ _recv(nc, buf[:k], peer, stream)
++ put_rows(rows[i:i + k], buf[:k], spanned)
++
++
++def relayed(nc=None) -> bool:
++ """Whether a carry goes round the ring (TF_NCCL_RING=1, three ranks or more, and a communicator that opened the
++ neighbour links: the tp4 branch's ``comm._open_links``) instead of straight to the destination: on a switchless
++ ring each rank reaches only its neighbours, and even a neighbour's point-to-point send may land on a port without
++ the peer, so every hop is a two-rank all-gather on the cabled link. A base without the links (main) never relays."""
++
++ return WORLD > 2 and ring() and (nc is None or bool(getattr(nc, "links", None)))
++
++
++def ring_path(so: int, do: int, world: int | None = None) -> list[int]:
++ """The ranks a carry from rank ``so`` to rank ``do`` passes, both ends included, the shorter way round (the rank
++ opposite, at an even world, the way up: every rank computes the same path from the same two ranks)."""
++
++ n = WORLD if world is None else world
++ d = (do - so) % n
++ step = 1 if 2 * d <= n else -1
++ path = [so]
++ while path[-1] != do:
++ path.append((path[-1] + step) % n)
++ return path
++
++
++def _hop(nc, x: int, y: int, buf: torch.Tensor, k: int, stream: int) -> int:
++ """One hop of a relay, x to its neighbour y, on the link joining them: a two-rank all-gather in place over
++ ``buf[:2 k]`` (the link's rank 0 contributes rows [0, k), its rank 1 rows [k, 2 k); both get both). Link a joins
++ rank a (its rank 0) and rank a + 1: a rank's link to the next rank is ``links[1]`` (it is that link's rank 0),
++ to the previous ``links[-1]`` (rank 1). Returns this rank's link rank: its half of ``buf``."""
++
++ import ctypes
++
++ low = x if (y - x) % WORLD == 1 else y # the link's rank 0
++ direction = 1 if RANK == low else -1
++ me = 0 if direction == 1 else 1
++ f = nc.lib.ncclAllGather
++ if f.argtypes is None:
++ f.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_size_t, ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p]
++ w = buf[:2 * k].view(torch.int32).view(-1)
++ cnt = w.numel() // 2
++ nc._check(f(w[me * cnt:].data_ptr(), w.data_ptr(), cnt, _DTYPES[torch.int32], nc.links[direction], stream))
++ return me
++
++
++def relay_rows(nc, so: int, do: int, rows: torch.Tensor | None, n: int, row_bytes: int, device,
++ spanned: bool = False) -> None:
++ """``send_rows`` / ``recv_rows`` on a ring: rank ``so``'s rows [n, row bytes] to rank ``do``'s ``rows``, one hop at a
++ time along ``ring_path`` (each rank between them takes a piece from the hop before and passes it on). Every rank
++ of a carry calls it with the same arguments (``Arena.carry`` is a collective): ``rows`` the source's rows on
++ ``so``, the destination's view on ``do``, None elsewhere; a rank off the path returns. Pieces of ``_piece`` rows,
++ hop after hop on one stream, so each link meets its two ranks' calls in the same order. A plane in the display
++ span reaches the staging buffer and leaves it by kernel (``put_rows``), as ``send_rows`` does."""
++
++ from .pool import put_rows
++
++ path = ring_path(so, do)
++ if RANK not in path or n <= 0:
++ return
++ j = path.index(RANK)
++ piece = _piece(row_bytes)
++ buf = _grown("relay", 2 * min(n, piece), row_bytes, device)
++ stream = _stream()
++ for i in range(0, n, piece):
++ k = min(piece, n - i)
++ half = lambda h: buf[h * k:(h + 1) * k] # noqa: E731 (a half of this piece's 2 k rows)
++ got = None # the half holding the piece, once it is here
++ if j > 0: # the hop in: from the rank before on the path
++ me = _hop(nc, path[j - 1], RANK, buf, k, stream)
++ got = 1 - me
++ if j + 1 < len(path): # the hop out: to the next rank on the path
++ low = RANK if (path[j + 1] - RANK) % WORLD == 1 else path[j + 1]
++ mine = 0 if RANK == low else 1
++ if got is None:
++ put_rows(half(mine), rows[i:i + k], spanned) # the source: its rows into its half
++ elif got != mine:
++ half(mine).copy_(half(got)) # (a relay: the staging buffer only)
++ _hop(nc, RANK, path[j + 1], buf, k, stream)
++ else:
++ put_rows(rows[i:i + k], half(got), spanned) # the destination: into its plane
++
++
++def _broadcast(nc, lc, hist, n: int, row_bytes: int, device, extra: int, root: int, piece: int, stream):
++ """``fetch`` past two ranks: the owner (``root``) gathers each piece and broadcasts it; every other rank receives
++ it into its compact copy."""
++
++ import ctypes
++
++ if root is None or int(root) < 0: # (a caller that names no owner, as the MTP layer's dsa_block, would
++ raise ValueError( # broadcast from rank -1)
++ f"TF_GLM_KV_SHARD: a fetch past two ranks needs the rank that owns the rows, not {root}")
++ f = nc.lib.ncclBroadcast
++ if f.argtypes is None:
++ f.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_size_t, ctypes.c_int, ctypes.c_int, ctypes.c_void_p,
++ ctypes.c_void_p]
++ i32 = _DTYPES[torch.int32]
++ if lc is not None:
++ buf = _grown("send", min(n, piece), row_bytes, device)
++ for i in range(0, n, piece):
++ k = min(piece, n - i)
++ torch.index_select(lc, 0, hist[i:i + k], out=buf[:k])
++ w = buf[:k].view(torch.int32)
++ nc._check(f(w.data_ptr(), w.data_ptr(), w.numel(), i32, int(root), nc.comm, stream))
++ return None
++ buf = _grown("comp", n + extra, row_bytes, device)[:n + extra]
++ for i in range(0, n, piece):
++ k = min(piece, n - i)
++ w = buf[i:i + k].view(torch.int32)
++ nc._check(f(w.data_ptr(), w.data_ptr(), w.numel(), i32, int(root), nc.comm, stream))
++ return buf
diff --git a/tools/chat_continued_check.py b/tools/chat_continued_check.py
index 2763faf..1f178a3 100644
--- a/tools/chat_continued_check.py
+++ b/tools/chat_continued_check.py
@@ -7,7 +7,11 @@ inside the image that scripts/prepare.sh built:
continued_chat on stubbed kept states (no GPU or model): issue #104's in-turn rewind before the kept turns continues
its conversation; another conversation behind the same system prompt and opening message, an edit of the first message,
shared and picture states start or skip as before; the most recently used match wins; the counters and the log line of
-a large prefill (rank 0 only). Exit code 1 when a check fails.
+a large prefill (rank 0 only). Then MultiDecoder._admitted itself on a stubbed slot state (forward.State) and a real
+Pool: the conversation an admitted stream joins (a rewind resumed from nothing joins its conversation and is counted,
+another conversation behind the same opening, draft:false and a picture prompt get new ids, a session whose opening and
+first reply are the same as another's joins it), and chat_roots pruned past 4 x max(16, TF_GLM_CACHE_ENTRIES)
+conversations to those a kept state is in. Exit code 1 when a check fails.
"""
import contextlib
import io
@@ -80,5 +84,87 @@ with contextlib.redirect_stdout(out):
d._continued(1, prior, None, 0, prompt) # rank 1 counts, never logs
check("a small prefill and rank 1: counted, not logged", d.chats_continued == 3 and out.getvalue() == "")
+
+# -- MultiDecoder._admitted itself: which conversation an admitted stream joins, and chat_roots pruned ----------------
+from tensorfold.families.glm5_next.cuda import forward as F # noqa: E402
+from tensorfold.families.glm5_next.cuda.pool import ALIGN, Pool # noqa: E402
+
+
+class FakeState: # forward.State: only what _admitted calls with no kept prompt
+ def __init__(self, *a, **kw):
+ pass
+
+ def reset(self):
+ pass
+
+
+def admitting(entries=8):
+ m = object.__new__(M.MultiDecoder)
+ m.rank, m.w = 0, NS(world=1, device="cpu")
+ m.g, m.e = NS(costs=None, cache_entries=entries), NS(rows=0, caches=None, slots=8)
+ m.pool, m.grid, m.drafts, m.kept, m.lanes = Pool(64 * ALIGN), 0, None, [], {}
+ m.next_sid = m.next_kid = m.next_order = m.next_chat = 0
+ m.chat_roots, m.chats_continued, m.chats_continued_prefill = {}, 0, 0
+ m._kept_by_id = lambda kid: None
+ m.boot = "check" # (the spill tier's blocks name a stream's lineage after it)
+ return m
+
+
+def admit(m, prompt, draft=True, images=False):
+ """An ADMIT with no kept prompt to resume from (a rewind past every kept state, a state read back from disk or
+ dropped): the stream's conversation, and the stream."""
+
+ sid = m.next_sid
+ a = dict(kid=-1, prompt=list(prompt), copy=True, base=(sid % 32) * ALIGN, size=ALIGN, sid=sid, slot=sid % 8,
+ code=[0], images=images, draft=draft, keyed=None, shared=[])
+ s = NS()
+ m._admitted(a, s, None, None)
+ lane = m.lanes[sid]
+ m.pool.remove(lane.extent) # (its extent free for the next one; a test pool of 64 blocks)
+ return lane.chat
+
+
+State = F.State
+F.State = FakeState
+try:
+ m = admitting()
+ one = convo(7, 3)
+ c1 = admit(m, one[0])
+ check("_admitted: a first prompt starts conversation 1 and records its first prompt's length",
+ c1 == 1 and m.chat_roots == {1: len(one[0])})
+ m.kept = [state(SYSTEM, 0, own=False), state(one[3], c1)]
+ c = admit(m, one[1] + [9, 9])
+ check("_admitted: a rewind before the kept turns, resumed from nothing, joins its conversation (#104)",
+ c == c1 and m.chats_continued == 1 and m.chats_continued_prefill == len(one[1]) + 2 and m.next_chat == 1)
+ other = convo(8, 3)
+ c2 = admit(m, other[1])
+ check("_admitted: another conversation behind the same system prompt and opening gets its own id",
+ c2 == 2 and m.chats_continued == 1 and m.chat_roots[2] == len(other[1]))
+ c = admit(m, one[1] + [9], draft=False)
+ check("_admitted: draft:false is never counted as a continuation (a new id)", c == 3 and m.chats_continued == 1)
+ c = admit(m, one[1] + [9], images=True)
+ check("_admitted: a prompt with pictures is not matched (a new id)", c == 4 and m.chats_continued == 1)
+ twin = SYSTEM + OPEN + one[1][len(one[0]):len(one[0]) + M.CHAT_MATCH] + [77] * 40
+ c = admit(m, twin)
+ check("_admitted: a second session whose opening and first reply (temperature 0) are the same joins the first: "
+ "the match cannot tell them apart (README)", c == c1 and m.chats_continued == 2)
+
+ m = admitting(entries=8) # chat_roots holds at most 4 x max(16, entries) = 64 conversations
+ limit = 4 * max(16, m.g.cache_entries)
+ firsts = [convo(100 + i, 0)[0][:-1] + [300000 + i] for i in range(limit)]
+ for f in firsts:
+ admit(m, f)
+ check("_admitted: chat_roots grows to its limit without pruning", len(m.chat_roots) == limit)
+ m.kept = [state(firsts[0] + [1] * 40, 1), state(firsts[5] + [2] * 40, 6), state(SYSTEM, 0, own=False)]
+ newest = admit(m, convo(999, 0)[0][:-1] + [399999])
+ check("_admitted: past it, only the conversations a kept state is in stay, and the new one",
+ set(m.chat_roots) == {1, 6, newest} and newest == limit + 1)
+ c = admit(m, firsts[0] + [1] * 40 + [5])
+ check("_admitted: a pruned-to conversation is still continued", c == 1)
+ c = admit(m, firsts[2] + [5] * 40)
+ check("_admitted: a pruned conversation's prompt starts a new one (its root is gone)", c == newest + 1)
+finally:
+ F.State = State
+
print("all passed" if not fails else f"{len(fails)} failed")
raise SystemExit(1 if fails else 0)
diff --git a/tools/kv_shard_check.py b/tools/kv_shard_check.py
new file mode 100644
index 0000000..329be93
--- /dev/null
+++ b/tools/kv_shard_check.py
@@ -0,0 +1,2507 @@
+#!/usr/bin/env python3
+"""Checks for patch 0129 (KV sharding, TF_GLM_KV_SHARD: tensorfold/families/glm5_next/cuda/shard.py and its pool and
+placement hooks in pool.py / multi.py), CPU only, run inside the image that scripts/prepare.sh built (no GPU, no model,
+no server):
+
+ docker run --rm --entrypoint python -e CUDA_VISIBLE_DEVICES= -v "$PWD/tools/kv_shard_check.py:/c.py" \
+ tensorfold-glm53:v0.6.0 /c.py
+
+A real Pool split in parts (one a rank; two halves at two ranks) and MultiDecoder's own placement and eviction paths:
+- when no part has room, evictions happen in one part only, the one whose newest needed eviction is the oldest (the
+ same states one pool would lose, as near as parts allow), never in a part the new extent does not go to;
+- an explicit part (a resume into its owner's part) and a grown extent evict only in their own part;
+- a new stream goes to the part with fewer live streams (each row's owner computes its decode attention), then the
+ one with more free rows; free rows are cut at every part's end and no extent crosses one;
+- with one pool (no shard) placement and eviction are as before (least recently used first);
+- the sharded pool's size (each token's latent once over N ranks, its pooled keys on every rank) and its parts at
+ two, three and four ranks;
+- (9-) the v5 hardening: a filling prompt's twin is pinned (compaction goes around it, never moves it, never counts
+ its rows as room), a placement no part can make evicts nothing, ``fits`` looks at parts, the TP3 decode exchange
+ (uneven heads) has equal sends and receives, the ranks agree on one pool size, bf16 rows travel as bytes, the sharded
+ pool never exceeds its memory budget, and the shard-specific refusals, signature and asserts.
+- (10) the cross-part carry (TF_GLM_KV_SHARD_CARRY): ``_place_hit``'s rules (a full part no longer drops a hit: another part's
+ room keeps it; free rows elsewhere spare other conversations' states; a gap of 2 live streams carries to the lighter
+ part, never toward a busier one, never under 2,048 tokens, never by evicting) against the old placement code as the
+ reference (carry off, or one pool: identical decisions, evictions, moves and counters), rows that are pinned (a twin,
+ a slice in flight, a read) never carried, ADMIT copy 2 and XMOVE flushed before the collective and applied alike on
+ rank 1, ``Arena.carry`` on simulated ranks (two and three: FP8 and bf16 bytes, the display span by kernel, a partial
+ pooled-key row, pad rows, who sends and who receives), live streams relocated when they cannot grow, and the spill
+ tier (block names carry the part, unsharded names unchanged, a carried state and a state moved with writes waiting
+ restore byte for byte). tools/kv_shard_mutants.sh runs it on faithful mutants of each.
+The decode and prompt kernels' equality (64 heads at once == 32 + 32; a compact copy of the selected rows == the
+arena; the marks-and-prefix-sums history == a sort and a search) needs a GPU and is checked on two Sparks."""
+import os, random, sys
+from types import SimpleNamespace
+from tensorfold.families.glm5_next.cuda import multi
+from tensorfold.families.glm5_next.cuda.pool import Pool, align_up
+
+A = 4096
+fails = []
+def check(name, ok):
+ print(("PASS " if ok else "FAIL ") + name); (fails.append(name) if not ok else None)
+
+def section(name, fn):
+ """Run one group of checks; an exception (a missing function, a refusal that did not come) is a FAIL, not a crash."""
+ try:
+ fn()
+ except Exception as exc: # noqa: BLE001
+ check(f"{name}: raised {type(exc).__name__}: {str(exc)[:90]}", False)
+ if os.environ.get("KV_CHECK_TRACE"): # (a failing section's traceback, for whoever is debugging it)
+ import traceback; traceback.print_exc()
+
+class Stub:
+ _room = multi.MultiDecoder._room; _victims = multi.MultiDecoder._victims
+ _gathered = multi.MultiDecoder._gathered; _compact = multi.MultiDecoder._compact
+ _settle = multi.MultiDecoder._settle; _grow = multi.MultiDecoder._grow
+ _eviction_cost = getattr(multi.MultiDecoder, "_eviction_cost", None)
+ _cheaper_half = getattr(multi.MultiDecoder, "_cheaper_half", None)
+ _revoke_twins = getattr(multi.MultiDecoder, "_revoke_twins", lambda self, half: False)
+ def __init__(self, rows, half):
+ self.pool = Pool(rows, half=half); self.kept = []; self.evicted = []; self.moves = 0
+ self.lanes, self.partial, self.twins = {}, None, {"made": 0, "revoked": 0}
+ self.no_part = 0
+ def _emit(self, op, payload): return []
+ def _evict(self, c, spill=True):
+ self.evicted.append(c.name); self.kept = [k for k in self.kept if k is not c]
+ c.extent.kept = [k for k in c.extent.kept if k is not c]; self._settle(c.extent)
+ def _move(self, x, base, size): self.moves += 1; self.pool.move(x, base, size)
+ def _resize(self, x, size): self.pool.resize(x, size)
+ def keep(self, name, base, n):
+ x = self.pool.add(base, n); c = SimpleNamespace(name=name, ids=[0] * n, extent=x); x.kept.append(c)
+ self.kept.append(c); return c
+
+H = 64 * A
+# 1. halves: LRU interleaved; the half whose needed victims are oldest is chosen, evictions only there
+s = Stub(2 * H, H)
+s.keep("a0", 0, 20 * A); s.keep("b0", H, 20 * A); s.keep("a1", 20 * A, 20 * A); s.keep("b1", H + 20 * A, 30 * A)
+s.keep("a2", 40 * A, 24 * A); s.keep("b2", H + 50 * A, 14 * A)
+# free: half0 0, half1 0. need 30A: half0 needs a0+a1 (newest index 2), half1 needs b0+b1? b0 frees 20 -> 20<30, b1 -> 50: newest idx 3
+base = s._room(30 * A)
+check("1 room in the half losing older states", base is not None and s.pool.half_of(base) == 0)
+check("1 evictions only there (a0, a1)", s.evicted == ["a0", "a1"])
+# 2. explicit half: evicts only in it, even when the globally oldest is in the other
+s = Stub(2 * H, H)
+s.keep("a0", 0, 64 * A); s.keep("b0", H, 32 * A); s.keep("b1", H + 32 * A, 32 * A)
+base = s._room(16 * A, half=1)
+check("2 explicit half evicts only its own", s.evicted == ["b0"] and s.pool.half_of(base) == 1)
+# 3. unsharded unchanged: global LRU
+s = Stub(2 * H, 0)
+s.keep("a0", 0, 64 * A); s.keep("b0", H, 32 * A); s.keep("b1", H + 32 * A, 32 * A)
+base = s._room(16 * A)
+check("3 one pool: least recently used first", s.evicted == ["a0"])
+# 4. placement: fewer live streams first when both fit
+s = Stub(2 * H, H)
+x = s.pool.add(0, 8 * A); x.owner = 1; y = s.pool.add(8 * A, 8 * A); y.owner = 2
+z = s.pool.add(H, 40 * A) # kept, no owner
+check("4 fewer live streams first", s.pool.half_of(s.pool.place(4 * A)) == 1)
+y.owner = None; x.owner = None
+check("4 tie: more free rows", s.pool.half_of(s.pool.place(4 * A)) == 0)
+# 5. grow evicts only in its half
+s = Stub(2 * H, H)
+c0 = s.keep("a0", 0, 32 * A); s.keep("b0", H, 32 * A); s.keep("a1", 32 * A, 32 * A)
+g = s.pool.add(H + 32 * A, 16 * A); g.owner = 7
+ok = s._grow(g, 40 * A)
+check("5 grow evicts in its own half only", ok and s.evicted == ["b0"])
+# 6. random: with halves every eviction is in the half the placement lands in; never more than needed in it
+rnd = random.Random(5)
+bad = 0
+for trial in range(300):
+ s = Stub(2 * H, H)
+ for h in (0, 1):
+ at = h * H
+ while True:
+ n = rnd.randrange(1, 20) * A
+ if at + n > (h + 1) * H: break
+ if rnd.random() < 0.8: s.keep(f"{h}-{at}", at, n)
+ at += n
+ rnd.shuffle(s.kept)
+ need = rnd.randrange(1, 64) * A
+ before = list(s.kept)
+ base = s._room(need)
+ if base is None: continue
+ hb = s.pool.half_of(base)
+ ev = [c for c in before if c.name in s.evicted]
+ if any(s.pool.half_of(c.extent) != hb for c in ev if c.extent in s.pool.extents) or \
+ any(int(c.name.split("-")[0]) != hb for c in ev):
+ bad += 1; continue
+ # minimality: undoing the newest eviction leaves too little room in that half
+ if ev:
+ freed_last = len(ev[-1].ids)
+ if s.pool.free_rows(hb) - align_up(freed_last) >= need and len(ev) > 0:
+ bad += 1
+check("6 random: evictions in one half, none beyond the need", bad == 0)
+# 7. N parts (TP3/TP4): placement, cuts at every part's end, eviction in the part losing the oldest states
+for N in (3, 4):
+ P = 32 * A
+ s = Stub(N * P, P)
+ check(f"7 N={N} parts", s.pool.parts == N)
+ gaps = s.pool.gaps()
+ check(f"7 N={N} free rows cut at every part's end", gaps == [(i * P, P) for i in range(N)])
+ x = s.pool.add(0, 8 * A); x.owner = 1
+ y = s.pool.add(P, 8 * A); y.owner = 2
+ check(f"7 N={N} new stream to a part with no live stream", s.pool.half_of(s.pool.place(4 * A)) == 2)
+ try:
+ s.pool.add(P - A, 2 * A); crossed = True
+ except ValueError:
+ crossed = False
+ check(f"7 N={N} no extent across a part's end", not crossed)
+ s = Stub(N * P, P)
+ names = []
+ for h in range(N): # each part full: two kept prompts of 16 A; LRU interleaved by part
+ for j in range(2):
+ names.append(s.keep(f"{h}-{j}", h * P + j * 16 * A, 16 * A))
+ order = [c for j in range(2) for c in names if c.name.endswith(f"-{j}")]
+ s.kept = order # oldest first: every part's first, then every part's second
+ base = s._room(24 * A) # needs both of one part's prompts: the part whose second is oldest
+ check(f"7 N={N} eviction in one part, the one losing the oldest", s.evicted == ["0-0", "0-1"] and s.pool.half_of(base) == 0)
+# 8. sharded sizes and setup at N ranks
+from tensorfold.families.glm5_next.cuda import shard
+for N, want in ((2, 1.88), (3, 2.66), (4, 3.36)):
+ rows = shard.sizes(2_000_000, 11, "fp8", 1_048_576, N)
+ check(f"8 N={N} sizes: whole parts of extents ({rows}, x{rows / 2_000_000:.2f})", rows % (N * 2048) == 0 and abs(rows / 2_000_000 - want) < 0.06)
+ shard.setup(1, N, rows, heads=[22, 21, 21] if N == 3 else None)
+ check(f"8 N={N} setup: part {rows // N}", shard.HALF == rows // N and shard.WORLD == N and shard.owner(shard.HALF * (N - 1)) == N - 1)
+shard.setup(0, 2, 4096 * 512)
+
+# ---- 9- : the v5 review fixes ------------------------------------------------------------------------------------------
+import torch
+
+H = 32 * A # (a part of 32 A rows from here on)
+
+class Real(Stub):
+ """Stub with the real _move / _used / _untwin / fits (a twin lane has a State stub that records its binds)."""
+ _move = multi.MultiDecoder._move; _used = multi.MultiDecoder._used; _untwin = multi.MultiDecoder._untwin
+ fits = multi.MultiDecoder.fits; _need = multi.MultiDecoder._need
+ _shard_health = getattr(multi.MultiDecoder, "_shard_health", None)
+ _pinned = getattr(multi.MultiDecoder, "_pinned", None)
+ _revoke = multi.MultiDecoder._revoke_twins
+ def __init__(self, rows, half):
+ super().__init__(rows, half); self.rank = 0; self.disk = None; self.rows_max = 2048; self.ops = []
+ self.carry = getattr(multi, "carry_stats", dict)()
+ self.arena = SimpleNamespace(copy=lambda a, b, n: None)
+ self.lanes = Lanes()
+ def _emit(self, op, payload): self.ops.append((op, list(payload))); return []
+ def _move(self, x, base, size):
+ return multi.MultiDecoder._move(self, x, base, size)
+
+class Lanes(dict):
+ """The lanes by sid; a live stream the test did not make a lane for reads as one at position 0."""
+ def __missing__(self, sid): return SimpleNamespace(sid=sid, twin=None, st=St(), extent=None, decoding=False)
+
+class St:
+ def __init__(self, pos=0): self.twin_base = None; self.twin_size = None; self.pos = pos; self.binds = []
+ def bind(self, b, n): self.binds.append((b, n))
+
+def twin(s, base, n, lane_x, pos=A, sid=1):
+ """A twin of the lane filling in ``lane_x``: an extent (flagged like Pool.add(twin=True), so the same on a tree whose
+ add does not take it) that the lane's state points at."""
+ t = s.pool.add(base, n); t.twin = True
+ st = St(pos); st.twin_base = base; st.twin_size = n
+ lane = SimpleNamespace(sid=sid, twin=[t], st=st, extent=lane_x, decoding=False)
+ s.lanes[sid] = lane
+ return t, lane
+
+def twin_pinned():
+ # the reviewer's scenario: part 1 = free 8A | twin of a sliced fill 8A | free 8A | kept 8A; a placement of 10A
+ s = Real(2 * H, H)
+ x = s.pool.add(0, 8 * A); x.owner = 1
+ t, lane = twin(s, H + 8 * A, 8 * A, x)
+ s.partial = SimpleNamespace(contains=lambda sid: sid == 1, group=[(lane, 8 * A)])
+ k = s.keep("k", H + 24 * A, 8 * A)
+ base = s._room(10 * A, half=1)
+ check("9 twin: compaction leaves a twin where it is", t.base == H + 8 * A and lane.st.twin_base == t.base)
+ check("9 twin: no extent overlaps a live twin",
+ all(y is t or y.end <= t.base or y.base >= t.end for y in s.pool.extents))
+ check("9 twin: the room came from evicting the kept prompt (gathered rows are around the twin)",
+ base is not None and base == H + 16 * A and s.evicted == ["k"])
+ check("9 twin: the twin was not revoked mid-fill", lane.twin is not None and s.twins["revoked"] == 0)
+section("9 twin", twin_pinned)
+
+def twin_not_room():
+ # free 8A | twin 8A | free 8A: 16A free but never together: not gatherable, no victims, nothing moves
+ s = Real(2 * H, H)
+ x = s.pool.add(0, 8 * A); x.owner = 1
+ t, lane = twin(s, H + 8 * A, 8 * A, x)
+ s.partial = SimpleNamespace(contains=lambda sid: sid == 1, group=[(lane, 8 * A)])
+ s.pool.add(H + 24 * A, 8 * A).owner = 9 # part 1: free 8A | twin 8A | free 8A | a live stream 8A
+ check("9 twin: its rows are not gatherable room (16A free, 8A together at most)", s._gathered(12 * A, 1) is False)
+ check("9 twin: no eviction can make room around it", s._eviction_cost(12 * A, (), 1) is None)
+ check("9 twin: _room finds none and moves nothing", s._room(12 * A, half=1) is None and t.base == H + 8 * A
+ and not [op for op, _ in s.ops if op == multi.MOVE])
+section("9 twin room", twin_not_room)
+
+def twin_move_refused():
+ s = Real(2 * H, H)
+ x = s.pool.add(0, 8 * A); x.owner = 1
+ t, lane = twin(s, H + 8 * A, 8 * A, x)
+ for what, fn in (("pool.move", lambda: s.pool.move(t, H, 8 * A)), ("_move", lambda: multi.MultiDecoder._move(s, t, H, 8 * A))):
+ try:
+ fn(); ok = False
+ except (ValueError, RuntimeError):
+ ok = True
+ check(f"9 twin: {what} of a twin is refused", ok and t.base == H + 8 * A)
+section("9 twin move", twin_move_refused)
+
+def twin_random():
+ rnd = random.Random(11); bad = []
+ for trial in range(400):
+ s = Real(2 * H, H)
+ keep_n = 0
+ # part 0: a filling stream; part 1: its twin among kept prompts and a live stream
+ x = s.pool.add(0, 8 * A); x.owner = 1
+ at = H; items = []
+ while True:
+ n = rnd.randrange(1, 7) * A
+ if at + n > 2 * H: break
+ kind = rnd.choice(["free", "kept", "kept", "live", "twin"])
+ if kind == "twin" and not items.count("twin"):
+ t, lane = twin(s, at, n, x); items.append("twin"); s.twin_obj = t
+ elif kind == "kept": s.keep(f"k{keep_n}", at, n); keep_n += 1; items.append("kept")
+ elif kind == "live": s.pool.add(at, n).owner = 100 + len(items); items.append("live")
+ at += n + rnd.choice([0, 0, A])
+ if "twin" not in items: continue
+ t = s.twin_obj
+ lane = s.lanes[1]
+ # the lane's fill is pending (twin kept) in half the trials: the other half it may be revoked, then rows vanish
+ pend = rnd.random() < 0.5
+ s.partial = SimpleNamespace(contains=lambda sid: pend and sid == 1, group=[(lane, 8 * A)]) if pend else None
+ base0 = t.base
+ rnd.shuffle(s.kept)
+ need = rnd.randrange(1, 20) * A
+ ev0 = len(s.evicted)
+ r = s._room(need, half=1) if rnd.random() < 0.5 else s._room(need)
+ if lane.twin is not None and t.base != base0: bad.append((trial, "twin moved")); continue
+ if lane.twin is not None and any(y is not t and y.base < t.end and t.base < y.end for y in s.pool.extents):
+ bad.append((trial, "overlap")); continue
+ if r is None and len(s.evicted) != ev0: bad.append((trial, "evicted for nothing")); continue
+ if r is not None:
+ try: s.pool.add(r, need)
+ except ValueError: bad.append((trial, "placed on taken rows"))
+ check(f"9 twin: random layouts: twin never moves or overlaps, no eviction for nothing ({bad[:2]})", not bad)
+section("9 twin random", twin_random)
+
+def no_part():
+ # two parts of 32A, each a 24A live stream and an 8A kept prompt; 16A wanted (the reviewer's repro 2)
+ for half in (None, 1):
+ s = Real(2 * H, H)
+ s.pool.add(0, 24 * A).owner = 1; s.pool.add(H, 24 * A).owner = 2
+ s.keep("k0", 24 * A, 8 * A); s.keep("k1", H + 24 * A, 8 * A)
+ r = s._room(16 * A, half=half)
+ check(f"9 room (half={half}): none when no part can make it, and no kept prompt is evicted",
+ r is None and s.evicted == [] and len(s.kept) == 2)
+ check(f"9 room (half={half}): the refusal is counted", s.no_part == 1)
+ s = Real(2 * H, H)
+ s.pool.add(0, 24 * A).owner = 1; s.pool.add(H, 24 * A).owner = 2
+ s.keep("k0", 24 * A, 8 * A); s.keep("k1", H + 24 * A, 8 * A)
+ r = s._room(8 * A)
+ check("9 room: still evicts the least needed when a part can (8A: one prompt)", r is not None and len(s.evicted) == 1)
+section("9 room", no_part)
+
+def fits_parts():
+ def lanes(s):
+ for sid, x in enumerate([e for e in s.pool.extents if e.owner is not None], 1):
+ s.lanes[sid] = SimpleNamespace(sid=sid, twin=None, st=St(), extent=x, decoding=False)
+ need_prompt = 16 * A - 2048 # _need = 16A
+ # (a) 12A free in each part (24A together): fits() used to say yes
+ s = Real(2 * H, H)
+ s.pool.add(0, 20 * A).owner = 1; s.pool.add(H, 20 * A).owner = 2; lanes(s)
+ check("9 fits: free rows spread over parts are not room for one prompt", s.fits(SimpleNamespace(prompt=[0] * need_prompt)) is False)
+ # (b) a kept prompt makes the room in one part
+ s = Real(2 * H, H)
+ s.pool.add(0, 16 * A).owner = 1; s.pool.add(H, 20 * A).owner = 2; lanes(s)
+ s.keep("k", 16 * A, 8 * A)
+ check("9 fits: free + kept rows of ONE part cover it", s.fits(SimpleNamespace(prompt=[0] * need_prompt)) is True)
+ # (c) twin rows are not room
+ s = Real(2 * H, H)
+ x = s.pool.add(0, 20 * A); x.owner = 1
+ t, lane = twin(s, H + 12 * A, 20 * A, x)
+ s.pool.add(H, 12 * A).owner = 2; lanes(s); s.lanes[1] = lane
+ s.partial = SimpleNamespace(contains=lambda sid: sid == 1, group=[(lane, 20 * A)]) # (its fill is in flight)
+ check("9 fits: a pinned twin's rows are not evictable room", s.fits(SimpleNamespace(prompt=[0] * need_prompt)) is False)
+ # (d) decoding streams in the part need headroom
+ s = Real(2 * H, H)
+ s.pool.add(0, 24 * A).owner = 1; s.pool.add(H, 24 * A).owner = 2; lanes(s)
+ s.keep("k", H + 24 * A, 8 * A)
+ for l in s.lanes.values(): l.decoding = True
+ check("9 fits: headroom for the part's decoding stream counts (8A of room: a prompt needing 8A - 2048 fits, 8A does not)",
+ s.fits(SimpleNamespace(prompt=[0] * (8 * A - 4096))) is True and s.fits(SimpleNamespace(prompt=[0] * (8 * A - 2048))) is False)
+ # (e) unsharded unchanged
+ s = Real(2 * H, 0)
+ s.pool.add(0, 40 * A).owner = 1; lanes(s); s.keep("k", 40 * A, 8 * A)
+ check("9 fits: one pool as before", s.fits(SimpleNamespace(prompt=[0] * (20 * A))) is True
+ and s.fits(SimpleNamespace(prompt=[0] * (30 * A))) is False)
+section("9 fits", fits_parts)
+
+def fits_revocable_twin():
+ # the re-review's case: a 30A prompt between chunks of its fill (no slice in flight) in part 0, its 30A twin in
+ # part 1. The twin can be given back, so a 10A request fits (the scheduler holds a request fits() refuses and
+ # nothing calls _room, so a twin counted as pinned would hold it for the other prompt's whole fill)
+ def build(pending):
+ s = Real(2 * H, H)
+ x = s.pool.add(0, 30 * A); x.owner = 1
+ t, lane = twin(s, H, 30 * A, x)
+ if pending:
+ s.partial = SimpleNamespace(contains=lambda sid: sid == 1, group=[(lane, 30 * A)])
+ return s, x, t, lane
+ prompt = SimpleNamespace(prompt=[0] * (8 * A))
+ s, x, t, lane = build(False)
+ check("9 fits: a twin between chunks is room (it is given back)", s.fits(prompt) is True)
+ if s._shard_health is not None:
+ check("9 health: its rows count as gatherable room", s._shard_health()["parts"][1]["gatherable"] == H)
+ base = s._room(s._need(8 * A))
+ check("9 fits: and _room does place it, after one UNTWIN", base is not None and lane.twin is None
+ and [op for op, _ in s.ops].count(multi.UNTWIN) == 1)
+ s, x, t, lane = build(True)
+ check("9 fits: a twin of the fill part way through its layers is not room", s.fits(prompt) is False)
+ check("9 fits: and _room refuses it too, keeping the twin", s._room(s._need(8 * A)) is None and lane.twin is not None)
+section("9 fits revocable twin", fits_revocable_twin)
+
+def grow_twin():
+ s = Real(2 * H, H)
+ x = s.pool.add(0, 8 * A); x.owner = 1
+ t, lane = twin(s, H + 16 * A, 8 * A, x)
+ g = s.pool.add(H + 4 * A, 4 * A); g.owner = 7 # free 4A | g 4A | free 8A | twin | free 8A
+ s.pool.add(H + 12 * A, 2 * A).owner = 8
+ s.partial = SimpleNamespace(contains=lambda sid: sid == 1, group=[(lane, 8 * A)]) # (the twin stays)
+ ok = s._grow(g, 14 * A)
+ check("9 grow: around a pinned twin the segment's free rows gather after the extent",
+ ok and g.size == 14 * A and t.base == H + 16 * A and
+ all(y is t or y.end <= t.base or y.base >= t.end for y in s.pool.extents))
+ check("9 grow: beyond the segment's rows it is refused, the twin still where it was",
+ s._grow(g, 20 * A) is False and t.base == H + 16 * A)
+section("9 grow", grow_twin)
+
+def pool_segments():
+ from tensorfold.families.glm5_next.cuda.pool import Pool as P
+ p = P(2 * H, half=H)
+ t = p.add(8 * A, 8 * A); t.twin = True
+ p.add(H, 16 * A)
+ check("9 pool: segments cut at a twin and at the part", p.segments(0) == [(0, 8 * A), (16 * A, H)])
+ check("9 pool: compactable is the largest segment, not the sum", p.compactable(0) == H - 16 * A and p.compactable(1) == H - 16 * A)
+section("9 pool", pool_segments)
+
+def tp3_exchange():
+ heads = [22, 21, 21]; R = 5; LW = 8; N = 3
+ torch.manual_seed(0)
+ truth = torch.randn(R, sum(heads), LW).bfloat16()
+ owners = torch.tensor([0, 1, 2, 1, 0])
+ bufs, oalls, sends, recvs = [], [], [], []
+ for r in range(N):
+ shard.RANK = r
+ hp = shard.head_plan(heads, r)
+ send, recv = shard.exchange_buffers(hp, R, LW, "cpu")
+ b = SimpleNamespace(heads=heads, offs=hp.offs, peers=hp.peers, send=send, recv=recv)
+ oall = torch.full_like(truth, float("nan")) # only the rows it owns are computed
+ for i in range(R):
+ if int(owners[i]) == r: oall[i] = truth[i]
+ bufs.append(b); oalls.append(oall); sends.append(shard.pack_heads(b, oall, R))
+ # the exchange_all contract (comm.py): each pair's send and receive alike in numel and dtype, contiguous
+ for r in range(N):
+ for p in bufs[r].peers:
+ s_, r_ = sends[r][0][p][0], sends[p][1][r][0]
+ if s_.numel() != r_.numel() or s_.dtype != r_.dtype or not (s_.is_contiguous() and r_.is_contiguous()):
+ raise ValueError(f"exchange_all: rank {r} -> {p} sends {tuple(s_.shape)}, rank {p} receives {tuple(r_.shape)}")
+ r_.copy_(s_)
+ good = True
+ for r in range(N):
+ shard.RANK = r
+ out = torch.empty(R, heads[r], LW, dtype=torch.bfloat16)
+ shard.unpack_heads(bufs[r], oalls[r], owners, out, R)
+ want = truth[:, bufs[r].offs[r]:bufs[r].offs[r] + heads[r]]
+ good &= bool(torch.equal(out, want))
+ check("9 tp3: the decode exchange of uneven heads (22/21/21): pairs alike, every rank gets its own heads", good)
+ shard.RANK = 0
+section("9 tp3", tp3_exchange)
+
+def tp3_scratch():
+ # the buffers the decode window really allocates (_scratch_n): comm.exchange_all refuses, on each rank, a peer whose
+ # send and receive differ in size, and at 22/21/21 heads they did (rank 0 sent 21 heads' worth, expected 22)
+ from tensorfold.families.glm5_next.cuda import latent
+ saved = (torch.cuda.is_current_stream_capturing, latent.LatentScratch, shard.WORLD, shard.RANK, shard.HEADS)
+ torch.cuda.is_current_stream_capturing = lambda: False
+ latent.LatentScratch = lambda *a, **k: None
+ try:
+ shard.WORLD, shard.HEADS = 3, [22, 21, 21]
+ bad = []
+ for r in range(3):
+ shard.RANK = r; shard._buf.clear()
+ b = shard._scratch_n(8, [22, 21, 21][r], 16, "cpu", 4)
+ for p in b.peers:
+ if b.send[p].numel() != b.recv[p].numel():
+ bad.append((r, p, b.send[p].numel(), b.recv[p].numel()))
+ check(f"9 tp3: every rank's send and receive alike per peer, as exchange_all demands ({bad[:2]})", not bad)
+ finally:
+ shard._buf.clear()
+ torch.cuda.is_current_stream_capturing, latent.LatentScratch, shard.WORLD, shard.RANK, shard.HEADS = saved
+section("9 tp3 scratch", tp3_scratch)
+
+def pool_agree():
+ # two ranks' unsharded pools differ by a few extents (their KDA state sizes): the ranks take the smallest
+ a, b = 2_000_000 // 2048 * 2048, 2_000_000 // 2048 * 2048 - 3 * 2048
+ halves = []
+ for rows in (a, b):
+ shard.setup(0, 3, shard.budget(rows, 11, "fp8", 3), heads=[22, 21, 21]); halves.append(shard.HALF)
+ check("9 agree: ranks sizing alone can disagree on a part's rows (the failure)", halves[0] != halves[1])
+ p, d = shard.agree([[a, 1000], [b, 500], [a, 700]])
+ check("9 agree: the smallest pool and display rows on every rank", (p, d) == (b, 500))
+ halves = []
+ for r in range(3):
+ shard.setup(r, 3, shard.budget(p, 11, "fp8", 3), heads=[22, 21, 21]); halves.append(shard.HALF)
+ check("9 agree: then every rank's part is the same", len(set(halves)) == 1)
+ shard.setup(0, 2, 4096 * 512)
+section("9 agree", pool_agree)
+
+def bf16_bytes():
+ lc = torch.randn(64, 512).bfloat16()
+ lcb = shard.as_bytes(lc)
+ check("9 bf16: a bf16 plane's rows are 1,024 bytes, a uint8 (FP8) plane's unchanged",
+ lcb.shape == (64, 1024) and lcb.dtype == torch.uint8 and shard.as_bytes(lcb) is lcb and shard.as_bytes(None) is None)
+ hist = torch.tensor([3, 5, 9, 40])
+ buf = torch.empty((8, lcb.shape[1]), dtype=torch.uint8)
+ torch.index_select(lcb, 0, hist, out=buf[:4])
+ old = shard.DTYPE
+ shard.DTYPE = torch.bfloat16
+ got = shard.as_cache(buf[:6])
+ check("9 bf16: the received bytes viewed back as the plane's rows", got.dtype == torch.bfloat16 and torch.equal(got[:4], lc[hist]))
+ shard.DTYPE = torch.uint8
+ check("9 fp8: received rows stay bytes", shard.as_cache(buf).dtype == torch.uint8)
+ shard.DTYPE = old
+section("9 bf16", bf16_bytes)
+
+def floor_budget():
+ # the window a request may use is what a part holds (limit = part - max_rows, the engine's own cap), noted not refused
+ # unless a part would be absurdly small
+ cap = lim = 1_048_576
+ for N, unsh in ((2, 1_118_208), (2, 1_060_864), (3, 1_060_864), (4, 1_060_864)):
+ have = shard.budget(unsh, 11, "fp8", N)
+ part = have // N
+ rows, note = shard.plan(unsh, 11, "fp8", lim, N, 16)
+ want = f"up to {min(lim, part - 16)} tokens"
+ check(f"9 floor N={N} pool {unsh}: a part of {part} short of the {lim} window: shrink, one note with the numbers, "
+ f"never past the budget", rows == have and rows <= shard.budget(unsh, 11, "fp8", N) and part - 16 < lim
+ and want in note and str(part) in note and str(lim) in note and "\n" not in note)
+ rows, note = shard.plan(4_000_000, 11, "fp8", lim, 2, 16)
+ check("9 floor: a budget that holds the windows is untouched", rows == shard.budget(4_000_000, 11, "fp8", 2) and not note)
+ for N, unsh, what in ((2, 100_000, "a part of ~94K"), (2, 250_000, "a part below a quarter of the window"),
+ (4, 150_000, "a part of ~140K at four ranks")):
+ have = shard.budget(unsh, 11, "fp8", N)
+ try:
+ shard.plan(unsh, 11, "fp8", lim, N, 16); refused = False
+ except ValueError as exc:
+ refused = str(have) in str(exc) and str(have // N) in str(exc) and str(lim) in str(exc)
+ check(f"9 floor N={N}: {what} ({have // N} tokens) is refused with the numbers", refused)
+ rows, note = shard.plan(1_060_864, 11, "fp8", 262_144, 2, 16)
+ check("9 floor: a smaller window that a part holds is untouched", not note)
+section("9 floor", floor_budget)
+
+def refusals():
+ check("9 refuse: serial verify with the shard says why", "serial" in (shard.unsupported("serial") or ""))
+ check("9 refuse: batched verify is fine", shard.unsupported("batched") is None)
+section("9 refuse", refusals)
+
+def hardening():
+ from tensorfold.families.glm5_next.cuda import forward, segments
+ shard.ON = True
+ try:
+ shard.setup(0, 2, 4096 * 512)
+ # Caches.bind: a twin the extent's size
+ ca = SimpleNamespace(arena=SimpleNamespace(view=lambda i, b, n: (i, b, n)), kc=[0], vc=[None], mtp=None, index=None)
+ st = St(); st.twin_base = shard.HALF + 2048; st.twin_size = 4096
+ try:
+ forward.Caches.bind(ca, st, 0, 8192); ok = False
+ except ValueError:
+ ok = True
+ check("9 bind: a twin of another size than its extent is refused", ok)
+ forward.Caches.bind(ca, st, 0, 4096)
+ check("9 bind: the same size binds", True)
+ # SegRows.fill: a window past the trash rows
+ sr = object.__new__(segments.SegRows); sr.rows, sr.max_segs, sr.ring = shard.TRASH + 64, 4, None
+ try:
+ sr.fill([(0, 0, shard.TRASH + 1)], sparse_from=None); ok = False
+ except ValueError:
+ ok = True
+ check("9 window: more rows than the trash rows hold is refused", ok)
+ try:
+ shard._broadcast(None, None, None, 0, 8, "cpu", 0, -1, 1, 0); ok = False
+ except ValueError:
+ ok = True
+ check("9 broadcast: no owner (root -1) is refused", ok)
+ s = Real(2 * H, H)
+ try:
+ s._untwin(SimpleNamespace(sid=4, twin=None, st=St(), extent=None)); ok = False
+ except RuntimeError:
+ ok = True
+ check("9 untwin: a lane with no twin is refused", ok)
+ h = Real(2 * H, H)
+ x = h.pool.add(0, 8 * A); x.owner = 1; t, lane = twin(h, H, 8 * A, x); h.pool.add(H + 8 * A, 4 * A); h.keep("q", H + 16 * A, 4 * A)
+ hh = h._shard_health()
+ check("9 health: per-part rows (free, twin, kept, live) and the fetch counters",
+ hh["parts"][1]["twin_rows"] == 8 * A and hh["parts"][1]["kept_rows"] == 4 * A + 4 * A and "fetches" in hh["fetch"])
+ finally:
+ shard.ON = False
+ shard.setup(0, 2, 4096 * 512)
+section("9 hardening", hardening)
+
+def signature():
+ import types, tensorfold.cuda.spill as spill, tensorfold.cuda.spill_blocks as sb
+ got = {}
+ class Store:
+ def __init__(self, cfg, **kw): got["sig"] = kw["signature"]
+ def ring(self): pass
+ saved = (spill.build_id, spill.weights_id, sb.BlockStore)
+ spill.build_id = lambda *a: "b"; spill.weights_id = lambda *a: "w"; sb.BlockStore = Store
+ try:
+ def make(sharded):
+ shard.ON = sharded
+ d = SimpleNamespace(
+ g=SimpleNamespace(spill_cfg=object(), drafter=None, model_dir="m", drafter_dir=None, agreed=[1, 2],
+ _gather_ints=None),
+ arena=SimpleNamespace(planes=[SimpleNamespace(tensor=torch.zeros(4, 512, dtype=torch.bfloat16), div=1, pad=0)]),
+ grid=0, drafts=None, w=SimpleNamespace(world=2, device="cpu"), rank=0, pool=Pool(2 * H, half=H if sharded else 0),
+ _guard_pool=lambda: None)
+ multi.MultiDecoder._spill_store(d)
+ return got["sig"]
+ a, b = make(False), make(True)
+ finally:
+ shard.ON = False
+ spill.build_id, spill.weights_id, sb.BlockStore = saved
+ check("9 spill: sharded and unsharded runs have different stores", a != b)
+ check("9 spill: an unsharded run's signature is unchanged (no kvshard marker)", "kvshard" not in a and "kvshard" in b)
+section("9 spill", signature)
+
+# ---- 10 : the cross-part carry (TF_GLM_KV_SHARD_CARRY): decisions, the ops and their order ------------------------------
+# A hit used to be forced into its state's part: a full part dropped it (the prompt prefilled again) or evicted other
+# conversations' states, while the other part sat empty. Now rank 0 may carry the rows into another part
+# (``Arena.carry``): ADMIT copy=2, XMOVE for a live stream. Only to avoid a real cost: never to even the parts out, never
+# when the hit's part fits the request without evicting anything. These are the decisions (``_place_hit``, ``_relocate``),
+# the ops and their order around the collective, the follower's side, and what the old code decided.
+import collections
+import contextlib
+from tensorfold.families.glm5_next.cuda import pool as poolmod
+from tensorfold.families.glm5_next.cuda.pool import Arena, Plane
+from tensorfold.engine import grammar as _grammar # noqa: F401 (imported by admit)
+
+
+def carry_on(on=True):
+ saved = multi.KV_CARRY
+ multi.KV_CARRY = on
+ try:
+ yield
+ finally:
+ multi.KV_CARRY = saved
+
+
+def _mm(name):
+ return getattr(multi.MultiDecoder, name, None)
+
+
+class FakeArena:
+ """What the decoder asks of its arena, recorded in the decoder's event list (its order against the ops matters)."""
+ def __init__(self, ev): self.ev = ev; self.planes = [SimpleNamespace(div=4)]
+ def copy(self, a, b, n): self.ev.append(("copy", a, b, n))
+ def carry(self, a, b, n, comm): self.ev.append(("carry", a, b, n))
+ def sharded_bytes(self, n): return n * 5808
+
+
+class Car(Real):
+ """Real + the carry's decisions and ops, with the events (ops emitted, syncs, evictions, copies, carries) in order."""
+ _place_hit = _mm("_place_hit"); _place = _mm("_place"); _pins = _mm("_pins"); _pressed = _mm("_pressed")
+ _fits_unevicted = _mm("_fits_unevicted"); _placeable = _mm("_placeable")
+ _refused = _mm("_refused"); _room_free = _mm("_room_free"); _free_elsewhere = _mm("_free_elsewhere")
+ _grow_fits = _mm("_grow_fits"); _rescue = _mm("_rescue"); _relocate = _mm("_relocate"); _xmove = _mm("_xmove")
+ _legal = _mm("_legal"); _move_to = _mm("_move_to"); _move_lane = _mm("_move_lane")
+ _carry = _mm("_carry"); _recent = _mm("_recent"); _touch = _mm("_touch")
+ _guard_pool = _mm("_guard_pool"); _release_rows = _mm("_release_rows")
+
+ def __init__(self, rows, half):
+ super().__init__(rows, half)
+ self.carry = multi.carry_stats(); self.tune = SimpleNamespace(lone=False); self.events = []
+ self.arena = FakeArena(self.events); self.g = SimpleNamespace(comm=None); self.partial = None
+ self.w = SimpleNamespace(world=2); self.xticks = 0; self.entered = {}; self.carry_kind = None
+ def _emit(self, op, payload): self.events.append(("emit", op)); return super()._emit(op, payload)
+ def _sync(self): self.events.append(("sync",))
+ def _evict(self, c, spill=True): self.events.append(("evict", c.name)); return super()._evict(c, spill)
+
+
+def place(s, hit, need, key):
+ """_place_hit, and the count ``admit`` makes once the ADMIT is queued."""
+ base, copy, h = s._place_hit(hit, need, key)
+ if copy == 2 and s.carry_kind:
+ s.carry[s.carry_kind] += 1
+ return base, copy, h
+
+
+def put_state(s, x, cid, n, own=False, name=None):
+ """A kept state of extent x: n tokens of conversation ``cid`` (its ids and key are [cid] * n, so a prompt of the same
+ conversation extends it and another's does not)."""
+ c = SimpleNamespace(name=name or f"s{len(s.kept)}", ids=[cid] * n, key=[cid] * n, extent=x, own=own, shared=False,
+ kid=len(s.kept), chat=cid, images=False, head=None, drafter_end=-1, drafter_rows=None)
+ x.kept.append(c); s.kept.append(c)
+ return c
+
+
+def lane_of(s, x, sid, pos=None, **kw):
+ """A decoding stream in extent x (``pos`` tokens in; default: the extent's size)."""
+ lane = SimpleNamespace(sid=sid, twin=None, st=St(x.size if pos is None else pos), extent=x, decoding=True, xwhy=None,
+ paused=False, s=SimpleNamespace(done=False, count=10 ** 9, out=[], emit=None), depth=0, head=None,
+ moved_at=-(1 << 30), came_from=-1, **kw)
+ s.lanes[sid] = lane
+ x.owner = sid
+ return lane
+
+
+def rescue_layout():
+ """Part 0: a live stream (24A) and the kept hit (8A): full. Part 1 empty."""
+ s = Car(2 * H, H)
+ s.pool.add(0, 24 * A).owner = 1
+ x = s.pool.add(24 * A, 8 * A)
+ return s, x, put_state(s, x, 7, 8 * A, own=True)
+
+
+def pressure_layout(live1=0, hit_n=8 * A):
+ """Part 0: a live stream (12A), the hit's extent (8A), another conversation's kept prompt y (8A) and 4A free: a request
+ of 14A fits only by evicting y. Part 1: ``live1`` rows of a live stream."""
+ s = Car(2 * H, H)
+ s.pool.add(0, 12 * A).owner = 1
+ x = s.pool.add(12 * A, 8 * A)
+ hit = put_state(s, x, 7, hit_n, own=True, name="hit")
+ y = put_state(s, s.pool.add(20 * A, 8 * A), 3, 8 * A, name="y")
+ if live1:
+ s.pool.add(H, live1 * A).owner = 2
+ return s, x, hit, y
+
+
+def rescue_cases():
+ with carry_on():
+ s, x, hit = rescue_layout()
+ base, copy, h = place(s, hit, 16 * A, [7] * (20 * A))
+ check("10 rescue: a full part no longer drops the hit: it is carried into the part with room",
+ copy == 2 and h is hit and s.pool.half_of(base) == 1 and s.evicted == [] and hit in s.kept)
+ check("10 rescue: the hit's extent and kept state stay (a carry copies)", x in s.pool.extents and x.kept == [hit])
+ check("10 rescue: counted as rescued, and it is not a refusal (no_part back where it was)",
+ s.carry["rescued"] == 1 and s.carry["pressure"] == s.carry["others"] == 0 and s.no_part == 0)
+ check("10 rescue: nothing moved or evicted to make the room", not [e for e in s.events if e[0] in ("evict", "emit")])
+ # the old code's refusal count survives a rescue that is refused: a live stream's extent holding a small hit, its part
+ # full (the copy beside it is refused: counted), the hit under the minimum (no rescue), the request placed elsewhere
+ for on in (True, False):
+ with carry_on(on):
+ s = Car(2 * H, H)
+ s.pool.add(0, 24 * A).owner = 1
+ x = s.pool.add(24 * A, 8 * A); hit = put_state(s, x, 7, 1024); x.owner = 3
+ yy = put_state(s, s.pool.add(H, 32 * A), 3, 32 * A, name="yy")
+ base, copy, h = place(s, hit, 16 * A, [7] * (20 * A))
+ check(f"10 rescue (carry {int(on)}): a hit under the minimum in a live stream's extent whose part is full is dropped, "
+ f"the other part's kept prompt evicted, and the refusal of the part's own try counted once, as before",
+ h is None and s.evicted == ["yy"] and s.no_part == 1)
+ # the other part has the room, but not a block for each stream it holds and the arriving one: free, not roomy
+ s, x, hit = rescue_layout()
+ s.pool.add(H, 16 * A).owner = 2 # (the 16A would fit, its headroom would not)
+ base, copy, h = place(s, hit, 16 * A, [7] * (20 * A))
+ check("10 rescue: no headroom in the free rows of the other part: the pressure rule leaves it alone, the rescue "
+ "(evicting there as the drop would have) still keeps the hit", copy == 2 and s.pool.half_of(base) == 1 and s.carry["rescued"] == 1)
+ # the other part is full of kept prompts: the oldest go (as dropping the hit would have evicted them), the hit stays
+ s, x, hit = rescue_layout()
+ s.kept = []
+ q0 = put_state(s, s.pool.add(H, 16 * A), 3, 16 * A, name="q0"); q1 = put_state(s, s.pool.add(H + 16 * A, 16 * A), 4, 16 * A, name="q1")
+ s.kept.append(hit)
+ base, copy, h = place(s, hit, 16 * A, [7] * (20 * A))
+ check("10 rescue: a part full of kept prompts gives up its oldest, the hit stays and its rows travel",
+ copy == 2 and h is hit and base == H and s.evicted == ["q0"] and q1 in s.kept and s.carry["rescued"] == 1)
+ # a grow that cannot work evicts nothing: part 0 holds the hit's extent (4A), another kept prompt (4A), a live
+ # stream (20A) and 4A free; 16A wanted. Growing the extent in place would evict the other prompt and still fall
+ # short (12A), so the hit is carried instead and the other conversation keeps its state
+ s = Car(2 * H, H)
+ s.pool.add(0, 20 * A).owner = 1
+ x = s.pool.add(20 * A, 4 * A); hit = put_state(s, x, 7, 4 * A, own=True, name="hit")
+ y = put_state(s, s.pool.add(24 * A, 4 * A), 3, 4 * A, name="y")
+ base, copy, h = place(s, hit, 16 * A, [7] * (20 * A))
+ check("10 rescue: a grow that cannot work evicts no other conversation's state before the hit is carried",
+ copy == 2 and h is hit and s.evicted == [] and y in s.kept and s.pool.half_of(base) == 1)
+ # a live stream's extent holding the hit (a shared prefix its stream wrote): the copy needs room beside it
+ s = Car(2 * H, H)
+ s.pool.add(0, 24 * A).owner = 1
+ x = s.pool.add(24 * A, 8 * A); hit = put_state(s, x, 7, 8 * A); x.owner = 3
+ base, copy, h = place(s, hit, 16 * A, [7] * (20 * A))
+ check("10 rescue: also when the hit lies in a live stream's extent (the copy has no room beside it)",
+ copy == 2 and h is hit and s.pool.half_of(base) == 1 and s.carry["rescued"] == 1 and s.evicted == [])
+ # nothing anywhere: NoRoom, and the counters are what the old code left
+ for on in (True, False):
+ with carry_on(on):
+ s = Car(2 * H, H)
+ s.pool.add(0, 24 * A).owner = 1; s.pool.add(H, 32 * A).owner = 2
+ x = s.pool.add(24 * A, 8 * A); hit = put_state(s, x, 7, 8 * A)
+ try:
+ place(s, hit, 16 * A, [7] * (20 * A)); raised = False
+ except multi.NoRoom:
+ raised = True
+ check(f"10 rescue (carry {int(on)}): no room in any part is NoRoom, the refusal counted once, nothing evicted",
+ raised and s.no_part == 1 and s.evicted == [])
+ # carry off: the old drop, exactly
+ with carry_on(False):
+ s, x, hit = rescue_layout()
+ base, copy, h = place(s, hit, 16 * A, [7] * (20 * A))
+ check("10 carry off: the hit is dropped as before (a fresh prompt in the other part)",
+ h is None and copy == 0 and s.pool.half_of(base) == 1 and s.no_part == 0 and s.carry["hits"] == 0
+ and not s.carry["rescued"])
+section("10 rescue", rescue_cases)
+
+
+def lane_twin(s, x, sid=5):
+ """x's stream (a lane filling in it) holds a twin in part 1."""
+ t, lane = twin(s, H + 24 * A, 8 * A, x, sid=sid)
+ x.owner = sid
+ return lane
+
+
+def pins_cases():
+ pins = (("loading", lambda s, x: setattr(x, "loading", object())),
+ ("twin", lambda s, x: setattr(x, "twin", True)),
+ ("twin", lambda s, x: lane_twin(s, x)),
+ ("partial", lambda s, x: (lane_of(s, x, 5), setattr(s, "partial", SimpleNamespace(contains=lambda sid: sid == 5, group=[])))))
+ for why, setup in pins:
+ with carry_on():
+ s, x, hit = rescue_layout()
+ setup(s, x)
+ base, copy, h = place(s, hit, 16 * A, [7] * (20 * A))
+ check(f"10 pins: rows pinned ({why}) are not carried (the rescue): the hit is dropped as before, refusal counted once",
+ h is None and copy == 0 and s.carry["refused"][why] == 1 and s.carry["hits"] == s.carry["rescued"] == 0
+ and not [e for e in s.events if e[0] == "carry"])
+ with carry_on():
+ s, x, hit, y = pressure_layout()
+ setup(s, x)
+ base, copy, h = place(s, hit, 14 * A, [7] * (20 * A))
+ check(f"10 pins: rows pinned ({why}) are not carried (the pressure rule): the request is placed in its part as before",
+ copy != 2 and s.carry["refused"][why] == 1 and s.carry["hits"] == s.carry["pressure"] == 0)
+ with carry_on(): # a pinned twin: the fill part way through its layers
+ s, x, hit = rescue_layout()
+ x.twin = True
+ lane = SimpleNamespace(sid=8, twin=[x], st=St(), extent=None, decoding=False)
+ s.lanes[8] = lane
+ s.partial = SimpleNamespace(contains=lambda sid: sid == 8, group=[(lane, A)])
+ check("10 pins: a pinned twin extent says pinned (before twin)", s._pins(x) == "pinned")
+ x.twin = False; s.partial = None
+ check("10 pins: nothing pins an ordinary kept extent", s._pins(x) is None)
+section("10 pins", pins_cases)
+
+
+def pressure_cases():
+ key = [7] * (20 * A)
+ need = 14 * A
+ with carry_on():
+ s, x, hit, y = pressure_layout()
+ check("10 pressure: the setup: its part would evict y to place the request, and could (so it is no rescue)",
+ not s._fits_unevicted(hit, need, []) and s._placeable(hit, need))
+ base, copy, h = place(s, hit, need, key)
+ check("10 pressure: fitting the request would evict a kept prompt and the other part has the room free: the hit is "
+ "carried there, y keeps its state", copy == 2 and h is hit and s.pool.half_of(base) == 1 and s.evicted == [] and y in s.kept)
+ check("10 pressure: counted as pressure only; nothing moved in the other part", s.carry["pressure"] == 1
+ and s.carry["rescued"] == s.carry["others"] == 0 and not [e for e in s.events if e[0] == "emit"])
+ # the same pool, the other part without headroom for its streams (free exactly the request): evict as before
+ s, x, hit, y = pressure_layout(live1=18)
+ base, copy, h = place(s, hit, need, key)
+ check("10 pressure: free rows without the headroom (a block for each stream there and the one arriving) are no room: "
+ "no carry, y is evicted and the extent grows in place as before",
+ copy == 0 and base == x.base and s.evicted == ["y"] and s.carry["hits"] == 0 and s.carry["refused"]["no_target"] == 1)
+ s, x, hit, y = pressure_layout(live1=17) # (1A more free than the request: its headroom, a block each
+ base, copy, h = place(s, hit, need, key) # for the stream there and the arriving one, is 2 blocks = A)
+ check("10 pressure: ... and with the headroom free it carries", copy == 2 and s.pool.half_of(base) == 1 and s.evicted == [])
+ # P fits without evicting anything: never, however much emptier the other part is
+ s = Car(2 * H, H)
+ s.pool.add(0, 12 * A).owner = 1
+ x = s.pool.add(12 * A, 8 * A); hit = put_state(s, x, 7, 8 * A, own=True)
+ base, copy, h = place(s, hit, need, key)
+ check("10 no pressure: its part fits the request without evicting (12A of live streams, 20A of room): no carry, the "
+ "extent grows in place, though the other part is empty",
+ copy == 0 and base == x.base and s.carry["hits"] == 0 and not any(s.carry["refused"].values()))
+ s = Car(2 * H, H) # ...and with live streams all on one side
+ for i in range(5):
+ s.pool.add(i * 4 * A, 4 * A).owner = 10 + i
+ x = s.pool.add(20 * A, 8 * A); hit = put_state(s, x, 7, 8 * A, own=True)
+ base, copy, h = place(s, hit, 10 * A, key)
+ check("10 no pressure: 5 live streams against none is no reason (decode spread is not worth a move)",
+ copy == 0 and s.carry["hits"] == 0 and not any(s.carry["refused"].values()))
+ # free rows that are not together: compacting gathers them, no eviction, no carry
+ s = Car(2 * H, H)
+ s.pool.add(0, 4 * A).owner = 1; s.pool.add(8 * A, 4 * A).owner = 2
+ x = s.pool.add(16 * A, 4 * A); hit = put_state(s, x, 7, 4 * A, own=True); x.owner = 3
+ base, copy, h = place(s, hit, 10 * A, key)
+ check("10 no pressure: scattered free rows of its own part (gathered by compacting) fit it: no carry",
+ copy == 1 and s.pool.half_of(base) == 0 and s.carry["hits"] == 0 and s.evicted == [])
+ # a hit under the minimum is never carried: placed as before
+ s, x, hit, y = pressure_layout(hit_n=1024)
+ base, copy, h = place(s, hit, need, key)
+ check("10 pressure: a hit under 2,048 tokens is never carried: refused as small, y evicted as before",
+ copy == 0 and s.carry["refused"]["small"] == 1 and s.carry["hits"] == 0 and s.evicted == ["y"])
+ s, x, hit, y = pressure_layout(hit_n=2048)
+ check("10 pressure: a hit of exactly 2,048 tokens carries", place(s, hit, need, key)[1] == 2)
+ # the rescue and the others branch have the minimum too
+ s, x, hit = rescue_layout()
+ s.kept[0].ids = s.kept[0].key = [7] * 1024
+ base, copy, h = place(s, hit, 16 * A, key)
+ check("10 rescue: a hit under 2,048 tokens is dropped as before (cheaper to recompute than to carry)",
+ h is None and s.carry["refused"]["small"] == 1)
+ # no ping-pong: the conversation was carried to part 1 because part 0 lacked room; its next turn, kept there, grows
+ # there (room), and is not carried back while part 0 still lacks room
+ s, x, hit = rescue_layout()
+ base, copy, h = place(s, hit, 16 * A, key)
+ nx = s.pool.add(base, 16 * A) # the stream's extent, then its kept state (turn 2)
+ turn2 = put_state(s, nx, 7, 12 * A, own=True, name="turn2")
+ b2, c2, _ = place(s, turn2, 20 * A, [7] * (24 * A))
+ check("10 no ping-pong: the next turn grows in the part it was carried to (room there): not carried back",
+ c2 == 0 and b2 == nx.base)
+ s.pool.add(nx.end, 2 * H - nx.end).owner = 9 # part 1 fills up; part 0 still has no room
+ try:
+ b3, c3, _ = place(s, turn2, 28 * A, [7] * (30 * A))
+ except multi.NoRoom:
+ c3 = None
+ check("10 no ping-pong: a turn that part 1 cannot fit is not carried back into part 0 while part 0 lacks room",
+ c3 != 2)
+section("10 pressure", pressure_cases)
+
+
+def others_cases():
+ def lay(live0=16, live1=0):
+ s = Car(2 * H, H)
+ s.pool.add(0, live0 * A).owner = 1
+ if live1:
+ s.pool.add(H, live1 * A).owner = 2
+ x = s.pool.add(live0 * A, 16 * A)
+ hit = put_state(s, x, 7, 8 * A, name="hit"); other = put_state(s, x, 9, 16 * A, name="other")
+ return s, x, hit, other
+ with carry_on():
+ s, x, hit, other = lay()
+ base, copy, h = place(s, hit, 6 * A, [7] * (20 * A))
+ check("10 others: the part has no free rows for the copy: another part's free rows carry it, the other conversation keeps its state",
+ copy == 2 and h is hit and s.pool.half_of(base) == 1 and s.evicted == [] and other in x.kept and s.carry["others"] == 1)
+ check("10 others: counted as others only", s.carry["rescued"] == s.carry["pressure"] == 0)
+ s, x, hit, other = lay(live0=8)
+ base, copy, h = place(s, hit, 6 * A, [7] * (20 * A))
+ check("10 others: free rows in its own part still get the copy (copy 1), nothing carried",
+ copy == 1 and s.pool.half_of(base) == 0 and s.carry["others"] == 0 and s.carry["hits"] == 0)
+ s, x, hit, other = lay(live1=32)
+ base, copy, h = place(s, hit, 6 * A, [7] * (20 * A))
+ check("10 others: no free rows anywhere: the others are evicted and the extent grows in place, as before",
+ copy == 0 and h is hit and base == x.base and s.evicted == ["other"] and s.carry["refused"]["no_target"] == 1)
+ s, x, hit, other = lay()
+ hit.ids = hit.key = [7] * 1024
+ base, copy, h = place(s, hit, 6 * A, [7] * (20 * A))
+ check("10 others: a hit under 2,048 tokens is not carried (small), the others are evicted as before",
+ copy == 0 and s.carry["refused"]["small"] == 1 and s.evicted == ["other"])
+ s, x, hit, other = lay()
+ s.tune.lone = True
+ base, copy, h = place(s, hit, 6 * A, [7] * (20 * A))
+ check("10 others (a lone setting that would overwrite them): the others kept by carrying the hit, nothing evicted",
+ copy == 2 and s.evicted == [] and s.carry["pressure"] == 1)
+ with carry_on(False):
+ s, x, hit, other = lay()
+ base, copy, h = place(s, hit, 6 * A, [7] * (20 * A))
+ check("10 others (carry off): the others are evicted and the extent grows in place, as before",
+ copy == 0 and base == x.base and s.evicted == ["other"] and s.carry["refused"]["no_target"] == 0)
+section("10 others", others_cases)
+
+
+# -- the old code as the reference: the same decisions with the carry off or without parts --------------------------------
+def old_place(s, hit, need, key):
+ """MultiDecoder.admit's placement block as of kvshard-v7, verbatim."""
+ copy = 0
+ base = None
+ if hit is not None and hit.extent.owner is None:
+ x = hit.extent
+ others = [c for c in x.kept if len(c.ids) > len(hit.ids) and key[:len(c.ids)] != c.key]
+ if others and not s.tune.lone:
+ base = s.pool.place(need, half=s.pool.half_of(x) if s.pool.half else None)
+ copy = int(base is not None)
+ if base is None:
+ for c in others:
+ s._evict(c)
+ if s._grow(x, need, protect=[x]):
+ base = x.base
+ else:
+ hit = None
+ if base is None:
+ base = s._room(need, [hit.extent] if hit is not None else [],
+ half=s.pool.half_of(hit.extent) if hit is not None and s.pool.half else None)
+ if base is None and hit is not None:
+ hit = None
+ base = s._room(need)
+ if base is None:
+ raise multi.NoRoom("no room")
+ copy = int(hit is not None)
+ return base, copy, hit
+
+
+def rand_car(seed, parts=2, sharded=True, heavy=False):
+ """A random pool of live (some with a stream), kept, loading and free ranges, twins of filling prompts and a slice in
+ flight, in ``parts`` parts: (decoder, hit, need, key); the same seed builds the same pool, so one decoder can run
+ the old code and another the new."""
+ rnd = random.Random(seed)
+ s = Car(parts * H, H if sharded else 0)
+ states, nxt, lives, twins = [], 0, [], []
+ for h in range(parts):
+ at = h * H
+ while True:
+ n = rnd.randrange(1, 9) * A
+ if at + n > (h + 1) * H:
+ break
+ kind = rnd.choice(["live", "live", "live", "kept", "free", "load", "twin"] if heavy else
+ ["live", "kept", "kept", "kept", "free", "load", "twin"])
+ if kind == "live":
+ x = s.pool.add(at, n)
+ x.owner = 100 + at // A
+ if rnd.random() < 0.5:
+ lane_of(s, x, x.owner, pos=rnd.randrange(1, n // A + 1) * A - 512)
+ lives.append(x)
+ elif kind == "kept":
+ x = s.pool.add(at, n)
+ for L in sorted({rnd.randrange(1, n // A + 1) * A for _ in range(rnd.choice([1, 1, 2]))}):
+ states.append(put_state(s, x, rnd.choice([3, 5, 7]), L, own=rnd.random() < 0.5, name=f"k{nxt}"))
+ nxt += 1
+ elif kind == "load" and sharded:
+ x = s.pool.add(at, n)
+ x.loading = SimpleNamespace(n=n // 2, lj=None)
+ elif kind == "twin" and sharded and lives:
+ t = s.pool.add(at, n, twin=True)
+ twins.append(t)
+ at += n + rnd.choice([0, 0, A])
+ for t in twins: # each twin belongs to a filling prompt living in another part
+ homes = [x for x in lives if s.pool.half_of(x) != s.pool.half_of(t)]
+ if not homes:
+ s.pool.remove(t)
+ continue
+ x = rnd.choice(homes)
+ lane = s.lanes.get(x.owner) or lane_of(s, x, x.owner, pos=A)
+ lane.decoding = False
+ lane.twin = (lane.twin or []) + [t]
+ lane.st.twin_base, lane.st.twin_size = t.base, t.size
+ filling = [l for l in s.lanes.values() if not l.decoding]
+ if filling and rnd.random() < 0.5:
+ chosen = {rnd.choice(filling).sid}
+ s.partial = SimpleNamespace(contains=lambda sid: sid in chosen, group=[(l, A) for l in filling if l.sid in chosen])
+ rnd.shuffle(s.kept)
+ hit = rnd.choice(states) if states and rnd.random() < 0.9 else None
+ need = rnd.randrange(2, 20) * A
+ key = ([hit.ids[0]] if hit is not None else [0]) * (need + A)
+ s.tune.lone = rnd.random() < 0.15
+ return s, hit, need, key
+
+
+def run_new(s, hit, need, key):
+ try:
+ base, copy, h = s._place_hit(hit, need, key)
+ return ("ok", base, copy, h.name if h is not None else None)
+ except multi.NoRoom:
+ return ("noroom",)
+
+
+def run_old(s, hit, need, key):
+ try:
+ base, copy, h = old_place(s, hit, need, key)
+ return ("ok", base, copy, h.name if h is not None else None)
+ except multi.NoRoom:
+ return ("noroom",)
+
+
+def snapshot_of(s):
+ return (sorted((x.base, x.size, x.owner is not None, tuple(c.name for c in x.kept), x.twin) for x in s.pool.extents),
+ list(s.evicted), s.no_part, [e for e in s.events if e[0] in ("emit", "evict")])
+
+
+def old_equivalence():
+ bad = []
+ for sharded, on in ((True, False), (False, True), (False, False)):
+ n = 0
+ for seed in range(500):
+ a = rand_car(seed, sharded=sharded)
+ b = rand_car(seed, sharded=sharded)
+ with carry_on(on):
+ got = run_new(*a)
+ want = run_old(*b)
+ n += 1
+ if got != want or snapshot_of(a[0]) != snapshot_of(b[0]):
+ bad.append((sharded, on, seed, got, want))
+ check(f"10 old code ({'parts, carry off' if sharded else 'one pool, carry ' + ('on' if on else 'off')}): {n} random pools (with "
+ f"streams, twins, stored prompts being read and a slice in flight) place, evict, move and count exactly as "
+ f"kvshard-v7 did ({bad[:1]})", not [b for b in bad if b[0] == sharded and b[1] == on])
+
+
+def new_invariants():
+ bad, carried, saved_evictions, dropped_kept, same_no_part, no_part_checked = [], 0, 0, 0, 0, 0
+ kinds = collections.Counter()
+ for seed in range(1200):
+ for heavy in (False, True):
+ a = rand_car(seed, heavy=heavy)
+ b = rand_car(seed, heavy=heavy)
+ pins = a[0]._pins(a[1].extent) if a[1] is not None else None
+ with carry_on(False):
+ old = run_new(*b)
+ with carry_on():
+ new = run_new(*a)
+ s, hit = a[0], a[1]
+ tag = (seed, heavy)
+ if (old[0] == "noroom") != (new[0] == "noroom"):
+ bad.append((tag, "room", old, new)); continue
+ if new[0] == "noroom":
+ continue
+ _, base, copy, kept = new
+ old_evicted = b[0].evicted
+ if copy == 2:
+ carried += 1
+ kinds[s.carry_kind] += 1
+ if hit is None or kept != hit.name or s.pool.half_of(base) == s.pool.half_of(hit.extent) or pins is not None \
+ or len(hit.ids) < multi.CARRY_MIN:
+ bad.append((tag, "copy 2 not across parts, or pinned, or small", new, pins)); continue
+ # a carry avoids a real cost: the old code evicted something, or dropped the hit
+ if not (old_evicted or old[3] is None):
+ bad.append((tag, "carried where the old code evicted nothing and kept the hit", old, new)); continue
+ if old_evicted or old[3] is None:
+ saved_evictions += 1
+ if s.carry_kind != "rescued" and [e for e in s.events if e[0] == "evict"]:
+ bad.append((tag, "a pressure/others carry evicted something", s.events)); continue
+ else:
+ # the part fits the request without evicting: the old code's decision, exactly, hit kept
+ if old[3] is not None and not old_evicted and old != new:
+ bad.append((tag, "no eviction in the old code and the new one decided otherwise", old, new)); continue
+ if copy == 1 and hit is not None and s.pool.half_of(base) != s.pool.half_of(hit.extent):
+ bad.append((tag, "copy 1 across parts", new)); continue
+ if old[3] is not None and new[3] is None:
+ bad.append((tag, "dropped a hit the old code kept", old, new)); continue
+ no_part_checked += 1
+ if s.no_part == b[0].no_part:
+ same_no_part += 1
+ try:
+ s.pool.add(base, a[2])
+ except ValueError:
+ if copy != 0:
+ bad.append((tag, "placed on taken rows", new))
+ check(f"10 random pools: a carry only where the old code evicted or dropped, never where its part fits the request without "
+ f"evicting (decided as before, hit kept), pressure and others carries evict nothing, nothing pinned or under 2,048 "
+ f"tokens, NoRoom the same ({carried} carried {dict(kinds)}, {saved_evictions} evictions or drops avoided; {bad[:1]})", not bad)
+ check("10 random pools: the carry actually happens in every kind (the sweep reaches them)",
+ carried > 40 and kinds["pressure"] >= 3 and kinds["rescued"] >= 3)
+ check(f"10 random pools: where nothing is carried the refusal count (/health refused_no_part) is the old code's "
+ f"({same_no_part} of {no_part_checked})", same_no_part == no_part_checked > 100)
+
+
+def grow_fits_sound():
+ bad = checked = 0
+ for seed in range(2500):
+ s, hit, need, key = rand_car(seed, heavy=True)
+ if hit is None or hit.extent.owner is not None:
+ continue
+ x = hit.extent
+ no = not s._grow_fits(x, need)
+ if no:
+ checked += 1
+ if s._grow(x, need, protect=[x]): # (on a pool this check does not reuse)
+ bad += 1
+ check(f"10 grow fits: never says no to a grow that works, with streams, twins and stored prompts being read "
+ f"({checked} refusals checked)", bad == 0 and checked > 20)
+
+
+def unevicted_sound():
+ """``_fits_unevicted`` against what the old code does: it says yes exactly when the old code places the request
+ without evicting anything."""
+ bad = yes = no = 0
+ for seed in range(2500):
+ a = rand_car(seed, heavy=bool(seed % 2))
+ s, hit, need, key = a
+ if hit is None:
+ continue
+ others = [c for c in hit.extent.kept if len(c.ids) > len(hit.ids) and key[:len(c.ids)] != c.key] \
+ if hit.extent.owner is None else []
+ fits = s._fits_unevicted(hit, need, others)
+ b = rand_car(seed, heavy=bool(seed % 2))
+ with carry_on(False):
+ old = run_new(*b)
+ silent = old[0] == "ok" and old[3] is not None and not b[0].evicted
+ if fits and not silent:
+ bad += 1
+ if (not fits) and silent:
+ bad += 1
+ yes += fits; no += not fits
+ check(f"10 fits unevicted: yes exactly where the old code placed the request without evicting anything and kept the hit "
+ f"({yes} yes, {no} no; {bad} differ)", bad == 0 and yes > 50 and no > 50)
+section("10 old equivalence", old_equivalence)
+section("10 invariants", new_invariants)
+section("10 grow fits", grow_fits_sound)
+section("10 unevicted", unevicted_sound)
+
+
+# -- the ops, in order: ADMIT copy=2 flushes before the collective; both ranks end with the same pool ---------------------
+from tensorfold.cuda.streams import Stream
+from tensorfold.families.glm5_next.cuda import forward as _forward
+
+
+class FakeState:
+ """forward.State without tensors of the pool: what _admitted touches."""
+ def __init__(self, w, size, rows, caches=None, base=0, slots=None, slot=0, **kw):
+ self.size, self.base, self.slot, self.pos = size, base, slot, 0
+ self.rec = [torch.zeros(2)]; self.cur = [0]; self.conv = torch.zeros(2); self.index = None; self.kc = []
+ self.twin_base = self.twin_size = None; self.binds = []
+ def reset(self): pass
+ def set_pos(self, p): self.pos = p
+ def bind(self, b, n): self.base, self.size = b, n; self.binds.append((b, n))
+
+
+class Adm(Car):
+ """Car with admit and _admitted themselves (rank 0 decides and applies, rank 1 applies what it is sent)."""
+ admit = _mm("admit"); _admitted = _mm("_admitted"); _parse_admit = staticmethod(multi.MultiDecoder._parse_admit)
+ _resume = _mm("_resume"); _kept_by_id = _mm("_kept_by_id"); _rewrites = _mm("_rewrites"); _need = _mm("_need")
+ apply = _mm("apply"); parse = staticmethod(multi.MultiDecoder.parse); _continued = _mm("_continued")
+
+ def __init__(self, rows, half, rank=0):
+ super().__init__(rows, half)
+ self.rank = rank; self.outbox = []
+ self.g = SimpleNamespace(limit=10 ** 9, serial_only=False, vision=None, shared=0, opener=None, comm=None,
+ cache_entries=8, costs=None)
+ self.e = SimpleNamespace(rows=2048, caches=None, slots=None); self.w = SimpleNamespace(world=2)
+ self.count = 4; self.drafts = None; self.dflash_code = [0, 0, 0, 0]; self.grid = 0
+ self.next_sid = self.next_kid = self.next_order = self.next_chat = 0
+ self.broken = None; self.boot = "boot"; self.chat_roots = {}; self.chats_continued = self.chats_continued_prefill = 0
+ self.arena.planes = [SimpleNamespace(div=4)]
+ def _check(self): pass
+ def _emit(self, op, payload):
+ self.events.append(("emit", op)); self.ops.append((op, [int(v) for v in payload]))
+ return multi.MultiDecoder._emit(self, op, payload) # (outbox: what rank 1 is sent)
+ def _sync(self): self.events.append(("sync",))
+
+
+def fake_state():
+ saved = _forward.State
+ _forward.State = FakeState
+ try:
+ yield
+ finally:
+ _forward.State = saved
+
+
+def hit_state(s, x, cid, n, own=False, name="hit"):
+ """A kept state a request can resume from (the fields _admitted and _resume read)."""
+ c = put_state(s, x, cid, n, own=own, name=name)
+ c.rec, c.conv, c.tail, c.mtp_len, c.lineage, c.kid = torch.zeros(2), torch.zeros(2), None, -1, "", s.next_kid
+ s.next_kid += 1
+ return c
+
+
+def adm_rescue(rank=0):
+ """The rescue pool as an Adm: part 0 full (a live stream and the kept hit), part 1 empty."""
+ s = Adm(2 * H, H, rank)
+ s.pool.add(0, 24 * A).owner = 1
+ x = s.pool.add(24 * A, 8 * A)
+ return s, x, hit_state(s, x, 7, 8 * A, own=True)
+
+
+def admit_order():
+ with carry_on(), fake_state():
+ s, x, hit = adm_rescue()
+ s.admit(Stream([7] * (14 * A), 4, None, True))
+ ev = [e[0] if e[0] != "emit" else e for e in s.events]
+ i, j, k = ev.index(("emit", multi.ADMIT)), ev.index("sync"), ev.index("carry")
+ check("10 admit: copy 2 is flushed (_sync) after the ADMIT is queued and BEFORE the carry runs", i < j < k)
+ check("10 admit: the ADMIT says copy 2 and names the hit", s.ops[-1][0] == multi.ADMIT and s.ops[-1][1][5] == 2
+ and s.ops[-1][1][4] == hit.kid)
+ check("10 admit: exactly one sync, and the carry is the hit's rows to the new extent",
+ ev.count("sync") == 1 and s.events[k] == ("carry", hit.extent.base, s.pool.get(max(e.eid for e in s.pool.extents)).base, 8 * A)
+ and not [e for e in s.events if e[0] == "copy"])
+ check("10 admit: carry stats on this rank (hits, tokens, bytes)",
+ s.carry["hits"] == 1 and s.carry["tokens"] == 8 * A and s.carry["bytes"] == 8 * A * 5808 and s.carry["live"] == 0)
+ # copy 1 and copy 0 flush nothing of their own
+ s = Adm(2 * H, H)
+ s.pool.add(H, 4 * A).owner = 2 # (one live stream a part: no balance carry)
+ x = s.pool.add(0, 8 * A); hit = hit_state(s, x, 7, 8 * A); x.owner = 3 # the hit's extent is a live stream's
+ s.admit(Stream([7] * (9 * A), 4, None, True))
+ check("10 admit: a copy within the part (copy 1) has no sync of its own",
+ "sync" not in [e[0] for e in s.events] and s.ops[-1][1][5] == 1
+ and [e for e in s.events if e[0] == "copy"] == [("copy", 0, s.pool.get(max(e.eid for e in s.pool.extents)).base, 8 * A)])
+ s = Adm(2 * H, H)
+ s.pool.add(0, 24 * A).owner = 1
+ x = s.pool.add(24 * A, 4 * A); hit = hit_state(s, x, 7, 4 * A)
+ s.pool.add(H, 24 * A).owner = 2
+ s.admit(Stream([7] * (7 * A), 4, None, True))
+ check("10 admit: taking the extent over in place (copy 0) has no sync either",
+ "sync" not in [e[0] for e in s.events] and s.ops[-1][1][5] == 0 and [e for e in s.events if e[0] in ("carry", "copy")] == [])
+section("10 admit order", admit_order)
+
+
+def two_ranks():
+ # rank 0 admits, rank 1 applies the message: the same pool, the same kept order, the same carry
+ with carry_on(), fake_state():
+ r0, x0, h0 = adm_rescue(0)
+ r1, x1, h1 = adm_rescue(1)
+ r0.admit(Stream([7] * (14 * A), 4, None, True))
+ msg = list(r0.outbox)
+ r1.apply(msg)
+ shape = lambda s: sorted((x.base, x.size, x.owner is not None, [c.name for c in x.kept]) for x in s.pool.extents)
+ check("10 two ranks: rank 1 applying the ADMIT ends with rank 0's pool", shape(r0) == shape(r1))
+ check("10 two ranks: rank 1 carries the same rows to the same place",
+ [e for e in r0.events if e[0] == "carry"] == [e for e in r1.events if e[0] == "carry"] != [])
+ check("10 two ranks: neither copies instead", not [e for e in r0.events + r1.events if e[0] == "copy"])
+ check("10 two ranks: the same kept order (the carried own state is not touched)",
+ [c.name for c in r0.kept] == [c.name for c in r1.kept] and r0.kept[-1] is h0)
+ check("10 two ranks: rank 1 counts the carry too", r1.carry["hits"] == 1 and r1.carry["tokens"] == 8 * A)
+ # a shared prefix (not the conversation's own turn state) stays for the others: touched as ever
+ for own in (True, False):
+ r = []
+ for rank in (0, 1):
+ s, x, hit = adm_rescue(rank)
+ hit.own = own
+ other = put_state(s, s.pool.add(H, 4 * A), 5, 4 * A, name="old")
+ s.kept = [hit, other] # (the hit is the older)
+ r.append(s)
+ r[0].admit(Stream([7] * (14 * A), 4, None, True))
+ r[1].apply(list(r[0].outbox))
+ last = [[c.name for c in s.kept][-1] for s in r]
+ check(f"10 admit: after a carry the resumed state {'keeps its place (its own turn state: the LRU reclaims it first)' if own else 'is touched (a shared prefix stays for the others)'}, on both ranks",
+ last == (["old", "old"] if own else ["hit", "hit"]))
+ # a malformed copy 2 fails closed
+ with carry_on(), fake_state():
+ s = Adm(2 * H, H, 1)
+ x = s.pool.add(0, 8 * A); hit = hit_state(s, x, 7, 8 * A)
+ a = dict(sid=0, slot=0, base=16 * A, size=16 * A, kid=hit.kid, copy=2, count=4, stop_eos=True, draft=True, sampling=None,
+ shared=[], code=[0, 0, 0, 0], prompt=[7] * (9 * A), packed=[], positions=[], images=False, keyed=None)
+ try:
+ s._admitted(a, Stream([7] * (9 * A), 4, None, True), None, None); ok = False
+ except RuntimeError:
+ ok = True
+ check("10 follower: a copy 2 inside one part fails closed", ok and not [e for e in s.events if e[0] == "carry"])
+ s = Adm(2 * H, H, 1)
+ s.pool.add(0, 8 * A)
+ try:
+ s._admitted(dict(a, kid=-1, base=H), Stream([7] * (9 * A), 4, None, True), None, None); ok = False
+ except RuntimeError:
+ ok = True
+ check("10 follower: a copy 2 of no kept prompt fails closed", ok)
+section("10 two ranks", two_ranks)
+
+
+def recent_cases():
+ s = Car(2 * H, H)
+ a = put_state(s, s.pool.add(0, 4 * A), 1, 4 * A, own=True, name="a")
+ b = put_state(s, s.pool.add(H, 4 * A), 2, 4 * A, own=True, name="b")
+ c = put_state(s, s.pool.add(8 * A, 4 * A), 3, 4 * A, own=False, name="c")
+ s._recent(a, 2)
+ check("10 recent: a carried own turn state keeps its place in the LRU order", [k.name for k in s.kept] == ["a", "b", "c"])
+ s._recent(c, 2)
+ check("10 recent: a carried shared prefix is touched (other conversations resume from it)", [k.name for k in s.kept] == ["a", "b", "c"][:2] + ["c"])
+ s._recent(a, 1)
+ check("10 recent: a copy within the part touches an own state as ever", [k.name for k in s.kept][-1] == "a")
+ s._recent(b, 0)
+ check("10 recent: so does taking the extent over", [k.name for k in s.kept][-1] == "b")
+section("10 recent", recent_cases)
+
+
+# -- a live stream moves whole: XMOVE ---------------------------------------------------------------------------------------
+class FakeDisk:
+ """The spill tier as far as a move touches it: what it is asked to release, and the extent's base then; ``waiting``:
+ the rows of states this rank has still to write (what ``_used`` counts), per extent."""
+ def __init__(self, waiting=None): self.releases = []; self.pending = []; self.waiting = []; self.want = waiting
+ def release(self, x, keep): self.releases.append((x.eid, keep, x.base))
+ def stop_load(self, lj, why): pass
+ def put(self, x, n):
+ self.pending.append(SimpleNamespace(point=SimpleNamespace(n=n), where=x, next=0, new=[1]))
+
+
+def xlay(pos=8 * A - 1024, kept=0, lane2=True):
+ """Part 0: stream 1 (extent 8A, ``pos`` tokens in) and stream 2 (24A): full; part 1 empty. ``lane2`` False: stream 2
+ is a live extent without a lane to move."""
+ s = Car(2 * H, H)
+ x = s.pool.add(0, 8 * A)
+ lane = lane_of(s, x, 1, pos=pos)
+ y = s.pool.add(8 * A, 24 * A)
+ if lane2:
+ lane_of(s, y, 2, pos=20 * A)
+ else:
+ y.owner = 2
+ if kept:
+ put_state(s, x, 7, kept, own=True, name="k")
+ return s, x, lane
+
+
+def xmove_cases():
+ with carry_on():
+ s, x, lane = xlay(lane2=False)
+ eid, old = x.eid, x.base
+ check("10 xmove: the lane cannot grow in its part (the setup)", s._grow(x, lane.st.pos + 2048, protect=[x]) is False)
+ ok = s._relocate(lane)
+ size = align_up(lane.st.pos + s.rows_max)
+ check("10 xmove: relocated: the same extent, now in the other part, big enough for the round",
+ ok and x.eid == eid and s.pool.half_of(x) == 1 and x.size == size and x.owner == 1 and x in s.pool.extents)
+ ev = [e for e in s.events if e[0] in ("emit", "sync", "carry")]
+ check("10 xmove: XMOVE is queued, flushed (_sync), and only then does the carry run, of the used rows",
+ ev == [("emit", multi.XMOVE), ("sync",), ("carry", old, x.base, lane.st.pos)])
+ check("10 xmove: the op names the extent, its new base, size and the rows used (rank 0's count rides along)",
+ s.ops[-1] == (multi.XMOVE, [eid, x.base, size, lane.st.pos]))
+ check("10 xmove: the stream is rebound to its new rows", lane.st.binds[-1] == (x.base, x.size))
+ check("10 xmove: no overlap in the pool, the old rows are free",
+ all(a.end <= b.base for a, b in zip(s.pool.extents, s.pool.extents[1:])) and old == 0
+ and s.pool.place(8 * A, half=0) == 0)
+ check("10 xmove: headroom: a block for the arriving stream is free after it in the part it went to",
+ s.pool.room_after(x) >= 2048)
+ check("10 xmove: counted (live, tokens, bytes), the stream remembers where it was and when", s.carry["live"] == 1
+ and s.carry["tokens"] == lane.st.pos and s.carry["bytes"] == lane.st.pos * 5808 and s.carry["hits"] == 0
+ and lane.xwhy is None and lane.came_from == 0 and lane.moved_at == s.xticks and s.entered == {1: s.xticks})
+ # kept states travel with the extent
+ s, x, lane = xlay(kept=8 * A, lane2=False)
+ k = x.kept[0]
+ s._relocate(lane)
+ check("10 xmove: the extent's kept prompts move with it (still in its list and the kept order)",
+ s.pool.half_of(x) == 1 and x.kept == [k] and k in s.kept and k.extent is x)
+ check("10 xmove: the rows carried are the used ones (kept states and the stream's position, whichever is more)",
+ [e for e in s.events if e[0] == "carry"][0][3] == max(8 * A, lane.st.pos))
+ # the free rows are not together: compacting the target part first (MOVEs before the XMOVE)
+ s, x, lane = xlay(lane2=False)
+ for i in range(4):
+ put_state(s, s.pool.add(H + i * 8 * A, 4 * A), 20 + i, 4 * A)
+ ok = s._relocate(lane)
+ ops = [e[1] for e in s.events if e[0] == "emit"]
+ check("10 xmove: free rows gathered by compacting the other part first (MOVEs, then the XMOVE), nothing evicted",
+ ok and ops[-1] == multi.XMOVE and multi.MOVE in ops and set(ops[:-1]) == {multi.MOVE} and s.evicted == [])
+ # headroom in the target: the rows without a block for each stream there and the arriving one are no room
+ s, x, lane = xlay(lane2=False)
+ size = align_up(lane.st.pos + s.rows_max)
+ s.pool.add(H, 32 * A - size).owner = 7 # (exactly size free, no headroom)
+ r = [s._relocate(lane), s.carry["refused"]["no_target"]]
+ s2, x2, lane2_ = xlay(lane2=False)
+ s2.pool.add(H, 32 * A - size - 2 * 2048).owner = 7 # (size and a block each for the stream there and the arriving)
+ check("10 xmove: free rows without headroom are no room (pause as before); with a block for each stream there and the "
+ "arriving one it moves", r == [False, 1] and s2._relocate(lane2_) is True)
+ # the cheapest stream moves: a small one whose leaving lets the stream that cannot grow grow in place
+ s = Car(2 * H, H)
+ a = s.pool.add(0, 16 * A); la = lane_of(s, a, 1, pos=16 * A - 1024) # needs 2048 more rows
+ b = s.pool.add(16 * A, 4 * A); lb = lane_of(s, b, 2, pos=3 * A)
+ s.pool.add(20 * A, 12 * A).owner = 3
+ ok = s._relocate(la)
+ ev = [e for e in s.events if e[0] == "emit"]
+ check("10 xmove: the smallest stream that frees the rows moves, not the stream that cannot grow (3A carried, not 16A): "
+ "the stream then grows in place", ok and s.pool.half_of(b) == 1 and s.pool.half_of(a) == 0 and a.base == 0
+ and ev.count(("emit", multi.XMOVE)) == 1 and [e for e in s.events if e[0] == "carry"][0][3] == 3 * A
+ and a.size >= align_up(la.st.pos + s.rows_max) and lb.moved_at == s.xticks and la.moved_at < 0)
+ # one carry a relocation: the bystander moved but the stream still cannot grow -> it pauses, no second carry
+ s = Car(2 * H, H)
+ a = s.pool.add(0, 16 * A); la = lane_of(s, a, 1, pos=16 * A - 1024)
+ b = s.pool.add(16 * A, 4 * A); lb = lane_of(s, b, 2, pos=3 * A)
+ s.pool.add(20 * A, 12 * A).owner = 3
+ s._grow = lambda *a_, **k_: False
+ ok = s._relocate(la)
+ check("10 xmove: after a bystander's move the stream grows or pauses: one XMOVE, never a second carry",
+ ok is False and [e for e in s.events if e[0] == "emit"].count(("emit", multi.XMOVE)) == 1
+ and s.pool.half_of(b) == 1 and s.pool.half_of(a) == 0)
+ # ...but not one that something pins; then the stream itself
+ s = Car(2 * H, H)
+ a = s.pool.add(0, 16 * A); la = lane_of(s, a, 1, pos=16 * A - 1024)
+ b = s.pool.add(16 * A, 4 * A); lb = lane_of(s, b, 2, pos=3 * A); lb.twin = [s.pool.add(H + 24 * A, 4 * A, twin=True)]
+ s.pool.add(20 * A, 12 * A).owner = 3
+ ok = s._relocate(la)
+ check("10 xmove: the smaller stream is pinned (a twin): the stream that cannot grow moves itself",
+ ok and s.pool.half_of(a) == 1 and s.pool.half_of(b) == 0)
+ # ...nor one that is not small: the stream itself is the cheaper carry
+ s = Car(2 * H, H)
+ a = s.pool.add(0, 4 * A); la = lane_of(s, a, 1, pos=4 * A - 1024)
+ b = s.pool.add(4 * A, 20 * A); lb = lane_of(s, b, 2, pos=19 * A)
+ s.pool.add(24 * A, 8 * A).owner = 3
+ ok = s._relocate(la)
+ check("10 xmove: when the stream that cannot grow is the smaller, it moves itself", ok and s.pool.half_of(a) == 1
+ and s.pool.half_of(b) == 0)
+ # cooldown: a stream that moved is not moved again within the window, nor back; no stream leaves a part another entered
+ K = multi.RELOCATE_HOLD
+ s, x, lane = xlay(lane2=False)
+ s.xticks = 1000
+ lane.moved_at, lane.came_from = 1000 - K + 1, 1
+ check("10 xmove: a stream that moved less than RELOCATE_HOLD rounds ago is not moved again",
+ s._relocate(lane) is False and s.carry["refused"]["no_target"] == 1 and not s.events)
+ s.xticks = 1000 - K + 1 + K
+ check("10 xmove: ... and may after the window", s._relocate(lane) is True)
+ # three parts, so the part it came from is not the only one with room: only the cooldown stops it
+ def three():
+ t = Car(3 * H, H)
+ tx = t.pool.add(0, 8 * A); tl = lane_of(t, tx, 1, pos=8 * A - 1024)
+ t.pool.add(8 * A, 24 * A).owner = 2
+ t.xticks = 1000
+ tl.moved_at, tl.came_from = 1000 - K + 1, 1
+ return t, tx, tl
+ t, tx, tl = three()
+ check("10 xmove: inside the window it stays put though a third part has the room (the cooldown, not the part it left)",
+ t._relocate(tl) is False and not t.events and t._move_to(tl, 8 * A) == 2)
+ t, tx, tl = three()
+ tl.moved_at = 1000 - K
+ check("10 xmove: ... and the window passed it may move again",
+ t._relocate(tl) is True and t.pool.half_of(tx) in (1, 2))
+ s, x, lane = xlay(lane2=False)
+ s.xticks = 1000
+ s.entered[0] = 1000 - K + 1
+ check("10 xmove: no stream leaves a part another entered within the window (moves do not answer one another)",
+ s._relocate(lane) is False and not s.events)
+ s.xticks = 1000 + 1
+ check("10 xmove: ... and may after it", s._relocate(lane) is True)
+ s, x, lane = xlay(lane2=False)
+ s.xticks = 1000
+ lane.moved_at, lane.came_from = 1000 - K + 1, 1
+ check("10 xmove: never back into the part a stream just left (_move_to), though it has the room",
+ s._move_to(lane, 8 * A) is None)
+ lane.moved_at = 1000 - K
+ check("10 xmove: ... once the window has passed it may", s._move_to(lane, 8 * A) == 1)
+ # refusals: counted once a reason, nothing queued, nothing moved
+ def refuse(why, setup):
+ s, x, lane = xlay(lane2=False)
+ setup(s, x, lane)
+ r = [s._relocate(lane), s._relocate(lane)]
+ check(f"10 xmove: a stream with {why} is not relocated, counted once; nothing queued or moved",
+ r == [False, False] and s.carry["refused"][why] == 1 and not s.events and x.base == 0)
+ refuse("loading", lambda s, x, l: setattr(x, "loading", object()))
+ refuse("partial", lambda s, x, l: setattr(s, "partial", SimpleNamespace(contains=lambda sid: sid == 1, group=[(l, A)])))
+
+ def tw(s, x, l):
+ t = s.pool.add(H + 8 * A, 8 * A); t.twin = True
+ l.twin = [t]
+ refuse("twin", tw)
+
+ def pn(s, x, l): # (the extent itself a pinned twin of a fill in flight)
+ x.twin = True
+ ex = s.pool.add(H, 4 * A); ex.owner = 9
+ f = SimpleNamespace(sid=9, twin=[x], st=St(), extent=ex, decoding=False)
+ s.lanes[9] = f
+ s.partial = SimpleNamespace(contains=lambda sid: sid == 9, group=[(f, A)])
+ refuse("pinned", pn)
+ s, x, lane = xlay(lane2=False)
+ s.pool.add(H, 32 * A).owner = 3
+ r = [s._relocate(lane), s._relocate(lane)]
+ check("10 xmove: no part with the room is no_target (counted once a stream), nothing evicted or moved",
+ r == [False, False] and s.carry["refused"]["no_target"] == 1 and not s.events)
+ lane.xwhy = None
+ s._relocate(lane)
+ check("10 xmove: and counted again when the reason is new again", s.carry["refused"]["no_target"] == 2)
+ with carry_on(False):
+ s, x, lane = xlay()
+ check("10 xmove: carry off: never", s._relocate(lane) is False and not s.events and not any(s.carry["refused"].values()))
+section("10 xmove", xmove_cases)
+
+
+class Fol(Car):
+ """Car that also applies a message (rank 1), with what XMOVE reads."""
+ apply = _mm("apply"); parse = staticmethod(multi.MultiDecoder.parse)
+ def __init__(self, rows, half):
+ super().__init__(rows, half); self.rank = 1; self.outbox = []
+ def _emit(self, op, payload):
+ self.events.append(("emit", op)); self.ops.append((op, [int(v) for v in payload]))
+ return multi.MultiDecoder._emit(self, op, payload)
+
+
+def xa_of(r):
+ return next(x for x in r.pool.extents if x.owner == 1)
+
+
+def xmove_two_ranks():
+ with carry_on():
+ s0, x0, l0 = xlay(kept=8 * A, lane2=False)
+ s1, x1, l1 = xlay(kept=8 * A, lane2=False)
+ r0, r1 = Fol(2 * H, H), Fol(2 * H, H)
+ for r, s in ((r0, s0), (r1, s1)):
+ r.pool, r.lanes, r.kept = s.pool, s.lanes, s.kept
+ r0.rank = 0
+ ok = r0._relocate(l0)
+ r1.apply(list(r0.outbox))
+ shape = lambda s: sorted((x.eid, x.base, x.size, x.owner, len(x.kept)) for x in s.pool.extents)
+ check("10 two ranks: rank 1 applying the XMOVE ends with rank 0's pool, its stream rebound the same",
+ ok and shape(r0) == shape(r1) and l1.st.binds == l0.st.binds and l1.st.binds[-1] == (x1.base, x1.size)
+ and s1.pool.half_of(x1) == 1)
+ check("10 two ranks: rank 1 carries the same rows between the same rows",
+ [e for e in r1.events if e[0] == "carry"] == [e for e in r0.events if e[0] == "carry"] != []
+ and r1.carry["live"] == 1 and r1.carry["tokens"] == r0.carry["tokens"])
+ # the rows to send are rank 0's count, whatever each rank's spill tier still has waiting (it advances them alone)
+ def pair(w0, w1):
+ a, xa, la = xlay(lane2=False); b, xb, lb = xlay(lane2=False)
+ ra, rb = Fol(2 * H, H), Fol(2 * H, H)
+ for r, s in ((ra, a), (rb, b)):
+ r.pool, r.lanes, r.kept = s.pool, s.lanes, s.kept
+ ra.rank = 0
+ ra.disk, rb.disk = FakeDisk(), FakeDisk()
+ if w0: ra.disk.put(xa, w0)
+ if w1: rb.disk.put(xb, w1)
+ ra._relocate(la)
+ return ra, rb, la
+ ra, rb, la = pair(8 * A, 7 * A)
+ rb.apply(list(ra.outbox))
+ na, nb = [e[3] for e in ra.events if e[0] == "carry"], [e[3] for e in rb.events if e[0] == "carry"]
+ want = la.st.pos # kept prompts and the stream's position: what every rank agrees on
+ check("10 xmove: ranks whose spill tiers have different writes waiting carry the same number of rows: rank 0's "
+ "count without the waiting writes (released to the host before the move), in the op",
+ na == nb == [want] and ra.ops[-1][1][3] == want and ra._used(xa_of(ra), pending=False) == want)
+ ra, rb, la = pair(7 * A, 8 * A)
+ try:
+ rb.apply(list(ra.outbox)); raised = False
+ except RuntimeError:
+ raised = True
+ nb = [e[3] for e in rb.events if e[0] == "carry"]
+ check("10 xmove: a rank with more writes waiting than rank 0 does not refuse (rank 0 would be left in its send): "
+ "it carries rank 0's count", not raised and nb == [e[3] for e in ra.events if e[0] == "carry"] == [want])
+section("10 xmove two ranks", xmove_two_ranks)
+
+
+class Loop(Car):
+ """Car with the real _iterate and what its decode branch reads."""
+ _iterate = _mm("_iterate"); _fill_turn = _mm("_fill_turn")
+ def __init__(self, rows, half):
+ super().__init__(rows, half)
+ self.fill_budget = 0; self.group = False; self.profiles = None; self.lone_rows = 0; self.short_round_due = False
+ self.decode_due = False; self.credit = 0.0; self.share = 0.5; self.profile = None; self.outbox = []
+ def _flush(self): self.events.append(("flush",))
+ def _round(self, lanes, **kw): self.events.append(("round", [l.sid for l in lanes]))
+ def _give_back(self): self.events.append(("giveback",)); return []
+
+
+def decode_loop():
+ for on in (True, False):
+ s, x, lane = xlay(lane2=False)
+ l = Loop(2 * H, H)
+ l.pool, l.lanes = s.pool, s.lanes
+ with carry_on(on):
+ l._iterate()
+ evs = [e[0] if e[0] != "emit" else e[1] for e in l.events]
+ if on:
+ check("10 decode loop: a stream that cannot grow is relocated, then decodes in the round (XMOVE, sync, carry, then ROUND)",
+ evs[:3] == [multi.XMOVE, "sync", "carry"] and ("round", [1]) in l.events)
+ check("10 decode loop: it is not paused, and the round counted", not lane.paused and l.pool.half_of(x) == 1
+ and l.xticks == 1)
+ else:
+ check("10 decode loop (carry off): it pauses, as before",
+ lane.paused and x.base == 0 and not any(e == ("emit", multi.XMOVE) for e in l.events))
+section("10 decode loop", decode_loop)
+
+
+class Grow(Loop):
+ """The loop with a round that moves every stream on by STEP tokens."""
+ STEP = 512
+ def _round(self, lanes, **kw):
+ self.events.append(("round", [l.sid for l in lanes]))
+ for l in lanes:
+ l.st.pos += self.STEP
+
+
+def thrash():
+ """Many rounds over a pool that cannot hold what its streams grow into: moves do not answer one another. (The review's
+ probe: stream 1 moved 0 -> 1, stream 3 back 1 -> 0 eight rounds later; two whole-extent transfers for one lack of room.)"""
+ K = multi.RELOCATE_HOLD
+ results = []
+ for variant in range(5):
+ s = Grow(2 * H, H)
+ layout = [[(1, 0, 16 * A, 16 * A - 1500), (2, 16 * A, 16 * A, 16 * A - 9000), (3, H, 12 * A, 12 * A - 6000), (4, H + 12 * A, 3 * A, 3 * A - 7000)],
+ [(1, 0, 8 * A, 8 * A - 1500), (2, 8 * A, 8 * A, 8 * A - 900), (3, 16 * A, 8 * A, 8 * A - 600), (4, 24 * A, 8 * A, 8 * A - 2000),
+ (5, H, 16 * A, 16 * A - 3000)],
+ [(1, 0, 12 * A, 12 * A - 800), (2, 12 * A, 12 * A, 12 * A - 400), (3, H, 20 * A, 20 * A - 2500), (4, H + 20 * A, 4 * A, 4 * A - 2000)],
+ [(1, 0, 8 * A, 8 * A - 1000), (2, 8 * A, 8 * A, 8 * A - 1000), (3, 16 * A, 8 * A, 8 * A - 1000), (4, 24 * A, 8 * A, 8 * A - 1000),
+ (5, H, 4 * A, 3 * A)],
+ [(1, 0, 10 * A, 10 * A - 1000), (2, 10 * A, 10 * A, 10 * A - 1000), (3, 20 * A, 12 * A, 12 * A - 1000), (4, H, 6 * A, 5 * A),
+ (5, H + 6 * A, 6 * A, 5 * A)]][variant]
+ for sid, base, size, pos in layout:
+ x = s.pool.add(base, size)
+ lane_of(s, x, sid, pos=pos)
+ s.outbox = []
+ moves = [] # (round, sid, from part, to part)
+ by_eid = {l.extent.eid: l.sid for l in s.lanes.values()}
+ where = {l.sid: s.pool.half_of(l.extent) for l in s.lanes.values()}
+ with carry_on():
+ for r in range(3000):
+ n0 = len(s.ops)
+ s._iterate()
+ for op, p in s.ops[n0:]:
+ if op == multi.XMOVE:
+ sid = by_eid[p[0]]
+ to = p[1] // H
+ moves.append((r, sid, where[sid], to))
+ where[sid] = to
+ gaps_ok = all(b[0] - a[0] >= K for sid in {m[1] for m in moves} for a, b in
+ zip([m for m in moves if m[1] == sid], [m for m in moves if m[1] == sid][1:]))
+ back = [(a, b) for a in moves for b in moves if b[1] == a[1] and 0 < b[0] - a[0] < K and b[3] == a[2]]
+ counter = [(a, b) for a in moves for b in moves if 0 < b[0] - a[0] < K and b[2] == a[3] and b[1] != a[1]]
+ results.append((len(moves), gaps_ok, back, counter, len({m[1] for m in moves})))
+ check(f"10 thrash [{variant}]: over 3000 rounds of growing streams, a stream moves at most once per {K} rounds, never "
+ f"back into the part it left within them, and no stream leaves a part another entered within them "
+ f"({len(moves)} moves, {len(counter)} counter-moves)", gaps_ok and not back and not counter)
+ check(f"10 thrash [{variant}]: the moves are bounded (at most one per stream per window)",
+ len(moves) <= len(s.lanes) * (3000 // K + 1))
+ check("10 thrash: the sweep moves streams (it reaches the rule)", sum(r[0] for r in results) >= 3)
+section("10 thrash", thrash)
+
+
+def move_guard():
+ s = Car(2 * H, H); s.disk = FakeDisk(); s._guard_pool()
+ x = s.pool.add(0, 8 * A); x.owner = 1
+ s.lanes[1] = SimpleNamespace(sid=1, twin=None, st=St(4 * A), extent=x, decoding=True)
+ s._move(x, 4 * A, 8 * A)
+ check("10 spill: a move inside the part releases nothing (as before)", s.disk.releases == [])
+ old = x.base
+ s._xmove(x, H, 8 * A, 4 * A)
+ check("10 spill: a move across parts first has the tier copy the waiting writes' rows to the host (release from 0, "
+ "while the extent is still at its old base)", s.disk.releases == [(x.eid, 0, old)])
+section("10 move guard", move_guard)
+
+
+def pool_cross():
+ p = Pool(2 * H, half=H)
+ x = p.add(0, 8 * A)
+ try:
+ p.move(x, H, 8 * A); refused = False
+ except ValueError:
+ refused = True
+ check("10 pool: a move to another part is still refused without cross", refused and x.base == 0)
+ check("10 pool: ...and is made with cross=True (returns the old base)", p.move(x, H, 8 * A, cross=True) == 0 and x.base == H)
+ try:
+ p.move(x, H - A, 8 * A, cross=True); crossed = True
+ except ValueError:
+ crossed = False
+ check("10 pool: even with cross an extent never straddles a part's end", not crossed and x.base == H)
+ t = p.add(0, 4 * A, twin=True)
+ try:
+ p.move(t, H + 16 * A, 4 * A, cross=True); ok = False
+ except ValueError:
+ ok = True
+ check("10 pool: a twin never moves, across parts or not", ok)
+ y = p.add(H + 8 * A, 4 * A)
+ try:
+ p.move(x, H + 4 * A, 8 * A, cross=True); ok = False
+ except ValueError:
+ ok = True
+ check("10 pool: a cross move onto taken rows is refused", ok)
+section("10 pool cross", pool_cross)
+
+
+def ops_and_settings():
+ check("10 ops: XMOVE is in the table, after the older ops", multi.OPS[multi.XMOVE] == "XMOVE" and multi.XMOVE == max(multi.OPS))
+ ok = multi.MultiDecoder.parse([multi.XMOVE, 4, 4, 5, 6, 7]) == [(multi.XMOVE, [4, 5, 6, 7])]
+ try:
+ multi.MultiDecoder.parse([multi.XMOVE, 3, 4, 5, 6]); bad = False
+ except RuntimeError:
+ bad = True
+ check("10 ops: XMOVE carries four values (the extent, base, size, rows used); other lengths are refused", ok and bad)
+ check("10 settings: TF_GLM_KV_SHARD_CARRY is 1 unless 0; anything else is refused",
+ multi.kv_carry("") is True and multi.kv_carry("1") is True and multi.kv_carry("0") is False)
+ try:
+ multi.kv_carry("yes"); bad = False
+ except ValueError:
+ bad = True
+ check("10 settings: a typo in it is refused, not read as on", bad)
+ check("10 settings: the minimum hit and the move cooldown are constants, and there is no count-based balance",
+ multi.CARRY_MIN == 2048 and multi.RELOCATE_HOLD == 256 and not hasattr(multi, "CARRY_GAP")
+ and not hasattr(multi, "kv_carry_min") and not hasattr(multi.MultiDecoder, "_carry_target"))
+
+
+def health_carry():
+ s = Car(2 * H, H)
+ h = s._shard_health()
+ want = {"hits", "rescued", "pressure", "others", "live", "tokens", "bytes", "ms_total", "ms_max", "refused"}
+ check("10 health: kv_shard.carry has hits, rescued, pressure, others, live, tokens, bytes, ms_total, ms_max, refused",
+ set(h["carry"]) == want)
+ check("10 health: refused has pinned, twin, loading, partial, no_target, small, all 0 at start",
+ h["carry"]["refused"] == dict(pinned=0, twin=0, loading=0, partial=0, no_target=0, small=0)
+ and all(h["carry"][k] == 0 for k in want - {"refused"}))
+ with carry_on():
+ s, x, hit = rescue_layout()
+ place(s, hit, 16 * A, [7] * (20 * A))
+ s2, x2, lane = xlay(lane2=False)
+ s2.carry = s.carry
+ s2._relocate(lane)
+ c = s._shard_health()["carry"]
+ check("10 health: counters reported (rescued 1, live 1, tokens/bytes/ms of the carries)",
+ c["rescued"] == 1 and c["live"] == 1 and c["tokens"] == lane.st.pos and c["bytes"] == lane.st.pos * 5808
+ and c["ms_total"] >= 0 and c["ms_max"] >= 0 and c["hits"] == 0)
+ s.carry["hits"] += 1
+ check("10 health: the reported dict is a copy", s._shard_health()["carry"] is not s.carry
+ and s._shard_health()["carry"]["refused"] is not s.carry["refused"])
+section("10 ops and settings", ops_and_settings)
+section("10 health", health_carry)
+
+
+# -- Arena.carry on simulated ranks: byte equality, who sends, who receives ---------------------------------------------------
+import collections
+import ctypes
+import math
+import os
+import tempfile
+
+SH = 4 * 2048 # a part: 4 pool blocks (rows)
+
+
+class SimNccl:
+ """ncclSend / ncclRecv between the simulated ranks of one process: bytes through FIFO mailboxes a (sender, receiver)
+ pair, as NCCL matches a pair's calls in order; ``shard.RANK`` says which rank is calling. A receive with no send
+ before it raises: the driver runs the sender first (the real ranks run side by side)."""
+ comm = None
+
+ def __init__(self):
+ self.box = collections.defaultdict(collections.deque); self.log = []; self.spans = []; self.touched = []
+ lib = property(lambda self: self)
+ def _check(self, code): assert code == 0
+ def _span(self, ptr, nbytes):
+ if any(ptr < hi and lo < ptr + nbytes for lo, hi in self.spans):
+ self.touched.append(("nccl", ptr))
+ def ncclSend(self, ptr, count, dtype, peer, comm, stream):
+ self._span(ptr, count * 4)
+ self.box[(shard.RANK, peer)].append(ctypes.string_at(ptr, count * 4)); self.log.append(("send", shard.RANK, peer, count))
+ return 0
+ def ncclRecv(self, ptr, count, dtype, peer, comm, stream):
+ self._span(ptr, count * 4)
+ data = self.box[(peer, shard.RANK)].popleft()
+ assert len(data) == count * 4, f"a receive of {count * 4} bytes meets a send of {len(data)}"
+ ctypes.memmove(ptr, data, len(data)); self.log.append(("recv", shard.RANK, peer, count))
+ return 0
+
+
+def sim_arenas(world, seed=0):
+ """One arena a rank over ``world`` parts of SH rows: a sharded FP8-like plane (uint8, 528 B a row), a sharded bf16
+ plane, a sharded plane in the display span, the pooled keys (div 4, pad 2, 36 B) and a per-token plane every rank
+ holds whole; replicated planes equal on every rank, sharded ones each rank's own."""
+ rows = world * SH
+ shard.setup(0, world, rows)
+ out = []
+ g = torch.Generator().manual_seed(seed)
+ rep_pk = torch.randint(0, 256, (rows // 4 + 2, 36), generator=g, dtype=torch.uint8)
+ rep_tok = torch.randn(rows, 8, generator=g).bfloat16()
+ for r in range(world):
+ planes = [Plane(torch.randint(0, 256, (SH + shard.TRASH, 528), generator=g, dtype=torch.uint8), 1, 0, shard=True),
+ Plane(torch.randn(SH + shard.TRASH, 64, generator=g).bfloat16(), 1, 0, shard=True),
+ Plane(torch.randint(0, 256, (SH + shard.TRASH, 528), generator=g, dtype=torch.uint8), 1, 0, spanned=True, shard=True),
+ Plane(rep_pk.clone(), 4, 2), Plane(rep_tok.clone(), 1, 0)]
+ out.append(Arena(rows, planes))
+ return out
+
+
+def bytes_eq(a, b):
+ return torch.equal(a.contiguous().view(torch.uint8), b.contiguous().view(torch.uint8))
+
+
+def carry_sim(world, src, dst, n, piece=None, order=None):
+ """Carry n tokens from pool row src to dst on ``world`` simulated ranks: the arenas before and after, the transport."""
+ ars = sim_arenas(world)
+ before = [[p.tensor.clone() for p in ar.planes] for ar in ars]
+ nc = SimNccl()
+ for ar in ars:
+ for p in ar.planes:
+ if p.spanned:
+ nc.spans.append((p.tensor.data_ptr(), p.tensor.data_ptr() + p.tensor.numel() * p.tensor.element_size()))
+ saved = (shard._stream, shard._piece, torch.Tensor.copy_)
+ shard._stream = lambda: 0
+ if piece is not None:
+ shard._piece = lambda rb: piece
+ orig_copy = torch.Tensor.copy_
+
+ def guarded(self, other, *a, **k): # a memcpy on the display span would be what the span forbids
+ for t in (self, other):
+ if isinstance(t, torch.Tensor) and t.numel() and any(
+ t.data_ptr() < hi and lo < t.data_ptr() + t.numel() * t.element_size() for lo, hi in nc.spans):
+ nc.touched.append(("copy_", t.data_ptr()))
+ return orig_copy(self, other, *a, **k)
+ torch.Tensor.copy_ = guarded
+ so = shard.owner(src)
+ try:
+ for r in (order if order is not None else [so] + [r for r in range(world) if r != so]):
+ shard.RANK = r
+ ars[r].carry(src, dst, n, nc)
+ finally:
+ shard._stream, shard._piece = saved[0], saved[1]
+ torch.Tensor.copy_ = orig_copy
+ shard.RANK = 0
+ return ars, before, nc
+
+
+def expected(ars, before, world, src, dst, n):
+ """What every rank's planes hold after: only the destination (its owner's sharded rows; every rank's replicated rows)."""
+ so, do = shard.owner(src), shard.owner(dst)
+ exp = [[t.clone() for t in b] for b in before]
+ for r in range(world):
+ for k, p in enumerate(ars[r].planes):
+ if p.shard:
+ if r == do:
+ exp[r][k][dst - do * SH:dst - do * SH + n] = before[so][k][src - so * SH:src - so * SH + n]
+ else:
+ m = -(-n // p.div)
+ exp[r][k][dst // p.div:dst // p.div + m] = before[r][k][src // p.div:src // p.div + m]
+ return exp
+
+
+def carry_cases():
+ shard.ON = False
+ try:
+ for world, src, dst, n, piece, label in (
+ (2, 2048, SH + 4096, 3001, None, "two ranks, a cut not a multiple of 4 (the last pooled-key row partly filled)"),
+ (2, 0, SH, 2048, 7, "two ranks, sent 7 rows at a time"),
+ (2, SH + 2048, 4096, 5000, 1000, "two ranks, the other way (part 1 to part 0), 1000-row pieces"),
+ (3, 4096, 2 * SH + 2048, 4097, 513, "TP3: part 0 to part 2, rank 1 a bystander"),
+ (3, 2 * SH, 2048, 3000, None, "TP3: part 2 to part 0"),
+ (3, SH + 2048, 2 * SH + 4096, 2049, 100, "TP3: part 1 to part 2, rank 0 a bystander")):
+ ars, before, nc = carry_sim(world, src, dst, n, piece)
+ exp = expected(ars, before, world, src, dst, n)
+ so, do = shard.owner(src), shard.owner(dst)
+ ok = all(bytes_eq(p.tensor, exp[r][k]) for r, ar in enumerate(ars) for k, p in enumerate(ar.planes))
+ check(f"10 carry [{label}]: every plane of every rank is the source's rows at the destination, nothing else touched "
+ f"(FP8 bytes, bf16, the display span's plane, the pooled keys with a partial last row, the pad rows)", ok)
+ sends = [e for e in nc.log if e[0] == "send"]; recvs = [e for e in nc.log if e[0] == "recv"]
+ paired = (bool(sends) and all(e[1] == so and e[2] == do for e in sends) and all(e[1] == do and e[2] == so for e in recvs)
+ and [e[3] for e in sends] == [e[3] for e in recvs] and not any(nc.box.values()))
+ check(f"10 carry [{label}]: only the source's owner sends (to the destination's), only the destination's receives "
+ f"(from it); every send meets its receive in order; a bystander does nothing", paired)
+ planes = sum(1 for p in ars[0].planes if p.shard)
+ if piece is None:
+ check(f"10 carry [{label}]: one piece a sharded plane when the rows fit one send ({planes} sends)", len(sends) == planes)
+ else:
+ want = planes * -(-n // piece)
+ check(f"10 carry [{label}]: pieces of {piece} rows ({want} sends)", len(sends) == want)
+ check(f"10 carry [{label}]: the display span is reached only by kernel (no copy_, no transport on it)", not nc.touched)
+ check(f"10 carry [{label}]: the source's rows stay", all(bytes_eq(ars[so].planes[k].tensor[src - so * SH:src - so * SH + n],
+ before[so][k][src - so * SH:src - so * SH + n])
+ for k, p in enumerate(ars[so].planes) if p.shard))
+ # one part: a plain local copy, no transport
+ ars, before, nc = carry_sim(2, 0, 4096, 3000)
+ check("10 carry: within one part it is the local copy (nothing sent)", not nc.log and bytes_eq(
+ ars[0].planes[0].tensor[4096:7096], before[0][0][0:3000]))
+ ars, before, nc = carry_sim(2, 0, SH, 0)
+ check("10 carry: zero tokens is a no-op", not nc.log and all(bytes_eq(p.tensor, before[r][k]) for r, ar in enumerate(ars) for k, p in enumerate(ar.planes)))
+ try:
+ carry_sim(2, 0, 2 * SH - 1000, 3000); bad = False
+ except ValueError:
+ bad = True
+ check("10 carry: a destination past the arena is refused", bad)
+ check("10 carry: sharded_bytes is the sharded planes' row bytes a token (528 + 128 + 528)",
+ sim_arenas(2)[0].sharded_bytes(10) == 10 * (528 + 128 + 528))
+ finally:
+ shard.setup(0, 2, 4096 * 512)
+section("10 carry sim", carry_cases)
+
+
+# -- the spill tier: block names carry the part; a carried state restores byte for byte -----------------------------------
+import numpy as np
+import tensorfold.cuda.spill as SP
+import tensorfold.cuda.spill_blocks as S
+
+SB = 2048 # the pool's block
+SPH = 12 * SB # a part of twelve blocks
+SPR = 2 * SPH
+SROOT = tempfile.mkdtemp(prefix="kv-shard-carry-")
+_n = [0]
+
+
+class SnapS:
+ """A stand-in for decode.Snapshot (the fields the tier stores and the ones _SPILL_SKIP leaves out)."""
+
+
+SCLASSES = [f"{SnapS.__module__}:{SnapS.__qualname__}"]
+
+
+def snap_s(ids, lineage, extent):
+ s = SnapS()
+ s.ids, s.shared, s.lineage = list(ids), False, lineage
+ s.rec, s.conv = torch.arange(64, dtype=torch.float32) + len(ids), torch.ones(8)
+ s.tail = s.head = s.drafter_rows = None
+ s.extent, s.key, s.images, s.own, s.chat, s.kid = extent, list(ids), False, True, 1, 0
+ return s
+
+
+def sp_arena(sharded):
+ if sharded:
+ shard.setup(0, 2, SPR)
+ lat = torch.zeros((shard.HALF + shard.TRASH, 4), dtype=torch.int32)
+ planes = [Plane(lat, 1, 0, shard=True)]
+ else:
+ planes = [Plane(torch.zeros((SPR, 4), dtype=torch.int32), 1, 0)]
+ return Arena(SPR, planes + [Plane(torch.zeros((SPR // 4 + 2, 8), dtype=torch.int16), 4, 2)])
+
+
+def sp_dec(ar, rank, sharded, nc=None):
+ """A MultiDecoder with what the tier's paths use, one rank's view: a real Pool guarded by _guard_pool, a real
+ BlockStore, the simulated transport as its comm."""
+ _n[0] += 1
+ cfg = SP.SpillConfig(root=os.path.join(SROOT, f"s{_n[0]}"), gib=1.0, min_tokens=1, min_free_gib=0.0)
+ os.makedirs(cfg.root, exist_ok=True)
+ shard.RANK = rank
+ st = S.BlockStore(cfg, planes=ar.planes, block=SB, rank=rank, device="cpu", classes=SCLASSES, quiet=True)
+ m = object.__new__(multi.MultiDecoder)
+ m.pool = Pool(SPR, half=SPH if sharded else 0)
+ m.arena, m.disk, m.rank = ar, st, rank
+ m.w = SimpleNamespace(world=2, device="cpu"); m.g = SimpleNamespace(cache_entries=8, comm=nc)
+ m.kept, m.lanes, m.partial, m.loads, m.outbox = [], {}, None, {}, []
+ m.next_lid = m.next_kid = 0; m.load_turn = 0; m.broken = None; m.idle = False
+ m.drafts = None; m.grid = 0; m.carry = multi.carry_stats(); m._flush = lambda: None
+ m._guard_pool()
+ return m
+
+
+def sp_fill(ars, base, a, b, seed):
+ """Tokens [a, b) (a a multiple of 4) of the extent at ``base``: the owner's latent rows, every rank's pooled keys; the
+ rows written, to compare against."""
+ g = torch.Generator().manual_seed(seed)
+ own = shard.owner(base) if shard.ON or ars[0].planes[0].shard else 0
+ lat = torch.randint(-2 ** 31, 2 ** 31 - 1, (b - a, 4), generator=g, dtype=torch.int32)
+ pk = torch.randint(-2 ** 15, 2 ** 15 - 1, (-(-b // 4) - a // 4, 8), generator=g, dtype=torch.int16)
+ for r, ar in enumerate(ars):
+ if ar.planes[0].shard:
+ if r == own:
+ lo = base - own * SPH
+ ar.planes[0].tensor[lo + a:lo + b] = lat
+ else:
+ ar.planes[0].tensor[base + a:base + b] = lat
+ ar.planes[1].tensor[base // 4 + a // 4:base // 4 + a // 4 + pk.shape[0]] = pk
+ return lat, pk
+
+
+def sp_rows(ar, rank, base, n):
+ """What rank ``rank`` holds of tokens [0, n) of the extent at ``base``: (latent rows or None, pooled-key rows)."""
+ if ar.planes[0].shard:
+ lat = ar.planes[0].tensor[base - rank * SPH:base - rank * SPH + n].clone() if shard.owner(base) == rank else None
+ else:
+ lat = ar.planes[0].tensor[base:base + n].clone()
+ return lat, ar.planes[1].tensor[base // 4:base // 4 + -(-n // 4)].clone()
+
+
+def sp_keep(decs, base, ids, lineage, size=None):
+ """The state kept in a new extent of every rank's pool and written (queued) by every rank; the kept snapshots."""
+ out = []
+ for r, d in enumerate(decs):
+ shard.RANK = r
+ x = d.pool.add(base, size or align_up(len(ids)))
+ c = snap_s(ids, lineage, x)
+ x.kept.append(c); d.kept.append(c)
+ d._persist(c)
+ out.append(c)
+ return out
+
+
+def sp_drain(decs):
+ for r, d in enumerate(decs):
+ shard.RANK = r
+ if not d.disk.drain(30):
+ print(" (a write did not end)")
+
+
+def sp_restore(decs, ars, ids, base, n):
+ """Read the state of ``ids`` back into a new extent at ``base`` on every rank: (rows per rank, the points)."""
+ out, pts = [], []
+ key = S.point_key(ids)
+ for r, (d, ar) in enumerate(zip(decs, ars)):
+ shard.RANK = r
+ x = d.pool.add(base, align_up(n))
+ try:
+ small, pt = d.disk.finish_load(d.disk.load_async(key, x))
+ except Exception as exc: # noqa: BLE001
+ print(f" (rank {r}: the read failed: {exc!r})")
+ out.append(None); pts.append(None)
+ continue
+ out.append(sp_rows(ar, r, base, n)); pts.append(pt)
+ return out, pts
+
+
+def same_rows(got, lat, pk, rank, owner):
+ if got is None:
+ return False
+ glat, gpk = got
+ return torch.equal(gpk, pk) and (glat is None if rank != owner else torch.equal(glat, lat))
+
+
+def spill_names():
+ L = "boot-3|boot-9@2048"
+ ids = np.arange(5 * SB + 77, dtype=np.int64)
+ n0 = [h for _, _, h in S.block_hashes(ids, SB, S.in_part(L, 0))]
+ n1 = [h for _, _, h in S.block_hashes(ids, SB, S.in_part(L, 1))]
+ check("10 spill: the part salts every block name (no block of the same ids in two parts shares a name)",
+ len(n0) == len(n1) == 6 and not set(n0) & set(n1))
+ check("10 spill: idempotent: salting a salted lineage replaces the part, never stacks",
+ S.in_part(S.in_part(L, 0), 0) == S.in_part(L, 0) and S.in_part(S.in_part(L, 0), 1) == S.in_part(L, 1)
+ and S.in_part(S.in_part(L, 1), 1).count("#") == 1)
+ check("10 spill: the forks after the first computation are untouched, and forking a salted lineage keeps the salt at the head",
+ S.in_part(L, 1) == "boot-3#1|boot-9@2048" and S.fork(S.in_part(L, 1), "x", 5000) == "boot-3#1|boot-9@2048|x@5000"
+ and S.in_part(S.fork(S.in_part(L, 1), "x", 5000), 0) == "boot-3#0|boot-9@2048|x@5000" and S.in_part("", 1) == "#1")
+ same = [h for _, _, h in S.block_hashes(ids, SB, S.in_part(L, 1))]
+ check("10 spill: the same part gives the same names (a conversation's turns in one part still share their blocks)", same == n1)
+section("10 spill names", spill_names)
+
+
+def spill_unsharded():
+ ar = sp_arena(False)
+ d = sp_dec(ar, 0, False)
+ ids = list(np.random.default_rng(3).integers(1, 150000, 3 * SB))
+ sp_fill([ar], 0, 0, len(ids), 1)
+ (c,) = sp_keep([d], 0, ids, "u-5|u-7@1024")
+ sp_drain([d])
+ pt = d.disk.index[S.point_key(ids)]
+ check("10 spill: an unsharded store's lineage and block names are unchanged (no part in them, no half field)",
+ d._lineage(c) == "u-5|u-7@1024" and pt.lineage == "u-5|u-7@1024" and "#" not in pt.lineage and not pt.fields
+ and pt.blocks == [h for _, _, h in S.block_hashes(np.asarray(ids, dtype=np.int64), SB, "u-5|u-7@1024")])
+section("10 spill unsharded", spill_unsharded)
+
+
+def spill_carried_restore():
+ n1, n2 = 2 * SB + 100, 3 * SB + 152
+ ids2 = [int(v) for v in np.random.default_rng(5).integers(1, 150000, n2)]
+ ids1 = ids2[:n1]
+ for carried in (True, False):
+ nc = SimNccl()
+ saved = shard._stream
+ shard._stream = lambda: 0
+ try:
+ ars = [sp_arena(True), sp_arena(True)]
+ decs = [sp_dec(ars[r], r, True, nc) for r in range(2)]
+ lat1, pk1 = sp_fill(ars, 0, 0, n1, 11)
+ sp_keep(decs, 0, ids1, "boot-1") # turn 1, kept in part 0 and written
+ sp_drain(decs)
+ base2 = SPH if carried else 3 * SB # turn 2: carried into part 1, or beside it in part 0
+ xs = []
+ for r in (0, 1): # (rank 0 first: it sends)
+ shard.RANK = r
+ xs.append(decs[r].pool.add(base2, align_up(n2)))
+ if carried:
+ decs[r]._carry(0, base2, n1, "admit")
+ else:
+ decs[r].arena.copy(0, base2, n1) # copy 1: within the part
+ sp_fill(ars, base2, n1 - n1 % 4, n2, 12) # the stream's own rows from the resume point on
+ lin2 = S.fork("boot-1", "boot-2", n1)
+ for r in (0, 1):
+ shard.RANK = r
+ c = snap_s(ids2, lin2, xs[r])
+ xs[r].kept.append(c); decs[r].kept.append(c); decs[r]._persist(c)
+ sp_drain(decs)
+ part = 1 if carried else 0
+ tag = "carried into part 1" if carried else "in place in part 0, control"
+ p1 = [d.disk.index[S.point_key(ids1)] for d in decs]
+ p2 = [d.disk.index[S.point_key(ids2)] for d in decs]
+ check(f"10 spill [{tag}]: every rank wrote the point under the part's lineage and recorded its half",
+ all(p.lineage == S.in_part(lin2, part) and p.fields.get("half") == part for p in p2)
+ and all(p.lineage == S.in_part("boot-1", 0) and p.fields.get("half") == 0 for p in p1))
+ if carried:
+ check(f"10 spill [{tag}]: its blocks are named for the new part: none shared with the turn it grew from",
+ not set(p2[0].blocks) & set(p1[0].blocks) and not set(p2[1].blocks) & set(p1[1].blocks))
+ else:
+ full = n1 // SB
+ check(f"10 spill [{tag}]: a turn in the same part still names the blocks of the turn before it ({full} whole blocks)",
+ p2[0].blocks[:full] == p1[0].blocks[:full] and p2[1].blocks[:full] == p1[1].blocks[:full])
+ rbase = SPH + 6 * SB if carried else 8 * SB
+ got, pts = sp_restore(decs, ars, ids2, rbase, n2)
+ want = [sp_rows(ars[r], r, base2, n2) for r in (0, 1)]
+ ok = all(got[r] is not None and torch.equal(got[r][1], want[r][1]) and (got[r][0] is None) == (want[r][0] is None)
+ and (want[r][0] is None or torch.equal(got[r][0], want[r][0])) for r in (0, 1))
+ check(f"10 spill [{tag}]: the state restores byte for byte on both ranks (the owner's latent rows, every rank's pooled keys)",
+ ok and all(p is not None and p.n == n2 for p in pts))
+ if carried:
+ check(f"10 spill [{tag}]: and its first {n1} tokens are what turn 1 wrote in part 0",
+ got[1] is not None and got[1][0] is not None and torch.equal(got[1][0][:n1], lat1)
+ and torch.equal(got[1][1][:n1 // 4], pk1[:n1 // 4]) and got[0][0] is None)
+ lins = {pt.lineage for pt in pts if pt is not None}
+ check(f"10 spill [{tag}]: the restored point keeps the salted lineage, and salting it for its part again changes nothing "
+ f"(a restored state persisted again names the same blocks)", lins == {S.in_part(lin2, part)}
+ and all(S.in_part(l, part) == l for l in lins))
+ finally:
+ shard._stream = saved
+ shard.RANK = 0
+ shard.setup(0, 2, 4096 * 512)
+section("10 spill carried", spill_carried_restore)
+
+
+def spill_pending_move():
+ # a state waiting to be written when its extent moves to the other part: the tier copies its rows to the host first
+ # (the old owner's), so what is written is what part 0 held, under part 0's name
+ n = 3 * SB
+ ids = [int(v) for v in np.random.default_rng(8).integers(1, 150000, n)]
+ nc = SimNccl()
+ saved = shard._stream
+ shard._stream = lambda: 0
+ try:
+ ars = [sp_arena(True), sp_arena(True)]
+ decs = [sp_dec(ars[r], r, True, nc) for r in range(2)]
+ lat, pk = sp_fill(ars, 0, 0, n, 21)
+ cs = sp_keep(decs, 0, ids, "boot-4")
+ waiting = [len(d.disk.pending) for d in decs]
+ for r in (0, 1):
+ shard.RANK = r
+ decs[r]._xmove(decs[r].pool.get(cs[r].extent.eid), SPH + 2 * SB, 4 * SB, n)
+ sp_drain(decs)
+ check("10 spill xmove: the writes still waiting when the extent changed part were released to the host first (both ranks)",
+ all(w > 0 for w in waiting) and all(d.disk.stats["released_blocks"] > 0 for d in decs))
+ check("10 spill xmove: the extent is in part 1 now and the point records the part its rows were written from (0)",
+ all(d.pool.half_of(cs[r].extent) == 1 for r, d in enumerate(decs))
+ and all(d.disk.index[S.point_key(ids)].fields.get("half") == 0 for d in decs)
+ and all(d.disk.index[S.point_key(ids)].lineage == S.in_part("boot-4", 0) for d in decs))
+ got, pts = sp_restore(decs, ars, ids, 7 * SB, n)
+ check("10 spill xmove: restored into part 0 it is byte for byte what part 0's owner held before the move",
+ got[0] is not None and got[1] is not None and torch.equal(got[0][0], lat) and torch.equal(got[0][1], pk)
+ and got[1][0] is None and torch.equal(got[1][1], pk))
+ # and the moved extent has the rows (the carry): its owner now holds them
+ moved = [sp_rows(ars[r], r, SPH + 2 * SB, n) for r in (0, 1)]
+ check("10 spill xmove: the moved extent holds the rows in part 1 (rank 1) and the pooled keys on both",
+ moved[0][0] is None and torch.equal(moved[1][0], lat) and torch.equal(moved[0][1], pk) and torch.equal(moved[1][1], pk))
+ finally:
+ shard._stream = saved
+ shard.RANK = 0
+ shard.setup(0, 2, 4096 * 512)
+section("10 spill xmove", spill_pending_move)
+
+
+# -- review fixes: the time of a carry, TP3 warm-up, the lone setting, counting at the ADMIT -----------------------------------
+import inspect
+from tensorfold.families.glm5_next.cuda import engine as _engine
+from tensorfold.families.glm5_next.cuda.multi_tune import MultiSettings
+
+
+def carry_ms():
+ # the time /health reports is the transfer's: the ranks that send or receive measure it, with three ranks or more the
+ # longest of them is shared in one all-gather every rank joins; two ranks need none
+ gathered = []
+ def mk(world, rank, rows):
+ s = Car(world * H, H)
+ s.w = SimpleNamespace(world=world); s.rank = rank
+ def gi(values):
+ gathered.append((rank, list(values)))
+ if rows is None:
+ raise AssertionError("no all-gather at two ranks")
+ return rows
+ s.g = SimpleNamespace(comm=None, _gather_ints=gi)
+ return s
+ s = mk(3, 1, [[0], [0], [7000]]) # rank 1 owns neither part 0 nor part 2
+ s._carry(0, 2 * H, 4096, "admit")
+ check("10 carry time: a rank that owns neither part sends nothing to the gather but 0, and reports the longest transfer "
+ "(7.0 ms) of the ranks that took part", gathered == [(1, [0])] and abs(s.carry["ms_total"] - 7.0) < 1e-9
+ and abs(s.carry["ms_max"] - 7.0) < 1e-9)
+ gathered.clear()
+ s = mk(3, 0, [[4000], [0], [7000]])
+ s._carry(0, 2 * H, 4096, "live")
+ check("10 carry time: an involved rank shares what it measured, and reports the longest too",
+ len(gathered) == 1 and gathered[0][0] == 0 and gathered[0][1][0] >= 0 and abs(s.carry["ms_total"] - 7.0) < 1e-9)
+ gathered.clear()
+ s = mk(2, 0, None)
+ s._carry(0, H, 4096, "admit")
+ check("10 carry time: with two ranks (both take part) it is the rank's own, with no all-gather", not gathered
+ and s.carry["ms_total"] >= 0 and s.carry["hits"] == 1)
+section("10 carry time", carry_ms)
+
+
+def warm_up():
+ from tensorfold.cuda.comm import _DTYPES
+
+ class Rec:
+ comm = None
+ def __init__(self): self.log = []; self.lib = self
+ def _check(self, code): assert code == 0
+ def ncclSend(self, ptr, count, dtype, peer, comm, stream): self.log.append(("send", peer, count)); return 0
+ def ncclRecv(self, ptr, count, dtype, peer, comm, stream): self.log.append(("recv", peer, count)); return 0
+ saved = shard._stream
+ shard._stream = lambda: 0
+ try:
+ for world in (2, 3, 4):
+ shard.setup(0, world, world * 2048 * 4)
+ logs = []
+ for r in range(world):
+ shard.RANK = r
+ rec = Rec()
+ shard.warm(rec, "cpu")
+ logs.append(rec.log)
+ pairs = [(a, b) for a in range(world) for b in range(a + 1, world)]
+ if world == 2:
+ check("10 warm-up: with two ranks there is nothing to warm (the fetch's sends are the first, as ever)", not any(logs))
+ continue
+ ok = True
+ for a, b in pairs:
+ ok &= [e[:2] for e in logs[a] if e[1] == b] == [("send", b), ("recv", b)]
+ ok &= [e[:2] for e in logs[b] if e[1] == a] == [("recv", a), ("send", a)]
+ check(f"10 warm-up: {world} ranks: every pair sends and receives once each way, the lower rank sending first, the "
+ f"higher receiving first (each call meets its partner's)", ok and all(e[2] == 4 for l in logs for e in l)
+ and all(len(logs[r]) == 2 * (world - 1) for r in range(world)))
+ order = []
+ for r in range(world):
+ seen = []
+ for e in logs[r]:
+ pr = tuple(sorted((r, e[1])))
+ if not seen or seen[-1] != pr:
+ seen.append(pr)
+ order.append(seen)
+ check(f"10 warm-up: {world} ranks: the pairs come in the same order on every rank (a, then b), none skipped",
+ all(o == [p for p in pairs if r in p] for r, o in enumerate(order)))
+ finally:
+ shard._stream = saved
+ shard.RANK = 0
+ shard.setup(0, 2, 4096 * 512)
+ check("10 warm-up: the engine calls it once the shard is set up, on every rank",
+ "shard.warm(self.comm" in inspect.getsource(_engine))
+section("10 warm-up", warm_up)
+
+
+def lone_setting():
+ t = MultiSettings.from_env({})
+ check("10 lone: unset, TF_GLM_MULTI_LONE is on in the settings (the review's finding)", t.lone is True)
+ saved = shard.ON
+ try:
+ shard.ON = True
+ u = multi.shard_tune(t)
+ check("10 lone: with the shard on it is off, whatever the default (the others branch and its carry are not skipped)",
+ u.lone is False and t.lone is True and MultiSettings.from_env({"TF_GLM_MULTI_LONE": "0"}).lone is False
+ and multi.shard_tune(MultiSettings.from_env({"TF_GLM_MULTI_LONE": "0"})).lone is False)
+ shard.ON = False
+ check("10 lone: without the shard it is as set", multi.shard_tune(t) is t and multi.shard_tune(t).lone is True)
+ shard.ON = True
+ with carry_on(False):
+ check("10 lone: TF_GLM_KV_SHARD_CARRY=0 leaves it as set (the decoder as before the carry)",
+ multi.shard_tune(t) is t and multi.shard_tune(t).lone is True)
+ shard.ON = False
+ shard.ON = True
+ s = Car(2 * H, H); s.tune = multi.shard_tune(t)
+ s.pool.add(0, 16 * A).owner = 1
+ x = s.pool.add(16 * A, 16 * A)
+ hit = put_state(s, x, 7, 8 * A, name="hit"); other = put_state(s, x, 9, 16 * A, name="other")
+ with carry_on():
+ base, copy, h = place(s, hit, 6 * A, [7] * (20 * A))
+ check("10 lone: with LONE unset and the shard on the others branch runs: the shared rows are carried, the other "
+ "conversation keeps its state", copy == 2 and s.carry["others"] == 1 and s.evicted == [] and other in x.kept)
+ finally:
+ shard.ON = saved
+ check("10 lone: the decoder takes its settings through it", "shard_tune(" in inspect.getsource(multi.MultiDecoder.__init__))
+ check("10 lone: and an explicit LONE=1 is still refused at start", "TF_GLM_MULTI_LONE" in inspect.getsource(_engine))
+section("10 lone", lone_setting)
+
+
+def counted_at_admit():
+ class Boom(Adm):
+ def _emit(self, op, payload):
+ if op == multi.ADMIT:
+ raise RuntimeError("the op could not be queued")
+ return super()._emit(op, payload)
+ def lay(cls, q_live):
+ s = cls(2 * H, H)
+ s.pool.add(0, 24 * A).owner = 1
+ x = s.pool.add(24 * A, 8 * A); hit_state(s, x, 7, 8 * A, own=True)
+ if q_live:
+ s.pool.add(H, q_live * A).owner = 2
+ return s
+ with carry_on(), fake_state():
+ for label, q_live, kind in (("free rows elsewhere", 0, "rescued"), ("rescue, evicting there", 17, "rescued")):
+ s = lay(Boom, q_live)
+ try:
+ s.admit(Stream([7] * (14 * A), 4, None, True)); raised = False
+ except RuntimeError:
+ raised = True
+ check(f"10 counters [{label}]: a placement whose ADMIT never got queued is not counted (decision made, "
+ f"carry_kind={s.carry_kind}, hits/rescued/pressure/others all 0)",
+ raised and s.carry_kind == kind and s.carry["rescued"] == s.carry["pressure"] == s.carry["others"] == 0)
+ s = lay(Adm, q_live)
+ s.admit(Stream([7] * (14 * A), 4, None, True))
+ check(f"10 counters [{label}]: and counted once when it was", s.carry["rescued"] == 1 and s.carry["hits"] == 1
+ and s.carry["pressure"] == s.carry["others"] == 0)
+section("10 counters at the ADMIT", counted_at_admit)
+
+
+def no_import_per_piece():
+ check("10 shard: the send and the receive of a piece import nothing (the dtype table is read once, at import)",
+ all("import" not in inspect.getsource(f) for f in (shard._send, shard._recv)))
+section("10 no import per piece", no_import_per_piece)
+
+
+def tp4_guard():
+ """(11, kv-shard-tp4-exp) Four ranks, the tp4 prompt settings and the carry on a ring all run with the shard; the
+ warm-up opens no point-to-point connection on a ring (the neighbour links are the communicator's own) nor without
+ the carry; the own-row front and microbatching reach the owner's rows through ``forward._sharded_attend``."""
+
+ keys = shard.PROMPT_SETTINGS + ("TF_NCCL_RING", "TF_GLM_KV_SHARD_CARRY")
+ saved = {k: os.environ.pop(k, None) for k in keys}
+ try:
+ check("11 guard: two, three and four ranks run", all(shard.unsupported("batched", n) is None for n in (2, 3, 4)))
+ check("11 guard: serial verify still refused", shard.unsupported("serial", 4) is not None)
+ for k in shard.PROMPT_SETTINGS:
+ os.environ[k] = "1"
+ check(f"11 guard: {k}=1 runs with the shard at four ranks", shard.unsupported("batched", 4) is None)
+ os.environ.pop(k)
+ os.environ["TF_NCCL_RING"] = "1"
+ check("11 guard: the carry on a four-rank ring runs (relayed)", shard.unsupported("batched", 4) is None)
+ os.environ.pop("TF_NCCL_RING")
+
+ class NoSend:
+ nccl = None
+
+ def __getattr__(self, name):
+ raise AssertionError(f"warm-up touched the communicator ({name})")
+
+ saved_world = shard.WORLD
+
+ def warm_touches():
+ try:
+ shard.warm(NoSend(), "cpu")
+ return False
+ except Exception:
+ return True
+ try:
+ shard.WORLD = 4
+ os.environ["TF_GLM_KV_SHARD_CARRY"] = "0"
+ check("11 warm-up: carry off, four ranks: no point-to-point connection", not warm_touches())
+ os.environ["TF_GLM_KV_SHARD_CARRY"] = "1"
+ os.environ["TF_NCCL_RING"] = "1"
+ check("11 warm-up: carry on, on a ring: none either (the relay uses the neighbour links)", not warm_touches())
+ os.environ.pop("TF_NCCL_RING")
+ check("11 warm-up: carry on, on a switch: the pairs' connections", warm_touches())
+ finally:
+ shard.WORLD = saved_world
+ check("11 guard: the engine passes its rank count",
+ "shard.unsupported(verify_kind(), world)" in inspect.getsource(_engine))
+ finally:
+ for k, v in saved.items():
+ if v is None:
+ os.environ.pop(k, None)
+ else:
+ os.environ[k] = v
+section("11 tp4 guard", tp4_guard)
+
+
+def exp_paths():
+ """(13) The own-row front and microbatching with the shard, checked by structure (their kernels need a GPU)."""
+
+ from tensorfold.families.glm5_next.cuda import forward as fw
+ try: # (the tp4 branch's own-row front; main has none)
+ from tensorfold.families.glm5_next.cuda import own_front as of
+ except ImportError:
+ of = None
+ rest = inspect.getsource(of.rest) if of is not None else None
+ if rest is not None:
+ check("13 own-front: the owner only writes the chunk's latents into the cache (sharded, not a twin)",
+ "sharded = shard.ON and w.comm is not None and getattr(st, \"twin_base\", None) is None" in rest
+ and "if not sharded or lc is not None:" in rest)
+ check("13 own-front: sharded rows take their tokens from the shared pools, then the owner's rows through "
+ "_sharded_attend with the stream's owner as root",
+ "sparse.pool_tokens(pools[:R], pos_dev, tokens[:R], counts[:R])" in rest and "_sharded_attend(" in rest
+ and "shard.owner(st.base)" in rest)
+ check("13 own-front: the unsharded path is the tp4 one (dense and sparse attention on lc)",
+ "dense_attention(qa[:dense], lc, pos_dev" in rest and "sparse_prompt(qa, lc, tokens[:R], counts[:R], ol, scale)" in rest)
+ att = inspect.getsource(fw._sharded_attend)
+ i, j, k2 = att.find("wait_stream(side)"), att.find("shard.fetch("), att.find("side.wait_stream(")
+ check("13 fetch: ordered with the split's side stream (it waits for the side stream, then the side stream for it)",
+ 0 <= i < j < k2)
+ check("13 fetch: the dsa_rows path and the own-row front share it",
+ "_sharded_attend(" in inspect.getsource(fw._sharded_rows))
+ sp = inspect.getsource(fw._shard_sparse)
+ check("13 kernel: sharded rows use the unsharded path's sparse kernel choice (sparse_prompt where the base has it)",
+ "_shard_sparse(qa, att, tok, counts, ol, scale, b.prefill)" in att and 'globals().get("sparse_prompt")' in sp
+ and "latent.SPARSE_ONEPASS" in sp)
+
+ class B:
+ split = SimpleNamespace(stream="side")
+ check("13 side stream: found on a row-split chunk, none without a split",
+ fw._side_stream(B()) == "side" and fw._side_stream(SimpleNamespace()) is None
+ and fw._side_stream(SimpleNamespace(split=None)) is None)
+section("13 exp paths", exp_paths)
+
+
+class SimRing:
+ """A switchless ring's links for ``relay_rows``: ``links`` as the calling rank sees them (to the next rank: link r,
+ this rank its rank 0; to the previous: link r - 1, its rank 1), and ``lib.ncclAllGather`` as a two-rank mailbox:
+ a call posts its half and takes the partner's if already posted (the sender never needs the receiver's half; the
+ ranks run in path order, so each receive finds its sender's piece). No ncclSend / ncclRecv exist here."""
+
+ def __init__(self, world):
+ import collections
+ self.world, self.box, self.log, self.touched, self.spans = world, collections.defaultdict(collections.deque), [], [], []
+ ring = self
+
+ class AllGather:
+ argtypes = None
+
+ def __call__(self, send, recv, count, dtype, link, stream):
+ import ctypes
+ me = (send - recv) // (count * 4)
+ assert me in (0, 1) and dtype == 2, (me, dtype)
+ for ptr in (send, recv):
+ if any(lo <= ptr < hi for lo, hi in ring.spans):
+ ring.touched.append(("allgather", ptr))
+ ring.box[(link, me)].append(ctypes.string_at(send, count * 4))
+ got = bool(ring.box[(link, 1 - me)])
+ if got:
+ data = ring.box[(link, 1 - me)].popleft()
+ ctypes.memmove(recv + (1 - me) * count * 4, data, len(data))
+ ring.log.append(("ag", shard.RANK, link, me, count, got))
+ return 0
+
+ self.lib = type("Lib", (), {})()
+ self.lib.ncclAllGather = AllGather()
+
+ def no(*a, **k):
+ raise AssertionError("a point-to-point send or receive on the ring")
+ self.lib.ncclSend = self.lib.ncclRecv = self.lib.ncclBroadcast = no
+
+ @property
+ def links(self):
+ r = shard.RANK
+ return {1: ("L", r), -1: ("L", (r - 1) % self.world)}
+
+ def _check(self, code):
+ assert code == 0
+
+
+def ring_carry_sim(world, src, dst, n, piece=None):
+ ars = sim_arenas(world)
+ before = [[p.tensor.clone() for p in ar.planes] for ar in ars]
+ nc = SimRing(world)
+ for ar in ars:
+ for p in ar.planes:
+ if p.spanned:
+ nc.spans.append((p.tensor.data_ptr(), p.tensor.data_ptr() + p.tensor.numel() * p.tensor.element_size()))
+ saved = (shard._stream, shard._piece, os.environ.get("TF_NCCL_RING"))
+ shard._stream = lambda: 0
+ if piece is not None:
+ shard._piece = lambda rb: piece
+ os.environ["TF_NCCL_RING"] = "1"
+ so, do = shard.owner(src), shard.owner(dst)
+ path = shard.ring_path(so, do, world)
+ try:
+ for r in path + [r for r in range(world) if r not in path]:
+ shard.RANK = r
+ ars[r].carry(src, dst, n, nc)
+ finally:
+ shard._stream, shard._piece = saved[0], saved[1]
+ if saved[2] is None:
+ os.environ.pop("TF_NCCL_RING", None)
+ else:
+ os.environ["TF_NCCL_RING"] = saved[2]
+ shard.RANK = 0
+ return ars, before, nc, path
+
+
+def ring_carry_cases():
+ shard.ON = False
+ try:
+ check("12 ring path: neighbours one hop, the shorter way round, the opposite rank the way up",
+ shard.ring_path(0, 1, 4) == [0, 1] and shard.ring_path(0, 3, 4) == [0, 3] and shard.ring_path(3, 0, 4) == [3, 0]
+ and shard.ring_path(0, 2, 4) == [0, 1, 2] and shard.ring_path(2, 0, 4) == [2, 3, 0]
+ and shard.ring_path(1, 3, 4) == [1, 2, 3] and shard.ring_path(0, 2, 3) == [0, 2] and shard.ring_path(1, 0, 3) == [1, 0])
+ for world, src, dst, n, piece, label in (
+ (4, 2048, SH + 4096, 3001, None, "part 0 to its neighbour 1"),
+ (4, 4096, 2 * SH + 2048, 4097, 513, "part 0 to the opposite part 2 (relayed by rank 1), 513-row pieces"),
+ (4, 2 * SH + 1024, 4096, 2500, 700, "part 2 to the opposite part 0 (the way up: relayed by rank 3)"),
+ (4, 3 * SH, 2048, 2049, None, "part 3 to part 0 across the ring's seam"),
+ (4, SH + 2048, 3 * SH + 4096, 3000, 1000, "part 1 to the opposite part 3 (relayed by rank 2)"),
+ (4, 4096, 3 * SH + 2048, 2000, 7, "part 0 down to part 3, 7 rows a piece"),
+ (3, 4096, 2 * SH + 2048, 3000, 999, "TP3 ring: part 0 to 2, one hop down")):
+ ars, before, nc, path = ring_carry_sim(world, src, dst, n, piece)
+ exp = expected(ars, before, world, src, dst, n)
+ ok = all(bytes_eq(p.tensor, exp[r][k]) for r, ar in enumerate(ars) for k, p in enumerate(ar.planes))
+ check(f"12 ring carry [{label}]: every plane of every rank is the source's rows at the destination, nothing "
+ f"else touched (relays included)", ok)
+ planes = sum(1 for p in ars[0].planes if p.shard)
+ pieces = -(-n // (piece or n))
+ calls = {r: [e for e in nc.log if e[1] == r] for r in range(world)}
+ want = {r: (0 if r not in path else (1 if r in (path[0], path[-1]) else 2) * planes * pieces) for r in range(world)}
+ check(f"12 ring carry [{label}]: only the path's ranks call ({path}), each hop once a piece and plane "
+ f"(ends one hop, relays two); no point-to-point", all(len(calls[r]) == want[r] for r in range(world)))
+ recv = [e for e in nc.log if e[5]]
+ check(f"12 ring carry [{label}]: every hop's receiver found its sender's piece ({len(recv)} = hops x pieces x planes)",
+ len(recv) == (len(path) - 1) * pieces * planes and not any(e[1] == path[0] for e in recv))
+ check(f"12 ring carry [{label}]: the display span is reached only by kernel", not nc.touched)
+ os.environ["TF_NCCL_RING"] = "1"
+ shard.setup(0, 4, 4 * SH)
+ check("12 relayed: a four-rank ring relays, two ranks never do", shard.relayed())
+ check("12 relayed: only over a communicator with the ring links (main's has none: direct sends, as before)",
+ shard.relayed(SimpleNamespace(links={1: "next", -1: "prev"})) and not shard.relayed(SimpleNamespace())
+ and not shard.relayed(SimpleNamespace(links={})))
+ shard.setup(0, 2, 2 * SH)
+ check("12 relayed: (two ranks: no)", not shard.relayed())
+ os.environ.pop("TF_NCCL_RING")
+ shard.setup(0, 4, 4 * SH)
+ check("12 relayed: four ranks on a switch send straight", not shard.relayed())
+ finally:
+ os.environ.pop("TF_NCCL_RING", None)
+ shard.setup(0, 2, 4096 * 512)
+section("12 ring carry", ring_carry_cases)
+print("FAILED" if fails else "ALL PASS", len(fails))
+sys.stdout.flush()
+os._exit(1 if fails else 0)
diff --git a/tools/kv_shard_mutants.sh b/tools/kv_shard_mutants.sh
new file mode 100755
index 0000000..35b1744
--- /dev/null
+++ b/tools/kv_shard_mutants.sh
@@ -0,0 +1,141 @@
+#!/bin/bash
+# kv_shard_mutants.sh <dir> [names] CPU only: tools/kv_shard_check.py must pass on the tree as it is and FAIL on each
+# faithful mutant of the cross-part carry (TF_GLM_KV_SHARD_CARRY): the code with one of its guards, rules or steps taken
+# out or turned the wrong way. <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/kv_shard_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 NCCL calls themselves, the CUDA events that time a carry, and the collectives' order across real ranks
+# (the check simulates the ranks one after the other in one process: the sender first, a receive with no send before
+# it raises).
+set -u
+TARGET=$1; ONLY=${2:-.}
+HERE=$(cd "$(dirname "$0")" && pwd)
+C="$HERE/kv_shard_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" PYTHONDONTWRITEBYTECODE=1 CUDA_VISIBLE_DEVICES= 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 PASS" "$OUT" && ! grep -q "^FAIL" "$OUT"; then
+ echo "patched: all passed ($(grep -c '^PASS' "$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
+}
+MU=families/glm5_next/cuda/multi.py; PO=families/glm5_next/cuda/pool.py; SH=families/glm5_next/cuda/shard.py; SB=cuda/spill_blocks.py; EN=families/glm5_next/cuda/engine.py
+run patched
+# the collective: the other ranks hold the op before rank 0 sends (ADMIT copy 2, XMOVE)
+run drop-sync $MU " if copy == 2: # a carry is a collective: the other ranks hold this ADMIT before rank 0 sends\n self._sync()\n" ""
+run xmove-no-sync $MU " self._sync() # a carry is a collective: rank 1 holds the op before rank 0 sends\n" ""
+run follower-copies $MU " self._carry(hit.extent.base, x.base, cut, \"admit\")" " self.arena.copy(hit.extent.base, x.base, cut)"
+# the transport: the rows, byte for byte, between the two owners only
+run carry-cut-minus-1 $PO "shard.send_rows(nc, do, _byte_rows(p, shard.local(src), n), p.spanned)" "shard.send_rows(nc, do, _byte_rows(p, shard.local(src), n - 1), p.spanned)" \
+ $PO "shard.recv_rows(nc, so, _byte_rows(p, shard.local(dst), n), p.spanned)" "shard.recv_rows(nc, so, _byte_rows(p, shard.local(dst), n - 1), p.spanned)"
+run skip-replicated-copy $PO " _move(p.tensor, a, b, min(-(-n // p.div), p.tensor.shape[0] - max(a, b)), p.spanned)\n elif relay:" " pass\n elif relay:"
+run bystander-receives $PO " elif shard.RANK == do:\n shard.recv_rows" " else:\n shard.recv_rows"
+run span-send-by-memcpy $SH " put_rows(buf[:k], rows[i:i + k], spanned)" " put_rows(buf[:k], rows[i:i + k], False)"
+run span-recv-by-memcpy $SH " put_rows(rows[i:i + k], buf[:k], spanned)" " put_rows(rows[i:i + k], buf[:k], False)"
+run pool-move-crosses-by-default $PO "size: int | None = None, cross: bool = False) -> int:" "size: int | None = None, cross: bool = True) -> int:"
+run xmove-not-applied $MU " elif op == XMOVE:\n self._xmove(self.pool.get(p[0]), p[1], p[2], p[3])" " elif op == XMOVE:\n pass"
+run grow-fits-true $MU " if hi - lo - held >= size:\n return True\n return False\n" " return True\n return False\n"
+run grow-fits-held-flipped $MU "and id(y) not in gone and (y.owner is not None or not y.kept))" "and id(y) not in gone and (y.owner is not None or y.kept))"
+# the pressure rule: a carry only to avoid a real cost
+run pressure-count-balance $MU " if self._fits_unevicted(hit, need, others):\n return None\n" " if self._fits_unevicted(hit, need, others) and self.pool.live(self.pool.half_of(hit.extent)) - min(self.pool.live(q) for q in range(self.pool.parts)) < 2:\n return None\n"
+run pressure-without-eviction-condition $MU " if self._fits_unevicted(hit, need, others):\n return None\n" ""
+run pressure-no-headroom $MU " want = need + ALIGN * (pool.live(q) + 1)\n if pool.place(want, half=q)" " want = need\n if pool.place(want, half=q)"
+run pressure-may-evict-in-target $MU " if pool.place(want, half=q) is not None or pool.compactable(q) >= want:\n base = self._room_free(want, q)" " if True:\n base = self._room(want, [hit.extent], half=q)"
+run unevicted-ignores-lone-others $MU " if others:\n return not self.tune.lone and pool.place(need, half=p) is not None" " if others:\n return pool.place(need, half=p) is not None"
+run unevicted-compacts-for-others $MU " return not self.tune.lone and pool.place(need, half=p) is not None" " return not self.tune.lone"
+run small-ignored-pressure $MU " return None\n if len(hit.ids) < CARRY_MIN:" " return None\n if False:"
+run small-uses-need $MU " return None\n if len(hit.ids) < CARRY_MIN:" " return None\n if need < CARRY_MIN:"
+run small-ignored-others $MU " pool = self.pool\n if len(hit.ids) < CARRY_MIN:" " pool = self.pool\n if False:"
+run small-ignored-rescue $MU "room either.\"\"\"\n\n if len(hit.ids) < CARRY_MIN:" "room either.\"\"\"\n\n if False:"
+run recent-copy-1-untouched $MU " if copy == 2 and getattr(hit, \"own\", False):" " if copy and getattr(hit, \"own\", False):"
+# counters
+run no-part-never-restored $MU "self.no_part = spent if got is not None or hit.extent.owner is None else refused" "self.no_part = refused"
+run no-part-always-spent $MU "self.no_part = spent if got is not None or hit.extent.owner is None else refused" "self.no_part = spent"
+run counted-at-decision $MU " self.carry_kind = \"rescued\"\n return base, 2" " self.carry[\"rescued\"] += 1\n return base, 2"
+run never-counted $MU " if copy == 2 and self.carry_kind: # (counted once the ADMIT is queued: a placement that failed earlier is not)\n self.carry[self.carry_kind] += 1\n" ""
+# the XMOVE rows are rank 0's
+run follower-recomputes-used $MU " self._carry(old, base, used, \"live\")" " self._carry(old, base, mine, \"live\")"
+run xmove-used-with-pending $MU " used = self._used(x, pending=False)\n if used > size:\n return False\n" " used = self._used(x)\n"
+run xmove-follower-refuses $MU " if used > size: # (rank 0's own arguments: checked before anything is sent)\n" " if self._used(x) > used or used > size:\n"
+# live streams: no bouncing
+run no-headroom-in-target $MU " want = size + ALIGN * (pool.live(q) + 1)\n if pool.place(want, half=q)" " want = size\n if pool.place(want, half=q)" \
+ $MU " base = self._room_free(size + ALIGN * (pool.live(q) + 1), q)" " base = self._room_free(size, q)"
+run no-cooldown $MU "and self.xticks - lane.moved_at >= RELOCATE_HOLD)" "and True)"
+run move-back-allowed $MU "(lane.came_from == q and self.xticks - lane.moved_at < RELOCATE_HOLD)" "False"
+run no-entered-guard $MU " if self.xticks - self.entered.get(p, -(1 << 30)) >= RELOCATE_HOLD:" " if True:"
+run no-cheapest-stream $MU " for m in self.lanes.values():\n if m is lane or" " for m in []:\n if m is lane or"
+run hold-1 $MU "RELOCATE_HOLD = 256\n" "RELOCATE_HOLD = 1\n"
+# the settings
+run lone-not-forced-off $MU " if not shard.ON or not tune.lone or not KV_CARRY: # (TF_GLM_KV_SHARD_CARRY=0: the decoder as before the carry)\n return tune\n" " return tune\n"
+run lone-off-at-carry0 $MU " if not shard.ON or not tune.lone or not KV_CARRY:" " if not shard.ON or not tune.lone:"
+run relocate-second-carry $MU " lane.xwhy = None\n return True\n break\n" " lane.xwhy = None\n return True\n"
+run init-ignores-shard-tune $MU "self.tune = shard_tune(tune if tune is not None else MultiSettings.from_env())" "self.tune = tune if tune is not None else MultiSettings.from_env()"
+# the time of a carry
+run ms-own-side-only $MU " if self.w.world > 2:\n ms = max(" " if False:\n ms = max("
+run ms-gathered-at-two-ranks $MU " if self.w.world > 2:\n ms = max(" " if self.w.world > 1:\n ms = max("
+# TP3 warm-up
+run warm-not-called $EN " shard.warm(self.comm, w.device) # (TP3 and up: the pairs' send/recv connections now, not at a carry)\n" ""
+run warm-at-two-ranks $SH " if WORLD < 3 or not carry_on() or relayed(nc):" " if WORLD < 2 or not carry_on() or relayed(nc):"
+run warm-pairs-reversed $SH " for b in range(a + 1, WORLD):" " for b in range(WORLD - 1, a, -1):"
+run warm-both-send-first $SH " elif RANK == b:\n _recv(nc, got, a, stream)\n _send(nc, out, a, stream)" " elif RANK == b:\n _send(nc, out, a, stream)\n _recv(nc, got, a, stream)"
+run import-per-piece $SH " w = rows.view(torch.int32)\n nc._check(nc.lib.ncclSend(" " from tensorfold.cuda.comm import _DTYPES\n\n w = rows.view(torch.int32)\n nc._check(nc.lib.ncclSend("
+# what is refused: rows that something pins
+run pins-all-gone $MU " if getattr(x, \"loading\", None) is not None:\n return \"loading\"\n if self._pinned()(x):\n return \"pinned\"\n lane = self.lanes.get(x.owner) if x.owner is not None else None\n if x.twin or (lane is not None and lane.twin is not None):\n return \"twin\"\n if lane is not None and self.partial is not None and self.partial.contains(lane.sid):\n return \"partial\"\n return None" " return None"
+run pins-no-loading $MU " if getattr(x, \"loading\", None) is not None:\n return \"loading\"\n if self._pinned()(x):" " if self._pinned()(x):"
+run pins-no-pinned $MU " if self._pinned()(x):\n return \"pinned\"\n" ""
+run pins-no-twin $MU " if x.twin or (lane is not None and lane.twin is not None):\n return \"twin\"\n" ""
+run pins-no-partial $MU " if lane is not None and self.partial is not None and self.partial.contains(lane.sid):\n return \"partial\"\n return None" " return None"
+# the balance rule
+run min-0 $MU "CARRY_MIN = 2048\n" "CARRY_MIN = 0\n"
+# the rescue and the others branch
+run rescue-off $MU " got = self._rescue(hit, need, why) if sharded else None" " got = None"
+run others-off $MU " if base is None and sharded: # its part is full: free rows of another carry them instead" " if False:"
+# the LRU
+run touch-carried-own $MU " if copy == 2 and getattr(hit, \"own\", False):\n return\n self._touch(hit)" " self._touch(hit)"
+# live streams
+run relocate-not-called $MU " elif KV_CARRY and self.pool.half:\n ok = self._relocate(l)" " elif False:\n ok = self._relocate(l)"
+run xmove-no-rebind $MU " self._carry(old, base, used, \"live\")\n if x.owner is not None:\n self.lanes[x.owner].st.bind(x.base, x.size)\n" " self._carry(old, base, used, \"live\")\n"
+run refusal-recounted $MU " if lane.xwhy != why:\n self._refused(why)" " if True:\n self._refused(why)"
+# the spill tier
+run no-spill-salt $MU " return in_part(c.lineage, self.pool.half_of(c.extent)) if self.pool.half else c.lineage" " return c.lineage"
+run salt-unsharded $MU " return in_part(c.lineage, self.pool.half_of(c.extent)) if self.pool.half else c.lineage" " return in_part(c.lineage, self.pool.half_of(c.extent))"
+run salt-stacks $SB " return f\"{head.partition('#')[0]}#{int(part)}{bar}{rest}\"" " return f\"{head}#{int(part)}{bar}{rest}\""
+run no-release-on-cross-move $MU " self._release_rows(x, 0 if cross else None)" " self._release_rows(x, None)"
+rm -f "$OUT"
+echo "exit $bad"
+exit $bad