GLM-5.3-Flash EXL3 on 2x DGX Spark with TensorFold
Python
v1.6 (draft): 0071 shared-prefix copy (#43, by @ezoushen, #44), 0072 display reservation (#55, by @ezoushen, #56), TF_ROCE_WAIT_S 300 (#54), SPLIT retried at start (#36)
MiaAI-Lab90d0c8e6e4b2
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c584d3f..b535706 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -3,6 +3,38 @@Every change to this recipe, newest first. Each release names the image it serves: `scripts/prepare.sh` pulls`ghcr.io/miaai-lab/glm-5.3-flash-exl3-2x-dgx-sparks-tensorfold` by the digest pinned in `scripts/config.sh`.+## v1.6 (unreleased): agent sessions keep their history beside sub-agents, the display reservation in the pool, a longer RoCE wait, SPLIT retried at start++Image: not built yet (patches `23ba9d861151`, 72 patches); until it is published, `scripts/prepare.sh` builds it locally.++### Fixed+- **#43: a conversation lost its kept prompt whenever another conversation with the same system prompt resumed from+ it** (patch `0071-glm-shared-prefix-copy`, by @ezoushen, #44). The resume took over the extent that held the shared+ state and evicted the longer states in it, which belong to the conversation that wrote it, so a coding agent re-read+ its whole history after each sub-agent request. The shared rows are now copied into free rows of their own; with no+ free rows, or `TF_GLM_MULTI_LONE=1`, it behaves as before. Placement only: the same replies. Two Sparks, v1.5 ++ 0071, `tools/prompt_reuse.py` (new): 5% -> 99% of a ~33k-token turn resumed, 16.5 s -> 1.0 s to the first token+ (measured by @ezoushen and @plotarmordev); the same replies, drafted == serial.+- **#54: a RoCE all-gather failed on long prompts and took both Sparks down.** `TF_ROCE_WAIT_S` is now 300 s (was the+ patch's 20): in the reports the failing rank's own writes had all completed, so the peer was late rather than lost.+ A late peer now costs a slow round; a rank that is really gone is noticed after 300 s, like the watchdog's report.+- **#36: with `SPLIT=1` a rank's first NCCL connection failed about half the time on some pairs** (NCCL error 2,+ `ibv_reg_mr`: cannot allocate memory, before any weights load). `start.sh` now tries such a start once more as it+ was, then starts with `SPLIT=0` (the same replies, long prompts fill slower) and says so.++### Added+- **`DISPLAY_KV_MIB`** (patch `0072-glm-display-kv`, by @ezoushen, #56; off by default): with `PARALLEL` above 1, up to+ 2032 MiB of the GB10's display reservation, which a headless Spark never uses and `MemAvailable` never counts, joins+ the shared pool on every rank without taking host memory. Measured by @ezoushen at `PARALLEL=8`: 1792 MiB adds+ 276,480 tokens a boot (1,611,776 -> 1,992,704), the same reply hashes on and off, decode, prefill and the 195k+ needle within boot-to-boot noise. Headless Sparks only: refused while a display is connected; fails closed.+ `tools/display_kv_check.py` runs its checks in the image.++### To do before release+- Build and publish the image; pin its digest in `scripts/config.sh` and on this entry.+- Two Sparks: concurrent == serial, drafted == serial, the 195k needle, `tools/prompt_reuse.py`, a boot with+ `DISPLAY_KV_MIB=1792` (and one with `SPLIT=1`), and a 3-Spark start.+## v1.5 (2026-10-03): up to 8 requests at once (8 by default on three Sparks), serial requests stop when their client leavesImage: `v0.6.0-9f73cca659a1` (`sha256:ef83797d791fef96c4605e8d37367aca6de5aeac7bb672792cb682e2e55d4237`), 70 patches, for two and three Sparks.diff --git a/CREDITS.md b/CREDITS.mdindex a0b9e5b..666d321 100644--- a/CREDITS.md+++ b/CREDITS.md@@ -90,6 +90,14 @@ checkpoint's ShapleyMcg attribution and the drafter's license).[SxMShaDoW](https://github.com/SxMShaDoW)), backported to v0.6.0.- `0060-glm-keep-thinking` (earlier turns keep their reasoning, `TF_GLM_CLEAR_THINKING`): by[kky42](https://github.com/kky42), pull request #23.+- `0071-glm-shared-prefix-copy` (a shared system prompt's resume keeps the writer's kept prompt, issue #43): by+ [ezoushen](https://github.com/ezoushen), [pull request #44](https://github.com/MiaAI-Lab/GLM-5.3-Flash-EXL3-2x-DGX-Sparks-TensorFold/pull/44),+ applied as contributed, with `tools/prompt_reuse.py`.+- `0072-glm-display-kv` (`DISPLAY_KV_MIB`, the display reservation in the shared pool, issue #55): by+ [ezoushen](https://github.com/ezoushen), [pull request #56](https://github.com/MiaAI-Lab/GLM-5.3-Flash-EXL3-2x-DGX-Sparks-TensorFold/pull/56),+ applied as contributed, with `tools/display_kv_check.py`. It applies to TensorFold's pool the display-reserve KV+ technique that [gabewillen](https://github.com/gabewillen) proposed for the vLLM kit in+ [MiaAI-Lab/GLM-5.3-Flash-EXL3-2x-DGX-Sparks#234](https://github.com/MiaAI-Lab/GLM-5.3-Flash-EXL3-2x-DGX-Sparks/pull/234).- Every patch, except the parts credited above: by MiaAI-Lab, developed with[Claude Code](https://claude.com/claude-code), under the Apache License 2.0; the TensorFold code the patches modify orquote as context stays under TensorFold's licenses (Apache 2.0, and MIT for code written before v0.6.0; seediff --git a/README.md b/README.mdindex 26d0b7e..fbe2bcd 100644--- a/README.md+++ b/README.md@@ -14,7 +14,7 @@Serve **GLM-5.3-Flash** from two NVIDIA DGX Sparks (GB10, 128 GB each, linked by their ConnectX-7 ports) through anOpenAI-compatible API, with **4 concurrent requests**, the model's full **1,048,576-token context** and **image andvideo input**. It runs [TensorFold](https://github.com/ashhart/TensorFold) v0.6.0 on both Sparks (one rank on each)-in NVIDIA's PyTorch container, plus 70 patches (65 of v1.4, 3 for 3 Sparks, experimental, 1 for up to 8 requests at once, 1 for stopping serial requests): DFlash2 and copy drafts, 4-bit dense weights, an FP8 KV cache,+in NVIDIA's PyTorch container, plus 72 patches (65 of v1.4, 3 for 3 Sparks, experimental, 1 for up to 8 requests at once, 1 for stopping serial requests, 2 of v1.6 by [ezoushen](https://github.com/ezoushen): a shared system prompt keeps each conversation's history, the display reservation in the pool): DFlash2 and copy drafts, 4-bit dense weights, an FP8 KV cache,faster prompt kernels, a one-shot RoCE all-gather between the Sparks, several requests over one shared cache pool,vision, tool calling, `/tokenize` and `/metrics`.@@ -259,6 +259,7 @@ caches from **one shared pool**:| Rank 0's startup estimate | 88.09 GiB || Free memory (`MemAvailable`) at idle | 7.0 GiB on rank 0, 10.5 GiB on rank 1 || Lowest free memory under a 1M-token prompt | 5.6 GiB on rank 0, 9.5 GiB on rank 1 |+| Display reservation in the pool (`DISPLAY_KV_MIB`) | off; 1792 MiB adds ~277k tokens at `PARALLEL=8` without taking host memory |Any one request can grow to the full window, and the four together share the pool: e.g. one 1M-token conversationnext to one more of 1M, or next to three of ~640k. A request the pool cannot place yet waits until others finish (kept prompt states give way@@ -267,6 +268,14 @@ first); `/health` shows `pool_tokens`, `pool_free_tokens` and the streams decodiTensorFold's budget on each Spark is `MemAvailable` at start minus a host reserve (`MEMORY_RESERVE_GIB`, 14.5 GiB here;TensorFold's own default is a tenth of RAM). The server uses about 10 GiB beyond its own estimate at its peak, so thereserve also sets the lowest free memory.+The GB10 firmware also keeps about 2 GiB for a screen, which a headless Spark never uses and `MemAvailable` never+counts. With `PARALLEL` above 1, `DISPLAY_KV_MIB=1792` (patch 0072) adds that much of it to the pool on every rank, on+top of `KV_POOL_GIB`: the first DSA layers' latent planes sit in a span of ordinary memory with the reservation mapped+right above it, so the pool takes no more host memory than the budget gives it. Same replies, decode and prefill. It+needs `/dev/dri/card0` in the containers (`nvidia_drm` with `modeset=1`; `--gpus all` passes the device); `start.sh`+checks it on the head, and a worker without it stops at load. **Headless Sparks only:** a monitor's framebuffer lives+in that reservation, so `start.sh` and each rank refuse the setting while any `card0` output reports `connected`.+1792 is measured; 2048 failed in the vLLM kit (#234).On the Spark's unified memory, running out tends to freeze the machine rather than fail an allocation. A setting thatdoes not fit is refused before any weights load, with the largest window that fits; `start.sh` then restarts oncewith that window and says so (free memory on both Sparks for the full one). Other settings' windows:@@ -403,6 +412,7 @@ sets a value wins: the environment, then `scripts/local.sh`, then `.env`, then t| `KV` | `fp8` | `fp8` or `bf16` (exact, shorter window) DSA latent cache and indexer keys || `WORKER_WEIGHTS` | `copy` | `copy`: the worker keeps its own copy of the weights; `nfs`: it reads the head's over NFS ([Worker weights over NFS](#worker-weights-over-nfs)); with `NFS_PATH`, `NFS_SERVER`, `NFS_VOLUME` || `KV_POOL_GIB` / `MEMORY_RESERVE_GIB` | `12.5` (`32` at `TP=3`) / `14.5`, plus ~0.95 a request past 4 and ~0.04 a window row past 32 (`19.6` at 8 requests and 64 rows) | the shared pool beyond the window (kept prompts, more long conversations at once) grows into what is free at start minus the reserve, up to `KV_POOL_GIB` GiB a Spark; the reserve sets the lowest free memory on the head (~4.5-5 GiB under a 1M-token prompt); it grows with `PARALLEL` because more requests at once take more than the startup estimate counts; raise it when other work shares the Sparks |+| `DISPLAY_KV_MIB` | `0` (off) | MiB of the GPU's display reservation added to the shared pool on every rank (patch 0072, `PARALLEL` above 1; a multiple of 16 up to 2032, 1792 measured): pool tokens without host memory, on top of `KV_POOL_GIB`; needs `/dev/dri/card0`; headless Sparks only (refused while a display is connected) || `DENSE` | `q4` | the checkpoint's BF16 weights (attention, shared experts, dense layers, head): `q4` (4-bit groups of 64, the head in FP8, kv_b in BF16), `fp8` or `bf16`. **Non-English prompts:** `q4` can lose the end of turn on short French coding prompts (replies run to `max_tokens`, issue #18); `fp8` keeps it, at ~10% decode speed || `DRAFTER` | `dflash2` | `dflash2`: IncoAI's DFlash2 drafter, licensed [CC BY-NC-ND 4.0](https://creativecommons.org/licenses/by-nc-nd/4.0/), **non-commercial use only**; +5-10% decode. `mtp`: the checkpoint's own MTP head, one request at a time, which avoids that license (set it before the first `./start.sh` and DFlash2 is never downloaded) || `TF_GLM_MTP` | `auto` | the checkpoint's MTP head beside DFlash2: `auto` leaves it out while DFlash2 drafts every request; `1` (TensorFold v0.6.0's own default) loads it, 1.77 GiB a Spark, with `PARALLEL=1`. `DRAFTER=mtp` always loads it |@@ -414,12 +424,12 @@ sets a value wins: the environment, then `scripts/local.sh`, then `.env`, then t| `THINKING` | `1` | think before answering by default; `0` answers directly unless a request asks to think || `VISION` / `VISION_URLS` | `1` / `0` | image and video input; `1` also accepts public `https://` URLs || `COMM` | `roce` | the ranks' small all-gathers as one-shot RDMA writes over the RoCE link; `nccl`: NCCL for all |-| `SPLIT` | `1` | prompt chunks' hyper-connection work split between the Sparks, its exchanges overlapped with the next rows' work |+| `SPLIT` | `1` | prompt chunks' hyper-connection work split between the Sparks, its exchanges overlapped with the next rows' work; when a rank's first NCCL connection fails with it (NCCL error 2, issue #36), `start.sh` tries once more, then starts with `SPLIT=0` and says so || `KDA_CHUNKED` | `1` | KDA prompt chunks in chunked (WY) form, one CUDA kernel || `TF_GLM_L2PF` | `1` | L2 prefetch in decode: the weights the next kernels read brought into L2 during each layer's all-gathers; `0`: off || `TF_GLM_EXL3_LOADS` | `nc` | the decode expert kernel's trellis as 16-byte non-coherent loads a step ahead (`nc2` / `nc4`: 2 or 4 steps); `0`: TensorFold's 32-bit loads || `TF_ROCE_MAX_KB` | `512` | the largest all-gather (KiB) sent over RoCE with `COMM=roce` (TensorFold's default: 256); 512 covers the 17-32-row verify windows of concurrent requests |-| `TF_ROCE_WAIT_S` | `20` | seconds a RoCE all-gather waits for the other Spark before it fails (1 to 3600); until the engine is built, each gather first meets the peer in an NCCL barrier, so a long first start (kernels compiling) does not run into it |+| `TF_ROCE_WAIT_S` | `300` | seconds a RoCE all-gather waits for the other Spark before it fails (1 to 3600; the patch's own default is 20, which a late peer on long prompts outlasted, issue #54); until the engine is built, each gather first meets the peer in an NCCL barrier, so a long first start (kernels compiling) does not run into it || `TF_GLM_MULTI_WINDOW` | `32`, `64` past 4 requests | with `PARALLEL` above 1, the rows of every request's verify window together in a round (16 to 64 in steps of 8): with more requests at once each one's drafts get fewer of them (8 requests' code: 141.2 / 160.3 / 167.0 tok/s at 32 / 48 / 64 rows); past 32 rows `TF_ROCE_MAX_KB` rises with it (64: 1024) unless you set it. Exact at any size || `TF_GLM_MULTI_LONE` | `0` | `1`: with `PARALLEL` above 1, a request decoding alone runs on the one-stream graphs (+0.6-0.9%), but its move to the pool's first rows evicts other conversations' kept prompts there (issues #12, #13); `0`: on the batched ones || `TF_GLM_CACHE_ENTRIES` | `32` | kept prompt states at most (TensorFold's default is 8); past this count a conversation's earlier (superseded) states go first, then the least recently used, however much of the pool is free (patch `0063`, @Alexbob0). An agent request keeps 1 to 3 (issue #17); each costs ~45 MiB at start |@@ -506,14 +516,15 @@ 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 || 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 || Prompt, two Sparks | `0010-glm-hc-split`, `0033-glm-prefill-overlap2`, `0017-glm-overlap-priority`, `0022-glm-overlap-normal-priority`, `0064-glm-split-connect-early` | hyper-connection glue split by rows between the Sparks, exchanges overlapped with the next rows' work (`SPLIT`); the split's send/receive connection opened before the weights and the cache pool (issue #36) | 50k prefill ~1,270 -> ~1,730 tok/s with 0009 and 0020; decode rounds pay ~1.5% || Prompt, KDA | `0012-glm-kda-chunked`, `0014-glm-kda-chunked-gb10`, `0039-glm-kda-chunked-kernel` | the linear-attention layers' prompt chunks in chunked (WY) form, one CUDA kernel (`KDA_CHUNKED`) | 50k prefill 29.3 -> 26.4 s, 149k 91.1 -> 84.5 s (one start each) |-| Prompt reuse | `0008-glm-prompt-grid`, `0015-glm-shared-prefix`, `0042-glm-prompt-replay`, `0054-glm-image-prompt-reuse`, `0060-glm-keep-thinking`, `0063-glm-kept-cap-superseded-first` | prompt chunks and kept states on a token grid; a shared system prompt's state reused; an identical prompt resumes from its kept end state; prompts with pictures resume too, their kept states told apart by each picture's content (by abhicnv007, issue #11); earlier turns' reasoning kept in the prompt (`TF_GLM_CLEAR_THINKING`, by kky42, #23); past the kept-state cap a conversation's superseded states go first (by Alexbob0, #32) | [Performance](#performance) |+| Prompt reuse | `0008-glm-prompt-grid`, `0015-glm-shared-prefix`, `0042-glm-prompt-replay`, `0054-glm-image-prompt-reuse`, `0060-glm-keep-thinking`, `0063-glm-kept-cap-superseded-first`, `0071-glm-shared-prefix-copy` | prompt chunks and kept states on a token grid; a shared system prompt's state reused (copied out of the conversation that wrote it, which keeps its own state, by ezoushen, #43); an identical prompt resumes from its kept end state; prompts with pictures resume too, their kept states told apart by each picture's content (by abhicnv007, issue #11); earlier turns' reasoning kept in the prompt (`TF_GLM_CLEAR_THINKING`, by kky42, #23); past the kept-state cap a conversation's superseded states go first (by Alexbob0, #32) | [Performance](#performance) || Decode | `0013-glm-decode-rounds`, `0016-glm-decode-kernels`, `0019-glm-decode-kernels2`, `0031-glm-decode-index-regs` | verify windows of up to 16 rows; faster decode matmuls, hyper-connection mixing and indexer scoring | faster decode rounds; long copy drafts (`COPY_MAX` 15: edit replies 84 -> 119 tok/s) || Decode, memory | `0046-glm-l2-prefetch`, `0047-glm-exl3-decode-loads` | the next kernels' weights prefetched into L2 during each layer's all-gathers (`TF_GLM_L2PF`, adapted from jayleaton/glm53-tensorfold-spark's patch 0460); the routed experts' trellis as 16-byte non-coherent loads a step ahead (`TF_GLM_EXL3_LOADS`, adapted from its patch 0580) | with `TF_ROCE_MAX_KB=512`: one request's prose 48.36 -> 49.68 tok/s, code 59.54 -> 61.49 (+2.7% / +3.3%); 4 at once prose 74.8 -> 76.6, code 100.0 -> 102.7 (two starts each); the same bits || Decode, indexer | `0043-glm-visible-pools` | a decode row's token scoring and split selection bounded to the pools it can see (TensorFold v0.6.0 bounds its one-program selection, PR #140) | the same tokens |-| Link | `0006-cuda-roce-allgather`, `0052-cuda-roce-startup` | the small all-gathers as one-shot RDMA writes over RoCE (`COMM=roce`; up to 512 KiB, `TF_ROCE_MAX_KB`: code at 4 streams +1.4%); until the engine is built, each eager gather first waits for the peer in an NCCL barrier, and the RoCE kernel builds during setup (`TF_ROCE_WAIT_S`, default 20 s; errors print the proxy's counters); an idle rank 1 waiting on a socket is TensorFold v0.6.0's (#132) | 11 us a 16 KiB gather against NCCL's 45, decode +6%; an idle server holds no GPU or CPU core; a first start whose ranks drift apart while building kernels no longer fails |+| Link | `0006-cuda-roce-allgather`, `0052-cuda-roce-startup` | the small all-gathers as one-shot RDMA writes over RoCE (`COMM=roce`; up to 512 KiB, `TF_ROCE_MAX_KB`: code at 4 streams +1.4%); until the engine is built, each eager gather first waits for the peer in an NCCL barrier, and the RoCE kernel builds during setup (`TF_ROCE_WAIT_S`, 300 s here; errors print the proxy's counters); an idle rank 1 waiting on a socket is TensorFold v0.6.0's (#132) | 11 us a 16 KiB gather against NCCL's 45, decode +6%; an idle server holds no GPU or CPU core; a first start whose ranks drift apart while building kernels no longer fails || Drafts | `0007-glm-copy-drafts`, `0032-glm-code-copy-drafts`, `0018-glm-noise-policies`, `0021-glm-dflash-policy-env`, `0025-glm-dflash2-ring` | copy (prompt-lookup) drafts ahead of DFlash2's (`COPY`, `COPY_CODE`); DFlash2 stop rules aware of the sampling noise (`DRAFT_POLICY`); kept prompt states' DFlash2 window with shared prefixes (the ring itself and `TF_GLM_MTP` are TensorFold v0.6.0's; the recipe sets `TF_GLM_MTP=auto`, so the MTP head is not loaded when DFlash2 drafts) | `COPY`: quote / edit replies 80.3 -> 84.4 tok/s; `COPY_CODE`: code 55.4 -> 56.2, edit 120 -> 125; `DRAFT_POLICY` over `fc5:0.3`: prose 47.2 -> 50.6 tok/s, code 51.7 -> 55.5; memory for the window || Drafts, tooling | `0011-glm-draft-sim` | records of DFlash2's drafts for an offline simulator of stop rules (`TF_GLM_DRAFT_DUMP`, off) | how the stop rules were tuned || Concurrent requests | `0026-glm-multi-kda`, `0027-glm-multi-dflash2`, `0029-glm-multi-dsa`, `0030-glm-multi-stream-engine`, `0035-glm-multi-rounds`, `0040-glm-parallel-deadlocks`, `0041-glm-parallel-ring-base`, `0048-glm-timing-tokens`, `0049-glm-multi-prefill`, `0065-glm-rank-checks` | several streams over one shared pool of per-token caches, one batched verify window a round, both ranks kept in step; prompts that arrive together filled in one forward (`MULTI_PREFILL`: 4 prose requests at once 103.4 -> 108.8 tok/s, first token 590 -> 340 ms); a request alone on the one-stream graphs (`TF_GLM_MULTI_LONE=1`, off by default since v1.3.1: +0.6-0.9%); the startup timings of verify windows on distinct tokens | 4 requests at once ([Performance](#performance)) |@@ -570,7 +581,9 @@ with [sparkDash](https://github.com/MiaAI-Lab/sparkDash) ([Performance](#perform| --- | --- || `tools/needle.py [label] [size]` | hides a passphrase in a ~195k-token prompt (the prompt comes out at ~0.8 x `size` tokens) and checks the model returns it || `tools/toolcheck.py` | makes a tool call with an array parameter and checks it comes back as a JSON array |+| `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/end_of_turn.py [label] [max_cut]` | 8 short French coding prompts, thinking off: counts the replies that run to `max_tokens` (48 requests) and measures P(end of turn) right after each reply's closing code fence; exit 1 above `max_cut` cut replies (default 4) |+| `tools/prompt_reuse.py [size]` | a ~33k-token conversation takes three more turns, each after a request of another conversation with the same system prompt (an agent and its sub-agents); exit 1 when a turn resumes less than 90% of its prompt. Needs `PARALLEL` above 1 |## Repository layout@@ -582,7 +595,7 @@ scripts/ config.sh (all settings), local.sh.example (this setup's WORKER),both Sparks), nodes.sh (ssh and the RoCE links), publish-image.sh (push the image to GHCR),banner.sh (start.sh's banner)patches/ patches baked into the image-tools/ checks against the running server (needle, tool calls, end of turn)+tools/ checks against the running server (needle, tool calls, end of turn, prompt reuse) and patch 0072's in the imageCHANGELOG.md what changed in each releaseCREDITS.md who and what this builds onLICENSE Apache License 2.0diff --git a/patches/0071-glm-shared-prefix-copy.patch b/patches/0071-glm-shared-prefix-copy.patchnew file mode 100644index 0000000..4a645ff--- /dev/null+++ b/patches/0071-glm-shared-prefix-copy.patch@@ -0,0 +1,42 @@+# A request that resumes from a shared system prompt's kept state took over the extent holding it, and evicted every+# longer kept state in that extent. That extent belongs to the conversation that first wrote the shared prefix, so+# any other conversation with the same system prompt (an agent's sub-agents, several chats on one system prompt)+# deleted that conversation's state, and its next turn read its whole history again. The shared rows are now copied+# into an extent of their own when free rows hold it; without room the rows are overwritten as before. With+# TF_GLM_MULTI_LONE=1 it stays as before (the copy, decoding alone, would move home and evict the writer's extent).+# Same replies: placement only, the copied rows are the same bytes (issue #43). By @ezoushen (PR #44).++diff --git tensorfold/families/glm5_next/cuda/multi.py tensorfold/families/glm5_next/cuda/multi.py+index 24d3e6f..35409ed 100644+--- tensorfold/families/glm5_next/cuda/multi.py++++ tensorfold/families/glm5_next/cuda/multi.py+@@ -729,13 +729,23 @@ class MultiDecoder:+ base = None+ if hit is not None and hit.extent.owner is None:+ x = hit.extent+- for c in list(x.kept): # kept prompts the stream would overwrite: gone+- if len(c.ids) > len(hit.ids) and key[:len(c.ids)] != c.key:++ # 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 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 freshdiff --git a/patches/0072-glm-display-kv.patch b/patches/0072-glm-display-kv.patchnew file mode 100644index 0000000..c57771b--- /dev/null+++ b/patches/0072-glm-display-kv.patch@@ -0,0 +1,462 @@+# The shared pool also takes part of the GB10's display reservation (DISPLAY_KV_MIB, off by default). The firmware keeps+# ~2 GiB for a screen that a headless Spark never uses and MemAvailable never counts. With --parallel the pool is+# credited TF_GLM_DISPLAY_KV_MIB of it, and the first DSA layers' latent planes are carved from one span: ordinary host+# memory, then a DRM dumb buffer on /dev/dri/card0 mapped right above it, both registered with cuMemHostRegister, so the+# planes take exactly the credit from the reservation and no more host memory than without it. CUDA refuses a memcpy+# across the two registrations, so the pool's row copies of those planes go through an elementwise kernel. Placement+# only: the same bits. Headless Sparks only: a connected display stops the start. Fails closed. After @gabewillen's+# display-reserve KV for the vLLM kit (MiaAI-Lab/GLM-5.3-Flash-EXL3-2x-DGX-Sparks#234). By @ezoushen.++diff --git tensorfold/families/glm5_next/cuda/decode.py tensorfold/families/glm5_next/cuda/decode.py+index eeb54be..2e4b01e 100644+--- tensorfold/families/glm5_next/cuda/decode.py++++ tensorfold/families/glm5_next/cuda/decode.py+@@ -143,14 +143,15 @@ class Engine:+ def __init__(self, w: Weights, *, capacity: int = 2560, max_rows: int = 8, prefill_rows: int = PREFILL_ROWS,+ graphs: bool = False, graph_rows: tuple[int, ...] = (1, 2, 3, 4), long_context: bool = False,+ taps: tuple[int, ...] = (), grid: int = 0, split=None, mtp_rows: int | None = None,+- streams: int = 1, pool_rows: int | None = None, kv: str | None = None) -> None:++ streams: int = 1, pool_rows: int | None = None, kv: str | None = None, display: int = 0) -> None:+ """``kv``: the DSA caches' format (``kv8``; default TF_GLM_KV, bf16 unless set: fp8 halves the latent cache and+ the indexer's pooled keys); ``grid``: prompt chunks start on multiples of it (TF_GLM_PROMPT_GRID; 0:+ anywhere); ``split``: a ``hcsplit.SplitSettings`` (TF_GLM_HC_SPLIT, TF_GLM_PREFILL_OVERLAP) for prompt+ chunks, None or off: unsplit; ``mtp_rows``: rows of an MTP step (its absorb chunks; default ``max_rows``):+ draft chains take one row a step, so the MTP buffers need not be as wide as the verify windows; ``streams``:+ stream slots (``forward.Slots``) and ``pool_rows``: tokens of the shared cache pool (``forward.Caches``,+- default ``capacity``) for concurrent streams (``multi``). ``st`` is the state the single-stream paths run on: ``home`` (slot 0, the pool's first++ default ``capacity``) for concurrent streams (``multi``); ``display``: bytes of the GB10's display reservation++ the pool was sized with (``display_kv``, TF_GLM_DISPLAY_KV_MIB). ``st`` is the state the single-stream paths run on: ``home`` (slot 0, the pool's first+ ``capacity`` tokens), the one the CUDA graphs were captured on, unless ``use`` points it at another."""++ if grid and prefill_rows % grid:+@@ -192,7 +193,7 @@ class Engine:++ self.caches = Caches(w, pool_rows or capacity, streams=streams,+ ring=index_ring(pool_rows or capacity, max(max_rows, prefill_rows)),+- kv=kv8.kv_kind() if kv is None else kv)++ kv=kv8.kv_kind() if kv is None else kv, display=display)+ self.slots = Slots(w, streams, max_rows)+ self.home = self.st = State(w, capacity, max_rows, caches=self.caches, slots=self.slots)+ self.last_hidden: torch.Tensor | None = None+diff --git tensorfold/families/glm5_next/cuda/display_kv.py tensorfold/families/glm5_next/cuda/display_kv.py+new file mode 100644+index 0000000..8e8c621+--- /dev/null++++ tensorfold/families/glm5_next/cuda/display_kv.py+@@ -0,0 +1,270 @@++"""The cache pool's first latent planes in the GB10's UEFI display reservation (TF_GLM_DISPLAY_KV_MIB).++++The firmware sets aside a framebuffer region that nothing claims on a headless Spark and that MemAvailable never++counts. A DRM dumb buffer on /dev/dri/card0, mmap'd and registered with cuMemHostRegister(DEVICEMAP|IOMEMORY), is++memory the GPU reads like any other (on GB10 the device pointer is the host address). ``--parallel`` sizes its pool++from free memory; with this setting it is credited the reservation's bytes too, and the first latent planes (one per++DSA layer, every token's row) are carved from one span: an ordinary host mapping, then the display buffer right above++it, so the planes take exactly the credited bytes of the reservation and nothing more of the host's memory than++without it. Placement only: the planes hold the same bytes.++++``TF_GLM_DISPLAY_KV_MIB``: unset or 0 off; a multiple of 16 up to 2032 (2048 fails ENOMEM on GB10).++``TF_GLM_DISPLAY_KV_CARD``: the DRM card (default /dev/dri/card0; the container needs it as a device).++For headless Sparks only: a card with a connected output (a monitor) keeps its reservation, and the start stops.++Fails closed: the credited bytes were never budgeted against host memory, so a span that cannot be mapped stops the++start instead of falling back to ordinary memory.++"""++from __future__ import annotations++++import os++++import torch++++ENV = "TF_GLM_DISPLAY_KV_MIB"++CARD_ENV = "TF_GLM_DISPLAY_KV_CARD"++LARGEST_MIB = 2032++SYSFS = "/sys/class/drm"++++++def mib() -> int:++ """The display reservation credited to the pool, in MiB; 0 when off."""++ raw = (os.environ.get(ENV) or "").strip()++ if not raw:++ return 0++ try:++ value = int(raw)++ except ValueError:++ raise ValueError(f"{ENV}={raw!r}: a number of MiB") from None++ if value == 0:++ return 0++ if value < 0 or value % 16 or value > LARGEST_MIB:++ raise ValueError(f"{ENV}={value}: a multiple of 16 from 16 to {LARGEST_MIB} (1792 measured on GB10; 2048 "++ "fails ENOMEM)")++ return value++++++def credit() -> int:++ """The bytes the pool is credited (0 when off)."""++ return mib() << 20++++++def span_planes(count: int, plane_bytes: int, display: int) -> int:++ """How many of ``count`` latent planes of ``plane_bytes`` the span takes: the fewest that hold ``display``."""++ k = -(-int(display) // int(plane_bytes))++ if k > count:++ raise ValueError(f"{ENV}: {display >> 20} MiB is more than the {count} latent planes hold "++ f"({count * plane_bytes >> 20} MiB); lower it")++ return max(1, k)++++++def connected_outputs(sysfs: str, card: str) -> list[str]:++ """The outputs of ``card`` (e.g. card0) with a display connected, by their sysfs status."""++ import glob++++ found = []++ for path in sorted(glob.glob(os.path.join(sysfs, f"{card}-*", "status"))):++ with open(path) as f:++ if f.read().strip() == "connected":++ found.append(os.path.basename(os.path.dirname(path))[len(card) + 1:])++ return found++++++class System:++ """Every DRM and CUDA driver call the span makes, one method a call (the seam the checks replace)."""++++ CREATE_DUMB = 0xC02064B2 # DRM_IOCTL_MODE_CREATE_DUMB++ MAP_DUMB = 0xC01064B3 # DRM_IOCTL_MODE_MAP_DUMB++ GEM_CLOSE = 0x40086409 # DRM_IOCTL_GEM_CLOSE++ DEVICEMAP, IOMEMORY = 0x02, 0x04++ PITCH = 16384 # 4096 pixels at 32 bits++ MAP_FAILED = (1 << 64) - 1++++ def __init__(self) -> None:++ import ctypes++++ self.card = os.environ.get(CARD_ENV, "/dev/dri/card0")++ self.libc = ctypes.CDLL("libc.so.6", use_errno=True)++ self.libc.mmap.restype = ctypes.c_void_p++ self.libc.mmap.argtypes = [ctypes.c_void_p, ctypes.c_size_t, ctypes.c_int, ctypes.c_int, ctypes.c_int,++ ctypes.c_long]++ self.libc.munmap.argtypes = [ctypes.c_void_p, ctypes.c_size_t]++ # the _v2 entry points: the unversioned ones predate I/O-memory registration and fail on the display mapping++ self.cuda = ctypes.CDLL("libcuda.so.1")++ torch.zeros(1, device="cuda") # registration needs a context current on this thread++++ def open_card(self) -> int:++ return os.open(self.card, os.O_RDWR | os.O_CLOEXEC)++++ def create_dumb(self, fd: int, size: int) -> tuple[int, int]:++ """(GEM handle, the bytes the kernel gave)."""++ import fcntl++ import struct++++ layout = "=6IQ" # drm_mode_create_dumb: height width bpp flags handle pitch size++ out = struct.unpack(layout, fcntl.ioctl(fd, self.CREATE_DUMB,++ struct.pack(layout, -(-size // self.PITCH), 4096, 32, 0, 0, 0, 0)))++ return out[4], out[6]++++ def map_offset(self, fd: int, handle: int) -> int:++ import fcntl++ import struct++++ layout = "=2IQ" # drm_mode_map_dumb: handle pad offset++ return struct.unpack(layout, fcntl.ioctl(fd, self.MAP_DUMB, struct.pack(layout, handle, 0, 0)))[2]++++ def reserve(self, size: int) -> int:++ """A PROT_NONE placeholder for the whole span, so the halves land next to each other."""++ return self._mmap(None, size, 0, 0x02 | 0x20 | 0x4000, -1, 0)++++ def map_ordinary(self, address: int, size: int) -> None:++ self._mmap(address, size, 0x03, 0x02 | 0x20 | 0x10, -1, 0)++++ def map_display(self, address: int, size: int, fd: int, offset: int) -> None:++ self._mmap(address, size, 0x03, 0x01 | 0x10, fd, offset)++++ def register(self, address: int, size: int, *, io_memory: bool) -> None:++ import ctypes++++ flags = self.DEVICEMAP | (self.IOMEMORY if io_memory else 0)++ self._check(self.cuda.cuMemHostRegister_v2(ctypes.c_void_p(address), ctypes.c_size_t(size),++ ctypes.c_uint(flags)))++++ def device_pointer(self, address: int) -> int:++ import ctypes++++ pointer = ctypes.c_void_p()++ self._check(self.cuda.cuMemHostGetDevicePointer_v2(ctypes.byref(pointer), ctypes.c_void_p(address),++ ctypes.c_uint(0)))++ return int(pointer.value or 0)++++ def unregister(self, address: int) -> None:++ import ctypes++++ self._check(self.cuda.cuMemHostUnregister(ctypes.c_void_p(address)))++++ def unmap(self, address: int, size: int) -> None:++ import ctypes++++ if self.libc.munmap(ctypes.c_void_p(address), ctypes.c_size_t(size)) != 0:++ raise OSError(ctypes.get_errno(), "munmap")++++ def close_gem(self, fd: int, handle: int) -> None:++ import fcntl++ import struct++++ fcntl.ioctl(fd, self.GEM_CLOSE, struct.pack("=2I", handle, 0))++++ def close_fd(self, fd: int) -> None:++ os.close(fd)++++ def _mmap(self, address, size: int, prot: int, flags: int, fd: int, offset: int) -> int:++ import ctypes++++ ctypes.set_errno(0)++ result = int(self.libc.mmap(address, size, prot, flags, fd, offset) or 0)++ if result in (0, self.MAP_FAILED):++ errno = ctypes.get_errno()++ raise OSError(errno, os.strerror(errno))++ return result++++ def _check(self, result: int) -> None:++ import ctypes++++ if result:++ name = ctypes.c_char_p()++ self.cuda.cuGetErrorName(ctypes.c_int(result), ctypes.byref(name))++ raise OSError(f"CUDA driver error {result} ({(name.value or b'?').decode()})")++++++SYSTEM = System++++++class Span:++ """The mapped span as device memory (``__cuda_array_interface__``)."""++++ def __init__(self, pointer: int, size: int) -> None:++ self.pointer, self.size = int(pointer), int(size)++++ @property++ def __cuda_array_interface__(self) -> dict:++ return {"shape": (self.size,), "typestr": "|u1", "data": (self.pointer, False), "version": 3}++++++def _step(name: str, call, *args, **kwargs):++ try:++ return call(*args, **kwargs)++ except Exception as exc:++ raise RuntimeError(f"{ENV}: {name} failed: {exc}") from exc++++++def _quiet(call, *args) -> None:++ try:++ call(*args)++ except Exception:++ pass # unwinding: the first failure is the one to report++++++def map_span(ordinary: int, display: int) -> Span:++ """``ordinary`` bytes of host memory and the ``display`` bytes of the reservation right above them, both++ registered with CUDA, as one span. Unwound completely on any failure."""++ card = os.path.basename(os.environ.get(CARD_ENV, "/dev/dri/card0"))++ if busy := connected_outputs(SYSFS, card):++ raise RuntimeError(f"{ENV}: {', '.join(f'{card}-{o}' for o in busy)} has a display connected, which uses the "++ f"reservation; unset {ENV} on a Spark with a monitor")++ total = ordinary + display++ system = SYSTEM()++ fd = handle = base = None++ registered: list[int] = []++ try:++ fd = _step("open(display card)", system.open_card)++ handle, got = _step("DRM_IOCTL_MODE_CREATE_DUMB", system.create_dumb, fd, display)++ if got < display:++ raise RuntimeError(f"{ENV}: the display reserve gave {got} B, short of {display} B")++ offset = _step("DRM_IOCTL_MODE_MAP_DUMB", system.map_offset, fd, handle)++ base = _step("mmap(span)", system.reserve, total)++ if ordinary:++ _step("mmap(ordinary half)", system.map_ordinary, base, ordinary)++ _step("mmap(display half)", system.map_display, base + ordinary, display, fd, offset)++ if ordinary:++ _step("cuMemHostRegister(ordinary half)", system.register, base, ordinary, io_memory=False)++ registered.append(base)++ _step("cuMemHostRegister(display half)", system.register, base + ordinary, display, io_memory=True)++ registered.append(base + ordinary)++ pointer = _step("cuMemHostGetDevicePointer", system.device_pointer, base)++ top = _step("cuMemHostGetDevicePointer", system.device_pointer, base + ordinary)++ if top - pointer != ordinary:++ raise RuntimeError(f"{ENV}: the halves are {top - pointer} B apart on the device, not {ordinary}")++ return Span(pointer, total)++ except BaseException:++ for address in reversed(registered):++ _quiet(system.unregister, address)++ if base is not None:++ _quiet(system.unmap, base, total)++ if handle is not None:++ _quiet(system.close_gem, fd, handle)++ if fd is not None:++ _quiet(system.close_fd, fd)++ raise++++++def as_tensor(span: Span, device) -> torch.Tensor:++ return torch.as_tensor(span, device=device)++++++_OWNERS: list[Span] = [] # the span lives as long as the process: the pool never gives it back++++++def latent_planes(count: int, rows: int, width: int, kind: str, device, display: int) -> list[torch.Tensor]:++ """The first of ``count`` latent planes (``kv8.zeros(rows, width, kind)`` each) as views of one span whose top++ ``display`` bytes are the display reservation: as many planes as hold it. Once a process."""++ from . import kv8++++ if _OWNERS:++ raise RuntimeError(f"{ENV}: the display reservation already holds a cache pool in this process")++ like = kv8.zeros(rows, width, kind, "meta")++ plane_bytes = like.numel() * like.element_size()++ k = span_planes(count, plane_bytes, display)++ span = map_span(k * plane_bytes - display, display)++ _OWNERS.append(span)++ flat = as_tensor(span, device)++ return [flat[i * plane_bytes:(i + 1) * plane_bytes].view(like.dtype).view(like.shape).zero_() for i in range(k)]+diff --git tensorfold/families/glm5_next/cuda/engine.py tensorfold/families/glm5_next/cuda/engine.py+index be14353..4de2fb1 100644+--- tensorfold/families/glm5_next/cuda/engine.py++++ tensorfold/families/glm5_next/cuda/engine.py+@@ -690,9 +690,11 @@ class GlmEngine:+ # TF_GLM_CACHE_GIB gives kept prompts (their rows in the pool, their KDA states and DFlash2 windows beside it),+ # whole 2,048-token extents; each stream holds up to the window (pool.py, multi.py)+ pool_rows = None++ display = 0+ if parallel > 1:+ from tensorfold.cuda.capacity import config as read_config+++ from . import display_kv+ from .pool import ALIGN++ text = read_config(model_dir)+@@ -700,7 +702,10 @@ class GlmEngine:+ per_token = max(1, -(-(g.bytes_at(capacity + 65536) - g.bytes_at(capacity)) // 65536))+ states = int(os.environ.get("TF_GLM_CACHE_ENTRIES", "8")) * (slot_bytes(text, world, rows=0, rank=rank) // 2 ++ (22 << 20))+- pool_rows = (capacity + max(0, self.cache_bytes - states) // per_token) // ALIGN * ALIGN++ # TF_GLM_DISPLAY_KV_MIB: the display reservation's bytes too, which free memory never counted++ display = display_kv.credit()++ pool_rows = (capacity + max(0, self.cache_bytes + display - states) // per_token) // ALIGN * ALIGN++ display_rows = pool_rows - (capacity + max(0, self.cache_bytes - states) // per_token) // ALIGN * ALIGN+ if pool_rows < ALIGN:+ raise ValueError(f"--parallel {parallel}: a pool of {pool_rows} tokens is less than one {ALIGN}-token "+ f"extent; free memory or lower --context")+@@ -744,7 +749,12 @@ class GlmEngine:+ self.e = Engine(w, capacity=pool_rows or capacity, max_rows=MAX_ROWS, prefill_rows=prefill_rows, graphs=graphs,+ graph_rows=GRAPH_ROWS + WIDE_GRAPHS, long_context=long_context,+ taps=self.drafter.tap_layers if self.drafter is not None else (), grid=self.grid,+- split=self.split, mtp_rows=MTP_ROWS, streams=parallel, pool_rows=pool_rows, kv=kv)++ split=self.split, mtp_rows=MTP_ROWS, streams=parallel, pool_rows=pool_rows, kv=kv,++ display=display)++ if display and rank == 0:++ print(f"[tensorfold] {display >> 20} MiB of the pool in the GPU's display reservation "++ f"(TF_GLM_DISPLAY_KV_MIB), which free memory does not count: +{display_rows} tokens, "++ f"{sum(p.spanned for p in self.e.caches.arena.planes)} latent planes in its span", flush=True)+ if self.e.pbuf.split is not None:+ self.e.pbuf.split.warm() # both ranks: open the send/receive connection now+ if rank == 0:+diff --git tensorfold/families/glm5_next/cuda/forward.py tensorfold/families/glm5_next/cuda/forward.py+index 4d6499e..e2cad87 100644+--- tensorfold/families/glm5_next/cuda/forward.py++++ tensorfold/families/glm5_next/cuda/forward.py+@@ -183,10 +183,13 @@ class Caches:+ pools still filling (``decode.Snapshot.tail``). None: arena planes (token t at its extent's row).++ ``kv``: the latent planes' and pooled keys' format (TF_GLM_KV, ``kv8``): bf16, or fp8 (a uint8 row a token /+- pool: e4m3 codes, an fp32 power-of-two scale, pad), with the latent cache only."""++ pool: e4m3 codes, an fp32 power-of-two scale, pad), with the latent cache only.++++ ``display``: bytes of the GB10's display reservation the pool was sized with (``display_kv``); the first DSA++ layers' latent planes are then carved from one span that holds them."""++ def __init__(self, w: Weights, rows: int, *, streams: int = 1, ring: int | None = None,+- kv: str = "bf16") -> None:++ kv: str = "bf16", display: int = 0) -> None:+ from .pool import Arena, Plane++ c = w.cfg+@@ -198,17 +201,24 @@ class Caches:+ raise ValueError(f"TF_GLM_KV={kv}: bf16, or fp8 with the latent cache (TF_GLM_LATENT=1)")+ self.kv = kv+ planes: list[Plane] = []++ spanned: list[torch.Tensor] = []++ 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)++- def add(shape, div: int = 1, pad: int = 0, fmt: str = "bf16") -> int:++ def add(shape, div: int = 1, pad: int = 0, fmt: str = "bf16", tensor=None) -> int:+ n = rows // div + pad+- t = (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))++ 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))+ 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), None++ return add((c.kv_lora,), fmt=kv, tensor=spanned.pop(0) if spanned else None), None+ return add((HL, c.qk_dim)), add((HL, c.v_dim))++ self.kc, self.vc = [], []+diff --git tensorfold/families/glm5_next/cuda/pool.py tensorfold/families/glm5_next/cuda/pool.py+index 1313652..2f39307 100644+--- tensorfold/families/glm5_next/cuda/pool.py++++ tensorfold/families/glm5_next/cuda/pool.py+@@ -30,10 +30,11 @@ def align_up(n: int, align: int = ALIGN) -> int:++ class Plane:+ """One cache tensor over the arena's rows: row r of token t at t // div (``div`` tokens a row), ``pad`` rows+- past the last token's."""++ 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) -> None:+- self.tensor, self.div, self.pad = tensor, int(div), int(pad)++ def __init__(self, tensor, div: int = 1, pad: int = 0, spanned: bool = False) -> None:++ self.tensor, self.div, self.pad, self.spanned = tensor, int(div), int(pad), bool(spanned)++ def rows_for(self, tokens: int) -> int:+ return tokens // self.div+@@ -79,21 +80,29 @@ class Arena:+ 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)++ _move(p.tensor, a, b, m, p.spanned)+++-def _move(t, a: int, b: int, m: int) -> None:+- """t[b:b + m] = t[a:a + m] (rows), safe when they overlap."""++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."""++++ def put(dst, src):++ 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)++ gap = abs(a - b)+ if gap >= m:+- t[b:b + m].copy_(t[a:a + m])++ put(t[b:b + m], t[a:a + m])+ 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)+- t[b + s:b + s + k].copy_(t[a + s:a + s + k])++ put(t[b + s:b + s + k], t[a + s:a + s + k])+++ @dataclass(eq=False)diff --git a/scripts/config.sh b/scripts/config.shindex 98f977e..b73283d 100644--- a/scripts/config.sh+++ b/scripts/config.sh@@ -139,6 +139,12 @@ export TF_GLM_COMM="$COMM"# TensorFold's is 256) also takes the 17-32-row verify windows of concurrent requests: code at 4 streams +1.4%, prose# +0.5-1% (two boots each). Same bits.export TF_ROCE_MAX_KB="${TF_ROCE_MAX_KB:-512}"+# How long a RoCE all-gather waits for the other Spark before it fails, in seconds (patch 0052 reads it; 1 to 3600):+# 300 here (the patch's own default is 20). Issue #54: on long prompts (~475k-500k tokens, or after many hours) a rank+# failed after its 20 s while its own writes had all completed, i.e. the peer was late, not lost, and both Sparks went+# down. A late peer now costs a slow round instead; a rank that is really gone is noticed after 300 s instead of 20,+# like the watchdog's stall report (TF_GLM_MULTI_WATCHDOG_S, 300). NCCL's own gathers have no limit at all.+export TF_ROCE_WAIT_S="${TF_ROCE_WAIT_S:-300}"# Prompt-lookup ("copy") drafts (patch 0007): when the reply's last 8 tokens occurred before, the tokens that followed# them are verified ahead of DFlash2's; quote / edit replies +5% (80.3 -> 84.4 tok/s), prose and code unchanged. Exact.COPY="${COPY:-1}"@@ -247,6 +253,14 @@ export TENSORFOLD_MEMORY_RESERVE_GIB="$MEMORY_RESERVE_GIB"case "$TP" in 3) _pool=32 ;; *) _pool=12.5 ;; esacKV_POOL_GIB="${KV_POOL_GIB:-$_pool}"export TF_GLM_CACHE_GIB="$KV_POOL_GIB"+# The display reservation in the pool (patch 0072, PARALLEL above 1): the GB10 firmware keeps ~2 GiB for a screen that+# a headless Spark never uses and MemAvailable never counts. DISPLAY_KV_MIB of it (a multiple of 16, at most 2032;+# 2048 failed ENOMEM in the vLLM kit's #234; 1792 measured here) joins the shared pool on every rank, on top of+# KV_POOL_GIB, without taking host memory: 1792 adds ~277k tokens at PARALLEL=8 (276,480-278,528 with the pool's size).+# Same replies, decode and prefill. Headless Sparks only: start.sh and each rank refuse it while a display is connected+# to card0. Needs /dev/dri/card0 in the containers (nvidia_drm with modeset=1; --gpus all passes it). 0 (default): off.+DISPLAY_KV_MIB="${DISPLAY_KV_MIB:-0}"+export TF_GLM_DISPLAY_KV_MIB="$DISPLAY_KV_MIB"export TENSORFOLD_NO_UPDATE_CHECK="${TENSORFOLD_NO_UPDATE_CHECK:-1}"diff --git a/start.sh b/start.shindex dbe2bf2..c2dfe00 100755--- a/start.sh+++ b/start.sh@@ -65,6 +65,14 @@ check_workers[[ "$MAX_TOKENS" =~ ^[1-9][0-9]*$ ]] || die "MAX_TOKENS is a token count, not $MAX_TOKENS"[[ "$DRAFTER" == dflash2 || "$PARALLEL" == 1 ]] || die "PARALLEL=$PARALLEL needs DRAFTER=dflash2 (mtp serves one request at a time: PARALLEL=1)"for v in SPLIT SHARED_PREFIX KDA_CHUNKED COPY_CODE MULTI_PREFILL STREAM_SMOOTH; do [[ "${!v}" =~ ^[01]$ ]] || die "$v is 0 or 1, not ${!v}"; done+[[ "$DISPLAY_KV_MIB" =~ ^(0|[1-9][0-9]{0,3})$ ]] && (( DISPLAY_KV_MIB % 16 == 0 && DISPLAY_KV_MIB <= 2032 )) ||+ die "DISPLAY_KV_MIB is a multiple of 16 from 0 to 2032, not $DISPLAY_KV_MIB"+(( DISPLAY_KV_MIB == 0 || PARALLEL > 1 )) || die "DISPLAY_KV_MIB adds to the shared pool, which needs PARALLEL above 1"+(( DISPLAY_KV_MIB == 0 )) || [[ -e /dev/dri/card0 ]] || die "DISPLAY_KV_MIB needs /dev/dri/card0, which this Spark lacks"+if (( DISPLAY_KV_MIB )); then # headless only: a monitor's framebuffer lives in the reservation+ _shown=$(grep -lx connected /sys/class/drm/card0-*/status 2>/dev/null | sed 's|.*/\(card0-[^/]*\)/status|\1|' | paste -sd, -)+ [[ -z "$_shown" ]] || die "DISPLAY_KV_MIB is for headless Sparks, and $_shown has a display connected; set it to 0"+fi[[ "$WORKER_WEIGHTS" == copy || "$WORKER_WEIGHTS" == nfs ]] || die "WORKER_WEIGHTS is copy or nfs, not $WORKER_WEIGHTS"DRY=0; [[ "${DRY_RUN:-0}" == 1 ]] && DRY=1[[ "$KV_POOL_GIB" =~ ^[0-9]+([.][0-9]+)?$ ]] || die "KV_POOL_GIB is a number of GiB, not $KV_POOL_GIB"@@ -278,9 +286,13 @@ fi# docker commands run over ssh, where this shell's environment does not reach. None of them is a secret. At TP>2,# TF_ROCE_HCA names a node's own devices, so each rank gets its own (scripts/nodes.sh, rank_nccl_env); at TP=2 it# passes as set, as in v1.4 (unset: the ranks take NCCL_IB_HCA's devices).-ENV_ARGS=(-e HF_HUB_OFFLINE="${HF_HUB_OFFLINE:-1}")-_skip='^$'; (( TP == 2 )) || _skip='^TF_ROCE_HCA='-while IFS='=' read -r name _; do ENV_ARGS+=(-e "$name=${!name}"); done < <(env | grep -E '^(TENSORFOLD|TF_GLM|TF_ROCE)_[A-Z0-9_]+=' | grep -v "$_skip" || true)+env_args() {+ local _skip='^$' name+ ENV_ARGS=(-e HF_HUB_OFFLINE="${HF_HUB_OFFLINE:-1}")+ (( TP == 2 )) || _skip='^TF_ROCE_HCA='+ while IFS='=' read -r name _; do ENV_ARGS+=(-e "$name=${!name}"); done < <(env | grep -E '^(TENSORFOLD|TF_GLM|TF_ROCE)_[A-Z0-9_]+=' | grep -v "$_skip" || true)+}+env_argsRUN_ARGS=(--gpus all --ipc=host --network host --shm-size 16g --device /dev/infiniband --cap-add IPC_LOCK--ulimit memlock=-1 --ulimit stack=67108864)@@ -369,7 +381,19 @@ fail() {donedie "$1"}-for attempt in 1 2; do+# Issue #36: on some pairs a rank's first NCCL connection fails with SPLIT=1, seconds into the start and before any+# weights load (NCCL error 2, ibv_reg_mr: Cannot allocate memory), about half the time; a start that comes up stays up.+# Such a start is tried once more as it was, then with SPLIT=0 (prompt chunks unsplit: the same replies, long prompts+# fill slower), and says so.+split_nccl_failed() {+ local i+ [[ "$SPLIT" == 1 ]] || return 1+ { docker logs "$CONTAINER_NAME" 2>&1 || true+ for i in $(worker_ids); do worker "$i" docker logs "$CONTAINER_NAME" 2>&1 || true; done+ } | grep 'NCCL error 2: unhandled system error' >/dev/null # not -q: an early exit fails the pipe (pipefail)+}+split_tries=0; refitted=0+for attempt in 1 2 3 4; doif (( TP == 2 )); then step 3 "Launch: container $CONTAINER_NAME, rank 1 on $WORKER, then rank 0 here"else step 3 "Launch: container $CONTAINER_NAME, ranks $((TP - 1)) to 1 on the workers, then rank 0 here"; filaunch@@ -381,20 +405,23 @@ for attempt in 1 2; do# docker logs is the background job, so killing it ends the whole pipeline (no orphaned `docker logs -f`)docker logs -f "$CONTAINER_NAME" > >(grep --line-buffered -v -E "$NOISE" | sed -u "s/^/ ${D}│${R} /") 2>&1 &LOGS_PID=$!- start=$SECONDS; next_beat=15; refit=""+ start=$SECONDS; next_beat=15; refit=""; retry=""until curl -sf --max-time 5 "$URL/v1/models" >/dev/null 2>&1; doif ! running_here; then# the memory at this start holds a smaller window than asked: once, take the largest one TensorFold namesrefit=$(docker logs "$CONTAINER_NAME" 2>&1 | sed -n 's/.*largest fitting prompt-plus-reply window: \([0-9]*\) tokens.*/\1/p' | tail -1)- [[ -n "$refit" && $attempt == 1 ]] && break+ [[ -n "$refit" && $refitted == 0 ]] && break+ refit=""+ (( split_tries < 2 )) && split_nccl_failed && { retry=split; break; }fail "rank 0 exited (code $(docker inspect -f '{{.State.ExitCode}}' "$CONTAINER_NAME")) before it was ready"fi(( SECONDS - start < WAIT_TIMEOUT )) ||fail "not ready after ${WAIT_TIMEOUT}s (WAIT_TIMEOUT); the ranks are still running: docker logs -f $CONTAINER_NAME"if (( SECONDS - start >= next_beat )); thenfor i in $(worker_ids); do- running_worker "$i" ||- fail "rank $i on $(worker_host "$i") exited (code $(worker "$i" docker inspect -f '{{.State.ExitCode}}' "$CONTAINER_NAME" 2>/dev/null || echo "?")) before the server was ready"+ running_worker "$i" && continue+ (( split_tries < 2 )) && split_nccl_failed && { retry=split; break 2; }+ fail "rank $i on $(worker_host "$i") exited (code $(worker "$i" docker inspect -f '{{.State.ExitCode}}' "$CONTAINER_NAME" 2>/dev/null || echo "?")) before the server was ready"doneestimate=$(docker logs "$CONTAINER_NAME" 2>&1 | sed -n 's/.*startup estimate \([0-9.]*\) GiB.*/\1/p' | tail -1)there=""@@ -410,7 +437,21 @@ for attempt in 1 2; dodonekill $LOGS_PID 2>/dev/null || truesleep 0.3+ if [[ "$retry" == split ]]; then+ split_tries=$((split_tries + 1))+ if (( split_tries == 1 )); then+ warn "a rank's first NCCL connection failed with SPLIT=1 (NCCL error 2, issue #36): starting again as it was"+ else+ warn "it failed again: starting with SPLIT=0 (prompt chunks unsplit: the same replies, long prompts fill slower); SPLIT=0 in .env skips these tries (issue #36)"+ SPLIT=0+ export TF_GLM_HC_SPLIT=0 TF_GLM_PREFILL_OVERLAP=0+ env_args+ fi+ ./stop.sh >/dev/null+ continue+ fi[[ -z "$refit" ]] && break+ refitted=1warn "this start's memory budget holds a ${refit}-token window, not $(arg_value --context): starting again with --context $refit"CONTEXT=$refitSERVE_ARGS+=(--context "$refit")diff --git a/tools/display_kv_check.py b/tools/display_kv_check.pynew file mode 100755index 0000000..e9f505c--- /dev/null+++ b/tools/display_kv_check.py@@ -0,0 +1,297 @@+#!/usr/bin/env python3+"""Checks for patch 0072 (DISPLAY_KV_MIB), run inside the image that scripts/prepare.sh built:++ docker run --rm --gpus all --entrypoint python -v "$PWD/tools/display_kv_check.py:/c.py" tensorfold-glm53:v0.6.0 \+ /c.py [--gpu]++Without --gpu: the setting, the refusal while a display is connected, how many latent planes the span takes, the span's mapping and unwinding (a fake for every+DRM and CUDA driver call), the planes carved from a span, and the pool's row copies of spanned planes against stock+ones. With --gpu, on a Spark whose display reservation is free (the server stopped, or started with DISPLAY_KV_MIB=0):+the real span, written and read back by the GPU across both halves, and a pool copy across the boundary. Exit code 1+when a check fails.+"""+import os+import sys++import torch++from tensorfold.families.glm5_next.cuda import display_kv as dk+from tensorfold.families.glm5_next.cuda import kv8++MIB = 2 ** 20+failures = []+++def check(name, cond, detail=""):+ print(("ok " if cond else "FAIL ") + name + (f": {detail}" if detail and not cond else ""))+ if not cond:+ failures.append(name)+++def raises(call, *args, match=""):+ try:+ call(*args)+ except (ValueError, RuntimeError) as exc:+ return match in str(exc)+ return False+++# -- the setting --------------------------------------------------------------------------------------------------------+def setting(value):+ if value is None:+ os.environ.pop(dk.ENV, None)+ else:+ os.environ[dk.ENV] = value+ return dk.mib()+++check("unset is off", setting(None) == 0)+check("0 is off", setting("0") == 0)+check("1792 MiB", setting("1792") == 1792)+check("credit in bytes", dk.credit() == 1792 * MIB)+check("2032 is the largest", setting("2032") == 2032)+for bad in ("2048", "17", "-16", "abc"):+ check(f"{bad} refused", raises(setting, bad, match=dk.ENV))+setting(None)+check("no credit when off", dk.credit() == 0)++# -- how many latent planes the span takes ------------------------------------------------------------------------------+check("two planes cover 1792 MiB of 1 GB planes", dk.span_planes(17, 10 ** 9, 1792 * MIB) == 2)+check("one plane when it is larger", dk.span_planes(17, 2 * 10 ** 9, 1792 * MIB) == 1)+check("exact fit", dk.span_planes(4, 1792 * MIB // 2, 1792 * MIB) == 2)+check("too few planes refused", raises(dk.span_planes, 1, 10 ** 9, 1792 * MIB, match="latent planes"))+++# -- mapping the span: every driver call through the seam, unwound on failure ---------------------------------------+class FakeSystem:+ fail = None # (call, nth): the nth call of that name raises+ dumb_bytes = None # None: what was asked+ delta = None # None: the right one+ last = None++ def __init__(self):+ self.calls = []+ FakeSystem.last = self++ def _do(self, name, *args):+ self.calls.append((name, *args))+ if FakeSystem.fail and FakeSystem.fail == (name, sum(c[0] == name for c in self.calls)):+ raise OSError(f"{name} failed on purpose")++ def open_card(self):+ self._do("open_card")+ return 7++ def create_dumb(self, fd, size):+ self._do("create_dumb", size)+ return 3, size if FakeSystem.dumb_bytes is None else FakeSystem.dumb_bytes++ def map_offset(self, fd, handle):+ self._do("map_offset")+ return 1 << 40++ def reserve(self, size):+ self._do("reserve", size)+ return 1 << 44++ def map_ordinary(self, address, size):+ self._do("map_ordinary", address, size)++ def map_display(self, address, size, fd, offset):+ self._do("map_display", address, size)++ def register(self, address, size, *, io_memory):+ self._do("register", address, size, io_memory)++ def device_pointer(self, address):+ self._do("device_pointer", address)+ if FakeSystem.delta is not None and address != 1 << 44:+ return (1 << 44) + FakeSystem.delta+ return address++ def unregister(self, address):+ self._do("unregister", address)++ def unmap(self, address, size):+ self._do("unmap", address, size)++ def close_gem(self, fd, handle):+ self._do("close_gem")++ def close_fd(self, fd):+ self._do("close_fd")+++def names(system):+ return [c[0] for c in system.calls]+++def fake_sysfs(states):+ import tempfile++ root = tempfile.mkdtemp()+ for name, state in states.items():+ os.makedirs(f"{root}/{name}")+ with open(f"{root}/{name}/status", "w") as f:+ f.write(state + "\n")+ return root+++# -- a connected display keeps its reservation ------------------------------------------------------------------------+check("headless: no output of card0 connected",+ dk.connected_outputs(fake_sysfs({"card0-HDMI-A-1": "disconnected", "card0-Unknown-1": "disconnected",+ "card1-DP-1": "connected"}), "card0") == [])+check("a connected output is named",+ dk.connected_outputs(fake_sysfs({"card0-HDMI-A-1": "connected", "card0-DP-1": "disconnected"}), "card0")+ == ["HDMI-A-1"])+dk.SYSTEM = FakeSystem+D, O = 1792 * MIB, 256 * MIB+FakeSystem.last = None+dk.SYSFS = fake_sysfs({"card0-DP-2": "connected"})+check("a connected display refuses the span before any driver call",+ raises(dk.map_span, O, D, match="card0-DP-2") and FakeSystem.last is None)+dk.SYSFS = fake_sysfs({"card0-DP-2": "disconnected"})+span = dk.map_span(O, D)+check("span covers both halves", (span.pointer, span.size) == (1 << 44, O + D))+check("display half sits right above the ordinary half",+ ("map_display", (1 << 44) + O, D) in FakeSystem.last.calls)+check("both halves registered, the display half as I/O memory",+ ("register", 1 << 44, O, False) in FakeSystem.last.calls and+ ("register", (1 << 44) + O, D, True) in FakeSystem.last.calls)+span = dk.map_span(0, D)+check("no ordinary half when the planes are the display reservation exactly",+ "map_ordinary" not in names(FakeSystem.last) and span.size == D)++for step, nth in (("open_card", 1), ("create_dumb", 1), ("map_offset", 1), ("reserve", 1), ("map_ordinary", 1),+ ("map_display", 1), ("register", 1), ("register", 2), ("device_pointer", 1), ("device_pointer", 2)):+ FakeSystem.fail = (step, nth)+ ok = raises(dk.map_span, O, D)+ s = FakeSystem.last+ succeeded = lambda name: name in names(s) and name != step # noqa: E731+ registered = [c[1] for c in s.calls if c[0] == "register"][:-1 if step == "register" else None]+ unwound = (all(("unregister", a) in s.calls for a in registered) and+ len(registered) == sum(c[0] == "unregister" for c in s.calls) and+ (("unmap", 1 << 44, O + D) in s.calls) == succeeded("reserve") and+ ("close_gem" in names(s)) == succeeded("create_dumb") and+ ("close_fd" in names(s)) == succeeded("open_card"))+ check(f"{step} #{nth} failing raises and unwinds", ok and unwound, str(s.calls))+FakeSystem.fail = None+FakeSystem.dumb_bytes = D - 4096+check("a short display reserve is refused", raises(dk.map_span, O, D, match="display reserve gave"))+FakeSystem.dumb_bytes = None+FakeSystem.delta = O + 4096+check("halves apart on the device are refused", raises(dk.map_span, O, D, match="apart"))+check("and unwound", ("unmap", 1 << 44, O + D) in FakeSystem.last.calls and "close_fd" in names(FakeSystem.last))+FakeSystem.delta = None++# -- latent planes carved from one span --------------------------------------------------------------------------------+dk.map_span = lambda ordinary, display: dk.Span(0, ordinary + display) # noqa: E731+dk.as_tensor = lambda span, device: torch.full((span.size,), 7, dtype=torch.uint8) # noqa: E731+rows, width = 1 << 20, 512+want = kv8.zeros(rows, width, "fp8", "meta")+plane_bytes = want.numel() * want.element_size()+display = 1792 * MIB+planes = dk.latent_planes(17, rows, width, "fp8", "cpu", display)+k = len(planes)+check("as many planes as the display reservation needs", k == dk.span_planes(17, plane_bytes, display), str(k))+check("each plane is the stock plane's shape and type",+ all(p.shape == want.shape and p.dtype == want.dtype for p in planes))+check("each plane zeroed", all(int(p.count_nonzero()) == 0 for p in planes))+base = planes[0].data_ptr()+check("planes back to back in one buffer",+ all(p.data_ptr() == base + i * plane_bytes for i, p in enumerate(planes)))+check("a second claim is refused", raises(dk.latent_planes, 17, rows, width, "fp8", "cpu", display, match="already"))+dk._OWNERS.clear()+wb = kv8.zeros(rows, width, "bf16", "meta")+planes = dk.latent_planes(17, rows, width, "bf16", "cpu", display)+check("bf16 planes too", all(p.shape == wb.shape and p.dtype == wb.dtype for p in planes))+dk._OWNERS.clear()++# -- copies between pool rows of spanned planes ---------------------------------------------------------------------+# CUDA refuses a memcpy whose range crosses from one registration into the other (the ordinary half into the display+# half), so a spanned plane's rows move by a kernel; every other plane copies as before. Same rows either way.+from tensorfold.families.glm5_next.cuda.pool import Arena, Plane # noqa: E402++gen = torch.Generator().manual_seed(0)+for dtype, shape in ((torch.uint8, (64, 528)), (torch.bfloat16, (64, 512))):+ for src, dst, n in ((0, 32, 16), (4, 10, 30), (30, 2, 25), (0, 0, 8), (60, 1, 4)):+ base = torch.randint(0, 255, shape, generator=gen, dtype=torch.uint8) if dtype == torch.uint8 else \+ torch.randn(shape, generator=gen).to(dtype)+ pooled = torch.randint(0, 255, (64 // 4 + 2, 144), generator=gen, dtype=torch.uint8)+ stock = Arena(64, [Plane(base.clone()), Plane(pooled.clone(), 4, 2)])+ spanned = Arena(64, [Plane(base.clone(), spanned=True), Plane(pooled.clone(), 4, 2, spanned=True)])+ kernel = torch.bitwise_or+ calls = []+ torch.bitwise_or = lambda *a, **k: calls.append(1) or kernel(*a, **k) # noqa: E731+ try:+ stock.copy(src, dst, n)+ stock_calls = len(calls)+ spanned.copy(src, dst, n)+ finally:+ torch.bitwise_or = kernel+ same = all(torch.equal(a.tensor, b.tensor) for a, b in zip(stock.planes, spanned.planes))+ by_kernel = stock_calls == 0 and (len(calls) > 0) == (n > 0 and src != dst)+ check(f"spanned rows copy as stock, by a kernel: {dtype} {src}->{dst} x{n}", same and by_kernel,+ f"stock kernel calls {stock_calls}, spanned {len(calls) - stock_calls}")++# -- the real span on this node ---------------------------------------------------------------------------------------+if "--gpu" in sys.argv:+ import importlib++ importlib.reload(dk)+ os.environ[dk.ENV] = "1792"+ rows = 1 << 18 # small planes, so the span takes many and a live server keeps its headroom+ planes = dk.latent_planes(17, rows, 512, "fp8", "cuda", dk.credit())+ k = len(planes)+ flat = [p.view(-1) for p in planes]+ total = k * flat[0].numel()++ def pattern(i, n):+ return (torch.arange(n, device="cuda", dtype=torch.int32) + 7 * i).remainder_(251).to(torch.uint8)++ for i, f in enumerate(flat): # by a kernel, as the server writes them (a memcpy may not cross the halves)+ torch.bitwise_or(pattern(i, f.numel()), 0, out=f)+ torch.cuda.synchronize()+ same = all(torch.equal(f, pattern(i, f.numel())) for i, f in enumerate(flat))+ check(f"GPU writes read back across {k} planes ({total / MIB:.0f} MiB, top {dk.credit() // MIB} MiB display)", same)+ top = flat[-1][-MIB:].cpu()+ check("the display half's last MiB as written, read by the CPU", torch.equal(top, pattern(k - 1, flat[-1].numel())[-MIB:].cpu()))+ # a pool copy whose rows cross from the ordinary half into the display half (the plane holding the boundary)+ ordinary = total - dk.credit()+ j = ordinary // flat[0].numel()+ row_bytes = planes[j].shape[1]+ edge = (ordinary - j * flat[0].numel()) // row_bytes # the row the display half starts in (or within)+ arena = Arena(rows, [Plane(planes[j], spanned=True)])+ before = torch.bitwise_or(planes[j], 0) # a copy by a kernel (clone() is a memcpy)+ arena.copy(edge - 300, edge + 1000, 600) # source across the boundary, destination above it+ arena.copy(edge + 2000, edge - 500, 700) # destination across it+ expect = before.clone()+ expect[edge + 1000:edge + 1600] = before[edge - 300:edge + 300]+ expect[edge - 500:edge + 200] = expect[edge + 2000:edge + 2700].clone()+ torch.cuda.synchronize()+ check(f"pool copies across the halves (plane {j}, boundary at row {edge})", torch.equal(planes[j], expect))+ try:+ planes[j][edge + 1000:edge + 1600].copy_(planes[j][edge - 300:edge + 300])+ torch.cuda.synchronize()+ print(" note: this driver now allows a memcpy across the halves")+ except Exception as exc:+ print(f" a memcpy across the halves still fails ({str(exc).splitlines()[0][:50]}), as the kernel copy avoids")+ # bandwidth: a copy out of the display half against one out of ordinary device memory+ n = flat[-1].numel()+ src = flat[-1]+ dst = torch.empty(n, dtype=torch.uint8, device="cuda")+ ref = torch.empty(n, dtype=torch.uint8, device="cuda")+ for name, a, b in (("display -> device", src, dst), ("device -> device", ref, dst)):+ for _ in range(3):+ b.copy_(a)+ torch.cuda.synchronize()+ e0, e1 = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)+ e0.record()+ for _ in range(10):+ b.copy_(a)+ e1.record()+ torch.cuda.synchronize()+ print(f" {name}: {10 * n / (e0.elapsed_time(e1) / 1000) / 2 ** 30:.1f} GiB/s")++print(f"{len(failures)} failed" if failures else "all passed")+sys.exit(1 if failures else 0)diff --git a/tools/prompt_reuse.py b/tools/prompt_reuse.pynew file mode 100755index 0000000..ab9b09e--- /dev/null+++ b/tools/prompt_reuse.py@@ -0,0 +1,56 @@+#!/usr/bin/env python3+"""An agent's conversation keeps its prompt state while other conversations with the same system prompt run (a coding+agent and its sub-agents, or several chats on one system prompt): each of its next turns must resume from its kept+state, not re-read its history.++Usage: tools/prompt_reuse.py [size] (API_URL / PORT as in client.py). The conversation's history is ~0.82 x size+tokens (default 40000). Exit code 1 when a turn resumes less than 90% of its prompt. Needs a server started with+`PARALLEL` above 1.++Each round: one request of another conversation with the same system prompt, then the agent's next turn.+"""+import json+import os+import sys+import time+import urllib.request++sys.dont_write_bytecode = True # no tools/__pycache__ from importing client+from client import URL, open_url, prose # noqa: E402++MODEL = os.environ.get("MODEL", "GLM-5.3-Flash-EXL3")+SYSTEM = {"role": "system", "content": "You are a careful coding agent. Read the material, then answer briefly. "+ + prose(2000, 1)}+++def chat(messages: list) -> tuple[dict, int, int, float]:+ body = {"model": MODEL, "messages": messages, "max_tokens": 64, "temperature": 0, "reasoning_effort": "low"}+ req = urllib.request.Request(URL, json.dumps(body).encode(), {"Content-Type": "application/json"})+ t0 = time.time()+ reply = json.load(open_url(req, 1800))+ usage = reply["usage"]+ cached = (usage.get("prompt_tokens_details") or {}).get("cached_tokens") or 0+ return reply["choices"][0]["message"], usage["prompt_tokens"], cached, time.time() - t0+++def main() -> None:+ size = int(sys.argv[1]) if len(sys.argv) > 1 else 40000+ agent = [SYSTEM, {"role": "user", "content": "Summarize this log in one line.\n" + prose(size, 2)}]+ msg, prompt, cached, secs = chat(agent)+ print(f"agent turn 0: {prompt} prompt tokens, {cached} cached, {secs:.1f} s (cold)")+ worst = 1.0+ for turn in (1, 2, 3):+ chat([SYSTEM, {"role": "user", "content": f"Sub-task {turn}: name three uses of a hash map."}])+ agent += [{"role": "assistant", "content": msg.get("content") or ""},+ {"role": "user", "content": f"Note {turn}: " + prose(200, 10 + turn)}]+ msg, prompt, cached, secs = chat(agent)+ worst = min(worst, cached / prompt)+ print(f"agent turn {turn} (after another conversation): {prompt} prompt tokens, {cached} cached "+ f"({cached / prompt:.0%}), {secs:.1f} s")+ ok = worst >= 0.9+ print("prompt_reuse:", "OK" if ok else f"FAILED: a turn resumed only {worst:.0%} of its prompt")+ sys.exit(0 if ok else 1)+++if __name__ == "__main__":+ main()