GLM-5.3-Flash EXL3 on 2x DGX Spark with TensorFold
Python
v1.4: smooth concurrent streaming, three Sparks (experimental), our own checkpoint by default, agent and setup fixes
MiaAI-Labd89ffd0b9e53
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e55214b..f17a885 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -3,6 +3,157 @@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.4 (unreleased): image prompts resume, tool calls never dropped, pictures in tool results, earlier reasoning kept, smooth concurrent streaming, 3 Sparks (experimental)++Image: `v0.6.0-5e01f1bb74d8` (`sha256:14f15591eae5d6a540f09218d3852068962fe5381371bbfefe0e9194cd834529`), 68 patches, for two and three Sparks.++### Changed+- **Earlier turns' reasoning stays in the prompt** (#23, patch `0060-glm-keep-thinking`, by @kky42), as in zai-org's+ current template. The checkpoint's template dropped it at each new user message, so agents prefilled the previous+ turn's tool loop again (a replayed agent session: 85,127 -> 16,106 tokens). `TF_GLM_CLEAR_THINKING=1`, or a+ request's `chat_template_kwargs.clear_thinking: true`, restores the old rendering. Prompts without earlier-turn+ reasoning render as before.+- **`chat_template_kwargs.thinking`** (#25, patch `0057-server-thinking-alias`, from @Alexbob0's PR) is read as+ `enable_thinking` when that is absent: `true` / `false`, or `{"type": "enabled" | "disabled"}`. DeepSeek-V4 clients+ such as pi send it; it was ignored. Other values (`{"type": "adaptive"}`, a string) leave the server's default, as+ before, and are logged once; they are never refused.++### Added+- **Smooth streaming with several requests at once** (patches `0062-glm-sliced-fill` and `0061-server-smooth-stream`;+ `FILL_BUDGET_MS=200`, `FILL_DRAFTS=1`, `STREAM_SMOOTH=1`, all on by default). Concurrent replies arrived in bursts and+ froze while another request's prompt filled: each 1,024-row prompt chunk (~0.65 s) stopped every other reply.+ Now a new prompt's chunks run a few layers at a time (about `FILL_BUDGET_MS` each) with a drafted decode round between+ slices, and a streamed reply's tokens go out one event each at a steady pace from a 400 ms playout buffer+ (`STREAM_SMOOTH_MS`). Three replies streaming while a fresh ~25k-token prompt arrives (two boots each): the replies'+ gaps p50 / p90 / max **630 / 673-690 / 754-818 ms -> 81 / 149-150 / 230-231 ms**, none above 250 ms (75-78+ before); they received **81 -> 650-662 tokens** during the fill; the new prompt's first token **16.1 -> 21.1-21.3+ s** (`FILL_DRAFTS=0`: 18.1 s with gaps up to ~250 ms; `FILL_BUDGET_MS=0`: the old behaviour). Without a fill, four+ replies at once: gaps p50 / p90 **107 / 128 -> 40 / 58 ms**, one reply **50 / 68 -> 16 / 20 ms**; replies end when+ they did. Replies are byte-identical (22/22 concurrent cases against serial references, drafted == serial, long+ prompts, the needle); a request alone fills as before. Text appears ~0.4 s later than it is decoded; tool calls keep+ their place in the stream.+- **3 Sparks (experimental):** `./start-tp3.sh` (`TP=3`, `COMM=nccl` by default, `roce` allowed), with `WORKER2` for+ rank 2. Links are found per pair of nodes (a triangle of direct cables); `stop.sh` stops every configured worker;+ `prepare.sh` prepares every worker. Each rank's container gets `TF_ROCE_HCA`, the RoCE devices its NCCL uses toward+ its peers (at two Sparks it is not set: the RoCE all-gathers take the same devices from `NCCL_IB_HCA`). The+ PCIe-twin rail by name (#30) applies at two Sparks only: past two, a node's devices are the ones that share a subnet+ with a peer, so a twin without an address in such a subnet is not used. Three Sparks ran on v1.3.2's patches and, on+ 2026-10-03, on top of v1.4: exact (concurrent == one at a time 22/22, drafted == serial, sliced fill on == off, the+ 195k needle, cancellation mid-fill), measurements in the README. Two Sparks run as before: the same docker commands+ and defaults.+- **The TP-N GLM engine as patches 0066-0068, after 0001-0065:** `0066-glm-tp-n` (the engine on 3 ranks, `--tp 3`:+ heads, expert columns, vocab and DFlash2 KV groups in whole units, remainder to the lowest ranks; per-subnet RoCE,+ b12x's proxy modified for more than two Sparks), `0067-glm-tp3-split-pad` (at `TP=3` a 2,048-row prompt chunk pads+ to 2,049 rows, which the buffers did not hold, so the split prefill never ran: one pad row),+ `0068-glm-tpn-split-buffer-rows` (the memory estimate counts that row). On v1.4's code: the early split connection+ (0064, #36) opens one to every peer past two ranks instead of being skipped there, and the rank checks (0065, #29)+ name the follower's own rank in their errors. Two Sparks: buffers, estimate and connections unchanged.+- `DRY_RUN=1 ./start.sh` prints every rank's docker command and exits without stopping or starting anything;+ `DRY_RUN=1 ./stop.sh` says what it would stop on which Spark and stops nothing.+- **Per-worker settings** for the third Spark, as v1.3.3 / v1.4 do for the one worker: `FABRIC_PEER2`,+ `WORKER_HF_CACHE2`, `WORKER_WEIGHTS2`, `NFS_SERVER2`; every rank's log saved before its container is removed+ (`stop.sh`, and `start.sh` for a stopped container left from an earlier run); the image checked by content on every+ worker (#8); every worker's file list compared in byte order (#21) with only what `rsync` must send counted (#24); a+ `FABRIC_PEER2` host name resolved as at two Sparks.+- `KV_POOL_GIB` defaults per `TP`: 12.5 at two Sparks (unchanged), 32 at three (a 1M needle at 27 left rank 0 10.6 GiB+ at its lowest, so ~5.6 at 32).++### Fixed+- **#36, `SPLIT=1` failed to start on some Spark pairs** (NCCL `ibv_reg_mr ... Cannot allocate memory` on rank 1):+ the split's send/receive connection was opened after the cache pool had taken the memory. It now opens before the+ weights load (patch `0064-glm-split-connect-early`). Same replies.+- **#29, a stalled server said nothing** (patch `0065-glm-rank-checks`). Not the fix: the cause is not found yet. Each+ step's message between the ranks now carries a sequence number and a checksum, so ranks that fall out of step stop+ with an error naming it; `/health` reports `iteration_s`, how long the current step has run; and+ `TF_GLM_MULTI_WATCHDOG_EXIT=1` makes a server stuck past `TF_GLM_MULTI_WATCHDOG_S` (300 s) exit after printing every+ thread's stack, so a supervisor can restart it. Same replies.+- **An agent's tool loop pushed other conversations' kept prompts out** (PR #32 by @Alexbob0, patch+ `0063-glm-kept-cap-superseded-first`): past `TF_GLM_CACHE_ENTRIES` the least recently used state went, so a+ conversation taking many short turns dropped the only state of another one waiting on a long reply, whose next turn+ then read its whole history again. A conversation's earlier states, superseded by its own longer ones, now go first.+ Same replies.+- **Downloads without the host `hf` CLI left the Hugging Face cache root-owned** (PR #34 by @100menotu001): the+ fallback container ran as root, so later `hf` runs, the copy to the worker and cache cleanup failed with Permission+ denied. It now runs as your user, with the same `hub/` layout.+- **#11, a prompt with a picture anywhere in it never resumed from a kept state** under `PARALLEL` above 1: every turn+ of a conversation with pictures in its history read the whole history again (minutes at 100k+ tokens). Kept states+ are now told apart by each picture's content, and only the pictures past the resume point are encoded again+ (patch `0054-glm-image-prompt-reuse`, by @abhicnv007, applied as contributed with two review changes). Also+ reported, with measurements, by @DevRico003, @lukemdanastasi and @d4rkdpg.+- **#22, a tool call the model ended with its end token before `</tool_call>` was dropped** (`finish_reason: "stop"`,+ no call, no text). It is now closed and sent as a call when it then parses, else returned as text; a call whose+ `<arg_key>` the model wrote as whitespace gets it back (patch `0055-glm-open-tool-calls`). A call cut by the token+ limit is still never sent. Reported by @teamlewis-bot, confirmed by @andrejsstepanovs.+- **#28, pictures in tool results were refused with HTTP 400** (`image_url parts are supported only in user+ messages`), which every later request of an agent session replayed. They are now read in place, inside their+ `<tool_response>`, as the served template renders a tool result's media (patch `0056-glm-tool-result-media`).+ With `VISION=0` they become the template's own "unable to process this image" reminder, so the session goes on; a+ picture in a user message still needs `VISION=1` (HTTP 400 that says so). Reported by @d4rkdpg.+- A POST to an unknown route left its body on the kept-alive connection, so the next request on it failed with 400+ (TensorFold v0.6.1's fix for #181, commit 50dfe38a, backported: patch `0059-server-refused-bodies`).+- A client that left was not noticed once the server held more than ~1,000 descriptors, and its reply was decoded for+ nobody (TensorFold PR #218 by @jayleaton: patch `0058-server-client-gone-poll`).++## v1.3.3 (2026-10-02): our own checkpoint by default, setup fixes, saved server logs, both PCIe links of a QSFP port++Image unchanged: `v0.6.0-ae8d1c789b47`. No patch changes. The default checkpoint changes, so replies differ from v1.3.2+(with `MODEL_ID=Mia-AiLab/GLM-5.3-Flash-EXL3-TR3-4bpw` they are the same as before).++### Changed+- **Default checkpoint: [`Mia-AiLab/GLM-5.3-Flash-EXL3-4bpw-TensorFold`](https://huggingface.co/Mia-AiLab/GLM-5.3-Flash-EXL3-4bpw-TensorFold)** (rev `078455ff`), Mia's AI Lab's own EXL3+ quantization of GLM-5.3-Flash, Apache-2.0. Same format, size (~176 GB), speed and memory as TR3-4bpw. Against TR3-4bpw on+ the same build: KL divergence to the original model 4-18% lower as served, on every test set (paired 95% intervals+ exclude zero on 7 of 8); coding equal (HumanEval+ and MBPP+, thinking on: 469 vs 468 of 542, paired p = 1.0) with+ ~10% shorter replies; GSM8K 247 vs 245 of 250, HumanEval 157 vs 160 of 164 (neither significant). Details on its+ model card. TR3-4bpw stays pinned and one setting away: `MODEL_ID=Mia-AiLab/GLM-5.3-Flash-EXL3-TR3-4bpw`.+- **Disk:** the first `./start.sh` after updating downloads the new checkpoint (~176 GB) and copies it to the worker.+ To free TR3's space afterwards, delete `models--Mia-AiLab--GLM-5.3-Flash-EXL3-TR3-4bpw` from the Hugging Face cache+ on both Sparks (`~/.cache/huggingface/hub` unless `HF_HOME` / `WORKER_HF_CACHE` say otherwise); the recipe never+ deletes it itself.++### Added+- **Saved server logs.** `docker rm -f` deletes a container's log, so a crash's log was lost at the next stop or+ restart. `stop.sh`, and `start.sh` before it removes a stopped container left from an earlier run, now save each+ rank's log (stdout and stderr, with timestamps), gzipped, as `<date>-<time>-rank<N>.log.gz` in+ `~/.cache/tensorfold-glm53/logs` on each Spark (`LOG_DIR` on the head), keep the newest 10 of each rank+ (`LOG_KEEP`; `0` saves none), and print where. A log that cannot be saved only warns.+- **`WORKER` and `FABRIC_PEER` as host names** (#26): a name (an `/etc/hosts` alias of the CX7 address, a LAN name,+ mDNS) is resolved to IPv4 before the route lookup, which takes addresses only; before, it stopped with `no route+ from this node to <name>`. By @Alexbob0.+- **`WORKER_HF_CACHE`** (#26): the worker's Hugging Face cache when it is not its `HF_HOME` (a shared models folder,+ say), used by the copy, the checks and rank 1's mount. Unset, nothing changes. By @Alexbob0.+- **`tools/end_of_turn.py`** (#27): the end-of-turn check behind #18 (8 short French coding prompts, thinking off:+ replies cut by `max_tokens`, and P(end of turn) right after the closing code fence); exit code 1 above `max_cut`+ cut replies. By @Alexbob0.++### Changed (setup)+- **Both PCIe links of the cabled QSFP port** (#30): a Spark's QSFP port reaches the GB10 over two PCIe Gen5 x4+ links, so it shows up as two netdevs and two RoCE devices ("twins"). The rails scan only took a second device in+ the link's own subnet, so with the twins in different subnets (NVIDIA's two-Spark playbook) NCCL and the RoCE+ all-gathers ran on one x4. The twin is now paired by name as well. By @webzone. With a fix of ours: when the twins+ share the link's subnet (as on our pair), the twin was listed twice (`rocep1s0f1,roceP2p1s0f1,roceP2p1s0f1`); it+ is listed once. On our pair the devices are unchanged (head `rocep1s0f1,roceP2p1s0f1`, worker+ `rocep1s0f0,roceP2p1s0f0`, as before). `NCCL_RAILS=1` still uses one device.++### Fixed+- **#21, the worker copy check failing when the two Sparks sort differently.** The check compared the head's and the+ worker's `find | sort` manifests as strings, each sorted in its own host's locale (ssh carries none of ours), so+ identical copies failed after the full copy whenever the locales differed or the launcher set none (systemd, cron,+ Tailscale SSH). Every manifest is now sorted in byte order (`LC_ALL=C`), inside the commands sent to the worker too,+ and a mismatch prints the first differing lines. Reported by @alexandrupetraru, reproduced by @ThinkCode.+- **#24, the disk checks asking for the whole checkpoint when it is already cached.** The head asked for+ `MIN_FREE_GB` (180 GB) whenever the pinned revision's snapshot was new, even when every blob was in the cache from+ an earlier revision. It now asks the Hub which files the revisions hold and counts only those whose blob is missing+ (by name and size), plus 5 GB; that needs `huggingface_hub` on the host (`python3`, or the `hf` CLI's own Python),+ and without it or the Hub the old rule applies. The worker check counted the whole snapshot; it now counts what+ `rsync` must send. Reported by @ThinkCode.++### Unchanged+- The image, the patches and every serving setting besides the checkpoint: memory and speed are those of v1.3.2+ (except on pairs whose port twins were left out before, #30); with `MODEL_ID=Mia-AiLab/GLM-5.3-Flash-EXL3-TR3-4bpw`+ replies are too.+- `start.sh`'s help said `TF_GLM_MULTI_LONE` defaults to 1; it has been 0 since v1.3.1 (help text only).+## v1.3.2 (2026-10-01): more kept prompts, a note on non-English promptsImage unchanged: `v0.6.0-ae8d1c789b47`.diff --git a/CREDITS.md b/CREDITS.mdindex b681fa2..a0b9e5b 100644--- a/CREDITS.md+++ b/CREDITS.md@@ -10,7 +10,10 @@ checkpoint's ShapleyMcg attribution and the drafter's license).- **[GLM-5.3-Flash](https://huggingface.co/zai-org/GLM-5.3-Flash)** by [Z.ai](https://huggingface.co/zai-org): themodel's design, training and evaluations. Its license, on the model card, governs any use of the weights. Theweights are not part of this repository; `scripts/prepare.sh` downloads them from Hugging Face.-- **[brandonmusic](https://huggingface.co/brandonmusic)**: the EXL3 4-bit quantization,+- **Mia's AI Lab**: the default checkpoint since v1.3.3, [`Mia-AiLab/GLM-5.3-Flash-EXL3-4bpw-TensorFold`](https://huggingface.co/Mia-AiLab/GLM-5.3-Flash-EXL3-4bpw-TensorFold) (Apache-2.0), made with+ [exllamav3](https://github.com/turboderp-org/exllamav3) by turboderp (MIT).+- **[brandonmusic](https://huggingface.co/brandonmusic)**: the default checkpoint before v1.3.3, still selectable+ with `MODEL_ID`: the EXL3 4-bit quantization,[`brandonmusic/GLM-5.3-Flash-tr3-4bpw`](https://huggingface.co/brandonmusic/GLM-5.3-Flash-tr3-4bpw), served herefrom its mirror [`Mia-AiLab/GLM-5.3-Flash-EXL3-TR3-4bpw`](https://huggingface.co/Mia-AiLab/GLM-5.3-Flash-EXL3-TR3-4bpw)(a byte-identical copy), made with **ShapleyMcg** by Brandon M.@@ -46,7 +49,8 @@ checkpoint's ShapleyMcg attribution and the drafter's license).(Apache 2.0), the reference they follow; builds on TensorFold's Qwen image pipeline.- `0006-cuda-roce-allgather`: the one-shot RoCE all-gather (`COMM=roce`) is the "RoCEnante" transport of**[b12x](https://github.com/local-inference-lab/b12x)** by local-inference-lab (Apache 2.0): its C proxy- (`roce_proxy.c`) used as is, its CuTe all-gather kernel reimplemented in CUDA C++ (`roce.cu`).+ (`roce_proxy.c`), modified for more than two Sparks (per-peer routes over up to 4 network cards; its header lists the+ changes), and its CuTe all-gather kernel reimplemented in CUDA C++ (`roce.cu`).- `0012-glm-kda-chunked`, `0014-glm-kda-chunked-gb10`, `0039-glm-kda-chunked-kernel` (`KDA_CHUNKED`, on by default):the chunked WY / UT form of the delta-rule recurrence follows the published chunkwise algorithm of gated deltanetworks and Kimi Delta Attention, as implemented in@@ -75,6 +79,17 @@ checkpoint's ShapleyMcg attribution and the drafter's license).- `0047-glm-exl3-decode-loads` (routed-expert decode loads, `TF_GLM_EXL3_LOADS`): adapted from patch 0580 of[jayleaton/glm53-tensorfold-spark](https://github.com/jayleaton/glm53-tensorfold-spark) (Apache 2.0); changes listedin `NOTICE`.+- `0054-glm-image-prompt-reuse` (image prompts resume from kept prompt states, issue #11): by+ [abhicnv007](https://github.com/abhicnv007), applied as contributed, with two small review changes.+- `0057-server-thinking-alias` (`chat_template_kwargs.thinking`): from [Alexbob0](https://github.com/Alexbob0)'s+ pull request #25; the `{"type": ...}` forms and the refusal of other values were added here.+- `0058-server-client-gone-poll`: [TensorFold PR #218](https://github.com/ashhart/TensorFold/pull/218) by+ [jayleaton](https://github.com/jayleaton) (Apache 2.0), applied unchanged: the client-gone check sees descriptors+ past 1023.+- `0059-server-refused-bodies`: TensorFold v0.6.1's fix for #181 (commit 50dfe38a, by+ [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.- 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/NOTICE b/NOTICEindex 2d1f9f2..5747c84 100644--- a/NOTICE+++ b/NOTICE@@ -43,14 +43,19 @@ TensorFold(context_length_exceeded) for GLM's own window check and image prompts; 0045 adds the CUDA server's /healthfigures to /metrics as tensorfold_health:* families. Two comments in 0044 still name the upstream commit (68c6e35)whose wording they reuse.+ patches/0059-server-refused-bodies.patch is upstream TensorFold commit 50dfe38a (v0.6.1, #181, by Dorian /+ SxMShaDoW) backported to v0.6.0 (merged with 0037's /tokenize routes; its test's oversized body enlarged past+ 0050's 96 MiB limit).b12xhttps://github.com/local-inference-lab/b12xCopyright the b12x contributors (local-inference-lab). Apache License, Version 2.0.patches/0006-cuda-roce-allgather.patch: tensorfold/cuda/roce_proxy.c is b12x's RDMA proxy- (b12x/comm/roce/_roce_proxy.c at commit 8a99d639410e39d5f39cb4037675331beceea1d4), used as is except its header;- tensorfold/cuda/roce.cu reimplements b12x's CuTe DSL all-gather kernel (b12x/comm/roce/_allgather_cute.py at the- same commit) in CUDA C++, with the same stages and memory orderings.+ (b12x/comm/roce/_roce_proxy.c at commit 8a99d639410e39d5f39cb4037675331beceea1d4), modified: the multi-Spark+ (TP=3/4) patch extends it to up to 4 HCAs with a GID index each and per-peer routes (each peer's stripes over the+ HCAs that share its subnet), proxy ABI 5; with no routes set it behaves as b12x's file. Its header lists these+ changes. tensorfold/cuda/roce.cu reimplements b12x's CuTe DSL all-gather kernel (b12x/comm/roce/_allgather_cute.py+ at the same commit) in CUDA C++, with the same stages and memory orderings.glm53-tensorfold-sparkhttps://github.com/jayleaton/glm53-tensorfold-spark@@ -88,10 +93,21 @@ glm53-tensorfold-sparkthe first steps' words issued before the member rows reach shared memory. Changed here: built into thisproject's decode kernel (its expert plan, fused down / gate-up epilogues and per-row input rotation kept), ringdepth 1, 2 or 4 as a template parameter, no probe or PDL variants.+ patches/0058-server-client-gone-poll.patch is Jay Leaton's TensorFold pull request #218+ (https://github.com/ashhart/TensorFold/pull/218, Apache-2.0), applied to v0.6.0 unchanged:+ tensorfold/server/cancellation.py's client-gone check asks poll() instead of select().++Contributions to this project (Apache-2.0, through its issues and pull requests)+ patches/0054-glm-image-prompt-reuse.patch: by abhicnv007 (issue #11), with two review changes by MiaAI-Lab.+ patches/0057-server-thinking-alias.patch: from Alexbob0's pull request #25, extended by MiaAI-Lab.+ patches/0060-glm-keep-thinking.patch: by kky42 (pull request #23).Model files (downloaded from Hugging Face by scripts/prepare.sh; not included in this repository or its image)- The checkpoint, Mia-AiLab/GLM-5.3-Flash-EXL3-TR3-4bpw (a byte-identical mirror of- brandonmusic/GLM-5.3-Flash-tr3-4bpw), is under the ShapleyMcg License 1.0, which requires this attribution:+ The default checkpoint, Mia-AiLab/GLM-5.3-Flash-EXL3-4bpw-TensorFold, is licensed Apache-2.0 (Mia's AI Lab); it derives+ from zai-org/GLM-5.3-Flash, MIT-licensed by Z.AI (its license ships with the checkpoint).+ The earlier default, Mia-AiLab/GLM-5.3-Flash-EXL3-TR3-4bpw (a byte-identical mirror of+ brandonmusic/GLM-5.3-Flash-tr3-4bpw), still selectable with MODEL_ID, is under the ShapleyMcg License 1.0, which+ requires this attribution:This work includes or was produced using ShapleyMcg, created by Brandon M. Music(https://github.com/brandonmmusic-max/shapleymcg). ShapleyMcg is licensed under the ShapleyMcg License v1.0, andiff --git a/README.md b/README.mdindex fd7f455..9ba6341 100644--- a/README.md+++ b/README.md@@ -14,13 +14,14 @@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 53 patches: DFlash2 and copy drafts, 4-bit dense weights, an FP8 KV cache,+in NVIDIA's PyTorch container, plus 68 patches (65 of v1.4 and 3 for 3 Sparks, experimental): 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`.-- Checkpoint: [`Mia-AiLab/GLM-5.3-Flash-EXL3-TR3-4bpw`](https://huggingface.co/Mia-AiLab/GLM-5.3-Flash-EXL3-TR3-4bpw)- (EXL3 routed experts at 4 bits a weight, BF16 elsewhere, ~176 GB), a byte-identical mirror of- [`brandonmusic/GLM-5.3-Flash-tr3-4bpw`](https://huggingface.co/brandonmusic/GLM-5.3-Flash-tr3-4bpw)+- Checkpoint: [`Mia-AiLab/GLM-5.3-Flash-EXL3-4bpw-TensorFold`](https://huggingface.co/Mia-AiLab/GLM-5.3-Flash-EXL3-4bpw-TensorFold), Mia's AI Lab's own EXL3 quantization (routed experts at 4 bits a weight,+ BF16 elsewhere, ~176 GB): closer to the original model than the earlier default TR3-4bpw on every test set, equal in+ coding, same speed and memory ([model card](https://huggingface.co/Mia-AiLab/GLM-5.3-Flash-EXL3-4bpw-TensorFold)). TR3-4bpw stays one setting away:+ `MODEL_ID=Mia-AiLab/GLM-5.3-Flash-EXL3-TR3-4bpw`- Drafter: [`incoai/GLM-5.3-Flash-DFlash2`](https://huggingface.co/incoai/GLM-5.3-Flash-DFlash2), or the checkpoint'sown MTP head (`DRAFTER`, see [Configuration](#configuration))- API model id: `GLM-5.3-Flash-EXL3`@@ -65,12 +66,17 @@ of 11 sent in a burst).| An identical 64k-token prompt, sent again | 34 s | under 0.07 s || A new conversation with the same 7.9k-token system prompt | 4.24 s | 0.13 s |-**Quality** (FP8 KV cache and 4-bit dense weights, see [Checks](#checks); measured on a build with identical replies)+**Quality** (FP8 KV cache and 4-bit dense weights, see [Checks](#checks); both checkpoints on the same build)-| Benchmark | Score |-| --- | ---: |-| GSM8K (250 problems) | 98.0% |-| HumanEval (164 problems) | 97.6% |+| Benchmark | This checkpoint | TR3-4bpw (before v1.3.3) |+| --- | ---: | ---: |+| GSM8K (250 problems, thinking off) | 98.8% | 98.0% |+| HumanEval (164 problems, thinking off) | 95.7% | 97.6% |+| HumanEval+ and MBPP+ (542 problems, thinking on) | 86.5% | 86.3% |++None of the gaps is statistically significant (paired tests); the new checkpoint's gain is in fidelity to the+original model (KL divergence 4-18% lower as served) and ~10% shorter replies. Details on the+[model card](https://huggingface.co/Mia-AiLab/GLM-5.3-Flash-EXL3-4bpw-TensorFold).## Requirements@@ -79,17 +85,19 @@ of 11 sent in a burst).- **A direct ConnectX-7 link:** a QSFP cable between the CX7 ports and an IPv4 address on each end in one privatesubnet (e.g. `192.0.2.1/24` and `192.0.2.2/24`; `ping` must work), with a RoCE v2 GID (`start.sh` checks). One QSFPport of a Spark reaches the GB10 over two PCIe Gen5 x4 links, so it appears as two netdevs and two RoCE devices- (`enp1s0f0np0` / `enP2p1s0f0np0`, `rocep1s0f0` / `roceP2p1s0f0`), and the two twins need **different** subnets - that- is what NVIDIA's own two-Spark playbook does. Both twins of the cabled port are then used, as is a second cabled- port: a prompt chunk's all-gather is ~1.8x faster on two rails, and one rail is one x4 (~112 Gb/s of the port's 200).+ (`enp1s0f0np0` / `enP2p1s0f0np0`, `rocep1s0f0` / `roceP2p1s0f0`). Address both twins on each Spark, in the link's+ subnet or each in its own (NVIDIA's two-Spark playbook gives them different ones): both are then used, as is a second+ cabled port in the link's subnet. A prompt chunk's all-gather is ~1.8x faster on two rails; one rail is one x4+ (~112 Gb/s of the port's 200).- **Key-based ssh** from the first Spark (the head, which runs `./start.sh` and the API) to the second (the worker):`ssh-copy-id user@<worker>` (after `ssh-keygen -t ed25519` if you have no key); check with`ssh -o BatchMode=yes user@<worker> true`.- Docker with the NVIDIA container runtime, your user in the `docker` group, and `rsync`, on both Sparks.- **Disk, on each Spark:** ~205 GB: ~176 GB (164 GiB) for the checkpoint and ~2.3 GB for DFlash2 under- `~/.cache/huggingface`, ~25 GB for the image under Docker's root. `prepare.sh` wants 180 GB free for the download- (`MIN_FREE_GB`) and 35 GB under Docker's root (`IMAGE_FREE_GB`; the sum when they share a filesystem), and checks the- worker before the copy. With `WORKER_WEIGHTS=nfs` the worker needs only the image+ `~/.cache/huggingface`, ~25 GB for the image under Docker's root. `prepare.sh` asks for what the download still+ needs (files already in the cache, from an earlier revision say, do not count; 180 GB, `MIN_FREE_GB`, when it cannot+ ask the Hub what is missing) and 35 GB under Docker's root (`IMAGE_FREE_GB`; the sum when they share a filesystem),+ and checks the worker for what the copy must send. With `WORKER_WEIGHTS=nfs` the worker needs only the image([Worker weights over NFS](#worker-weights-over-nfs)).- Optional: the `hf` CLI on the head (faster download) and a Hugging Face token (`~/.cache/huggingface/token` or`HF_TOKEN`).@@ -135,6 +143,12 @@ ssh <worker> docker logs -f glm53-flash-tf # rank 1's log (why itcurl -s http://<head-address>:8888/health # busy flag, streams, free pool tokens```+**Logs of earlier runs.** `docker rm` deletes a container's log, so `stop.sh` (and `start.sh`, before it removes a+stopped container left from an earlier run, a crashed one say) first saves each rank's log, stdout and stderr with+timestamps, gzipped, and prints where: `~/.cache/tensorfold-glm53/logs/<date>-<time>-rank0.log.gz` on the head+(`LOG_DIR`) and `~/.cache/tensorfold-glm53/logs/<date>-<time>-rank1.log.gz` on the worker. The newest 10 of each+rank are kept (`LOG_KEEP`; `0` saves none). Read one with `zcat` or `zless`; attach both when you report a crash.+If `start.sh` stops at a check:| Message | What to do |@@ -160,6 +174,10 @@ curl -s http://<head-address>:8888/v1/chat/completions -H 'Content-Type: applica```A video is a `video_url` part (`{"type": "video_url", "video_url": {"url": "data:video/mp4;base64,..."}}`).+Pictures and clips can also be parts of a tool result (`"role": "tool"`, as agents return screenshots): the model+reads them inside that result (with `VISION=0`, it is told it cannot see them, in the template's own words). A+conversation with pictures in its history resumes from its kept prompt states like a text one, as long as the+pictures are the same.| | Images | Videos || --- | --- | --- |@@ -178,7 +196,7 @@ By default only data URLs are accepted; `VISION_URLS=1` also lets the server fet1. **Setup:** `scripts/prepare.sh`, when the setup is not ready on both Sparks (first run, new patches, anothermodel, drafter, revision, image or worker).2. **Checks:** the arguments (TensorFold's own parser), the link, the previous server (stopped on `restart`, or when- only one rank is up; a stopped container left from an earlier run is removed), the port, free memory (a warning+ only one rank is up; a stopped container left from an earlier run is removed, its log saved first), the port, free memory (a warningbelow ~110 GiB on either Spark).3. **Launch:** rank 1 on the worker over ssh, then rank 0 and the API here, with the settings from `scripts/config.sh`.4. **Loading:** rank 0's log as it comes, and every 15 s the elapsed time and how much of the startup estimate is on@@ -268,6 +286,72 @@ checks that the worker sees every file of both snapshots as the head has them, iexported path as the worker mounts it (default: the head's `HF_CACHE`; `/` for an NFSv4 export with `fsid=0`), and`NFS_SERVER` the head's address (default: its address on the link).+## 3 Sparks (experimental)++`./start-tp3.sh` runs the same recipe as tensor parallel over three Sparks (`TP=3` with `./start.sh`'s options;+`./stop.sh` stops every configured worker). **The engine for `--tp N` comes from this repo's patches 0066-0068**+(TensorFold v0.6.0 itself serves two ranks only), in the same published image as two Sparks (`prepare.sh` pulls it on the head and copies it to every worker). **Three Sparks** were tested on v1.3.2's patches (exact against two Sparks, drafted == serial, images and+tool calls, concurrent requests). On top of v1.4 (2026-10-03, `KV_POOL_GIB=27`, NCCL, two boots: sliced fill on and+off): concurrent requests equal one at a time (22/22 each boot), drafted == serial (6/6), long-prompt replies and every+streamed reply the same with the sliced fill on and off, the 195k needle right (prefill 115.0 s), a prompt cancelled+mid-fill gone in 0.16 s with the other replies unchanged, tool calls whole. Prefill 12k / 50k / 149k: 6.2 / 25.7 / 84.2 s+(two Sparks: 6.5 / 26.8 / 87.1). Streaming, gaps p50 / p90 between a reply's events: one reply 15 / 18 ms, four at+once 34 / 46 ms; three replies while a ~25k-token prompt fills 81 / 134 ms with the sliced fill (134 / 400 ms with+`FILL_BUDGET_MS=0`). Rank 0 had 10.6 GiB free idle and 8.4 GiB at its lowest (a 149k prompt); at the default 32 GiB+it had 5.8 GiB free idle, below the ~10 GiB this recipe keeps under load, so these runs used 27.++**Three Sparks, measured with sparkDash** (the default configuration otherwise: 4 streams, 1,048,576-token window, FP8 KV+cache, 4-bit dense weights, DFlash2 plus copy drafts, vision on)++| Concurrent requests | Prose | Prose, per request | TTFT | Code | Code, per request | TTFT |+| ---: | ---: | ---: | ---: | ---: | ---: | ---: |+| 1 | 77.6 tok/s | 77.6 tok/s | 144 ms | 104.3 tok/s | 104.3 tok/s | 192 ms |+| 2 | 95.7 tok/s | 49.5 tok/s | 264 ms | 139.0 tok/s | 72.7 tok/s | 293 ms |+| 3 | 121.2 tok/s | 42.0 tok/s | 249 ms | 158.7 tok/s | 55.5 tok/s | 379 ms |+| 4 | 146.2 tok/s | 37.3 tok/s | 262 ms | 169.6 tok/s | 45.7 tok/s | 348 ms |++| Prompt | Prefill | Time to first token |+| ---: | ---: | ---: |+| 8,212 tokens | 2,000.6 tok/s | 4.59 s |+| 16,408 tokens | 2,000.4 tok/s | 8.20 s |+| 32,790 tokens | 2,064.2 tok/s | 15.89 s |+| 65,560 tokens | 2,003.6 tok/s | 32.72 s |+| 131,094 tokens | 1,881.7 tok/s | 69.67 s |+| 262,169 tokens | 1,654.5 tok/s | 158.45 s |++Against two Sparks ([Performance](#performance)): prose decode 60.4 -> 77.6 tok/s for one request and 108.8 -> 146.2+tok/s for four at once; prefill about the same (1-4% faster).++`DRY_RUN=1 ./start-tp3.sh` shows what would run (every rank's `docker run`, the links found, nothing stopped or+started). It uses NCCL for every all-gather by default (`COMM=nccl`); `COMM=roce ./start-tp3.sh` sends the small+ones over RoCE, each peer on the devices that share its subnet (the TP-N engine's RoCE; `TF_ROCE_HCA` lists a node's+devices toward all its peers, and each device's RoCE v2 GID is found on its own).++- **Cabling.** A triangle, one direct QSFP cable per pair, each cable its own subnet (both CX7 ports of+ each Spark are used, each toward one peer). Wire it as a directed ring, each Spark's port 0 to the next Spark's+ port 1; a mirrored ring leaves one pair NCCL cannot connect. `start.sh` refuses a pair of ranks without a common+ subnet.+- **Settings** (in `scripts/local.sh`): `WORKER` (rank 1) and `WORKER2` (rank 2), each with its own `FABRIC_PEER`,+ `FABRIC_PEER2` if needed (`./start.sh` uses `WORKER` only). Weights per worker: `WORKER_WEIGHTS`, `WORKER_WEIGHTS2`+ (default: `WORKER_WEIGHTS`). With `nfs`, each worker mounts the head's export from the head's address on that+ worker's own link (`NFS_SERVER`, `NFS_SERVER2` override it), so the export must allow every worker's link address+ or subnet. `prepare.sh` says which worker cannot mount it. A worker whose Hugging Face cache is not its `HF_HOME`:+ `WORKER_HF_CACHE`, `WORKER_HF_CACHE2`.+- **Every worker as the one worker at two Sparks:** `prepare.sh` checks each worker's image by content (#8), compares+ each copy's file list in byte order (#21) and counts only what `rsync` must send (#24); `start.sh` and `stop.sh`+ save every rank's log (`<date>-<time>-rank<N>.log.gz` in `~/.cache/tensorfold-glm53/logs` on that worker).+- **Links.** At two Sparks the link and its rails are found as before (both PCIe twins of a cabled port, #30). Past+ two, the nodes' RoCE devices are paired by subnet: a twin is used when it has an address in a subnet its peer+ shares; one without an address is not added by name as at two Sparks.+- **What it sets.** The rendezvous (`--master`) is the head's LAN address, what its hostname resolves to (`MASTER_ADDR`+ overrides it); every worker must route to it. NCCL's bootstrap socket uses each node's default-route netdev+ (`SOCKET_IFNAME` overrides it), since no CX7 port reaches both peers of a triangle. Data stays on RoCE:+ `NCCL_IB_HCA` lists every CX7 device toward every peer (found from the subnets the nodes share), with+ `NCCL_CROSS_NIC=1`, `NCCL_IB_SUBNET_AWARE_ROUTING=1` (the image's NCCL 2.30.7 has it), the RoCE v2 GID index when+ it is the same on all of a node's devices, and no P2P or SHM transport. These come from a vLLM recipe that ran on+ the same three Sparks.+- `prepare.sh` on its own takes `TP` too: `TP=3 scripts/prepare.sh`.+## ConfigurationEvery setting lives in [`scripts/config.sh`](scripts/config.sh). Set one for a single run from the environment@@ -280,11 +364,13 @@ sets a value wins: the environment, then `scripts/local.sh`, then `.env`, then t| `WORKER` / `FABRIC_PEER` | empty | the worker's ssh target (`user@<address>` or `user@<host name>`), and its CX7 address when `WORKER` is on another network || `WORKER_HF_CACHE` | the worker's `HF_HOME` | the worker's Hugging Face cache, when it is not its `HF_HOME` (e.g. a shared models folder) || `MASTER_PORT` | `29551` | the ranks' rendezvous port (keep it on the private link) |+| `TP` / `WORKER2` | `2` / empty | Sparks in all (`2`, or `3` through `./start-tp3.sh`), and the ssh target of rank 2 ([3 Sparks](#3-sparks-experimental)); `FABRIC_PEER2`, `WORKER_HF_CACHE2`, `WORKER_WEIGHTS2`, `NFS_SERVER2` as the worker's own |+| `MASTER_ADDR` / `SOCKET_IFNAME` | see [3 Sparks](#3-sparks-experimental) | the rendezvous address (`TP=2`: the head's address on the link) and, with `TP` above 2, NCCL's bootstrap netdev || `PARALLEL` | `4` (`1` with `DRAFTER=mtp`) | requests decoded together, 1 to 4 (above 1 needs `DRAFTER=dflash2`) || `CONTEXT` | `1048576` | prompt + reply window per request (with `KV=fp8`; other defaults in [KV pool and memory](#kv-pool-and-memory)); `0`: the largest that fits || `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` / `14.5` | 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); raise it when other work shares the Sparks |+| `KV_POOL_GIB` / `MEMORY_RESERVE_GIB` | `12.5` (`32` at `TP=3`) / `14.5` | 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); raise it when other work shares the Sparks || `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 |@@ -303,14 +389,20 @@ sets a value wins: the environment, then `scripts/local.sh`, then `.env`, then t| `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_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); the oldest goes past this count, however much of the pool is free. An agent request keeps 1 to 3 (issue #17); each costs ~45 MiB at start |+| `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 |+| `TF_GLM_MULTI_WATCHDOG_S` / `TF_GLM_MULTI_WATCHDOG_EXIT` | `300` / `0` | a rank stuck this many seconds in one step prints every thread's stack to its log (`/health`'s `iteration_s` shows how long the current step has run); `EXIT=1`: the server then exits (code 1) instead of waiting, so a supervisor can restart it. Both ranks also check that they received the same message each step, and stop with an error naming it if not |+| `TF_GLM_CLEAR_THINKING` | `0` | `1`: drop earlier turns' reasoning from the prompt, as the checkpoint's template does (agents then prefill the previous turn's tool loop again); a request's `chat_template_kwargs.clear_thinking` wins || `MULTI_PREFILL` | `1` | prompts that arrive together are filled in one forward (each with the bits it gets alone); `0`: one after another |+| `STREAM_SMOOTH` / `STREAM_SMOOTH_MS` | `1` / `400` | streamed replies go out one token an event at a steady pace from a playout buffer of this many ms, so drafted bursts (~3 tokens every ~50-100 ms) and short pauses do not show; text appears that much later, the reply ends when it did, tool calls keep their place; `0`: one event a round |+| `FILL_BUDGET_MS` | `200` | while other requests decode, a new prompt fills in layer slices of about this many ms with a decode round between them; `0`: whole 1,024-row chunks, each of which froze the other replies ~0.65 s. A request alone fills at full speed either way |+| `FILL_DRAFTS` | `1` | the rounds between those slices draft as usual (the other replies ~10 tokens/s each during a fill); `0`: one token a reply (the new prompt's first token sooner, the other replies slower while it fills) || `SERVED_NAME` / `PORT` / `HOST` | `GLM-5.3-Flash-EXL3` / `8888` / `0.0.0.0` | the model id in `/v1/models` and replies; where the API listens || `TENSORFOLD_GLM_IMAGE_TOKENS` / `_VIDEO_TOKENS` / `_VIDEO_FRAMES` | `2048` / `16384` / `128` | a picture's and a clip's token caps, and a clip's frames || `TENSORFOLD_GLM_MAX_IMAGES` / `_MAX_VIDEOS` | `50` / `4` | pictures and clips a request || `TENSORFOLD_GLM_REQUEST_IMAGE_TOKENS` / `_REQUEST_VIDEO_TOKENS` | `16384` / `32768` | tokens a request's pictures and clips share (each still within its own cap) || `PREPARE` / `PULL` | `auto` / `1` | `start.sh` runs `scripts/prepare.sh` when needed (`1` always, `0` never); `prepare.sh` tries the prebuilt image first (`0`: always build locally) || `WAIT_TIMEOUT` / `STOP_TIMEOUT` | `1800` / `30` | seconds `start.sh` waits for the server, and `stop.sh` gives it to shut down |+| `LOG_DIR` / `LOG_KEEP` | `~/.cache/tensorfold-glm53/logs` / `10` | where `stop.sh` saves rank 0's log before it removes the container (rank 1's, and ranks 2 and 3's at `TP` above 2, to the same folder on their worker), and how many of each rank's to keep ([Logs of earlier runs](#quick-start)); `0`: none |Speed settings' measured effects: [What the patches change](#what-the-patches-change). Any `TENSORFOLD_*`,`TF_GLM_*` or `TF_ROCE_*` variable is passed to both ranks (export it in `scripts/local.sh`; `.env` lines are).@@ -334,7 +426,12 @@ The checkpoint's own sampling defaults apply (temperature 1.0, top_p 0.95). Per`seed`, the sampler's key comes from the prompt, so the same request gives the same reply.- `reasoning_effort`: `"low"`, `"high"` or `"max"`, at the top level or in `chat_template_kwargs` (`"medium"` is`"high"`, `"xhigh"` is `"max"`). Without it, GLM's template uses `max`; `"none"` (or- `"chat_template_kwargs": {"enable_thinking": false}`) answers without thinking.+ `"chat_template_kwargs": {"enable_thinking": false}`) answers without thinking. `chat_template_kwargs.thinking`+ (`true` / `false`, or `{"type": "enabled"}` / `{"type": "disabled"}`, as DeepSeek-V4 clients such as pi send it) is+ read as `enable_thinking` when that is absent; other values leave the server's default.+- Earlier turns' reasoning stays in the prompt (as in zai-org's current template), so an agent's previous tool loop+ is resumed from the cache at a new user message; `"chat_template_kwargs": {"clear_thinking": true}` or+ `TF_GLM_CLEAR_THINKING=1` drops it, as the checkpoint's template does.- The reasoning comes back in `reasoning_content`, the answer in `content`. A request without `max_tokens` gets32,768 tokens for both (`MAX_TOKENS`; cut to what the window has left, never refused). An empty `content` means the modelthought until `max_tokens`: give more, or use `reasoning_effort: "low"`.@@ -349,7 +446,8 @@ The checkpoint's own sampling defaults apply (temperature 1.0, top_p 0.95). PerOpenAI's wording, `"code": "context_length_exceeded"` and `param` naming the field (`messages` or `prompt`).- **Tool calling:** `tools` / `tool_calls`, each call streamed whole once it is written (empty deltas every 2 smeanwhile, for clients with an idle timeout; a reply that ends inside a call, at its token limit, ends with- `length` and never sends that call), with arguments typed by their schema (an array as a JSON array,+ `length` and never sends that call; a call the model ends without its `</tool_call>` is closed and sent when it+ then parses, else returned as text; a missing `<arg_key>` is put back), with arguments typed by their schema (an array as a JSON array,`null` and `const` values as such). Calls written inside the think block count when the reply ends on them, and atool-calling step's reasoning is put back into the next request when an agent client drops it(`TF_GLM_KEEP_REASONING=0` turns that off). A past tool call whose arguments are not a JSON object is left out of@@ -361,8 +459,10 @@ The checkpoint's own sampling defaults apply (temperature 1.0, top_p 0.95). Per- Refused with HTTP 400: `logprobs: true` / `top_logprobs` (this engine returns no token probabilities) and `n`other than 1. Accepted but ignored, with no error: `logit_bias`, and the presence, frequency and repetitionpenalties. `priority: "background"` serves a request after the others.-- Prompt reuse: a new prompt that extends a recent one token for token resumes from its kept state, and a shared- system prompt's state is reused (`SHARED_PREFIX`).+- Prompt reuse: a new prompt that extends a recent one token for token resumes from its kept state (with pictures+ and clips, only when they are the same ones), and a shared system prompt's state is reused (`SHARED_PREFIX`).+- A POST to an unknown route is answered 404 after its body is read, so a kept-alive connection stays usable; a+ client that leaves is noticed however many connections the server holds.## What the patches change@@ -374,18 +474,48 @@ 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 || 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` | hyper-connection glue split by rows between the Sparks, exchanges overlapped with the next rows' work (`SPLIT`) | 50k prefill ~1,270 -> ~1,730 tok/s with 0009 and 0020; decode rounds pay ~1.5% |+| 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` | 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 | [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` | 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) || 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 || 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` | 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)) |+| 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)) || Sampling | `0034-cuda-nucleus-union` | a top_p draw from both ranks' candidates together, the same draw with fewer whole-shard reads (`TENSORFOLD_NUCLEUS_UNION=1`, off by default) | opt-in |-| Server | `0003-glm-vision`, `0050-glm-many-media`, `0036-glm-tool-calls`, `0051-glm-tool-history-recovery`, `0053-glm-whole-tool-calls`, `0037-cuda-tokenize`, `0023-server-effort-max`, `0044-cuda-context-errors`, `0045-cuda-metrics` | GLM's image and video processors and vision tower; up to 50 pictures and 4 clips a request in 96 MiB bodies; GLM tool calls for agent clients; a past tool call whose arguments are not a JSON object left out of the prompt with its result and logged, instead of HTTP 400 (agents replay history, so a 400 ended the conversation); each call sent whole once written, a call the reply ends inside never sent; `/tokenize` and `/detokenize`; `reasoning_effort: "max"`; the `param` field and GLM's own refusals on TensorFold v0.6.0's `context_length_exceeded` errors, and `/health`'s figures in its Prometheus `/metrics` | the API features above |+| Server | `0003-glm-vision`, `0050-glm-many-media`, `0056-glm-tool-result-media`, `0036-glm-tool-calls`, `0051-glm-tool-history-recovery`, `0053-glm-whole-tool-calls`, `0055-glm-open-tool-calls`, `0037-cuda-tokenize`, `0023-server-effort-max`, `0057-server-thinking-alias`, `0044-cuda-context-errors`, `0045-cuda-metrics`, `0058-server-client-gone-poll`, `0059-server-refused-bodies`, `0061-server-smooth-stream` | GLM's image and video processors and vision tower; up to 50 pictures and 4 clips a request in 96 MiB bodies, in user messages and tool results; GLM tool calls for agent clients; a past tool call whose arguments are not a JSON object left out of the prompt with its result and logged, instead of HTTP 400 (agents replay history, so a 400 ended the conversation); each call sent whole once written, a call the token limit cuts never sent, one the model ends without `</tool_call>` closed when it parses (else text), a missing `<arg_key>` put back; `/tokenize` and `/detokenize`; `reasoning_effort: "max"`; `chat_template_kwargs.thinking` read as `enable_thinking` (from Alexbob0's #25); the `param` field and GLM's own refusals on TensorFold v0.6.0's `context_length_exceeded` errors, and `/health`'s figures in its Prometheus `/metrics`; the client-gone check past 1,023 descriptors (TensorFold PR #218, jayleaton); a refused POST's body read before the reply (TensorFold v0.6.1's #181 fix); smooth streaming from a playout buffer (`STREAM_SMOOTH`) | the API features above |+| 3 Sparks (experimental) | `0066-glm-tp-n`, `0067-glm-tp3-split-pad`, `0068-glm-tpn-split-buffer-rows` | the engine on 2 or 3 ranks (`--tp`): heads, expert columns, vocabulary and DFlash2 KV groups split in whole units, the remainder to the lowest ranks; the row split (`SPLIT`) and its early connection to every peer; RoCE all-gathers over per-peer routes (b12x's proxy modified for more than two Sparks); prompt buffers and the memory estimate hold the split's pad row at three ranks | [3 Sparks](#3-sparks-experimental); two Sparks unchanged |+| Concurrent fill | `0062-glm-sliced-fill` | a new prompt's chunks run in layer slices (`FILL_BUDGET_MS`) with decode rounds between them, drafted as usual (`FILL_DRAFTS`), both ranks on the same layer boundaries; the chunk's buffers kept between slices, grouped fills, cache moves and cancellation mid-fill; whole forwards when nothing else decodes | with smooth streaming, the other replies' pauses during a 25k-token fill 630-690 ms -> 81-149 ms (table below) |++Concurrent prompt fill and smooth streaming on two Sparks (`PARALLEL=4`, DFlash2, 1,024-row chunks): three 400-token+replies already streaming when a fresh ~25k-token prompt arrives. Gaps are between one reply's events as the client+receives them, from that prompt's arrival to its first token; tokens = what the three replies received in that time.+One boot a row; the replies' text is the same in every row. The default is the last two rows.++| `FILL_BUDGET_MS` | `FILL_DRAFTS` | `STREAM_SMOOTH` | Gap p50 / p90 / max (ms) | Gaps > 250 ms | Tokens | New prompt's first token (s) |+| --- | --- | --- | --- | --- | --- | --- |+| `0` (v1.3) | | `0` | 630 / 690 / 818 | 78 | 81 | 16.19 |+| `0` (v1.3) | | `0` | 632 / 673 / 754 | 75 | 81 | 16.07 |+| `150` | `0` | `0` | 185 / 199 / 230 | 0 | 324 | 19.49 |+| `150` | `0` | `0` | 185 / 199 / 211 | 0 | 327 | 19.49 |+| `200` | `0` | `0` | 220 / 244 / 256 | 9 | 243 | 17.85 |+| `200` | `0` | `0` | 229 / 245 / 270 | 12 | 246 | 17.99 |+| `300` | `0` | `0` | 310 / 334 / 342 | 123 | 174 | 16.71 |+| `300` | `0` | `0` | 314 / 335 / 338 | 126 | 171 | 16.74 |+| `200` | `0` | `1` | 201 / 236 / 250 | 1 | 288 | 18.12 |+| `300` | `0` | `1` | 305 / 335 / 344 | 111 | 202 | 16.56 |+| `300` | `1` | `1` | 106 / 201 / 379 | 18 | 448 | 18.94 |+| `300` | `1` | `1` | 101 / 200 / 392 | 17 | 450 | 18.89 |+| `200` | `1` | `1` | 81 / 150 / 230 | 0 | 650 | 21.13 |+| `200` | `1` | `1` | 81 / 149 / 231 | 0 | 662 | 21.32 |++Without a prompt filling, smooth streaming turns each round's burst into evenly spaced tokens: one reply's gaps p50 /+p90 50 / 68 -> 16 / 20 ms, four replies at once 107 / 128 -> 40 / 58 ms; the replies end when they did (last token+6.6 s alone, 16.8-17.0 s four at once, either way). A request alone fills as before: 50k and 150k-token prompts within+1%, 12k within the boot-to-boot drift (+0.25% against an unchanged build on the same day). The first boot of a new+image compiles a kernel during its first concurrent fill (one ~2 s pause, once).## Checks@@ -411,12 +541,13 @@ with [sparkDash](https://github.com/MiaAI-Lab/sparkDash) ([Performance](#perform```start.sh set up (first run) and start both ranks+start-tp3.sh the same on three Sparks (experimental, patches 0066-0068)stop.sh stop themscripts/ config.sh (all settings), local.sh.example (this setup's WORKER), prepare.sh (image + checkpoint on- both Sparks), nodes.sh (ssh and the RoCE link), publish-image.sh (push the image to GHCR),+ 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)+tools/ checks against the running server (needle, tool calls, end of turn)CHANGELOG.md what changed in each releaseCREDITS.md who and what this builds onLICENSE Apache License 2.0@@ -432,8 +563,10 @@ of patches 0006 (b12x), 0036, 0046 and 0047 (glm53-tensorfold-spark) come from Ain [`CREDITS.md`](CREDITS.md). The modelfiles are downloaded from Hugging Face and are not part of this repository:-- **The checkpoint** is under the ShapleyMcg License 1.0, an attribution-required license; its model card and- `LICENSE` file have the terms. Its attribution notice:+- **The checkpoint** [`Mia-AiLab/GLM-5.3-Flash-EXL3-4bpw-TensorFold`](https://huggingface.co/Mia-AiLab/GLM-5.3-Flash-EXL3-4bpw-TensorFold) is under the Apache License 2.0; the base model it derives from is MIT-licensed by Z.AI.+- **TR3-4bpw** (`MODEL_ID=Mia-AiLab/GLM-5.3-Flash-EXL3-TR3-4bpw`, the default before v1.3.3) is under the ShapleyMcg+ License 1.0, an attribution-required license; its model card and `LICENSE` file have the terms. Its attribution+ notice:> This work includes or was produced using ShapleyMcg, created by Brandon M. Music> (https://github.com/brandonmmusic-max/shapleymcg). ShapleyMcg is licensed under the ShapleyMcg License v1.0, an@@ -456,8 +589,9 @@ repository's own work only.## CreditsBuilt on [TensorFold](https://github.com/ashhart/TensorFold) by Ash Hart ([ashhart](https://github.com/ashhart)),-[GLM-5.3-Flash](https://huggingface.co/zai-org/GLM-5.3-Flash) by Z.ai, the EXL3 quantization by [Brandon M.-Music](https://huggingface.co/brandonmusic) (ShapleyMcg), the DFlash2 drafter by+[GLM-5.3-Flash](https://huggingface.co/zai-org/GLM-5.3-Flash) by Z.ai, the EXL3 format and converter (exllamav3) by+turboderp, the earlier TR3 quantization by [Brandon M. Music](https://huggingface.co/brandonmusic) (ShapleyMcg), the+DFlash2 drafter by[IncoAI](https://huggingface.co/incoai), b12x's RoCE transport by local-inference-lab, and code from[glm53-tensorfold-spark](https://github.com/jayleaton/glm53-tensorfold-spark) by Jay Leaton (tool calling, L2 prefetch,expert loads). The full list, including the runtime stack and licenses, is in [`CREDITS.md`](CREDITS.md).diff --git a/patches/0054-glm-image-prompt-reuse.patch b/patches/0054-glm-image-prompt-reuse.patchnew file mode 100644index 0000000..6f71b56--- /dev/null+++ b/patches/0054-glm-image-prompt-reuse.patch@@ -0,0 +1,268 @@+# Issue #11: image prompts resume from kept prompt states under --parallel (keyed by each picture's content).+# Contributed by @abhicnv007 (MiaAI-Lab/GLM-5.3-Flash-EXL3-2x-DGX-Sparks-TensorFold#11), applied unchanged,+# with two review changes by MiaAI-Lab. Apache-2.0.++diff --git tensorfold/families/glm5_next/cuda/multi.py tensorfold/families/glm5_next/cuda/multi.py+index c0c7dcf..9c66222 100644+--- tensorfold/families/glm5_next/cuda/multi.py++++ tensorfold/families/glm5_next/cuda/multi.py+@@ -301,6 +301,8 @@ class Lane:+ point: int | None = None # where the prompt's own state is kept (engine.grid_point), or None+ shared: list[int] = field(default_factory=list)+ head: Any = None # a replay's first-token logits row (its kept prompt's, ``decode.whole``)++ key: list[int] | None = None # rank 0: the prompt's ids with its pictures' keys in their rows (kept states)++ images: bool = False # both ranks: the prompt has pictures (its kept states are told apart by key)+ decoding: bool = False+ paused: bool = False+ t0: float = 0.0+@@ -548,7 +550,6 @@ class MultiDecoder:+ and queue its ADMIT; its prompt is prefilled chunk by chunk in later iterations."""++ from .engine import grid_point, shared_points+- from .engine import VisionFeed++ self._check()+ g = self.g+@@ -566,24 +567,22 @@ class MultiDecoder:+ self.dflash_code) if draft else [0, 0, 0, 0]+ positions: list[int] = []+ feed = None+- if s.vision is not None: # encoded before anything is decided or sent: a failure stops here++ key = prompt++ if s.vision is not None:+ if g.vision is None:+ raise ValueError("image inputs require starting this server with --vision")+ positions = [int(p) for p in s.vision.positions]+ if positions and (positions[-1] >= len(prompt) or positions != sorted(set(positions))):+ raise ValueError("image rows must sit at increasing positions inside the prompt")+- t = time.perf_counter()+- torch.cuda.empty_cache()+- rows = g.vision.features(s.vision)+- torch.cuda.empty_cache()+- if rows.shape[0] != len(positions):+- raise ValueError(f"the tower gave {rows.shape[0]} rows for {len(positions)} image positions")+- feed = VisionFeed(g, positions, rows)+- feed.encode_s = time.perf_counter() - t++ keyed = getattr(s.vision, "item_keys", None)++ key = s.vision.keyed_ids() if keyed and sum(s.vision.item_rows) == len(positions) else None+ slot = next((k for k in range(self.count) if k not in {l.slot for l in self.lanes.values()}), None)+ if slot is None:+ raise NoRoom(f"every one of the {self.count} stream slots is taken")+- hit = self._resume(prompt) if draft and feed is None else None++ hit = self._resume(key) if draft and key is not None else None++ encoded_from = len(hit.ids) if hit is not None else 0++ 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+@@ -591,7 +590,7 @@ class MultiDecoder:+ 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 prompt[:len(c.ids)] != c.ids:++ if len(c.ids) > len(hit.ids) and key[:len(c.ids)] != c.key:+ self._evict(c)+ if self._grow(x, need, protect=[x]):+ base = x.base+@@ -605,11 +604,15 @@ class MultiDecoder:+ 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)++ 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++ positions = feed.positions if feed is not None else []+ cut = len(hit.ids) if hit is not None else 0+ shared: list[int] = []+- if draft and feed is None and g.shared:+- known = [np.asarray(c.ids, dtype=np.int64) for c in self.kept]+- shared = shared_points(prompt, cut, grid_point(len(prompt), cut, self.grid), self.grid, g.shared, known,++ if draft and key is not None and g.shared:++ known = [np.asarray(c.key, dtype=np.int64) for c in self.kept if c.key is not None]++ shared = shared_points(key, cut, grid_point(len(prompt), cut, self.grid), self.grid, g.shared, known,+ g.opener)+ sid = self.next_sid+ payload = [sid, slot, base, need, hit.kid if hit is not None else -1, copy, s.count, int(s.stop_eos),+@@ -618,13 +621,43 @@ class MultiDecoder:+ from tensorfold.engine.grammar import pack++ packed = pack(s.constraint)+- payload += [len(packed), *packed, len(positions), *positions]++ payload += [len(packed), *packed, len(positions), *positions, int(s.vision is not None)]+ self._emit(ADMIT, payload)+ try:+ 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.broken = exc+ raise++ self.lanes[sid].key = key++++ 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."""++++ from .engine import VisionFeed++++ first, end = 0, 0++ if cut and getattr(prepared, "item_rows", None):++ for rows in prepared.item_rows:++ if prepared.positions[end + rows - 1] >= cut:++ break++ end += rows++ first += 1++ if first == len(prepared.item_rows):++ return None++ prepared = prepared.from_item(first)++ positions = [int(p) for p in prepared.positions]++ if not positions:++ return None++ t = time.perf_counter()++ torch.cuda.empty_cache()++ rows = self.g.vision.features(prepared)++ torch.cuda.empty_cache()++ if rows.shape[0] != len(positions):++ raise ValueError(f"the tower gave {rows.shape[0]} rows for {len(positions)} image positions")++ feed = VisionFeed(self.g, positions, rows)++ feed.encode_s = time.perf_counter() - t++ return feed++ @staticmethod+ def _parse_admit(p: list[int]) -> dict:+@@ -642,9 +675,10 @@ class MultiDecoder:+ i += 1 + n+ n = p[i]+ positions = p[i + 1:i + 1 + n]++ images = bool(p[i + 1 + n])+ return dict(sid=sid, slot=slot, base=base, size=size, kid=kid, copy=copy, count=count, stop_eos=bool(stop_eos),+ draft=bool(draft), sampling=sampling, shared=shared, code=code, prompt=prompt, packed=packed,+- positions=positions)++ positions=positions, images=images)++ def _admitted(self, a: dict, s: Stream, feed, constraint, spec: str = "") -> None:+ """Both ranks: an ADMIT's stream in its slot and extent, resumed from its kept prompt if it names one."""+@@ -674,7 +708,7 @@ class MultiDecoder:+ dflash = code[0] >= 10 and self.drafts is not None+ policy = decode_policy(code, g.costs) if code[0] else None+ lane = Lane(s, a["sid"], a["slot"], x, st, self.next_order, code, spec, policy, dflash, feed=feed,+- constraint=constraint)++ constraint=constraint, images=a["images"])+ self.next_sid = max(self.next_sid, a["sid"] + 1)+ self.next_order += 1+ s.sid, s.cached = a["sid"], cut+@@ -700,7 +734,7 @@ class MultiDecoder:+ lane.head = hit.head.clone()+ self._touch(hit)+ # where its prompt states are kept: the grid point (or the end) and rank 0's shared-prefix points+- if a["draft"] and feed is None:++ if a["draft"]:+ lane.point = grid_point(len(prompt), cut, self.grid)+ lane.shared = sorted(p for p in set(a["shared"]) if lane.point is not None and cut < p < lane.point)+ lane.stops = list(lane.shared) + ([lane.point] if lane.point is not None and lane.point < len(prompt)+@@ -720,16 +754,16 @@ class MultiDecoder:+ return c+ raise RuntimeError(f"rank {self.rank} holds no kept prompt {kid}")++- def _resume(self, prompt: list[int]):+- """The longest kept strict prefix of ``prompt``, or the whole prompt when it kept its head's logits row (a+- replay of an earlier prompt), whose DFlash2 window came along."""++ def _resume(self, key: list[int]):++ """The longest kept strict prefix of ``key`` (a prompt's keyed ids, ``Lane.key``), or the whole prompt when it++ kept its head's logits row (a replay of an earlier prompt), whose DFlash2 window came along."""+ best = None+ for c in self.kept:+ n = len(c.ids)+ fits = c.drafter_end == n and c.drafter_rows is not None or self.drafts is None+ fits = fits and not (self.grid and n % self.grid)+- short = n < len(prompt) or (n == len(prompt) and c.head is not None)+- if fits and short and prompt[:n] == c.ids and (best is None or n > len(best.ids)):++ short = n < len(key) or (n == len(key) and c.head is not None)++ if fits and short and c.key is not None and key[:n] == c.key and (best is None or n > len(best.ids)):+ best = c+ return best++@@ -752,10 +786,14 @@ class MultiDecoder:+ snap.drafter_end = n+ snap.drafter_rows = draft_window(self._ctx(lane), n)+ snap.head = head++ # rank 0's key: a text prompt's is its ids (shared, not a second list); rank 1 keeps none++ snap.key = None if lane.key is None else snap.ids if not lane.images else lane.key[:n]++ snap.images = lane.images+ snap.kid = self.next_kid+ self.next_kid += 1+ snap.extent = lane.extent+- for c in [c for c in self.kept if c.ids == snap.ids]:++ # the same ids: the same prompt, unless pictures are in it (rank 1 has no keys; rank 0 resumes by key)++ for c in [c for c in self.kept if c.ids == snap.ids and not (c.images or snap.images)]:+ self._drop(c)+ lane.extent.kept.append(snap)+ self.kept.append(snap)+@@ -1307,7 +1345,7 @@ class MultiDecoder:+ a grammar or images, the youngest fails instead (returned, to be finished)."""++ lanes = sorted(self.lanes.values(), key=lambda l: l.order, reverse=True)+- lane = next((l for l in lanes if l.constraint is None and l.feed is None), None)++ lane = next((l for l in lanes if l.constraint is None and not l.images), None)+ if lane is None:+ lane = lanes[0]+ lane.s.error = NoRoom("the pool is full: every stream waits for room, and the youngest cannot replay "+diff --git tensorfold/vision/glm.py tensorfold/vision/glm.py+index 08b7bac..d53889d 100644+--- tensorfold/vision/glm.py++++ tensorfold/vision/glm.py+@@ -251,13 +251,36 @@ class GlmPrepared:+ items: list[tuple[str, Any]]+ positions: list[int]+ content_hash: str = ""++ # per item, in order: its feature rows, and a 62-bit key of its kind, shape and pixels (prompt reuse tells++ # pictures apart by these: their placeholder tokens are all the same)++ item_rows: list[int] = field(default_factory=list)++ item_keys: list[int] = field(default_factory=list)++ def continued(self, ids: list[int]) -> "GlmPrepared":+ """The same pictures under a longer prompt (a tool gate's continuation): positions are token positions."""++ if list(ids[:len(self.token_ids)]) != list(self.token_ids):+ raise ValueError("a continued image prompt must extend the original prompt")+- return GlmPrepared(list(ids), self.items, self.positions, self.content_hash)++ return GlmPrepared(list(ids), self.items, self.positions, self.content_hash, self.item_rows, self.item_keys)++++ def from_item(self, k: int) -> "GlmPrepared":++ """Only items k.. and their feature rows' positions (a prompt resumed past the earlier items' rows)."""++++ skip = sum(self.item_rows[:k])++ return GlmPrepared(self.token_ids, self.items[k:], self.positions[skip:], self.content_hash,++ self.item_rows[k:], self.item_keys[k:])++++ def keyed_ids(self) -> list[int]:++ """The prompt's ids with each item's feature rows replaced by -1 - its key: equal prefixes then mean the same++ pictures in the same places, not only the same placeholder tokens."""++++ ids = list(self.token_ids)++ at = 0++ for rows, key in zip(self.item_rows, self.item_keys):++ for p in self.positions[at:at + rows]:++ ids[p] = -1 - key++ at += rows++ return ids+++ # -- the tower --------------------------------------------------------------------------------------------------+@@ -557,10 +580,14 @@ class GlmVision:+ if len(positions) != rows:+ raise ImageInputError(f"the prompt has {len(positions)} image positions for {rows} feature rows")+ digest = hashlib.sha256(b"tensorfold-glm-vision-v1\0")++ keys = []+ for kind, x in items:+- digest.update(kind.encode() + json.dumps(list(x.shape)).encode())+- digest.update(x.numpy().tobytes())+- return GlmPrepared(ids, items, positions, digest.hexdigest())++ head = kind.encode() + json.dumps(list(x.shape)).encode()++ data = x.numpy().tobytes()++ digest.update(head)++ digest.update(data)++ keys.append(int.from_bytes(hashlib.sha256(head + b"\0" + data).digest()[:8], "big") >> 2)++ return GlmPrepared(ids, items, positions, digest.hexdigest(), [self._rows(kind, x) for kind, x in items], keys)++ @staticmethod+ def _rows(kind: str, x) -> int:diff --git a/patches/0055-glm-open-tool-calls.patch b/patches/0055-glm-open-tool-calls.patchnew file mode 100644index 0000000..e69b89b--- /dev/null+++ b/patches/0055-glm-open-tool-calls.patch@@ -0,0 +1,159 @@+# Issue #22: a tool call the model's end token left open is closed and sent when it parses, else its markup is+# text (never dropped); a missing <arg_key> is put back. Reported by @teamlewis-bot, @andrejsstepanovs. MiaAI-Lab, Apache-2.0.++diff --git tensorfold/cuda/reply_text.py tensorfold/cuda/reply_text.py+index 1ad8ca7..55ccf2f 100644+--- tensorfold/cuda/reply_text.py++++ tensorfold/cuda/reply_text.py+@@ -138,7 +138,7 @@ def parse_tool_calls(text: str, tools: list[dict[str, Any]], *, max_calls: int |+ for key, value in ((p.group(1).strip(), p.group(2))+ for p in _TOOL_PARAMETER_BLOCK_RE.finditer(m.group(2)))}+ else:+- glm = parse_glm_tool_call_block(block, tools, complete=max_calls is not None)++ glm = parse_glm_tool_call_block(repair_glm_keys(block), tools, complete=max_calls is not None)+ if glm is not None:+ name, args = glm+ if not name or str(name).lower() not in known:+@@ -162,6 +162,45 @@ def parse_tool_calls(text: str, tools: list[dict[str, Any]], *, max_calls: int |+ _THINK_CLOSE = "</think>"+ _CALL_BLOCK = re.compile(r"<tool_call>.*?</tool_call>", re.DOTALL)+ THINK_CALL_HOLD = 1024 # characters of a call written inside the think block held before it streams as a call++_GLM_TAG = re.compile(r"</?arg_(?:key|value)>")++_LAST_WORD = re.compile(r"(\S+)\s*$")++++++def repair_glm_keys(block: str) -> str:++ """A GLM call whose ``<arg_key>`` the model left out, writing whitespace where that token belongs (issue #22:++ ``read path</arg_key><arg_value>..``, or ``</arg_value>\npath</arg_key>``), with it put back: the word before an++ unopened ``</arg_key>`` is its key. A block where nothing is missing comes back as it is."""++++ if block.count(_KEY_END) <= block.count(_KEY):++ return block++ out, at, prev, prev_end = [], 0, None, 0 # prev: the last tag seen (ending at prev_end); at: text copied++ for tag in _GLM_TAG.finditer(block):++ if tag.group(0) == _KEY_END and prev in (None, _VALUE_END):++ seg_start = 0 if prev is None else prev_end++ word = _LAST_WORD.search(block, seg_start, tag.start())++ # the name's segment keeps a name before the key (``read path``): no word, or no name, is not repaired++ if word is None or (prev is None and not block[seg_start:word.start()].strip()):++ return block++ out += [block[at:word.start()], _KEY]++ at = word.start()++ prev, prev_end = tag.group(0), tag.end()++ return "".join(out) + block[at:]++++++def close_glm_call(text: str, tools: list[dict[str, Any]]) -> str:++ """What closes the GLM call a reply ended inside when it parses as a whole call to an offered tool (issue #22:++ the model wrote its end token before ``</tool_call>``): ``</tool_call>``, after ``</arg_value>`` when a value is++ open; "" when the reply is not inside a call, or the closed call would not parse (its markup is then text)."""++++ at = text.rfind(_CALL_OPEN)++ if at < 0:++ return ""++ block = text[at + len(_CALL_OPEN):]++ if _CALL_CLOSE in block or _THINK_CLOSE in block:++ return ""++ suffix = (_VALUE_END if block.rfind(_VALUE) > block.rfind(_VALUE_END) else "") + _CALL_CLOSE++ # the strict reading (one whole call, nothing but its markup, arguments a JSON object)++ return suffix if parse_tool_calls(_CALL_OPEN + block + suffix, tools, max_calls=1)[1] else ""+++ def _call_run(text: str, start: int, finished: bool) -> tuple[int, str]:+@@ -247,6 +286,7 @@ class GlmCallStreamer:+ with the end parser."""++ def __init__(self, tools: list[dict[str, Any]]) -> None:++ self.tools = tools+ self.known = {_tool_name(t).lower(): _tool_name(t) for t in tools}+ self.schemas = parameter_schemas(tools)+ self.calls: list[dict[str, Any]] = [] # every call whose header was sent, its arguments as sent+@@ -315,6 +355,7 @@ class GlmCallStreamer:+ if close >= 0 and (key < 0 or close < key):+ self._args(out, "}" if self.calls[-1]["function"]["arguments"] else "{}")+ self.pos, self.state, self.open = self.pos + close + len(_CALL_CLOSE), "outside", False++ self._repaired(text[self.start:self.pos])+ elif key >= 0:+ self.pos, self.state = self.pos + key + len(_KEY), "key"+ else:+@@ -363,6 +404,16 @@ class GlmCallStreamer:+ return out+ self.pos, self.state = self.pos + end + len(_VALUE_END), "arguments"+++ def _repaired(self, block: str) -> None:++ """A whole call whose markup lost an ``<arg_key>`` (``repair_glm_keys``): its arguments as the end parser reads++ it repaired (the streamer skipped the argument it could not see); it has not been sent yet."""++++ if block.count(_KEY_END) <= block.count(_KEY):++ return++ calls = parse_tool_calls(block, self.tools)[1] or []++ if len(calls) == 1 and calls[0]["function"]["name"] == self.calls[-1]["function"]["name"]:++ self.calls[-1]["function"]["arguments"] = calls[0]["function"]["arguments"]+++ def _callable(self, name: str) -> bool:+ """Whether the end parser reads a block beginning ``name`` as a GLM call to an offered tool."""++diff --git tensorfold/cuda/server.py tensorfold/cuda/server.py+index 762cd3d..d44ae09 100644+--- tensorfold/cuda/server.py++++ tensorfold/cuda/server.py+@@ -25,7 +25,7 @@ from tensorfold.server.tools import active_tool_specs, tool_choice_requires_call+ from tensorfold.cuda import health+ from tensorfold.cuda.chat_template import ChatTemplate+ from tensorfold.cuda.reply_text import (THINK_CALL_HOLD, GlmCallStreamer, StopStrings, StreamDecoder, ThinkSplit,+- hide_tool_calls, parse_tool_calls)++ close_glm_call, hide_tool_calls, parse_tool_calls)+ from tensorfold.cuda.turns import Turns, Yield+ from tensorfold.server.text import is_title_request, reasoning_count, split_thinking++@@ -372,6 +372,7 @@ class App:+ # end parser+ xml_stream = ToolCallStreamer(tools) if tools and not glm_calls and not policy.single else None+ answer_raw = [""]++ closing = [""] # what closes a GLM call the reply ended inside on an end token (#22)+ # GLM's calls written inside the think block: calls when the reply ends on them (``ThinkSplit``)+ think = (ThinkSplit(THINK_CALL_HOLD if calls_stream is not None else None) if glm_calls and chat and thinking+ else None)+@@ -392,6 +393,7 @@ class App:+ raw = stream.final() if finished else stream.text+ # stop strings match the generated text, reasoning included, before it is split (as on the Mac)+ raw = stops.visible(raw, partial=not finished) if stops.strings else raw++ raw = raw + closing[0] if finished else raw+ reasoning, answer = split(raw, finished)+ answer_raw[0] = answer+ if tools:+@@ -522,11 +524,17 @@ class App:+ if stopped["client"]: # as the Mac server: nothing more is written+ raise RequestCancelled("the client left during the reply")+ stats = {**(stats or {}), "token_sha": token_sha(out)}++ # the model's end token (not a stop string or the token limit) ended the reply: a call it ended inside is++ # closed when it then parses (#22), else its markup is the reply's text; it is never dropped++ ended = bool(out) and out[-1] in ends and not stopped["stop"]++ if ended and glm_calls:++ final_raw = stream.final()++ closing[0] = close_glm_call(stops.visible(final_raw) if stops.strings else final_raw, tools)+ reasoning, answer, raw = visible(True)+ final: dict[str, Any] = {}+ if len(reasoning) > sent["reasoning"]:+ final["reasoning_content"] = reasoning[sent["reasoning"]:]+- text = stops.visible(self.tok.decode([t for t in out if t not in ends], skip_special_tokens=False))++ text = stops.visible(self.tok.decode([t for t in out if t not in ends], skip_special_tokens=False)) + closing[0]+ raw_answer = split(text, True)[1]+ content, calls = parse_tool_calls(raw_answer, tools, max_calls=policy.max_calls) if tools else (answer, None)+ content = policy.content(content) if tools else content+@@ -537,10 +545,12 @@ class App:+ call_deltas = calls_stream.feed(call_text(raw))+ streamed = calls_stream.sent+ calls = [*calls_stream.calls[:streamed], *calls_stream.rest(tools)] or None+- cut = calls_stream is not None and calls_stream.open # a call the reply ended inside: never sent+- if cut: # nor its markup as content++ # a call the token limit cut (the reply ended inside it): never sent, nor its markup as content; one the++ # model's end token left open that would not parse, its markup as text (``closing`` closed the others)++ cut = calls_stream is not None and calls_stream.open and not ended++ if cut:+ content = answer.strip()+- elif tools and (at := content.rfind("<tool_call>")) >= 0 and "</tool_call>" not in content[at:]:++ elif tools and not ended and (at := content.rfind("<tool_call>")) >= 0 and "</tool_call>" not in content[at:]:+ content, cut = content[:at].rstrip(), True # the same for the end parser: an unclosed call is cut text+ tail = content[sent["content"]:] if content.startswith(answer[:sent["content"]]) else ""+ if tail:diff --git a/patches/0056-glm-tool-result-media.patch b/patches/0056-glm-tool-result-media.patchnew file mode 100644index 0000000..b527087--- /dev/null+++ b/patches/0056-glm-tool-result-media.patch@@ -0,0 +1,242 @@+# Issue #28: pictures and clips in tool results render inside their <tool_response> instead of HTTP 400 (without+# --vision: as the template's own "unable to process" reminder).+# Reported by @d4rkdpg. MiaAI-Lab, Apache-2.0.++diff --git tensorfold/cuda/server.py tensorfold/cuda/server.py+index d44ae09..fb24558 100644+--- tensorfold/cuda/server.py++++ tensorfold/cuda/server.py+@@ -210,7 +210,7 @@ class App:+ if chat:+ if not isinstance(body.get("messages"), list):+ raise RequestError("messages must be a list")+- from tensorfold.server.prompts import has_images, prepare_images++ from tensorfold.server.prompts import has_images, prepare_images, tool_media_parts++ def render(messages: list[dict[str, Any]], **images: bool) -> str: # text renders as it always has+ try:+@@ -219,14 +219,20 @@ class App:+ except TemplateError as exc: # the checkpoint's template refuses the request (``raise_exception``)+ raise RequestError(f"the chat template rejected the request: {exc}") from exc++- if has_images(body["messages"]):++ # no --vision: a tool result's pictures as the template's own "unable to process" reminder (GLM)++ reminded = (tool_media_parts(body["messages"]) if getattr(self, "tool_media_reminders", False)++ and getattr(self, "vision", None) is None else None)++ if reminded is not None:++ text = render(reminded, allow_images=True)++ elif has_images(body["messages"]):+ rendered = prepare_images(self.vision, body["messages"],+ lambda messages: render(messages, allow_images=True),+ context_limit=self._context_limit())+ return PreparedRequest(rendered.tokens, max_tokens, tools, thinking,+ self.sampling_for(body, rendered.tokens), ignore_eos=ignore_eos, stop=stop,+ vision=rendered.vision, grammar=compiled, think_budget=budget)+- text = render(body["messages"])++ else:++ text = render(body["messages"])+ prompt = self.tok.encode(text, add_special_tokens=False).ids+ elif isinstance(body.get("prompt"), list): # token ids (vLLM's and OpenAI's form): served as given+ prompt = self.token_ids(body["prompt"])+diff --git tensorfold/families/glm5_next/cuda/app.py tensorfold/families/glm5_next/cuda/app.py+index 8a96996..161f218 100644+--- tensorfold/families/glm5_next/cuda/app.py++++ tensorfold/families/glm5_next/cuda/app.py+@@ -31,10 +31,12 @@ class ThinkingOffTemplate:+++ # the checkpoint's template answers a picture or clip with this reminder; with --vision it writes GLM's markers instead+-# (Glm5NextProcessor's layout), and every text-only prompt renders as before++# (Glm5NextProcessor's layout), and every text-only prompt renders as before. A part's ``tf_mark`` (server.prompts'++# MediaMarks, taken out again before the prompt is encoded) goes before its markers+ _NO_MEDIA = ('{{- "<reminder>You are unable to process this " ~ media_type ~ " because you don\'t have multi-modal '+ 'input ability. Try different methods.</reminder>" }}')+-_MEDIA = ("{%- if media_type == 'image' -%}<|begin_of_image|><|image|><|end_of_image|>"++_MEDIA = ("{%- if item.tf_mark is defined -%}{{- item.tf_mark -}}{%- endif -%}"++ "{%- if media_type == 'image' -%}<|begin_of_image|><|image|><|end_of_image|>"+ "{%- elif media_type == 'video' -%}<|begin_of_video|><|video|><|end_of_video|>"+ "{%- else -%}" + _NO_MEDIA + "{%- endif -%}")++@@ -51,6 +53,8 @@ def media_template(inner, model_dir) -> None:++ class GlmApp(App):+ reads_ignore_eos = True # ``run`` hands it to the engine's request++ # without --vision, a tool result's pictures render as the template's own reminder (issue #28): a user's are refused++ tool_media_reminders = True++ def __init__(self, engine, model_dir, served: str, **kwargs: Any) -> None:+ super().__init__(engine, model_dir, served, **kwargs)+diff --git tensorfold/server/messages.py tensorfold/server/messages.py+index 2679969..4f2a4bf 100644+--- tensorfold/server/messages.py++++ tensorfold/server/messages.py+@@ -49,7 +49,10 @@ def normalize_messages(messages: list[dict[str, Any]], *, late_system: str = "sy+ content = message.get("content")+ if isinstance(content, list) and allow_images and any(+ isinstance(p, dict) and p.get("type") in _VISUAL for p in content):+- if role != "user":++ # a tool result's pictures reach here only as the parts ``split_images`` makes of them, for a frontend++ # that renders them in place (``tool_media``); its raw image_url / video_url parts are refused++ if role != "user" and not (role == "tool" and all(++ p.get("type") not in ("image_url", "video_url") for p in content if isinstance(p, dict))):+ raise RequestError("images and videos are supported only in user messages")+ for part in content:+ if not isinstance(part, dict) or part.get("type") not in ("text", *_VISUAL):+diff --git tensorfold/server/prompts.py tensorfold/server/prompts.py+index 9c636df..07b2872 100644+--- tensorfold/server/prompts.py++++ tensorfold/server/prompts.py+@@ -22,6 +22,29 @@ def has_images(messages):+ for m in messages or [])++++def tool_media_parts(messages):++ """For a server without a vision frontend whose template answers media with its own reminder (GLM-5.3's "You are++ unable to process this image ..."): messages whose only pictures and clips are in tool results, those parts as the++ template's bare media parts (never fetched or decoded), so an agent session that keeps a screenshot in its history++ goes on (issue #28); None when there are none, or a user (or other) message has some."""++++ if not has_images(messages):++ return None++ out = []++ for m in messages:++ content = m.get('content') if isinstance(m, dict) else None++ if not (isinstance(content, list)++ and any(isinstance(p, dict) and p.get('type') in ('image_url', 'video_url') for p in content)):++ out.append(m)++ continue++ if m.get('role') != 'tool':++ return None++ out.append({**m, 'content': [{'type': p['type'][:-len('_url')]}++ if isinstance(p, dict) and p.get('type') in ('image_url', 'video_url') else p++ for p in content]})++ return out+++++ IMAGE_SLOTS = threading.BoundedSemaphore(16) # requests decoding and processing images at once (host memory)+ IMAGE_WAITERS = threading.BoundedSemaphore(128) # requests waiting for a slot; past that, refused at once+ IMAGE_WAIT_S = 60.0+@@ -39,6 +62,42 @@ def image_slot():+ return IMAGE_SLOTS++++class MediaMarks:++ """Each picture's and clip's place in the rendered prompt, for a frontend whose template renders tool results'++ media (``tool_media``): a template may sort tool results (GLM-5.3's orders them by their calls' ids) or leave++ one out (``agent_history``), so the media are matched to the markers by a mark rendered before each++ (``tf_mark``, a per-request nonce), then the marks are taken out: the prompt is the one rendered without them."""++++ def __init__(self, template) -> None:++ import re++ import secrets++++ nonce = secrets.token_hex(8)++ self.pattern = re.compile("\x00tf-media-" + nonce + r":(\d+)\x00")++ self.count = 0++ for message in template:++ for part in message.get("content") if isinstance(message.get("content"), list) else ():++ if isinstance(part, dict) and part.get("type") in ("image", "video"):++ part["tf_mark"] = f"\x00tf-media-{nonce}:{self.count}\x00"++ self.count += 1++++ @staticmethod++ def wanted(template) -> bool:++ """Whether a tool result carries media (a user's alone keep the prompt as it always rendered)."""++++ return any(m.get("role") == "tool" and isinstance(m.get("content"), list)++ and any(isinstance(p, dict) and p.get("type") in ("image", "video") for p in m["content"])++ for m in template)++++ def read(self, text: str) -> tuple[str, list[int]]:++ """(the text without its marks, the media's indices in the order the template rendered them)."""++++ order = [int(m.group(1)) for m in self.pattern.finditer(text)]++ if any(k >= self.count for k in order):++ raise ValueError("the rendered prompt's media marks do not match the request's media")++ return self.pattern.sub("", text), order+++++ def prepare_images(frontend, messages, render, *, context_limit=None):+ from tensorfold.vision.images import DEFAULT_LIMITS, ImageInputError, load_images, split_images++@@ -48,9 +107,16 @@ def prepare_images(frontend, messages, render, *, context_limit=None):+ videos = bool(getattr(frontend, 'videos', False)) # a frontend that encodes video frames too+ # a frontend's own limits (GLM: up to 50 pictures and 4 clips a request); the shared ones otherwise+ limits = getattr(frontend, 'image_limits', None) or DEFAULT_LIMITS++ # a frontend that renders tool results' media in place (GLM: inside their <tool_response>)++ tool_media = bool(getattr(frontend, 'tool_media', False))+ try:+ template, sources = split_images(messages, limits=limits, allow_urls=allow_urls, allow_videos=videos,+- max_videos=getattr(frontend, 'max_videos', None))++ max_videos=getattr(frontend, 'max_videos', None), tool_media=tool_media)++ text = None++ if tool_media and MediaMarks.wanted(template):++ marks = MediaMarks(template)++ text, order = marks.read(render(template))++ sources = [sources[k] for k in order] # as rendered: sorted, or left out with their result+ except (ImageInputError, ValueError) as exc:+ raise RequestError(str(exc)) from exc+ slot = image_slot()+@@ -70,9 +136,11 @@ def prepare_images(frontend, messages, render, *, context_limit=None):+ from tensorfold.vision.videos import load_videos++ clips = load_videos(clips, frontend.video_size, allow_urls=allow_urls)+- prepared = frontend.prepare(render(template), images, videos=clips, max_prompt_tokens=context_limit)++ prepared = frontend.prepare(text if text is not None else render(template), images, videos=clips,++ max_prompt_tokens=context_limit)+ else:+- prepared = frontend.prepare(render(template), images, max_prompt_tokens=context_limit)++ prepared = frontend.prepare(text if text is not None else render(template), images,++ max_prompt_tokens=context_limit)+ except (ImageInputError, ValueError, ImportError) as exc:+ raise refusal(str(exc)) from exc # a prompt past the window: context_length_exceeded+ finally:+diff --git tensorfold/vision/glm.py tensorfold/vision/glm.py+index d53889d..16c11e8 100644+--- tensorfold/vision/glm.py++++ tensorfold/vision/glm.py+@@ -435,6 +435,7 @@ class GlmVision:+ ``load_videos``, and the tower's ``features`` (rank 0)."""++ videos = True++ tool_media = True # tool results' pictures and clips, rendered inside their <tool_response> (issue #28)++ def __init__(self, model_dir: Path, device, *, allow_urls: bool = False,+ limits: GlmVisionLimits | None = None) -> None:+diff --git tensorfold/vision/images.py tensorfold/vision/images.py+index c90a79b..1f5734d 100644+--- tensorfold/vision/images.py++++ tensorfold/vision/images.py+@@ -114,11 +114,12 @@ def _check_source(source: ImageSource, limits: ImageLimits, allow_urls: bool = F+++ def split_images(messages: list[dict[str, Any]], *, limits: ImageLimits = DEFAULT_LIMITS, allow_urls: bool = False,+- allow_videos: bool = False, max_videos: int | None = None++ allow_videos: bool = False, max_videos: int | None = None, tool_media: bool = False+ ) -> tuple[list[dict[str, Any]], list[ImageSource]]:+ """Preserve ordered parts, replacing user image URLs with processor image markers; ``allow_videos``: also+ ``video_url`` parts (``VideoSource`` among the sources, a video marker in the template), at most ``max_videos``+- (default: the shared video limits')."""++ (default: the shared video limits'); ``tool_media``: tool results' parts too (a frontend whose template renders++ them in place)."""+ if not isinstance(messages, list) or not messages:+ raise ImageInputError("messages must be a non-empty list")+ output, sources = [], []+@@ -148,7 +149,7 @@ def split_images(messages: list[dict[str, Any]], *, limits: ImageLimits = DEFAUL+ elif kind == "video_url" and allow_videos:+ from .videos import DEFAULT_VIDEO_LIMITS, video_source++- if role != "user":++ if role != "user" and not (tool_media and role == "tool"):+ raise ImageInputError("video_url parts are supported only in user messages")+ if any(part.get(key) for key in _MEDIA - {"video_url"}):+ raise ImageInputError("video_url parts cannot contain other media")+@@ -159,7 +160,7 @@ def split_images(messages: list[dict[str, Any]], *, limits: ImageLimits = DEFAUL+ sources.append(video_source(part.get("video_url"), DEFAULT_VIDEO_LIMITS, allow_urls))+ parts.append({"type": "video"})+ elif kind == "image_url":+- if role != "user":++ if role != "user" and not (tool_media and role == "tool"):+ raise ImageInputError("image_url parts are supported only in user messages")+ if any(part.get(key) for key in _MEDIA - {"image_url"}):+ raise ImageInputError("image_url parts cannot contain other media")diff --git a/patches/0057-server-thinking-alias.patch b/patches/0057-server-thinking-alias.patchnew file mode 100644index 0000000..aa2901d--- /dev/null+++ b/patches/0057-server-thinking-alias.patch@@ -0,0 +1,45 @@+# PR #25: chat_template_kwargs.thinking read as enable_thinking (also {"type": "enabled"|"disabled"}).+# Contributed by @Alexbob0 (MiaAI-Lab/GLM-5.3-Flash-EXL3-2x-DGX-Sparks-TensorFold#25), extended by MiaAI-Lab. Apache-2.0.++diff --git tensorfold/server/request_options.py tensorfold/server/request_options.py+index ad97a21..da44c98 100644+--- tensorfold/server/request_options.py++++ tensorfold/server/request_options.py+@@ -70,10 +70,37 @@ def heard_effort(explicit: str | None, default: str | None, levels: frozenset[st+ return coerce_effort(default if explicit is None else explicit, levels)++++_IGNORED_THINKING: set[str] = set() # the kinds of unread ``thinking`` values already logged (once each)++++++def thinking_switch(value: Any) -> bool | None:++ """``chat_template_kwargs.thinking`` as ``enable_thinking``: true / false, or Anthropic's and DeepSeek's++ ``{"type": "enabled" | "disabled"}``. Null, and any other value (``{"type": "adaptive"}``, a string ...), is++ unset: the server's default, never a refusal (logged once a kind)."""++++ if value is None:++ return None++ if isinstance(value, bool):++ return value++ kind = value.get("type") if isinstance(value, dict) else None++ if kind in ("enabled", "disabled"):++ return kind == "enabled"++ shown = f"{{'type': {kind!r}}}" if isinstance(value, dict) else type(value).__name__++ if shown not in _IGNORED_THINKING and len(_IGNORED_THINKING) < 64:++ _IGNORED_THINKING.add(shown)++ print(f"[tensorfold] chat_template_kwargs.thinking {shown[:80]}: not true, false or "++ f'{{"type": "enabled" | "disabled"}}; the server\'s default applies (logged once)', flush=True)++ return None+++++ def thinking_fields(body: dict[str, Any], levels: frozenset[str] = frozenset()) -> dict[str, Any]:+ """A request's ``reasoning_effort`` and ``enable_thinking`` where it sets them; unset is the server's default."""++ kwargs = body.get("chat_template_kwargs") or {}++ if isinstance(kwargs, dict) and "thinking" in kwargs and "enable_thinking" not in kwargs:++ switch = thinking_switch(kwargs["thinking"]) # the switch DeepSeek-V4 clients (pi) send++ if switch is not None:++ kwargs = {**kwargs, "enable_thinking": switch}+ fields: dict[str, Any] = {}+ effort = body.get("reasoning_effort")+ if effort is None and isinstance(kwargs, dict):diff --git a/patches/0058-server-client-gone-poll.patch b/patches/0058-server-client-gone-poll.patchnew file mode 100644index 0000000..d3b84ad--- /dev/null+++ b/patches/0058-server-client-gone-poll.patch@@ -0,0 +1,33 @@+# Upstream TensorFold PR #218 by Jay Leaton (jayleaton), Apache-2.0, applied unchanged to v0.6.0: the client-gone+# check uses poll() instead of select(), so descriptors past 1023 are read.++diff --git tensorfold/server/cancellation.py tensorfold/server/cancellation.py+index f1f20c0..dde4890 100644+--- tensorfold/server/cancellation.py++++ tensorfold/server/cancellation.py+@@ -27,13 +27,23 @@ class Cancellation:+ raise RequestCancelled("request cancelled")++++def _readable(connection: socket.socket) -> bool:++ """Whether a read would not block; ``poll`` where available, since ``select`` refuses descriptors past 1023."""++++ if hasattr(select, "poll"):++ p = select.poll()++ p.register(connection, select.POLLIN | select.POLLPRI)++ return bool(p.poll(0))++ ready, _, _ = select.select([connection], [], [], 0)++ return bool(ready)+++++ def socket_cancellation(connection: socket.socket) -> Cancellation:+ def disconnected() -> bool:+ try:+ if connection.fileno() < 0:+ return True+- ready, _, _ = select.select([connection], [], [], 0)+- if not ready:++ if not _readable(connection):+ return False+ return connection.recv(1, socket.MSG_PEEK | socket.MSG_DONTWAIT) == b""+ except BlockingIOError:diff --git a/patches/0059-server-refused-bodies.patch b/patches/0059-server-refused-bodies.patchnew file mode 100644index 0000000..a8602f3--- /dev/null+++ b/patches/0059-server-refused-bodies.patch@@ -0,0 +1,97 @@+# Backport of upstream TensorFold commit 50dfe38a (v0.6.1, #181, by Dorian / SxMShaDoW), Apache-2.0: a refused+# POST's body no longer reaches the next request on its connection. Merged with 0037's routes by MiaAI-Lab.++diff --git tensorfold/cuda/http.py tensorfold/cuda/http.py+index bebd06f..faec521 100644+--- tensorfold/cuda/http.py++++ tensorfold/cuda/http.py+@@ -52,11 +52,25 @@ def make_handler(app: App):+ self.send_response(code)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(data)))++ if self.close_connection: # so a pooling client does not reuse the socket++ self.send_header("Connection", "close")+ self.end_headers()+ self.wfile.write(data)+ except (BrokenPipeError, ConnectionResetError): # the client has gone+ self.close_connection = True+++ def _discard_body(self) -> None:++ """Read a refused request's body, so it cannot reach the next request on this connection."""++++ try:++ length = int(self.headers.get("Content-Length", 0))++ except ValueError:++ length = -1++ if 0 <= length <= 32 * 1024**2:++ self.rfile.read(length)++ else:++ self.close_connection = True+++ def _stream_error(self, error: dict[str, Any]) -> None:+ """End an open stream with an error event and ``[DONE]``, as the MLX server does."""++@@ -90,6 +104,7 @@ def make_handler(app: App):+ chat = self.path.rstrip("/").endswith("/chat/completions")+ tokenizer = self.path.rstrip("/") in _TOKENIZER_ROUTES+ if not chat and not tokenizer and not self.path.rstrip("/").endswith("/completions"):++ self._discard_body()+ return self._json(404, {"error": "not found"})+ try:+ length = int(self.headers.get("Content-Length", 0))+diff --git tensorfold/server/http.py tensorfold/server/http.py+index 9c9330d..98ac60d 100644+--- tensorfold/server/http.py++++ tensorfold/server/http.py+@@ -92,9 +92,23 @@ def make_handler(app: Any) -> type[BaseHTTPRequestHandler]:+ self.send_response(status)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(body)))++ if self.close_connection: # so a pooling client does not reuse the socket++ self.send_header("Connection", "close")+ self.end_headers()+ self.wfile.write(body)+++ def _discard_body(self) -> None:++ """Read a refused request's body, so it cannot reach the next request on this connection."""++++ try:++ length = int(self.headers.get("Content-Length", "0"))++ except ValueError:++ length = -1++ if 0 <= length <= 32 * 1024**2:++ self.rfile.read(length)++ else:++ self.close_connection = True+++ def _route(self) -> str:+ # Tolerate query strings, trailing slashes and client URLs with or without the /v1 prefix.+ return self.path.split("?", 1)[0].rstrip("/")+@@ -174,12 +188,14 @@ def make_handler(app: Any) -> type[BaseHTTPRequestHandler]:+ is_chat_completion = route.endswith("/chat/completions")+ is_text_completion = route.endswith("/completions") and not is_chat_completion+ if not is_chat_completion and not is_text_completion:++ self._discard_body()+ self._send_json({"error": {"message": f"unknown path {self.path}"}}, status=404)+ return++ try:+ length = int(self.headers.get("Content-Length", "0"))+ if not 0 <= length <= 32 * 1024**2:++ self.close_connection = True # the unread body must not reach the next request+ raise RequestError("request body exceeds the 32 MiB limit")+ body = parse_numbers(json.loads(self.rfile.read(length) or b"{}"))+ validate_modalities(body)+diff --git tensorfold/server/responses.py tensorfold/server/responses.py+index 8cf8212..90179db 100644+--- tensorfold/server/responses.py++++ tensorfold/server/responses.py+@@ -111,6 +111,8 @@ def _send(handler: Any, status: int, payload: dict[str, Any]) -> None:+ handler.send_response(status)+ handler.send_header("Content-Type", "application/json")+ handler.send_header("Content-Length", str(len(data)))++ if handler.close_connection: # so a pooling client does not reuse the socket++ handler.send_header("Connection", "close")+ handler.end_headers()+ handler.wfile.write(data)+ except OSError: # the client has gonediff --git a/patches/0060-glm-keep-thinking.patch b/patches/0060-glm-keep-thinking.patchnew file mode 100644index 0000000..b70c812--- /dev/null+++ b/patches/0060-glm-keep-thinking.patch@@ -0,0 +1,47 @@+# PR #23: earlier turns keep their reasoning in the prompt (clear_thinking=False unless the request sets it);+# TF_GLM_CLEAR_THINKING=1 restores the old rendering. Contributed by @kky42+# (MiaAI-Lab/GLM-5.3-Flash-EXL3-2x-DGX-Sparks-TensorFold#23), applied unchanged. Apache-2.0.++diff --git tensorfold/families/glm5_next/cuda/app.py tensorfold/families/glm5_next/cuda/app.py+index 161f218..5a540cf 100644+--- tensorfold/families/glm5_next/cuda/app.py++++ tensorfold/families/glm5_next/cuda/app.py+@@ -2,6 +2,7 @@++ from __future__ import annotations+++import os+ from pathlib import Path+ from typing import Any, Callable++@@ -17,14 +18,17 @@ class ThinkingOffTemplate:+ (``prompts.agent_history``), with the reasoning of tool-calling steps the client dropped put back (``kept``,+ ``kept_reasoning.KeptReasoning``; None: off)."""++- def __init__(self, inner, kept: KeptReasoning | None = None) -> None:++ def __init__(self, inner, kept: KeptReasoning | None = None, clear_thinking: bool = False) -> None:+ self.inner = inner+ self.efforts = getattr(inner, "efforts", frozenset())+ self.kept = kept++ self.clear_thinking = clear_thinking++ def render(self, messages, *, tools, enable_thinking, extra=None, allow_images: bool = False) -> str:+ if self.kept is not None:+ messages = self.kept.restore(messages)++ # earlier turns keep their reasoning unless the request says otherwise, as in zai-org's current template++ extra = {"clear_thinking": self.clear_thinking, **(extra or {})}+ text = self.inner.render(agent_history(messages), tools=tools, enable_thinking=enable_thinking, extra=extra,+ allow_images=allow_images)+ return text if enable_thinking else thinking_off(text)+@@ -60,7 +64,10 @@ class GlmApp(App):+ super().__init__(engine, model_dir, served, **kwargs)+ if self.vision is not None:+ media_template(self.template, Path(model_dir))+- self.template = ThinkingOffTemplate(self.template, KeptReasoning.from_env())++ clear = os.environ.get("TF_GLM_CLEAR_THINKING", "0").strip() or "0"++ if clear not in ("0", "1"):++ raise ValueError(f"TF_GLM_CLEAR_THINKING={clear!r}: expected 0 or 1")++ self.template = ThinkingOffTemplate(self.template, KeptReasoning.from_env(), clear_thinking=clear == "1")++ def check(self, body: dict[str, Any], *, prepared: PreparedRequest | None = None) -> str | None:+ """Validate the rendered prompt plus max_tokens against the engine context limit before streaming."""diff --git a/patches/0061-server-smooth-stream.patch b/patches/0061-server-smooth-stream.patchnew file mode 100644index 0000000..bea70ba--- /dev/null+++ b/patches/0061-server-smooth-stream.patch@@ -0,0 +1,275 @@+# TF_GLM_STREAM_SMOOTH=1 (STREAM_SMOOTH): a streamed reply's tokens go out one event each at a steady pace from a+# short playout buffer (TF_GLM_STREAM_SMOOTH_MS, default 400), so drafted bursts and pauses shorter than the buffer+# (another request's prompt slices) do not show; same text and end, tool calls in place, the last round flushes.+# MiaAI-Lab, Apache-2.0.++diff --git tensorfold/cuda/server.py tensorfold/cuda/server.py+index fb24558..21f81ef 100644+--- tensorfold/cuda/server.py++++ tensorfold/cuda/server.py+@@ -26,6 +26,7 @@ from tensorfold.cuda import health+ from tensorfold.cuda.chat_template import ChatTemplate+ from tensorfold.cuda.reply_text import (THINK_CALL_HOLD, GlmCallStreamer, StopStrings, StreamDecoder, ThinkSplit,+ close_glm_call, hide_tool_calls, parse_tool_calls)++from tensorfold.cuda.stream_pacing import Playout, smooth_streaming+ from tensorfold.cuda.turns import Turns, Yield+ from tensorfold.server.text import is_title_request, reasoning_count, split_thinking++@@ -409,8 +410,36 @@ class App:++ serving: list[Any] = [None]+++ # TF_GLM_STREAM_SMOOTH=1: a streamed reply's tokens go out one event each at a steady pace from a short++ # playout buffer (``stream_pacing.Playout``), so drafted bursts and other requests' prompt fills do not show++ playout = Playout(emit, cancelled=cancelled) if body.get("stream") and smooth_streaming() else None++++ def send(delta: dict[str, Any], paced: bool) -> bool:++ """Write an event (through the playout queue when smoothing): False once the client has gone."""++++ if playout is None:++ return emit(delta)++ playout.put(delta, paced)++ return not playout.gone++++ def text_delta(tokens: list[int]) -> tuple[dict[str, Any], str]:++ """The reasoning and answer text these tokens add (the part not sent yet), and the raw text so far."""++++ stream.add(tokens)++ reasoning, answer, raw = visible(False)++ delta: dict[str, Any] = {}++ if len(reasoning) > sent["reasoning"]:++ delta["reasoning_content"] = reasoning[sent["reasoning"]:]++ sent["reasoning"] = len(reasoning)++ if len(answer) > sent["content"]:++ delta["content"] = answer[sent["content"]:]++ sent["content"] = len(answer)++ return delta, raw+++ def on_tokens(new: list[int]) -> bool:+ # True stops the engine after this round; engines that finish on both ranks keep calling and get True++ if playout is not None and playout.gone:++ stopped["client"] = True+ if stopped["client"] or stopped["stop"] or failed:+ return True+ try:+@@ -425,28 +454,34 @@ class App:+ new = kept+ else:+ out.extend(new)+- stream.add(new)+- reasoning, answer, raw = visible(False)+- delta: dict[str, Any] = {}+- if len(reasoning) > sent["reasoning"]:+- delta["reasoning_content"] = reasoning[sent["reasoning"]:]+- sent["reasoning"] = len(reasoning)+- if len(answer) > sent["content"]:+- delta["content"] = answer[sent["content"]:]+- sent["content"] = len(answer)+- parts = [delta] if delta else []+- if calls_stream is not None:++ # smooth streaming: token by token into the playout queue, unless the reply ends in this round (then++ # the queue is flushed: the end is never later)++ ending = stopped["stop"] or (bool(new) and (new[-1] in ends or len(out) >= max_tokens))++ if playout is not None and ending:++ playout.flush()++ pieces = [[t] for t in new] if playout is not None and not ending and len(new) > 1 else [new]++ raw, wrote = "", False++ for piece in pieces:++ delta, raw = text_delta(piece)++ if not delta:++ continue++ if not send(delta, True):++ stopped["client"] = True++ break++ wrote = True++ parts: list[dict[str, Any]] = []++ if calls_stream is not None and not stopped["client"]:+ parts += calls_stream.feed(call_text(raw))+- if parts:++ if parts or wrote:+ quiet_since[0] = time.monotonic()+ elif calls_stream.open and time.monotonic() - quiet_since[0] >= CALL_KEEPALIVE_S:+ parts.append({}) # a call held until whole: an empty delta keeps idle clients waiting+ quiet_since[0] = time.monotonic()+- if not all(emit(part) for part in parts):++ if not all(send(part, False) for part in parts):+ stopped["client"] = True+ if xml_stream is not None and not stopped["client"]:+ for call_delta in xml_stream.feed(answer_raw[0]): # never the reasoning+- if not emit(call_delta):++ if not send(call_delta, False):+ stopped["client"] = True+ break+ if not stopped["client"] and cancelled is not None and cancelled(): # every round, text or not+@@ -520,8 +555,18 @@ class App:+ serving[0] = request+ try:+ stats = request.stats = generate_gated(generate, prompt, max_tokens, gates, on_tokens)++ except BaseException:++ if playout is not None:++ playout.abort()++ raise+ finally:+ serving[0] = None++ if playout is not None: # what is still queued goes out now, before the reply's end++ (playout.abort if stopped["client"] or failed else playout.close)()++ if playout.error is not None:++ failed.append(playout.error)++ elif playout.gone:++ stopped["client"] = True+ finally:+ if turns is not None:+ turns.give()+diff --git tensorfold/cuda/stream_pacing.py tensorfold/cuda/stream_pacing.py+new file mode 100644+index 0000000..9c6b61c+--- /dev/null++++ tensorfold/cuda/stream_pacing.py+@@ -0,0 +1,147 @@++"""Smooth streaming (``TF_GLM_STREAM_SMOOTH=1``): a streamed reply's text goes out token by token at a steady pace++from a short playout buffer, instead of a burst of drafted tokens every round and a pause whenever the engine fills++another request's prompt.++++The engine's rounds come in bursts: a round accepts ~3 drafted tokens, a round takes longer while other requests++decode, and while a new prompt fills the rounds wait for its layer slices. The request's tokens enter a queue as they++arrive and a writer thread sends them one event each: the next goes out ``hold / queued`` after the previous one++(never before it arrived), so the queue settles at about ``hold`` seconds of tokens and a pause in the rounds shorter++than that is spread over the tokens already queued instead of showing as a freeze. No token is held longer than++``LONGEST_HOLD`` times ``hold``.++++The text, its order and the reply's end are unchanged: only when events go out. Events that are not text (tool-call++deltas, keep-alives) keep their place in the queue and are not paced; the round that ends the reply flushes the queue++at once, so the reply ends when it did. The engine never waits: the request thread only queues."""++++from __future__ import annotations++++import collections++import os++import threading++import time++from typing import Any, Callable++++HOLD_MS = 400 # the default playout buffer: about this much text is held, so shorter pauses never show++LONGEST_HOLD = 2.5 # no token is held longer than this many times the buffer++++++def smooth_streaming(value: str | None = None) -> bool:++ """``TF_GLM_STREAM_SMOOTH``: 1 paces a streamed reply's tokens, 0 (the default) sends each round as one event."""++++ raw = (os.environ.get("TF_GLM_STREAM_SMOOTH", "0") if value is None else value).strip() or "0"++ if raw not in ("0", "1"):++ raise ValueError(f"TF_GLM_STREAM_SMOOTH={raw!r}: expected 0 or 1")++ return raw == "1"++++++def hold_seconds(value: str | None = None) -> float:++ """``TF_GLM_STREAM_SMOOTH_MS``: the playout buffer in milliseconds (default ``HOLD_MS``)."""++++ raw = (os.environ.get("TF_GLM_STREAM_SMOOTH_MS", "") if value is None else value).strip() or str(HOLD_MS)++ try:++ ms = int(raw)++ except ValueError:++ raise ValueError(f"TF_GLM_STREAM_SMOOTH_MS={raw!r}: expected whole milliseconds") from None++ if not 1 <= ms <= 5000:++ raise ValueError(f"TF_GLM_STREAM_SMOOTH_MS={ms}: expected 1-5000")++ return ms / 1000.0++++++class _Item:++ __slots__ = ("delta", "paced", "arrived")++++ def __init__(self, delta: dict[str, Any], paced: bool, arrived: float) -> None:++ self.delta, self.paced, self.arrived = delta, paced, arrived++++++class Playout:++ """One streamed reply's playout queue, and the writer thread that empties it through ``emit``.++++ ``put`` queues an event (``paced``: a text delta; else it goes out as soon as it reaches the front); ``flush``++ sends everything queued at once from then on; ``close`` flushes, waits for the queue to empty and stops the writer;++ ``abort`` drops what is queued and stops it. ``gone`` holds once ``emit`` failed or ``cancelled()`` said the++ client left (checked before each held event)."""++++ def __init__(self, emit: Callable[[dict[str, Any]], bool], hold: float | None = None,++ cancelled: Callable[[], bool] | None = None, clock: Callable[[], float] = time.monotonic) -> None:++ self.emit, self.cancelled, self.clock = emit, cancelled, clock++ self.hold = hold_seconds() if hold is None else hold++ self.queue: collections.deque[_Item] = collections.deque()++ self.paced = 0 # paced items queued++ self.last: float | None = None # when the previous event went out++ self.flushing = self.closed = self.gone = False++ self.error: BaseException | None = None++ self.cond = threading.Condition()++ self.thread = threading.Thread(target=self._run, name="tf-playout", daemon=True)++ self.thread.start()++++ # -- the request thread -------------------------------------------------------------------------------------------++++ def put(self, delta: dict[str, Any], paced: bool = True) -> None:++ with self.cond:++ if self.closed or self.gone:++ return++ self.queue.append(_Item(delta, paced, self.clock()))++ self.paced += paced++ self.cond.notify()++++ def flush(self) -> None:++ with self.cond:++ self.flushing = True++ self.cond.notify()++++ def close(self) -> None:++ """Send everything still queued at once and stop the writer (the reply's end follows)."""++++ with self.cond:++ self.flushing = self.closed = True++ self.cond.notify()++ self.thread.join()++++ def abort(self) -> None:++ with self.cond:++ self.queue.clear()++ self.paced = 0++ self.closed = True++ self.cond.notify()++ self.thread.join()++++ # -- the writer ---------------------------------------------------------------------------------------------------++++ def due(self, now: float) -> float:++ """When the front of the queue goes out (the queue is not empty)."""++++ item = self.queue[0]++ if self.flushing or not item.paced or self.last is None:++ return now++ at = max(item.arrived, self.last + self.hold / max(self.paced, 1))++ return min(at, item.arrived + LONGEST_HOLD * self.hold)++++ def _run(self) -> None:++ while True:++ with self.cond:++ while True:++ if not self.queue:++ if self.closed:++ return++ self.cond.wait()++ continue++ now = self.clock()++ at = self.due(now)++ if at <= now:++ break++ self.cond.wait(at - now) # a new token shortens the wait; a flush ends it++ item = self.queue.popleft()++ self.paced -= item.paced++ held = item.paced and not self.flushing and now > item.arrived++ try:++ ok = not (held and self.cancelled is not None and self.cancelled()) and self.emit(item.delta)++ except BaseException as exc: # noqa: BLE001 re-raised by the request after generate++ self.error, ok = exc, False++ with self.cond:++ self.last = self.clock()++ if not ok:++ self.gone = True++ self.queue.clear()++ self.paced = 0++ returndiff --git a/patches/0062-glm-sliced-fill.patch b/patches/0062-glm-sliced-fill.patchnew file mode 100644index 0000000..e0d56c2--- /dev/null+++ b/patches/0062-glm-sliced-fill.patch@@ -0,0 +1,819 @@+diff --git tensorfold/cuda/server.py tensorfold/cuda/server.py+index 21f81ef..70a5c34 100644+--- tensorfold/cuda/server.py++++ tensorfold/cuda/server.py+@@ -540,6 +540,9 @@ class App:+ from tensorfold.vision.qwen_processing import continued++ extra["vision"] = continued(prepared.vision, ids, self.vision.frontend.config)++ # generate_gated wraps on_tokens: attach the poll to the actual callback++ # reaching the scheduler, without invoking its streaming/pacing state.++ feed.cancelled = cancelled+ stats = self.engine.generate(ids, count, sampling, feed, **extra)+ if not cached:+ cached.append(int((stats or {}).get("cached") or 0))+diff --git tensorfold/families/glm5_next/cuda/decode.py tensorfold/families/glm5_next/cuda/decode.py+index 9b80e31..be872ae 100644+--- tensorfold/families/glm5_next/cuda/decode.py++++ tensorfold/families/glm5_next/cuda/decode.py+@@ -558,6 +558,25 @@ def prefill_chunk(e: Engine, prompt: Sequence[int], start: int, R: int, *, draft+ return out++++def prefill_chunk_steps(e: Engine, prompt: Sequence[int], start: int, R: int, *, drafter=None, feed=None,++ head: bool = True):++ """The concurrent prompt path, with a yield per layer and commit only after the final slice."""++ from .forward import compute_steps++++ w, st, b = e.w, e.st, e.pbuf++ chunk = list(prompt[start:start + R])++ inject = feed.chunk(start, R) if feed is not None else None++ out = yield from compute_steps(w, st, b, stage(w, st, b, chunk), nch=chunks_for(st, R),++ host_pos=st.pos, inject=inject, head=head)++ out = out.clone() if head else None++ e.last_hidden = b.fnormed[R - 1:R].clone()++ if drafter is not None:++ drafter.add_taps(e.tap_rows(R, b))++ with prof.timed("commit"):++ commit(w, st, b, R, R)++ return out+++++ def _absorb_rows(e: Engine, hidden: torch.Tensor, next_tokens: Sequence[int]) -> None:+ """A prompt's rows into the MTP cache through the prefill buffers (the prefill arithmetic, like the prompt)."""++diff --git tensorfold/families/glm5_next/cuda/engine.py tensorfold/families/glm5_next/cuda/engine.py+index 267e84c..e4170a4 100644+--- tensorfold/families/glm5_next/cuda/engine.py++++ tensorfold/families/glm5_next/cuda/engine.py+@@ -533,7 +533,9 @@ class GlmEngine:+ verify_code = 1 + ("batched", "serial").index(verify_kind())+ from .multi_tune import MultiSettings++- verify_code = [verify_code] + MultiSettings.from_env().code()++ from .sliced_fill import budget_ms++++ verify_code = [verify_code] + MultiSettings.from_env().code() + _f64_ints(budget_ms())+ else:+ verify_code = [verify_code]+ # both ranks must run the same calls: refuse to start when they were given different settings+@@ -679,7 +681,8 @@ class GlmEngine:+ f"in one pool of {pool_rows} tokens (each up to {self.limit}); DFlash2 drafts, prompt chunks of "+ f"{self.multi.fill_rows} rows while others decode (TF_GLM_FILL_ROWS, TF_GLM_FILL_SHARE "+ f"{self.multi.share:g}){'; waiting prompts share prompt chunks (TF_GLM_MULTI_PREFILL)' if self.multi.group else ''}; "+- f"{self.multi.tune.describe()}", flush=True)++ f"{self.multi.tune.describe()}"++ f"{f'; prompt layer slices target {self.multi.fill_budget:g} ms' if self.multi.fill_budget else ''}", flush=True)+ if self.multi.row_ms is not None:+ print("[tensorfold] --parallel batched window ms by rows: " ++ " ".join(f"{i + 1}:{ms:.1f}" for i, ms in enumerate(self.multi.row_ms)), flush=True)+diff --git tensorfold/families/glm5_next/cuda/forward.py tensorfold/families/glm5_next/cuda/forward.py+index c32686e..f1c4d14 100644+--- tensorfold/families/glm5_next/cuda/forward.py++++ tensorfold/families/glm5_next/cuda/forward.py+@@ -856,8 +856,8 @@ def layer_forward(layer: LayerW, w: Weights, st: State, b: Buffers, R: int, nch:+ glue.hc_post(x, x, g, b.post[:R], b.comb[:R])+++-def split_layers(w: Weights, st: State, b: Buffers, R: int, nch: int | None, host_pos: int | None,+- mixer=None) -> None:++def split_layer_steps(w: Weights, st: State, b: Buffers, R: int, nch: int | None, host_pos: int | None,++ mixer=None):+ """Every layer of a prompt chunk with its hyper-connection glue split by rows between the ranks+ (``hcsplit``): the first hc_pre runs on every row as unsplit, each later one on this rank's rows, and b.normed,+ the taps and b.hidden come back whole from the peer. The same bits as the unsplit loop and its final mean.+@@ -890,10 +890,60 @@ def split_layers(w: Weights, st: State, b: Buffers, R: int, nch: int | None, hos+ sp.glue(nxt.attn_hc if nxt is not None else None, nxt.in_norm if nxt is not None else None,+ taps=tuple(b.tap_at.get(layer.index, ())), final=nxt is None, front=front)+ done = sp.own() if front is not None else None++ yield layer.index+ finally:+ sp.finish()++++def split_layers(w: Weights, st: State, b: Buffers, R: int, nch: int | None, host_pos: int | None,++ mixer=None) -> None:++ for _ in split_layer_steps(w, st, b, R, nch, host_pos, mixer):++ pass++++++def compute_steps(w: Weights, st: State, b: Buffers, R: int, *, nch: int | None = None,++ host_pos: int | None = None, inject=None, head: bool = True, mixer=None):++ """Prompt-only forward yielding after each complete layer; returns the head on exhaustion.++++ All live rows, taps and overlapped fronts stay in the engine's dedicated pbuf. A split boundary retains++ only this rank's hidden rows plus the already prepared next front, exactly as the uninterrupted split loop.++ The scheduler drains CUDA before a decode round; verify never borrows pbuf. KDA's global temporary scratch++ is consumed inside a layer, so nothing in it needs to survive this yield.++ """++ if not b.prefill:++ raise ValueError("layer-sliced forwards require prompt buffers")++ c = w.cfg++ glue.embed(b.ids[:R], w.embed, c.hidden, c.streams, b.x[:R])++ if inject is not None:++ rows, features = inject++ b.x.index_copy_(0, rows, features.repeat(1, c.streams))++ split = b.split is not None and b.split.applies(R)++ if split:++ steps = split_layer_steps(w, st, b, R, nch, host_pos, mixer)++ try:++ for i in steps:++ b.split.finish() # main stream joins the overlap exchanges/fronts++ yield i++ # A decode round may have used the main stream since the last yield. Geometry and prompt++ # buffers remain intact; the overlap stream must join the new main-stream work before reuse.++ if b.split.stream is not None:++ b.split.stream.wait_stream(torch.cuda.current_stream())++ b.split.active = True++ finally:++ steps.close()++ else:++ for layer in w.layers:++ layer_forward(layer, w, st, b, R, nch, host_pos, None, mixer)++ for slot in b.tap_at.get(layer.index, ()):++ glue.stream_mean(b.x[:R], b.taps[slot][:R])++ yield layer.index++ glue.stream_mean(b.x[:R], b.hidden[:R])++ glue.rmsnorm(b.hidden[:R], w.norm, c.eps, b.fnormed[:R], b.fxs[:R])++ if head:++ return mm(b, b.fnormed[R - 1:R], w.head, b.fxs[R - 1:R], b.logits[:1])++ return None+++++ def check_room(w: Weights, st: State, R: int, pos: int | None = None) -> None:+ pos = st.pos if pos is None else pos+ if pos + R > w.cfg.dense_limit and st.index is None:+diff --git tensorfold/families/glm5_next/cuda/multi.py tensorfold/families/glm5_next/cuda/multi.py+index 9c66222..1b2efbc 100644+--- tensorfold/families/glm5_next/cuda/multi.py++++ tensorfold/families/glm5_next/cuda/multi.py+@@ -8,7 +8,8 @@ window scratch; a DFlash2 context, ``dflash2_multi.DraftContext``; host side its++ Iterations (``GlmScheduler``, one worker thread on rank 0): admissions, then either one prompt chunk of the oldest+ filling stream (FIFO, at most TF_GLM_FILL_ROWS rows while others decode, the engine's prompt chunk alone) or one+-decode round, alternating by TF_GLM_FILL_SHARE; a prompt chunk never shares a forward with decode rows. With++decode round, alternating by TF_GLM_FILL_SHARE; a prompt chunk never shares a forward with decode rows. TF_GLM_FILL_BUDGET_MS>0++yields between layer slices of a busy fill, retaining its prompt buffers while a decode round runs. With+ TF_GLM_MULTI_PREFILL=1 a prompt chunk holds the next rows of several filling streams (``multi_prefill``: each+ stream's rows get the bits of a chunk of their own; the shortest remaining prompts first, within the same row+ budget). A round: each+@@ -16,10 +17,14 @@ decoding stream (admission order) proposes drafts under its own DFlash2 policy (+ window is capped at ``MAX_WINDOW`` rows (the longest tails trimmed), one verify over every stream's rows+ (``forward_streams``: ``verify.BatchedVerify``, one forward over every stream's rows through the segmented KDA and+ DSA kernels, or ``verify.SerialVerify``, the reference running each window as its own forward; TF_GLM_MULTI_VERIFY),+-one packed all-gather for the samplers, each stream accepts and commits its own.++one packed all-gather for the samplers, each stream accepts and commits its own. Between prompt slices, a++round takes one token per stream without drafts to keep its latency and the newcomer's inserted work small;++TF_GLM_FILL_SHARE applies to unsliced fills, slices alternate with these short rounds. Contiguous layer ranges++are balanced within the budget without adding rounds; GPU layer cost, finalization and dispatch overhead are++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, ROUND, FINISH, IDLE, which both ranks apply++ONE message (``GlmEngine._share``): ops ADMIT, EVICT, MOVE, 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.+@@ -42,14 +47,14 @@ import torch+ from tensorfold.cuda.scheduler import Scheduler+ from tensorfold.cuda.streams import Stream, next_fill++-from . import multi_prefill++from . import multi_prefill, 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 = range(1, 11)++ADMIT, EVICT, MOVE, GROW, FILL, ROUND, FINISH, IDLE, SLOT, MFILL, FILLPART, MFILLPART = range(1, 13)+ OPS = {ADMIT: "ADMIT", EVICT: "EVICT", MOVE: "MOVE", GROW: "GROW", FILL: "FILL", ROUND: "ROUND", FINISH: "FINISH",+- IDLE: "IDLE", SLOT: "SLOT", MFILL: "MFILL"}++ IDLE: "IDLE", SLOT: "SLOT", MFILL: "MFILL", FILLPART: "FILLPART", MFILLPART: "MFILLPART"}+++ def watchdog_seconds(value: str | None = None) -> float:+@@ -337,6 +342,12 @@ class MultiDecoder:+ self.arena = e.caches.arena+ self.grid = engine.grid+ self.fill_rows = fill_rows(e.prefill_rows, self.grid)++ self.fill_budget = sliced_fill.budget_ms()++ self.fill_drafts = sliced_fill.drafted_rounds() # rank 0 decides; the ROUND message carries it++ self.partial = None++ self.fill_costs = None++ self.decode_due = False++ self.short_round_due = False+ self.share = fill_share()+ self.credit = 0.0+ # TF_GLM_MULTI_PREFILL: rank 0 groups filling streams into one chunk (rank 1 applies whatever MFILL it gets)+@@ -394,6 +405,8 @@ class MultiDecoder:+ self.requeue: list[Stream] = [] # rank 0: streams given back to the scheduler's queue+ self.eos = tuple(self.w.cfg.eos)+ self.dflash_code = encode_policy(DFLASH_POLICY)++ if self.fill_budget:++ self.fill_costs = self._time_prompt_layers()++ # -- the scheduler's view ----------------------------------------------------------------------------------------+ @property+@@ -433,7 +446,7 @@ class MultiDecoder:+ self.g._ring()+ self.idle = False+ msg, self.outbox = self.outbox, []+- if self.tune.async_msg:++ if self.tune.async_msg or (self.fill_budget and (self.partial is not None or self.short_round_due)):+ self._send(msg)+ else:+ self.g._share(msg)+@@ -486,6 +499,45 @@ class MultiDecoder:+ self.g.comm.all_gather(mine, got)+ return [float(x) for x in got.view(2, -1).max(dim=0).values.tolist()]+++ @torch.no_grad()++ def _time_prompt_layers(self):++ """Both ranks calibrate isolated prompt forwards before requests are admitted (0 budget: no work)."""++ from .decode import prefill_chunk_steps++ from .verify import timing_tokens++++ e = self.e++ samples = {}++ prev = e.use(e.home)++ try:++ # Warm kernels first; this never publishes a kept prompt or draft context.++ e.reset()++ for _ in prefill_chunk_steps(e, timing_tokens(self.w.cfg.vocab, 64), 0, 64, head=False):++ pass++ for rows in sorted({min(r, self.fill_rows) for r in (64, 256, 512, 1024)} | {self.fill_rows}):++ e.reset()++ for _ in prefill_chunk_steps(e, timing_tokens(self.w.cfg.vocab, rows), 0, rows, head=False):++ pass # shape-specific warmup before its measured pass++ e.reset()++ events = [torch.cuda.Event(enable_timing=True) for _ in range(len(self.w.layers) + 2)]++ steps = prefill_chunk_steps(e, timing_tokens(self.w.cfg.vocab, rows), 0, rows, head=False)++ events[0].record()++ for i, _ in enumerate(steps):++ events[i + 1].record()++ events[-1].record()++ events[-1].synchronize()++ costs = [events[i].elapsed_time(events[i + 1]) for i in range(len(self.w.layers))]++ mine = torch.tensor(costs, dtype=torch.float32, device=self.w.device)++ if self.w.comm is not None:++ got = torch.empty((self.w.world * mine.numel(),), dtype=mine.dtype, device=mine.device)++ self.w.comm.all_gather(mine, got)++ costs = got.view(self.w.world, -1).max(dim=0).values.cpu().tolist()++ samples[rows] = costs++ finally:++ e.reset()++ e.last_hidden = None++ e.use(prev)++ return sliced_fill.LayerCosts(samples)+++ def _compare_paths(self, reps: int = 5) -> None:+ """TF_GLM_MULTI_PROFILE (at startup, on both ranks: the graphs all-gather; rank 0 prints): a lone stream's+ verify window on the one-stream graphs and on the batched graphs, ms by rows up to the one-stream graphs'+@@ -526,8 +578,18 @@ class MultiDecoder:+ def parse(msg: Sequence[int]) -> list[tuple[int, list[int]]]:+ ops, i = [], 0+ while i < len(msg):++ if i + 2 > len(msg):++ raise RuntimeError("truncated multi-stream op header")+ op, n = int(msg[i]), int(msg[i + 1])+- ops.append((op, [int(v) for v in msg[i + 2:i + 2 + n]]))++ if op not in OPS or n < 0 or i + 2 + n > len(msg):++ raise RuntimeError("invalid multi-stream op or payload length")++ p = [int(v) for v in msg[i + 2:i + 2 + n]]++ if op == FILLPART and (len(p) != 4 or not 0 <= p[2] < p[3]):++ raise RuntimeError("invalid FILLPART payload")++ 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")++ ops.append((op, p))+ i += 2 + n+ return ops++@@ -832,6 +894,8 @@ class MultiDecoder:+ used = max([len(k.ids) for k in x.kept], default=0)+ if x.owner is not None:+ used = max(used, self.lanes[x.owner].st.pos)++ if self.partial is not None:++ used = max([used] + [stop for lane, stop in self.partial.group if lane.extent is x])+ return used++ def _move(self, x, base: int, size: int) -> None:+@@ -930,7 +994,12 @@ class MultiDecoder:+ if not filling:+ return None+ decoding = [l for l in self.lanes.values() if l.decoding and not l.paused and not l.s.done]+- if decoding:++ if decoding and self.fill_budget and self.decode_due:++ self.decode_due = False++ return None++ if self.partial is not None:++ return self.partial.group[0][0]++ if decoding and not self.fill_budget:+ self.credit += self.share+ if self.credit < 1:+ return None+@@ -939,9 +1008,26 @@ class MultiDecoder:+ return self.lanes[s.sid]++ def _iterate(self) -> list[Stream]:++ if self.fill_budget:++ cancelled = []++ for lane in self.lanes.values():++ poll = getattr(lane.s.emit, "cancelled", None)++ if not lane.decoding and not lane.s.done and poll is not None and poll():++ lane.s.done = True++ lane.s.started = lane.s.finished = time.perf_counter()++ cancelled.append(lane.s)++ if cancelled:++ return cancelled # finish() mirrors cancellation and retires partial groups+ prof = self.profiles[False] if self.profiles is not None else None # prompt chunks count there+ lane = self._fill_turn()++ if self.partial is not None and lane is not None:++ return self._part_iteration()+ group = self._group(lane) if lane is not None and self.group else None++ busy = any(l.decoding and not l.s.done and not l.paused for l in self.lanes.values())++ if lane is not None and busy and self.fill_budget and lane.head is None:++ self.partial = sliced_fill.PendingFill(group if group is not None else [(lane, self._stop(lane))],++ many=group is not None)++ return self._part_iteration()+ if group is not None:+ t = time.perf_counter()+ rows = sum(stop - l.st.pos for l, stop in group)+@@ -988,15 +1074,87 @@ class MultiDecoder:+ if prof is not None:+ prof.begin(t_begin)+ plan = [(l.sid, l.depth) for l in active]+- self._emit(ROUND, [len(plan), *[v for p in plan for v in p], int(lone)])++ short = self.short_round_due++ self._emit(ROUND, [len(plan), *[v for p in plan for v in p], int(lone), int(short)])+ if prof is not None:+ prof.mark("plan")+ self._flush()++ self.short_round_due = False+ if prof is not None:+ prof.mark("message")+- self._round(active, lone=lone)++ self._round(active, lone=lone, short=short)+ return [l.s for l in active if l.s.done]+++ def _part_iteration(self) -> list[Stream]:++ pending = self.partial++ lo = pending.layer++ busy = any(l.decoding and not l.paused and not l.s.done for l in self.lanes.values())++ hi = self.fill_costs.stop(pending.rows, lo, self.fill_budget) if busy else len(self.w.layers)++ if pending.many:++ payload = [len(pending.group), lo, hi, *[v for lane, stop in pending.group for v in (lane.sid, stop)]]++ self._emit(MFILLPART, payload)++ else:++ lane, stop = pending.group[0]++ self._emit(FILLPART, [lane.sid, stop, lo, hi])++ self._flush()++ done = self._part(pending.group, lo, hi, pending.many)++ pending.layer_ms += pending.slice_layer_ms++ if hi == len(self.w.layers):++ tail = max(0.0, pending.slice_wall_ms - pending.slice_layer_ms - self.fill_costs.overhead)++ self.fill_costs.observe_tail(pending.rows, tail)++ self.fill_costs.observe(pending.rows, 0, hi, pending.layer_ms)++ else:++ self.fill_costs.observe_overhead(max(0.0, pending.slice_wall_ms - pending.slice_layer_ms))++ self.decode_due = True++ self.short_round_due = not self.fill_drafts++ return done++++ @torch.no_grad()++ def _part(self, group, lo: int, hi: int, many: bool) -> list[Stream]:++ """Both ranks: apply one contiguous slice, including publication only on its final layer."""++ if not group or any(l.decoding or stop != self._stop_bound(l, stop) for l, stop in group):++ raise RuntimeError("a prompt slice contains a decoding stream or crosses a kept point")++ if self.partial is None:++ if lo:++ raise RuntimeError("a resumed prompt slice has no pending chunk")++ self.partial = sliced_fill.PendingFill(list(group), many=many)++ pending = self.partial++ if pending.many != many or [(l.sid, stop) for l, stop in group] != [(l.sid, stop) for l, stop in pending.group]:++ raise RuntimeError("a prompt slice changed its chunk")++ t = time.perf_counter()++ begin = torch.cuda.Event(enable_timing=True)++ pending.layer_event = torch.cuda.Event(enable_timing=True)++ begin.record()++ before = [lane.s.prefill_s for lane, _ in group]++ if many:++ firsts = self._fill_many(group, layers=(lo, hi))++ else:++ lane, stop = group[0]++ firsts = [self._fill(lane, stop, layers=(lo, hi))]++ if hi < len(self.w.layers):++ pending.layer_event.record()++ # finish() joins HC overlap; drain all device work before the next iteration can run decode graphs.++ torch.cuda.synchronize(self.w.device)++ dt = time.perf_counter() - t++ pending.slice_wall_ms = dt * 1000++ pending.slice_layer_ms = begin.elapsed_time(pending.layer_event)++ for (lane, _), elapsed in zip(group, before):++ lane.s.prefill_s = elapsed + dt # include the slice's GPU execution, not just its enqueue++ for (lane, _), first in zip(group, firsts):++ if first is not None and lane.sid not in pending.retired:++ lane.s.take([first], self._ends(lane))++ done = [l.s for l, _ in group if l.s.done and l.sid not in pending.retired]++ if hi == len(self.w.layers):++ pending.close()++ self.partial = None++ for sid in pending.retired:++ self._finish(sid)++ if many and self.rank == 0:++ self.grouped["chunks"] += 1++ self.grouped["pieces"] += len(group)++ self.grouped["rows"] += pending.rows++ return done+++ def _home(self, lane: Lane) -> bool:+ """Rank 0: a lone stream into the one-stream graphs' home, slot 0 at the pool's first rows (SLOT, then+ kept prompts in the way evicted and its extent MOVEd); True once it is there."""+@@ -1083,11 +1241,11 @@ class MultiDecoder:+ return self.eos if lane.s.stop_eos else ()++ @torch.no_grad()+- def _fill(self, lane: Lane, stop: int) -> int | None:++ def _fill(self, lane: Lane, stop: int, *, layers=None) -> int | None:+ """Both ranks: the lane's prompt rows pos .. stop in one chunk; its kept states; at the prompt's end its first+ token (the stream then decodes)."""++- from .decode import prefill_chunk++ from .decode import prefill_chunk, prefill_chunk_steps++ e = self.e+ s = lane.s+@@ -1103,8 +1261,16 @@ class MultiDecoder:+ if replay:+ out, lane.head = lane.head, None+ else:+- out = prefill_chunk(e, prompt, start, stop - start, drafter=self._ctx(lane) if lane.dflash else None,+- feed=lane.feed, mtp=False, head=stop == n)++ if layers is None:++ out = prefill_chunk(e, prompt, start, stop - start, drafter=self._ctx(lane) if lane.dflash else None,++ feed=lane.feed, mtp=False, head=stop == n)++ else:++ complete, out = sliced_fill.advance(self.partial, *layers, len(self.w.layers),++ lambda: prefill_chunk_steps(e, prompt, start, stop - start,++ drafter=self._ctx(lane) if lane.dflash else None, feed=lane.feed, head=stop == n),++ before_finalize=self.partial.layer_event.record)++ if not complete:++ return None+ if stop < n:+ if stop in lane.stops:+ self._keep(lane, stop)+@@ -1140,7 +1306,7 @@ class MultiDecoder:+ lane.depth = min(lane.policy.next(0, 0), s.count - 1)++ @torch.no_grad()+- def _fill_many(self, group: Sequence[tuple[Lane, int]]) -> list[int | None]:++ def _fill_many(self, group: Sequence[tuple[Lane, int]], *, layers=None) -> list[int | None]:+ """Both ranks, TF_GLM_MULTI_PREFILL: every (lane, stop)'s prompt rows pos .. stop in ONE chunk+ (``multi_prefill.prefill_pieces``: each lane's rows the bits of a chunk of their own); then per lane, in+ order, what ``_fill`` does after its chunk: its kept states, and at its prompt's end its first token (all+@@ -1157,9 +1323,21 @@ class MultiDecoder:+ pieces.append(multi_prefill.Piece(lane.st, list(lane.s.prompt[start:stop]),+ drafter=self._ctx(lane) if lane.dflash else None, head=stop == n))+ t = time.perf_counter()+- heads = multi_prefill.prefill_pieces(e, pieces)++ if layers is None:++ heads = multi_prefill.prefill_pieces(e, pieces)++ else:++ complete, heads = sliced_fill.advance(self.partial, *layers, len(self.w.layers),++ lambda: multi_prefill.prefill_piece_steps(e, pieces),++ before_finalize=self.partial.layer_event.record)++ if not complete:++ dt = time.perf_counter() - t++ for lane, _ in group:++ lane.s.prefill_s += dt++ return [None] * len(group)+ parts, who = [], []+ for k, ((lane, stop), out) in enumerate(zip(group, heads)):++ if self.partial is not None and lane.sid in self.partial.retired:++ continue+ n = len(lane.s.prompt)+ if stop < n:+ if stop in lane.stops:+@@ -1187,9 +1365,11 @@ class MultiDecoder:+ return firsts++ @torch.no_grad()+- def _round(self, lanes: list[Lane], depths: list[int] | None = None, lone: bool = False) -> None:++ def _round(self, lanes: list[Lane], depths: list[int] | None = None, lone: bool = False,++ short: bool = False) -> None:+ """Both ranks: one decode round over ``lanes`` (``depths``: rank 0's, checked on rank 1); ``lone``: one+- stream at home, verified through the one-stream graphs when its window fits them."""++ stream at home, verified through the one-stream graphs when its window fits them. ``short``: between fill++ slices, commit one token per stream without proposing drafts (the same keyed sample, lower round cost)."""++ from .decode import copy_room+ from .dflash2_multi import DraftRequest+@@ -1202,10 +1382,10 @@ class MultiDecoder:+ copied: list[bool] = []+ asks = []+ for l in lanes:+- c = l.copies.propose(copy_room(l.copies, l.s.count, l.s.out)) if l.copies is not None else []++ c = l.copies.propose(copy_room(l.copies, l.s.count, l.s.out)) if l.copies is not None and not short else []+ copied.append(bool(c))+ drafts.append(list(c))+- if not c and l.dflash and l.depth > 0:++ if not short and not c and l.dflash and l.depth > 0:+ conf = l.policy.confidence+ if tune.depth == "scale":+ conf = scaled_confidence(conf, len(lanes), tune.alpha)+@@ -1245,7 +1425,9 @@ class MultiDecoder:+ if l.window is not None:+ l.constraint.mask(logits, l.window, self.w.vocab_offset)+ parts.append((logits, [l.st.pos + 1 + r for r in range(len(seg.tokens))], l.s.sampling))+- sampled = sample_packed(self.w, parts) if tune.sampler == "packed" else sample_streams(self.w, parts)++ # A short round has one row per stream: pack nucleus gathers too, avoiding++ # repeated rank exchanges between prompt slices with the same exact draws.++ sampled = sample_packed(self.w, parts) if short or tune.sampler == "packed" else sample_streams(self.w, parts)+ if prof is not None:+ prof.mark("sample")+ keeps = []+@@ -1282,7 +1464,9 @@ class MultiDecoder:+ l.copy_accepted += keep - 1+ room = s.count - len(s.out)+ s.take(new[:max(0, room)], self._ends(l))+- if l.policy is not None:++ if short:++ l.depth = min(l.depth, max(0, s.count - len(s.out)))++ elif l.policy is not None:+ l.depth = min(l.policy.next(*((0, 0) if was_copy else (ndrafts, keep - 1))),+ max(0, s.count - len(s.out)))+ if prof is not None:+@@ -1325,6 +1509,7 @@ class MultiDecoder:+ self._emit(FINISH, [lane.sid, reason])+ self._finish(lane.sid)+ if not self.lanes and not self.idle and self.broken is None:++ self.decode_due = self.short_round_due = False+ self._emit(IDLE, [])+ self._flush()+ self.idle = True+@@ -1333,6 +1518,17 @@ class MultiDecoder:+ def _finish(self, sid: int) -> None:+ """Both ranks: the stream's slot frees; its extent stays for its kept prompts (shrunk to them) or goes."""+++ pending = self.partial++ if pending is not None and pending.contains(sid):++ pending.retired.add(sid)++ if len(pending.retired) < len(pending.group):++ self.lanes[sid].s.done = True++ return # reserved slot/extent until the shared forward completes++ pending.close()++ torch.cuda.synchronize(self.w.device)++ self.partial = None++ for retired in pending.retired - {sid}:++ self._finish(retired)+ lane = self.lanes.pop(sid)+ x = lane.extent+ x.owner = None+@@ -1363,6 +1559,9 @@ class MultiDecoder:+ """After an error in an iteration: forget every stream (the ranks can no longer be trusted to agree)."""++ live = [l.s for l in self.lanes.values()]++ if self.partial is not None:++ self.partial.close()++ self.partial = None+ self.lanes = {}+ if self.broken is None:+ self.broken = RuntimeError("an iteration failed")+@@ -1442,11 +1641,19 @@ class MultiDecoder:+ for (lane, _), first in zip(group, self._fill_many(group)):+ if first is not None:+ lane.s.take([first], self._ends(lane))++ elif op == FILLPART:++ sid, stop, lo, hi = p++ self._part([(self.lanes[sid], stop)], lo, hi, False)++ elif op == MFILLPART:++ n, lo, hi = p[:3]++ group = [(self.lanes[sid], stop) for sid, stop in zip(p[3::2], p[4::2])]++ self._part(group, lo, hi, True)+ elif op == ROUND:+ n = p[0]+ sids, depths = p[1:1 + 2 * n:2], p[2:2 + 2 * n:2]+ lone = bool(p[1 + 2 * n]) if len(p) > 1 + 2 * n else False+- self._round([self.lanes[sid] for sid in sids], depths, lone=lone)++ short = bool(p[2 + 2 * n]) if len(p) > 2 + 2 * n else False++ self._round([self.lanes[sid] for sid in sids], depths, lone=lone, short=short)+ elif op == SLOT:+ self._reslot(self.lanes[p[0]], p[1])+ elif op == FINISH:+@@ -1487,6 +1694,7 @@ class GlmScheduler(Scheduler):+ stream.glm = dict(glm or {})+ cancel = [False]+ stream.emit = lambda new: (box.put(("tokens", new)), cancel[0])[1]++ stream.emit.cancelled = getattr(emit, "cancelled", None)+ self.waiting.put((stream, box))+ while True:+ kind, value = box.get()+diff --git tensorfold/families/glm5_next/cuda/multi_prefill.py tensorfold/families/glm5_next/cuda/multi_prefill.py+index da57788..474753d 100644+--- tensorfold/families/glm5_next/cuda/multi_prefill.py++++ tensorfold/families/glm5_next/cuda/multi_prefill.py+@@ -183,3 +183,29 @@ def prefill_pieces(e, pieces: Sequence[Piece]) -> list[torch.Tensor | None]:+ for p in pieces:+ commit(w, p.st, b, p.rows, p.rows)+ return heads++++++def prefill_piece_steps(e, pieces: Sequence[Piece]):++ """Sliced counterpart of prefill_pieces; no position/tap publication before the final slice."""++ from . import latent++ from .forward import commit, compute_steps, mm++++ if not latent.ENABLED:++ raise ValueError("multi-prompt chunks need the latent cache (TF_GLM_LATENT=1)")++ w, b = e.w, e.pbuf++ R = layout(pieces, b.rows)++ _stage(w, b, pieces, R)++ yield from compute_steps(w, None, b, R, head=False, mixer=PieceMixer(w, b, pieces, R))++ heads = []++ for p in pieces:++ if p.head:++ r = p.lo + p.rows - 1++ heads.append(mm(b, b.fnormed[r:r + 1], w.head, b.fxs[r:r + 1], b.logits[:1]).clone())++ else:++ heads.append(None)++ for p in pieces:++ if p.drafter is not None:++ p.drafter.add_taps(torch.cat([t[p.lo:p.lo + p.rows] for t in b.taps], dim=1))++ for p in pieces:++ commit(w, p.st, b, p.rows, p.rows)++ return heads+diff --git tensorfold/families/glm5_next/cuda/sliced_fill.py tensorfold/families/glm5_next/cuda/sliced_fill.py+new file mode 100644+index 0000000..26e82c5+--- /dev/null++++ tensorfold/families/glm5_next/cuda/sliced_fill.py+@@ -0,0 +1,169 @@++"""CPU policy and saved control state for opt-in layer-sliced concurrent prompt fills.++++The GPU rows live in Engine.pbuf, already counted by the startup memory estimate. Only one prompt chunk may++be suspended; its generator retains the HC split loop's next-front/done state. No additional GPU storage.++"""++from __future__ import annotations++++import math++import os++from dataclasses import dataclass, field++from typing import Any, Sequence++++++def budget_ms(value: str | None = None) -> float:++ value = os.environ.get("TF_GLM_FILL_BUDGET_MS", "") if value is None else value++ try:++ ms = float(value.strip() or "0")++ except ValueError:++ ms = -1.0++ if not math.isfinite(ms) or ms < 0:++ raise ValueError(f"TF_GLM_FILL_BUDGET_MS: finite milliseconds >= 0 (0: off), not {value!r}")++ return ms++++++def drafted_rounds(value: str | None = None) -> bool:++ """TF_GLM_FILL_DRAFTS: 1 makes the decode rounds between prompt slices full drafted rounds (more tokens for the++ decoding streams during a fill, a later first token for the filling one); 0 (default): one token per stream."""++++ raw = (os.environ.get("TF_GLM_FILL_DRAFTS", "") if value is None else value).strip() or "0"++ if raw not in ("0", "1"):++ raise ValueError(f"TF_GLM_FILL_DRAFTS: 0 or 1, not {raw!r}")++ return raw == "1"++++++class LayerCosts:++ """Startup timings at several row counts, interpolated separately for every KDA/DSA/dense layer.++++ The first cost includes embedding. Tail work and per-slice overhead are learned separately. A layer slower than the budget runs alone: CUDA++ kernels cannot be preempted, so this setting is a target, not a hard latency guarantee.++ """++ def __init__(self, samples: dict[int, Sequence[float]]) -> None:++ if not samples:++ raise ValueError("prompt cost model needs samples")++ self.samples = {r: tuple(float(v) for v in costs) for r, costs in sorted(samples.items())}++ self.layers = len(next(iter(self.samples.values())))++ if (not self.layers or any(r <= 0 or len(c) != self.layers or++ any(not math.isfinite(v) or v <= 0 for v in c)++ for r, c in self.samples.items())):++ raise ValueError("prompt costs need positive rows and equally sized finite positive layer timings")++ self.scale = 1.0++ self.overhead = 0.0++ self.tails: dict[int, float] = {}++++ def tail_cost(self, rows: int) -> float:++ if not self.tails:++ return 0.0++ lo = max((r for r in self.tails if r <= rows), default=min(self.tails))++ hi = min((r for r in self.tails if r >= rows), default=max(self.tails))++ if lo == hi:++ return self.tails[lo] * rows / lo++ t = (rows - lo) / (hi - lo)++ return self.tails[lo] + t * (self.tails[hi] - self.tails[lo])++++ def observe_tail(self, rows: int, ms: float) -> None:++ if rows > 0 and math.isfinite(ms) and ms >= 0:++ self.tails[rows] = 0.8 * self.tails[rows] + 0.2 * ms if rows in self.tails else ms++++ def observe_overhead(self, ms: float) -> None:++ if math.isfinite(ms) and ms >= 0:++ self.overhead = 0.8 * self.overhead + 0.2 * ms++++ def costs(self, rows: int) -> tuple[float, ...]:++ keys = list(self.samples)++ lo = max((r for r in keys if r <= rows), default=keys[0])++ hi = min((r for r in keys if r >= rows), default=keys[-1])++ if lo == hi:++ return tuple(v * self.scale for v in self.samples[lo])++ t = (rows - lo) / (hi - lo)++ return tuple((a + t * (b - a)) * self.scale for a, b in zip(self.samples[lo], self.samples[hi]))++++ def stop(self, rows: int, lo: int, budget: float) -> int:++ if not 0 <= lo < self.layers or not math.isfinite(budget) or budget <= 0:++ raise ValueError("slice needs a valid first layer and positive finite budget")++ costs = list(self.costs(rows))++ costs[-1] += self.tail_cost(rows)++ budget = max(0.001, budget - self.overhead)++ def greedy_end(start):++ end, ms = start + 1, costs[start]++ while end < self.layers and ms + costs[end] <= budget:++ ms += costs[end]++ end += 1++ return end++++ def pieces(start):++ count = 0++ while start < self.layers:++ start = greedy_end(start)++ count += 1++ return count++++ # Greedy gives the minimum number of contiguous slices. Among first cuts++ # that preserve that count, approach the mean cost instead of leaving a++ # tiny tail after several near-budget stalls. Never exceed the budget++ # except for one indivisible layer, as on the ordinary greedy path.++ count = pieces(lo)++ target = sum(costs[lo:]) / count++ ends = [hi for hi in range(lo + 1, greedy_end(lo) + 1) if pieces(hi) <= count - 1]++ return min(ends, key=lambda hi: (abs(sum(costs[lo:hi]) - target), -hi))++++ def observe(self, rows: int, lo: int, hi: int, ms: float) -> None:++ # Layer GPU time only: tail and dispatch cost must not inflate every layer's prediction.++ predicted = sum(self.costs(rows)[lo:hi])++ if predicted > 0 and math.isfinite(ms) and ms > 0:++ self.scale = min(8.0, max(0.5, self.scale * (0.8 + 0.2 * ms / predicted)))++++++@dataclass++class PendingFill:++ group: list[tuple[Any, int]]++ many: bool = False++ layer: int = 0++ steps: Any = None++ retired: set[int] = field(default_factory=set)++ layer_ms: float = 0.0++ layer_event: Any = None++ slice_layer_ms: float = 0.0++ slice_wall_ms: float = 0.0++ starts: list[int] = field(init=False)++++ def __post_init__(self) -> None:++ self.starts = [lane.st.pos for lane, _ in self.group]++++ @property++ def rows(self) -> int:++ return sum(stop - start for (_, stop), start in zip(self.group, self.starts))++++ def contains(self, sid: int) -> bool:++ return any(lane.sid == sid for lane, _ in self.group)++++ def close(self) -> None:++ if self.steps is not None:++ self.steps.close()++ self.steps = None++++++def advance(pending: PendingFill, lo: int, hi: int, layers: int, make_steps, before_finalize=None):++ """Run the requested contiguous layer range; return (complete, forward result)."""++ if not lo == pending.layer < hi <= layers:++ raise RuntimeError(f"out-of-order prompt slice [{lo}, {hi}), expected layer {pending.layer} of {layers}")++ if pending.steps is None:++ if lo:++ raise RuntimeError("a resumed prompt slice has no saved forward")++ pending.steps = make_steps()++ for _ in range(lo, hi):++ try:++ next(pending.steps)++ except StopIteration as exc:++ raise RuntimeError("prompt forward ended before its final layer") from exc++ pending.layer = hi++ if hi < layers:++ return False, None++ if before_finalize is not None:++ before_finalize()++ try:++ next(pending.steps) # final norm, taps, commit (after the last layer's yield)++ except StopIteration as result:++ pending.steps = None++ return True, result.value++ raise RuntimeError("prompt forward has more layers than the slice protocol")diff --git a/patches/0063-glm-kept-cap-superseded-first.patch b/patches/0063-glm-kept-cap-superseded-first.patchnew file mode 100644index 0000000..4fcbdd3--- /dev/null+++ b/patches/0063-glm-kept-cap-superseded-first.patch@@ -0,0 +1,48 @@+# Kept prompt cap: past TF_GLM_CACHE_ENTRIES a conversation's superseded (shorter) kept states go first, then the+# least recently used. By @Alexbob0 (PR #32), rebased on 0054. Same replies.++diff --git tensorfold/families/glm5_next/cuda/multi.py tensorfold/families/glm5_next/cuda/multi.py+index 1b2efbc..840d182 100644+--- tensorfold/families/glm5_next/cuda/multi.py++++ tensorfold/families/glm5_next/cuda/multi.py+@@ -132,6 +132,24 @@ def fill_share(value: str | None = None) -> float:+ return share++++def cap_victim(kept: list):++ """The kept prompt to drop past TF_GLM_CACHE_ENTRIES (``kept``: least recently used first). An extent's kept++ prompts are prefixes of its rows, so one shorter than another in its extent is an earlier point of that++ conversation, superseded by the longer one: those go first (the oldest that is not a shared-prefix state, then++ the oldest of any), then the least recently used. A conversation taking many turns thus drops its own earlier++ turns instead of the only state of a conversation that is waiting on a long reply. Deterministic in ``kept``'s++ order and extents, so both ranks drop the same one."""++++ longest: dict[int, int] = {}++ for c in kept:++ longest[id(c.extent)] = max(longest.get(id(c.extent), 0), len(c.ids))++ superseded = [c for c in kept if len(c.ids) < longest[id(c.extent)]]++ for c in superseded:++ if not getattr(c, "shared", False):++ return c++ return superseded[0] if superseded else kept[0]+++++ def multi_code(code: list[int], dflash: bool, dflash_policy: list[int]) -> list[int]:+ """A request's policy code under --parallel: serial stays serial; auto becomes TF_GLM_DFLASH_POLICY; an MTP+ policy its DFlash2 twin; without a draft model, serial."""+@@ -854,13 +872,14 @@ class MultiDecoder:+ snap.kid = self.next_kid+ self.next_kid += 1+ snap.extent = lane.extent++ snap.shared = n in lane.shared+ # the same ids: the same prompt, unless pictures are in it (rank 1 has no keys; rank 0 resumes by key)+ for c in [c for c in self.kept if c.ids == snap.ids and not (c.images or snap.images)]:+ self._drop(c)+ lane.extent.kept.append(snap)+ self.kept.append(snap)+ while len(self.kept) > max(1, self.g.cache_entries):+- self._drop(self.kept[0])++ self._drop(cap_victim(self.kept))++ def _drop(self, c) -> None:+ """Forget a kept prompt; its extent goes when nothing else holds it, else shrinks to what is kept."""diff --git a/patches/0064-glm-split-connect-early.patch b/patches/0064-glm-split-connect-early.patchnew file mode 100644index 0000000..6f621b3--- /dev/null+++ b/patches/0064-glm-split-connect-early.patch@@ -0,0 +1,22 @@+# TF_GLM_HC_SPLIT=1: the split's send/receive connection opens before the weights and the cache pool, so NCCL's+# buffer registration no longer fails with ENOMEM on some Spark pairs (issue #36). MiaAI-Lab, Apache-2.0.++diff --git tensorfold/families/glm5_next/cuda/engine.py tensorfold/families/glm5_next/cuda/engine.py+index e4170a4..87f265f 100644+--- tensorfold/families/glm5_next/cuda/engine.py++++ tensorfold/families/glm5_next/cuda/engine.py+@@ -590,6 +590,14 @@ class GlmEngine:+ raise ValueError(("TF_GLM_MTP=0 leaves" if cfg.mtp_layers else "this checkpoint has") + " no MTP head and "+ "no DFlash2 draft model was given, so every round would decode one token: pull the draft "+ "model on both machines (--drafter), or pass --no-drafts to both for the serial reference")++ if self.split.split and self.split.exchange == "p2p" and getattr(self.comm, "world", 2) == 2 \++ and hasattr(self.comm, "exchange"):++ # both ranks: open the split's send/receive connection before the weights and the cache pool take the++ # memory; opened at the split's warm-up (after the pool), NCCL's buffer registration could fail with++ # ENOMEM (ibv_reg_mr, issue #36). The connection stays open; nothing it sends changes++ a = torch.zeros((1,), dtype=torch.float32, device="cuda")++ self.comm.exchange([a], [torch.empty_like(a)], 1 - rank)++ torch.cuda.synchronize()+ w = load(model_dir, rank=rank, mtp=self.mtp_on)+ w.comm = self.comm+ self.comm.ready("loading") # a peer stuck loading is named, not waited on in NCCLdiff --git a/patches/0065-glm-rank-checks.patch b/patches/0065-glm-rank-checks.patchnew file mode 100644index 0000000..d7e20c8--- /dev/null+++ b/patches/0065-glm-rank-checks.patch@@ -0,0 +1,129 @@+# Rank messages sealed with a sequence number and a checksum (a desync is a named error), TF_GLM_MULTI_WATCHDOG_EXIT=1+# (a stalled server exits after its stack dump), /health iteration_s (issue #29 diagnostics). MiaAI-Lab, Apache-2.0.++diff --git tensorfold/families/glm5_next/cuda/multi.py tensorfold/families/glm5_next/cuda/multi.py+index 840d182..4c7f64e 100644+--- tensorfold/families/glm5_next/cuda/multi.py++++ tensorfold/families/glm5_next/cuda/multi.py+@@ -71,13 +71,25 @@ def watchdog_seconds(value: str | None = None) -> float:+ return s++++def watchdog_exits(value: str | None = None) -> bool:++ """TF_GLM_MULTI_WATCHDOG_EXIT: 1 ends the process after the watchdog's first stack dump (a stalled server then++ exits with code 1, so a supervisor can restart it, instead of holding its requests forever); 0 (default): dumps++ every TF_GLM_MULTI_WATCHDOG_S and keeps waiting."""++++ raw = (os.environ.get("TF_GLM_MULTI_WATCHDOG_EXIT", "") if value is None else value).strip() or "0"++ if raw not in ("0", "1"):++ raise ValueError(f"TF_GLM_MULTI_WATCHDOG_EXIT: 0 or 1, not {raw!r}")++ return raw == "1"+++++ def _watch(seconds: float, what: str) -> None:+ if seconds > 0:+ import faulthandler+ import sys+++ stop = watchdog_exits()+ try: # the process's stderr (a test may have swapped sys.stderr)+- faulthandler.dump_traceback_later(seconds, repeat=True, file=sys.__stderr__, exit=False)++ faulthandler.dump_traceback_later(seconds, repeat=not stop, file=sys.__stderr__, exit=stop)+ except (ValueError, OSError, AttributeError): # no file descriptor to write to: no watchdog+ pass++@@ -89,6 +101,36 @@ def _unwatch(seconds: float) -> None:+ faulthandler.cancel_dump_traceback_later()++++SEAL_MOD = 2_147_483_647 # a message's checksum, modulo this prime (int32 on the wire)++++++def seal(msg: Sequence[int], seq: int) -> list[int]:++ """Rank 0: an iteration's message with its sequence number and a checksum appended (``unseal`` on rank 1)."""++++ return [*msg, seq, digest(msg, seq)]++++++def digest(msg: Sequence[int], seq: int) -> int:++ a = np.asarray(msg, dtype=np.int64) % SEAL_MOD++ w = np.arange(1, len(a) + 1, dtype=np.int64) % SEAL_MOD++ return int((int((a * w % SEAL_MOD).sum()) + seq * 1_000_003) % SEAL_MOD)++++++def unseal(msg: Sequence[int], seq: int) -> list[int]:++ """Rank 1: the message rank 0 sealed as number ``seq``, or a RuntimeError naming what differs: the ranks would++ otherwise apply different ops and wait on each other's collectives forever (issue #29's hangs had no error)."""++++ if len(msg) < 2:++ raise RuntimeError(f"rank 1: message {seq} from rank 0 is {len(msg)} values long, too short to be sealed; "++ "the ranks are out of step: restart both")++ body, got_seq, got = list(msg[:-2]), int(msg[-2]), int(msg[-1])++ if got_seq != seq or got != digest(body, got_seq):++ raise RuntimeError(f"rank 1: expected rank 0's message {seq}, received number {got_seq} "++ f"({'checksum matches' if got == digest(body, got_seq) else 'checksum differs'}, "++ f"{len(body)} values): the ranks are out of step: restart both")++ return body+++++ LONE_LEFT = 16 # a lone stream moves home only with at least this many tokens still to go+ DONE, CANCELLED, REQUEUED = 0, 1, 2 # FINISH reasons+ MAX_WINDOW = 32 # rows of every stream's windows together in one round+@@ -414,6 +456,9 @@ class MultiDecoder:+ self._compare_paths()+ self.msg = None # TF_GLM_MULTI_ASYNC: rank 0's pinned message staging+ self.watchdog = watchdog_seconds() # stack dumps of a stalled iteration (TF_GLM_MULTI_WATCHDOG_S)++ watchdog_exits() # TF_GLM_MULTI_WATCHDOG_EXIT read now: a typo fails at start++ self.iteration_since = None # when rank 0's current iteration began (/health)++ self.sent = self.received = 0 # messages sealed on rank 0, unsealed on rank 1+ self.lanes: dict[int, Lane] = {} # by sid, in admission order+ self.kept: list = [] # kept prompts (decode.Snapshot + kid, extent), oldest first+ self.next_sid = self.next_kid = self.next_order = 0+@@ -445,7 +490,10 @@ class MultiDecoder:+ "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(),+- "kept_prompts": len(self.kept), **({"multi_prefill": dict(self.grouped)} if self.group else {})}++ "kept_prompts": len(self.kept), **({"multi_prefill": dict(self.grouped)} if self.group else {}),++ # how long rank 0's current iteration has run (0 between iterations): a stalled server keeps growing it++ "iteration_s": round(time.monotonic() - since, 1)++ if (since := getattr(self, "iteration_since", None)) is not None else 0.0}++ def _check(self) -> None:+ if self.broken is not None:+@@ -463,7 +511,8 @@ class MultiDecoder:+ if self.idle:+ self.g._ring()+ self.idle = False+- msg, self.outbox = self.outbox, []++ msg, self.outbox = seal(self.outbox, self.sent), []++ self.sent = (self.sent + 1) % SEAL_MOD+ if self.tune.async_msg or (self.fill_budget and (self.partial is not None or self.short_round_due)):+ self._send(msg)+ else:+@@ -1002,6 +1051,7 @@ class MultiDecoder:++ self._check()+ _watch(self.watchdog, "iteration") # cancelled at the end of ``finish``++ self.iteration_since = time.monotonic() # /health's iteration_s+ try:+ return self._iterate()+ except Exception as exc:+@@ -1533,6 +1583,7 @@ class MultiDecoder:+ self._flush()+ self.idle = True+ _unwatch(self.watchdog)++ self.iteration_since = None++ def _finish(self, sid: int) -> None:+ """Both ranks: the stream's slot frees; its extent stays for its kept prompts (shrunk to them) or goes."""+@@ -1609,7 +1660,8 @@ class MultiDecoder:+ self.g._await_bell()+ self.idle = False+ _watch(self.watchdog, "rank 1 message") # busy: rank 0's next message is due within a round+- self.apply(self.g._share(None))++ self.apply(unseal(self.g._share(None), self.received))++ self.received = (self.received + 1) % SEAL_MOD+ _unwatch(self.watchdog)+ if once:+ returndiff --git a/patches/0066-glm-tp-n.patch b/patches/0066-glm-tp-n.patchnew file mode 100644index 0000000..35d17dc--- /dev/null+++ b/patches/0066-glm-tp-n.patch@@ -0,0 +1,2380 @@+diff --git tensorfold/cli.py tensorfold/cli.py+index 4ee0f43..c2e3768 100644+--- tensorfold/cli.py++++ tensorfold/cli.py+@@ -232,10 +232,14 @@ def _serve_cuda(args: argparse.Namespace, family: Any, model_dir: Path, context:++ from tensorfold import hub++- if args.tp == 2 and not args.master:+- raise ValueError("--tp 2 needs --master: rank 0's address on the link between the two machines")+- if args.tp == 1 and args.rank != 0:+- raise ValueError("--rank 1 needs --tp 2")++ tp, rank = int(args.tp), int(args.rank)++ if tp > 1 and not args.master:++ raise ValueError(f"--tp {tp} needs --master: rank 0's address on the link between the machines")++ if not 0 <= rank < tp:++ raise ValueError(f"--rank {rank} needs --tp {rank + 1} or more")++ sizes = tuple(getattr(family.package, "CUDA_TP", (1, 2))) # tensor-parallel sizes the family's engine runs++ if tp not in sizes:++ raise ValueError(f"{family.title} runs on CUDA with --tp {' or '.join(map(str, sizes))}, not {tp}")+ started = time.perf_counter()+ drafter = "" if args.no_drafts else _drafter(family, args.drafter)+ options: dict[str, Any] = {"drafter": drafter, "tp": int(args.tp), "rank": int(args.rank), "master": args.master,+@@ -259,7 +263,7 @@ def _serve_cuda(args: argparse.Namespace, family: Any, model_dir: Path, context:+ if getattr(args, "checkpoint_slots", None) is not None and getattr(family.package, "CUDA_CHECKPOINT_SLOTS", False):+ options["checkpoint_slots"] = int(args.checkpoint_slots)+ served = args.name or (args.model.rstrip("/").split("/")[-1] if hub.is_repo_id(args.model) else model_dir.name)+- where = f", rank {args.rank} of 2" if args.tp == 2 else ""++ where = f", rank {rank} of {tp}" if tp > 1 else ""+ print(f"[tensorfold] loading {served}: {family.title} ({family.model_type}) on CUDA{where}", flush=True)+ from tensorfold.cuda import prompt_precision++@@ -271,8 +275,8 @@ def _serve_cuda(args: argparse.Namespace, family: Any, model_dir: Path, context:+ raise ValueError("--prefill-fp8: this checkpoint's prompt matmuls have no FP8 kernel (EXL3 packs, MLX formats "+ "other than Qwen's 4-bit g64, Flash Next without MXFP8 layers); drop the flag")+ stacks.arm() # its warmup may have loaded a compiler that took USR1+- if args.tp == 2 and args.rank == 1:+- print(f"[tensorfold] rank 1 ready in {time.perf_counter() - started:.1f}s, following rank 0", flush=True)++ if tp > 1 and rank > 0:++ print(f"[tensorfold] rank {rank} ready in {time.perf_counter() - started:.1f}s, following rank 0", flush=True)+ engine.follow()+ return 0+ from tensorfold.cuda.server import App, serve+diff --git tensorfold/cli_args.py tensorfold/cli_args.py+index a9eb51e..8b0583c 100644+--- tensorfold/cli_args.py++++ tensorfold/cli_args.py+@@ -112,12 +112,13 @@ def build_parser(handlers: dict[str, Callable[[argparse.Namespace], int]]) -> ar+ cuda = serve.add_argument_group("NVIDIA GPUs (DGX Spark)")+ cuda.add_argument("--backend", choices=("auto", "mlx", "cuda"), default="auto",+ help="auto: MLX on macOS, CUDA elsewhere")+- cuda.add_argument("--tp", type=int, choices=(1, 2), default=1,+- help="GPUs (one per machine) the model is split over; run the same command on each")+- cuda.add_argument("--rank", type=int, choices=(0, 1), default=0,+- help="with --tp 2: this machine's rank; rank 0 serves HTTP, rank 1 follows it")+- cuda.add_argument("--master", default="", help="with --tp 2: rank 0's address on the link between the machines")+- cuda.add_argument("--master-port", type=int, default=29551, help="with --tp 2: rank 0's rendezvous port")++ cuda.add_argument("--tp", type=int, choices=(1, 2, 3, 4), default=1,++ help="GPUs (one per machine) the model is split over; run the same command on each "++ "(3 and 4: GLM-5.3-Flash only)")++ cuda.add_argument("--rank", type=int, choices=(0, 1, 2, 3), default=0,++ help="with --tp N: this machine's rank, 0 to N-1; rank 0 serves HTTP, the others follow it")++ cuda.add_argument("--master", default="", help="with --tp N: rank 0's address on the link between the machines")++ cuda.add_argument("--master-port", type=int, default=29551, help="with --tp N: rank 0's rendezvous port")+ cuda.add_argument("--kv-dtype", choices=("bf16", "int8", "int4"), default="bf16",+ help="KV cache: bf16 (the default), int8, or int4. Quantized keys and values use one "+ "fp16 scale per 32 values (changes the output; Flash Next on CUDA only)")+diff --git tensorfold/cuda/comm.py tensorfold/cuda/comm.py+index b94a2ce..f541a89 100644+--- tensorfold/cuda/comm.py++++ tensorfold/cuda/comm.py+@@ -122,6 +122,30 @@ class NCCL:+ finally:+ self._check(self.lib.ncclGroupEnd())+++ def exchange_all(self, sends: dict[int, list[torch.Tensor]], recvs: dict[int, list[torch.Tensor]]) -> None:++ """One NCCL group on the current stream with several peers: every ``sends[p][i]`` to peer p and++ ``recvs[p][i]`` from it (an all-to-all of row blocks; each peer's matching call names this rank with the++ same sizes and dtypes in the same order)."""++++ if set(sends) != set(recvs) or any(p == self.rank or not 0 <= p < self.world for p in sends):++ raise ValueError("exchange_all: sends and receives with the same other ranks")++ for p in sends:++ if len(sends[p]) != len(recvs[p]):++ raise ValueError("exchange_all: one receive per send")++ for s, r in zip(sends[p], recvs[p]):++ if s.numel() != r.numel() or s.dtype != r.dtype or not (s.is_contiguous() and r.is_contiguous()):++ raise ValueError("exchange_all: each send and receive must be contiguous and alike")++ stream = torch.cuda.current_stream().cuda_stream++ self._check(self.lib.ncclGroupStart())++ try:++ for p in sorted(sends):++ for s, r in zip(sends[p], recvs[p]):++ if s.numel():++ self._check(self.lib.ncclSend(s.data_ptr(), s.numel(), _DTYPES[s.dtype], p, self.comm, stream))++ self._check(self.lib.ncclRecv(r.data_ptr(), r.numel(), _DTYPES[r.dtype], p, self.comm, stream))++ finally:++ self._check(self.lib.ncclGroupEnd())+++ def barrier(self) -> None:+ x = torch.zeros((1,), dtype=torch.float32, device="cuda")+ y = torch.zeros((self.world,), dtype=torch.float32, device="cuda")+diff --git tensorfold/cuda/geometry.py tensorfold/cuda/geometry.py+index d5ee33a..8256956 100644+--- tensorfold/cuda/geometry.py++++ tensorfold/cuda/geometry.py+@@ -98,7 +98,18 @@ def indexed_weights(world: int, mtp: bool, mapped_tables: bool = True):+ return transform+++-def split_weights(rule, world: int = 2):++def split_weights(rule, world: int = 2, cut=None):++ """GLM's per-rank weight bytes. ``cut(name, shape, kind)``: the rank's [start, stop) of a split tensor's axis++ (``kind``, or ``"vocab"`` for lm_head's rows); None: even shares of ``world``."""++++ def share(name: str, shape: list[int], kind: str, axis: int) -> int:++ if cut is not None:++ a, b = cut(name, shape, kind)++ return b - a++ if shape[axis] % world:++ raise ValueError(f"checkpoint tensor does not split evenly: {name}")++ return shape[axis] // world+++ def transform(name: str, info: dict) -> tuple[int, int]:+ kind = rule(name)+ if kind == "drop":+@@ -106,11 +117,9 @@ def split_weights(rule, world: int = 2):+ shape = list(info["shape"])+ if not info.get("split") and kind != "rep":+ axis = {"row": 0, "col": -1, "dim1": 1}[kind]+- if shape[axis] % world:+- raise ValueError(f"checkpoint tensor does not split evenly: {name}")+- shape[axis] //= world++ shape[axis] = share(name, shape, kind, axis)+ if name.startswith("lm_head."):+- shape[0] //= world++ shape[0] = share(name, shape, "vocab", 0)+ cast = name.endswith((".A_log", ".dt_bias", ".hc_attn_base", ".hc_attn_scale", ".hc_ffn_base",+ ".hc_ffn_scale", ".e_score_correction_bias"))+ total = padded(info, shape, float32=cast, name=name)+@@ -254,19 +263,27 @@ def exl3_expert_scratch(rows: int, slots: int, d: int, width: int, *, prompt: bo+ return total + 2 * 4 * pairs * max(width, d) * 4 + (pairs + pairs // 16 + 1) * max(1, width // 128) * 4 + 4++++def even_share(world: int):++ """A ``share(family, total)`` of even splits (the two-rank engine's): total // world."""++++ return lambda family, total: int(total) // int(world)+++++ def mla_geometry(t: dict, world: int, reserve: int, *, minimum_slots: int = 2560, latent: bool = False,+ prefill_rows: int = PREFILL_ROWS, mtp: bool | None = None, onepass: bool = False,+- exl3_prompt: bool = True, prompt_split_k: bool = True, kv: str = "bf16") -> Geometry:++ exl3_prompt: bool = True, prompt_split_k: bool = True, kv: str = "bf16", share=None) -> Geometry:+ """GLM's engine: ``mtp`` whether it holds the MTP head's caches and decode buffers (None: when the checkpoint has+ one; GLM's TF_GLM_MTP can leave it out); ``onepass``: prompt chunks' sparse latent attention keeps no partials+ (TF_GLM_SPARSE_ONEPASS); an EXL3 checkpoint's ``exl3_prompt``: prompt chunks run the prompt expert kernels+ (TF_GLM_EXL3_PROMPT: no split-K sums), ``prompt_split_k``: the prompt buffers keep split-K partials for BF16 / FP8+ projections (``forward.Buffers.sk``); ``kv``: the DSA caches' format (TF_GLM_KV: the latent rows and the+- indexer's pooled keys; the indexer's per-token keys and gates are bf16 rings)."""++ indexer's pooled keys; the indexer's per-token keys and gates are bf16 rings); ``share(family, total)``: this++ rank's share of a split dimension (GLM's ``tp.Layout``: heads, lin, dense, moe, vocab), default ``even_share``."""++ share = even_share(world) if share is None else share+ linear, attention = layer_counts(t)+ lin = t.get("linear_attn_config") or {}+- heads = int(t["num_attention_heads"]) // world+- lh = int(lin.get("num_heads", t.get("linear_num_heads", 64))) // world++ heads = share("heads", int(t["num_attention_heads"]))++ lh = share("lin", int(lin.get("num_heads", t.get("linear_num_heads", 64))))+ ld = int(lin.get("head_dim", t.get("linear_head_dim", 128)))+ conv = int(lin.get("short_conv_kernel_size", t.get("linear_conv_kernel_dim", 4)))+ kd = int(t["qk_nope_head_dim"]) + int(t.get("qk_rope_head_dim", 0))+@@ -277,13 +294,14 @@ def mla_geometry(t: dict, world: int, reserve: int, *, minimum_slots: int = 2560+ fixed += linear * rows * (3 * lh * ld + 2 * ld + lh) * 2+ fixed += linear * rows * lh * (12 * ld + 4)+ slots = int(t["num_experts_per_tok"]) + 1+- width = int(t["moe_intermediate_size"]) // world+- extent = d * streams + int(t["vocab_size"]) // world + slots * (d + width) + heads * (2 * kd + vd)++ width = share("moe", int(t["moe_intermediate_size"]))++ vocab = share("vocab", int(t["vocab_size"]))++ extent = d * streams + vocab + slots * (d + width) + heads * (2 * kd + vd)+ extent += int(t.get("q_lora_rank", d)) * 2 + int(t.get("kv_lora_rank", d)) * 2+- extent += int(t.get("intermediate_size", width)) * 3 // world + int(t.get("index_n_heads", 32)) * index++ extent += share("dense", int(t.get("intermediate_size", width))) * 3 + int(t.get("index_n_heads", 32)) * index+ fixed += (2 if mtp else 1) * (16 * rows * extent * 4 + 8 * rows * 16384 * 4)+ # prompt-chunk buffers: at most 5 row extents a row without the head+- fixed += prefill_rows * 5 * (extent - int(t["vocab_size"]) // world)++ fixed += prefill_rows * 5 * (extent - vocab)+ if (t.get("_quantization") or {}).get("quant_method") == "exl3":+ # the routed experts' scratch of the decode windows (the MTP head's too) and of a prompt chunk, and the prompt+ # buffers' split-K partials (8 x rows x 16,384 fp32, as forward.Buffers allocates them)+@@ -295,7 +313,8 @@ def mla_geometry(t: dict, world: int, reserve: int, *, minimum_slots: int = 2560+ if kv != "bf16" and not latent:+ raise ValueError("TF_GLM_KV=fp8 needs the latent cache")+ def bytes_at(capacity: int) -> int:+- scratch = mla_chunk_scratch(t, world, capacity, latent=latent, prefill_rows=prefill_rows, onepass=onepass)++ scratch = mla_chunk_scratch(t, world, capacity, latent=latent, prefill_rows=prefill_rows, onepass=onepass,++ share=share)+ if latent:+ # latent cache; a prompt chunk's latent partials (its dense pass runs MLA_PROMPT_ATT_ROWS rows at a time)+ # and absorbed rows (the MTP absorbs through the same buffers)+@@ -314,11 +333,12 @@ def mla_geometry(t: dict, world: int, reserve: int, *, minimum_slots: int = 2560+++ def mla_chunk_scratch(t: dict, world: int, capacity: int, *, latent: bool, prefill_rows: int = PREFILL_ROWS,+- onepass: bool = False) -> int:++ onepass: bool = False, share=None) -> int:+ """A prompt chunk's transient bytes: token selection (fp32 pool scores, chosen pools, token lists), then sparse+ attention's partials, which the latent path's one-pass kernel (``onepass``) does not allocate."""++- heads, topk = int(t["num_attention_heads"]) // world, int(t.get("index_topk", 2048))++ share = even_share(world) if share is None else share++ heads, topk = share("heads", int(t["num_attention_heads"])), int(t.get("index_topk", 2048))+ # the fp32 pool scores of at most MLA_SELECT_ROWS rows at once, the chosen pools and token lists of the chunk's+ select = min(prefill_rows, MLA_SELECT_ROWS) * 4 * ((capacity + 3) // 4) + prefill_rows * 16 * (topk + 3)+ if latent and onepass:+@@ -351,11 +371,12 @@ def draft_geometry(t: dict, world: int, reserve: int, *, bounded: bool = False,+ return Geometry(bytes_at, reserve)+++-def dflash2_geometry(t: dict, world: int, reserve: int, *, ring: bool) -> Geometry:+- """GLM's DFlash2 drafter on each rank: one context (a ring, or capacity + block rows) and a block pass."""++def dflash2_geometry(t: dict, world: int, reserve: int, *, ring: bool, kv_heads: int | None = None) -> Geometry:++ """GLM's DFlash2 drafter on each rank: one context (a ring, or capacity + block rows) and a block pass;++ ``kv_heads``: this rank's KV heads (default an even share)."""++ layers = int(t["num_hidden_layers"])+- heads = int(t["num_key_value_heads"]) // world++ heads = int(t["num_key_value_heads"]) // world if kv_heads is None else int(kv_heads)+ hd = int(t["head_dim"])+ block = int((t.get("dflash_config") or {}).get("block_size", 16))+ window = int(t.get("sliding_window", 0))+@@ -368,8 +389,12 @@ def dflash2_geometry(t: dict, world: int, reserve: int, *, ring: bool) -> Geomet+ return Geometry(bytes_at, reserve)+++-def dflash2_weights(draft_dir, world: int) -> Weights:+- """GLM's DFlash2 drafter as held on each rank (4-bit copies, bf16 norms, fp32 codebooks), and its staging."""++def dflash2_weights(draft_dir, world: int, fraction=None) -> Weights:++ """GLM's DFlash2 drafter as held on each rank (4-bit copies, bf16 norms, fp32 codebooks), and its staging;++ ``fraction(kind, n)``: this rank's share of n query (``q``), key/value (``kv``) or MLP (``mlp``) rows (default++ n // world)."""++++ part = (lambda kind, n: n // world) if fraction is None else fraction++ h = headers(draft_dir)+ shape = {name: [int(x) for x in info["shape"]] for name, info in h.items()}+@@ -385,8 +410,8 @@ def dflash2_weights(draft_dir, world: int) -> Weights:+ o, gate, up, down = (shape[p + x] for x in ("self_attn.o_proj.weight", "mlp.gate_proj.weight",+ "mlp.up_proj.weight", "mlp.down_proj.weight"))+ d = q[1]+- mats += [((q[0] + k[0] + v[0]) // world, d), ((k[0] + v[0]) // world, d), (o[0], o[1] // world),+- ((gate[0] + up[0]) // world, d), (down[0], down[1] // world)]++ mats += [(part("q", q[0]) + part("kv", k[0]) + part("kv", v[0]), d), (part("kv", k[0]) + part("kv", v[0]), d),++ (o[0], part("q", o[1])), (part("mlp", gate[0]) + part("mlp", up[0]), d), (down[0], part("mlp", down[1]))]+ quantized |= {p + x for x in ("self_attn.q_proj.weight", "self_attn.k_proj.weight", "self_attn.v_proj.weight",+ "self_attn.o_proj.weight", "mlp.gate_proj.weight", "mlp.up_proj.weight",+ "mlp.down_proj.weight")}+diff --git tensorfold/cuda/roce.py tensorfold/cuda/roce.py+index 93535a4..4ee4ac0 100644+--- tensorfold/cuda/roce.py++++ tensorfold/cuda/roce.py+@@ -74,13 +74,15 @@ def proxy_library() -> ctypes.CDLL:+ for name, res, args in (+ ("roce_abi_version", i, []), ("roce_layout", i, [i, u64, ctypes.POINTER(u64)]),+ ("roce_blob_bytes", u64, []),+- ("roce_create", p, [i, i, ctypes.POINTER(ctypes.c_char_p), i, i, i, p, u64, u64, ctypes.c_char_p, u64]),++ ("roce_create", p, [i, i, ctypes.POINTER(ctypes.c_char_p), i, ctypes.POINTER(i), i, p, u64, u64,++ ctypes.c_char_p, u64]),++ ("roce_set_routes", i, [p, i, i, ctypes.POINTER(i), ctypes.POINTER(i), i]),+ ("roce_local_blob", i, [p, p, u64]), ("roce_connect", i, [p, p, u64]), ("roce_start", i, [p]),+ ("roce_stop", None, [p]), ("roce_failed", i, [p]), ("roce_error", ctypes.c_char_p, [p]),+ ("roce_stat", u64, [p, i]), ("roce_hca_stat", u64, [p, i, i]), ("roce_destroy", None, [p])):+ fn = getattr(lib, name)+ fn.restype, fn.argtypes = res, args+- if lib.roce_abi_version() != 4:++ if lib.roce_abi_version() != 5:+ raise RuntimeError("unexpected RoCE proxy ABI version")+ return lib++@@ -94,19 +96,96 @@ def _ext():+ extra_cuda_cflags=["-O3"], verbose=False)+++-def _hcas() -> list[str]:++MAX_HCAS = 4 # roce_proxy.c's ROCE_MAX_HCAS++_SYS = Path("/sys/class/infiniband")++++++def _hcas(world: int = 2) -> list[str]:++ """The HCAs the transport uses: TF_ROCE_HCA (or NCCL_IB_HCA), else every ACTIVE one; two ranks take the first++ two (their one cable's rails), more ranks up to four (a triangle's two rails a peer)."""+++ raw = os.environ.get("TF_ROCE_HCA") or os.environ.get("NCCL_IB_HCA") or ""+ names = [x.strip().lstrip("=^").split(":")[0] for x in raw.split(",") if x.strip()]+ if not names:+- root = Path("/sys/class/infiniband")+- names = [d.name for d in sorted(root.glob("*")) if "ACTIVE" in (d / "ports/1/state").read_text()]+- return names[:2]++ names = [d.name for d in sorted(_SYS.glob("*")) if "ACTIVE" in (d / "ports/1/state").read_text()]++ return names[:2] if world == 2 else names[:MAX_HCAS]++++++def _ipv4_gid(hca: str) -> tuple[int, int, int] | None:++ """(GID index, IPv4 as an int, prefix length) of ``hca``'s first RoCE v2 IPv4 GID (sysfs and ``ip``), or None."""++++ import ipaddress++++ port = _SYS / hca / "ports" / "1"++ entries = []++ for path in (port / "gids").glob("*"):++ try:++ gid = path.read_text().strip()++ kind = (port / "gid_attrs" / "types" / path.name).read_text().strip()++ except OSError:++ continue++ if "v2" not in kind.lower() or not gid.replace(":", "").lower().startswith("0" * 20 + "ffff"):++ continue++ raw = bytes.fromhex(gid.replace(":", ""))++ if raw == bytes(16):++ continue++ entries.append((int(path.name), int(ipaddress.IPv4Address(raw[12:])), path))++ if not entries:++ return None++ index, ip, path = min(entries)++ prefix = 24++ try:++ dev = (port / "gid_attrs" / "ndevs" / path.name).read_text().strip()++ out = subprocess.run(["ip", "-o", "-4", "addr", "show", "dev", dev], capture_output=True, text=True).stdout++ for word in out.split():++ if "/" in word and word.split("/")[0] == str(ipaddress.IPv4Address(ip)):++ prefix = int(word.split("/")[1])++ except (OSError, ValueError):++ pass++ return index, ip, prefix++++++def plan_routes(addrs: list[list[tuple[int, int] | None]]) -> tuple[dict, int]:++ """Every rank's (IPv4, prefix) a listed HCA (None: unknown) -> ({(rank, peer): [(local HCA, peer HCA), ...]},++ stripes a peer). HCAs pair when they share a subnet, each HCA once a peer, in name order on both sides (so the++ two ends of a pair list the same pairs mirrored); every pair of ranks gets the fewest stripes any pair has,++ which must be at least one."""++++ world = len(addrs)++++ def net(a):++ return None if a is None else (a[0] >> (32 - a[1]) if a[1] else 0, a[1])++++ pairs: dict = {}++ for r in range(world):++ for p in range(world):++ if p == r:++ continue++ used, got = set(), []++ for h, a in enumerate(addrs[r]):++ for rh, b in enumerate(addrs[p]):++ if rh not in used and net(a) is not None and net(a) == net(b):++ used.add(rh)++ got.append((h, rh))++ break++ pairs[(r, p)] = got++ if world < 2:++ return pairs, 0++ least = min(len(v) for v in pairs.values())++ if least == 0:++ missing = ", ".join(f"{r}-{p}" for (r, p), v in sorted(pairs.items()) if not v and r < p)++ raise RuntimeError(f"RoCE: no HCA of rank(s) {missing} shares a subnet with the peer's: every pair of ranks "++ "needs a direct path (a cable or a switch); use TF_GLM_COMM=nccl on a ring")++ return {k: v[:least] for k, v in pairs.items()}, least+++ class RoceGather:+ """One rank's side of the exchange: the pinned region, the proxy thread and the gather launches."""++ def __init__(self, comm, rank: int, world: int, max_bytes: int = 256 << 10) -> None:++ """Two ranks: every listed HCA to the peer's of the same index (b12x's striping), GID index TF_ROCE_GID_INDEX++ (or NCCL_IB_GID_INDEX, 3). More ranks: each HCA's own RoCE v2 IPv4 GID (unless TF_ROCE_GID_INDEX) and routes++ by subnet (``plan_routes``), so a triangle of direct cables reaches each peer over that pair's rails."""+ lib = proxy_library()+ self.lib, self.rank, self.world, self.max_bytes = lib, rank, world, int(max_bytes)+ self.slot_bytes = -(-self.max_bytes // SLOT_ALIGN) * SLOT_ALIGN+@@ -121,24 +200,39 @@ class RoceGather:+ self.classes = BLOCKS.bit_length()+ # epoch, stage arrivals and tail arrivals by power-of-two grid, poison+ self.counters = torch.zeros(2 + 2 * self.classes, dtype=torch.int32, device="cuda")+- self.hcas = _hcas()+- gid = int(os.environ.get("TF_ROCE_GID_INDEX") or os.environ.get("NCCL_IB_GID_INDEX") or 3)++ self.hcas = _hcas(world)++ fixed = os.environ.get("TF_ROCE_GID_INDEX") or os.environ.get("NCCL_IB_GID_INDEX")++ found = [None] * len(self.hcas) if world == 2 else [_ipv4_gid(h) for h in self.hcas]++ if world == 2 or fixed:++ gids = [int(fixed or 3)] * len(self.hcas)++ else:++ gids = [f[0] if f is not None else 3 for f in found]++ self.addrs = [None if f is None else (f[1], f[2]) for f in found]+ tc = int(os.environ.get("NCCL_IB_TC", "0"), 0)+ names = (ctypes.c_char_p * len(self.hcas))(*[n.encode() for n in self.hcas])+ err = ctypes.create_string_buffer(512)+- self.ctx = lib.roce_create(world, rank, names, len(self.hcas), gid, tc, ctypes.c_void_p(base), total,+- self.slot_bytes, err, len(err))++ self.ctx = lib.roce_create(world, rank, names, len(self.hcas), (ctypes.c_int * len(gids))(*gids), tc,++ ctypes.c_void_p(base), total, self.slot_bytes, err, len(err))+ failed = 0 if self.ctx else 1+ blob_len = int(lib.roce_blob_bytes())+ blob = ctypes.create_string_buffer(blob_len)+ if not failed and lib.roce_local_blob(self.ctx, blob, blob_len) != 0:+ failed = 1+- # both ranks' verdict, geometry and connection blob through the existing communicator++ # every rank's verdict, geometry and connection blob through the existing communicator (more than two ranks:++ # each HCA's IPv4 and prefix too, for the routes)+ words = -(-blob_len // 4)+- mine = torch.zeros(4 + words, dtype=torch.int32)+- mine[:4] = torch.tensor([failed, len(self.hcas), self.slot_bytes >> 12, self.flag_stride])++ extra = 0 if world == 2 else 2 * MAX_HCAS++ mine = torch.zeros(4 + extra + words, dtype=torch.int32)++ n_hca = len(self.hcas) if world == 2 else 0++ mine[:4] = torch.tensor([failed, n_hca, self.slot_bytes >> 12, self.flag_stride])++ if extra: # (IPv4 as int32 bits, prefix) a slot; prefix -1: none++ mine[4:4 + extra] = torch.tensor([0, -1] * MAX_HCAS, dtype=torch.int32)++ for h, a in enumerate(self.addrs):++ if a is not None:++ mine[4 + 2 * h] = a[0] - (1 << 32) if a[0] >= 1 << 31 else a[0]++ mine[5 + 2 * h] = a[1]+ raw = torch.frombuffer(bytearray(blob.raw.ljust(words * 4, b"\0")), dtype=torch.int32)+- mine[4:] = raw++ mine[4 + extra:] = raw+ got = torch.empty(world * mine.numel(), dtype=torch.int32, device="cuda")+ comm.all_gather(mine.cuda(), got)+ rows = got.view(world, -1).cpu()+@@ -146,7 +240,27 @@ class RoceGather:+ why = err.value.decode(errors="replace") if not self.ctx else "the ranks' RoCE geometry differs"+ self.close()+ raise RuntimeError(f"RoCE all-gather setup failed on some rank: {why}")+- blobs = b"".join(bytes(r[4:].numpy().tobytes())[:blob_len] for r in rows)++ self.n_flag = len(self.hcas) # stripes a peer: every HCA at two ranks++ if extra:++ addrs = [[None if int(r[5 + 2 * h]) < 0 else (int(r[4 + 2 * h]) & 0xFFFFFFFF, int(r[5 + 2 * h]))++ for h in range(MAX_HCAS)] for r in rows]++ try:++ routes, self.n_flag = plan_routes(addrs)++ except RuntimeError:++ self.close()++ raise++ for p in range(world):++ if p == rank:++ continue++ local, remote = zip(*routes[(rank, p)])++ n = len(local)++ if lib.roce_set_routes(self.ctx, p, n, (ctypes.c_int * n)(*local), (ctypes.c_int * n)(*remote),++ self.n_flag) != 0:++ why = lib.roce_error(self.ctx).decode(errors="replace")++ self.close()++ raise RuntimeError(f"RoCE routes: {why}")++ self.routes = {p: routes[(rank, p)] for p in range(world) if p != rank}++ blobs = b"".join(bytes(r[4 + extra:].numpy().tobytes())[:blob_len] for r in rows)+ self.spin = spin_limit()+ _ext() # its first build (tens of seconds) here, before the verdict all-gather below+ ok = lib.roce_connect(self.ctx, blobs, len(blobs)) == 0 and lib.roce_start(self.ctx) == 0+@@ -175,7 +289,7 @@ class RoceGather:+ c = self.counters.data_ptr()+ _ext().gather(send, recv, packs, nbytes, packs, self.recv, self.flag, self.send, self.ctrl, self.slot_bytes,+ c, c + 4 * (1 + klass), c + 4 * (1 + self.classes + klass), c + 4 * (1 + 2 * self.classes),+- self.spin, self.world, self.rank, self.slots, self.flag_stride, len(self.hcas), grid, THREADS)++ self.spin, self.world, self.rank, self.slots, self.flag_stride, self.n_flag, grid, THREADS)+ if not torch.cuda.is_current_stream_capturing():+ self.check()++diff --git tensorfold/cuda/roce_proxy.c tensorfold/cuda/roce_proxy.c+index 5e605ae..d8ba88c 100644+--- tensorfold/cuda/roce_proxy.c++++ tensorfold/cuda/roce_proxy.c+@@ -1,6 +1,10 @@+ // Adapted from b12x (https://github.com/local-inference-lab/b12x), b12x/comm/roce/_roce_proxy.c at commit+ // 8a99d639410e39d5f39cb4037675331beceea1d4: "RoCEnante", Copyright the b12x contributors, Apache License 2.0+-// (http://www.apache.org/licenses/LICENSE-2.0). Unchanged except this header. Used by tensorfold/cuda/roce.py.++// (http://www.apache.org/licenses/LICENSE-2.0). Used by tensorfold/cuda/roce.py. Changes from b12x's file (TensorFold,++// 2026-10-01, ABI 5): up to 4 HCAs, a GID index per HCA, and routes: each peer's stripes go over chosen (local HCA,++// peer HCA) pairs (roce_set_route; default HCA h to the peer's HCA h, every HCA), so ranks cabled to each other++// directly (a triangle of Sparks: one /24 and two rails a pair) reach each peer over its own rails only. Flags are++// indexed by stripe (``n_flag`` stripes a peer, the same for every peer).++ // RDMA proxy for the b12x RoCE one-shot all-reduce.+ //+@@ -40,12 +44,12 @@+ #include <time.h>++ #define ROCE_MAX_PEERS 16+-#define ROCE_MAX_HCAS 2++#define ROCE_MAX_HCAS 4+ #define ROCE_SLOTS 2+ #define ROCE_FLAG_STRIDE 128+ #define ROCE_PORT 1+ #define ROCE_SEND_DEPTH 256+-#define ROCE_ABI_VERSION 4++#define ROCE_ABI_VERSION 5+ // Model graphs leave sub-millisecond gaps between collectives. Keep the+ // proxy hot across those gaps; sleeping there adds one scheduler wakeup to+ // every collective on the graph's critical path.+@@ -78,8 +82,13 @@ typedef struct {+ int world;+ int rank;+ int n_hca;+- int gid_index;++ int gid_index[ROCE_MAX_HCAS];+ int traffic_class;++ // routes: stripe s to peer p leaves on local HCA stripe_hca[p][s] for the peer's HCA stripe_remote[p][s]++ int n_stripe[ROCE_MAX_PEERS];++ int stripe_hca[ROCE_MAX_PEERS][ROCE_MAX_HCAS];++ int stripe_remote[ROCE_MAX_PEERS][ROCE_MAX_HCAS];++ int n_flag; // stripes (flags) a peer, the same for every peer and on every rank+ roce_hca_t hca[ROCE_MAX_HCAS];+ uint8_t *region;+ size_t region_bytes;+@@ -90,7 +99,7 @@ typedef struct {+ size_t ctrl_off;+ int started;+ uint64_t peer_addr[ROCE_MAX_PEERS];+- uint32_t peer_rkey[ROCE_MAX_HCAS][ROCE_MAX_PEERS];++ uint32_t peer_rkey[ROCE_MAX_HCAS][ROCE_MAX_PEERS]; // by stripe+ pthread_t thread;+ atomic_int running;+ atomic_int failed;+@@ -179,7 +188,7 @@ static int open_hca(roce_ctx_t *c, int h, const char *name) {+ }+ hca->lid = port.lid;+ hca->mtu = port.active_mtu;+- if (ibv_query_gid(hca->ctx, ROCE_PORT, c->gid_index, &hca->gid) != 0) {++ if (ibv_query_gid(hca->ctx, ROCE_PORT, c->gid_index[h], &hca->gid) != 0) {+ set_err(c, "ibv_query_gid", errno);+ return -1;+ }+@@ -235,7 +244,7 @@ static int open_hca(roce_ctx_t *c, int h, const char *name) {+ }++ roce_ctx_t *roce_create(int world, int rank, const char *const *hca_names, int n_hca,+- int gid_index, int traffic_class, void *region, uint64_t region_bytes,++ const int *gid_index, int traffic_class, void *region, uint64_t region_bytes,+ uint64_t slot_bytes, char *err, uint64_t err_len) {+ uint64_t layout[7];+ if (roce_layout(world, slot_bytes, layout) != 0 || layout[4] > region_bytes ||+@@ -252,7 +261,17 @@ roce_ctx_t *roce_create(int world, int rank, const char *const *hca_names, int n+ c->world = world;+ c->rank = rank;+ c->n_hca = n_hca;+- c->gid_index = gid_index;++ for (int h = 0; h < n_hca; h++) {++ c->gid_index[h] = gid_index[h];++ }++ for (int p = 0; p < world; p++) { // default routes: HCA h to the peer's HCA h, every HCA++ c->n_stripe[p] = p == rank ? 0 : n_hca;++ for (int h = 0; h < n_hca; h++) {++ c->stripe_hca[p][h] = h;++ c->stripe_remote[p][h] = h;++ }++ }++ c->n_flag = n_hca;+ c->traffic_class = traffic_class;+ c->region = region;+ c->region_bytes = region_bytes;+@@ -271,6 +290,26 @@ roce_ctx_t *roce_create(int world, int rank, const char *const *hca_names, int n+ return c;+ }+++int roce_set_routes(roce_ctx_t *c, int peer, int n, const int *local, const int *remote, int n_flag) {++ // before roce_connect: peer's stripes (n of them) over (local[s], remote[s]); n_flag: the stripes every peer has++ if (c->started || peer < 0 || peer >= c->world || peer == c->rank || n < 1 || n > ROCE_MAX_HCAS ||++ n != n_flag || n_flag > ROCE_MAX_HCAS) {++ snprintf(c->err, sizeof(c->err), "invalid RoCE route to rank %d (%d stripes, %d a peer)", peer, n, n_flag);++ return -1;++ }++ for (int s = 0; s < n; s++) {++ if (local[s] < 0 || local[s] >= c->n_hca || remote[s] < 0 || remote[s] >= ROCE_MAX_HCAS) {++ snprintf(c->err, sizeof(c->err), "invalid RoCE route to rank %d: stripe %d", peer, s);++ return -1;++ }++ c->stripe_hca[peer][s] = local[s];++ c->stripe_remote[peer][s] = remote[s];++ }++ c->n_stripe[peer] = n;++ c->n_flag = n_flag;++ return 0;++}+++ int roce_local_blob(roce_ctx_t *c, void *out, uint64_t out_len) {+ if (out_len < sizeof(roce_blob_t)) {+ return -1;+@@ -291,23 +330,24 @@ int roce_local_blob(roce_ctx_t *c, void *out, uint64_t out_len) {+ return 0;+ }++-static int connect_qp(roce_ctx_t *c, int h, int p, const roce_blob_t *peer) {++static int connect_qp(roce_ctx_t *c, int h, int p, const roce_blob_t *peer, int rh) {++ // local HCA h's QP for peer p <-> the peer's HCA rh's QP for this rank+ roce_hca_t *hca = &c->hca[h];+ struct ibv_qp_attr rtr;+ memset(&rtr, 0, sizeof(rtr));+ rtr.qp_state = IBV_QPS_RTR;+- rtr.path_mtu = (enum ibv_mtu)(peer->mtu[h] < (uint32_t)hca->mtu ? peer->mtu[h] : (uint32_t)hca->mtu);+- rtr.dest_qp_num = peer->qp_num[h][c->rank];++ rtr.path_mtu = (enum ibv_mtu)(peer->mtu[rh] < (uint32_t)hca->mtu ? peer->mtu[rh] : (uint32_t)hca->mtu);++ rtr.dest_qp_num = peer->qp_num[rh][c->rank];+ rtr.rq_psn = 0;+ rtr.max_dest_rd_atomic = 1;+ rtr.min_rnr_timer = 12;+ rtr.ah_attr.is_global = 1;+- rtr.ah_attr.dlid = peer->lid[h];++ rtr.ah_attr.dlid = peer->lid[rh];+ rtr.ah_attr.sl = 0;+ rtr.ah_attr.src_path_bits = 0;+ rtr.ah_attr.port_num = ROCE_PORT;+- memcpy(rtr.ah_attr.grh.dgid.raw, peer->gid[h], 16);+- rtr.ah_attr.grh.sgid_index = (uint8_t)c->gid_index;++ memcpy(rtr.ah_attr.grh.dgid.raw, peer->gid[rh], 16);++ rtr.ah_attr.grh.sgid_index = (uint8_t)c->gid_index[h];+ rtr.ah_attr.grh.hop_limit = 64;+ rtr.ah_attr.grh.traffic_class = (uint8_t)c->traffic_class;+ rtr.ah_attr.grh.flow_label = 0;+@@ -347,9 +387,15 @@ int roce_connect(roce_ctx_t *c, const void *blobs, uint64_t blobs_len) {+ continue;+ }+ c->peer_addr[p] = all[p].region_addr;+- for (int h = 0; h < c->n_hca; h++) {+- c->peer_rkey[h][p] = all[p].rkey[h];+- if (connect_qp(c, h, p, &all[p]) != 0) {++ if (c->n_stripe[p] != c->n_flag) {++ snprintf(c->err, sizeof(c->err), "rank %d has %d stripes, every peer needs %d", p, c->n_stripe[p],++ c->n_flag);++ return -1;++ }++ for (int s = 0; s < c->n_stripe[p]; s++) {++ const int h = c->stripe_hca[p][s], rh = c->stripe_remote[p][s];++ c->peer_rkey[s][p] = all[p].rkey[rh];++ if (connect_qp(c, h, p, &all[p], rh) != 0) {+ return -1;+ }+ }+@@ -395,7 +441,9 @@ static int post_op(roce_ctx_t *c, uint32_t seq, uint32_t nbytes) {+ continue;+ }+ uint32_t pack_offset = 0;+- for (int h = 0; h < c->n_hca; h++) {++ const int n_stripe = c->n_stripe[p];++ for (int s = 0; s < n_stripe; s++) {++ const int h = c->stripe_hca[p][s];+ roce_hca_t *hca = &c->hca[h];+ // Two work requests per stripe; keep the queue at most a quarter+ // full so a provider that needs extra entries can never fail a post.+@@ -413,8 +461,8 @@ static int post_op(roce_ctx_t *c, uint32_t seq, uint32_t nbytes) {+ return -1;+ }+ }+- uint32_t stripe_packs = total_packs / (uint32_t)c->n_hca;+- if ((uint32_t)h < total_packs % (uint32_t)c->n_hca) {++ uint32_t stripe_packs = total_packs / (uint32_t)n_stripe;++ if ((uint32_t)s < total_packs % (uint32_t)n_stripe) {+ stripe_packs += 1;+ }+ uint32_t stripe_bytes = stripe_packs * 16;+@@ -434,9 +482,9 @@ static int post_op(roce_ctx_t *c, uint32_t seq, uint32_t nbytes) {+ flag_wr.send_flags = IBV_SEND_SIGNALED | IBV_SEND_INLINE;+ flag_wr.wr.rdma.remote_addr =+ remote + c->flag_off ++- (((uint64_t)c->rank * ROCE_SLOTS + slot) * (uint64_t)c->n_hca ++- (uint64_t)h) * ROCE_FLAG_STRIDE;+- flag_wr.wr.rdma.rkey = c->peer_rkey[h][p];++ (((uint64_t)c->rank * ROCE_SLOTS + slot) * (uint64_t)c->n_flag +++ (uint64_t)s) * ROCE_FLAG_STRIDE;++ flag_wr.wr.rdma.rkey = c->peer_rkey[s][p];++ struct ibv_send_wr data_wr;+ struct ibv_sge data_sge;+@@ -457,7 +505,7 @@ static int post_op(roce_ctx_t *c, uint32_t seq, uint32_t nbytes) {+ remote + c->recv_off ++ ((uint64_t)c->rank * ROCE_SLOTS + slot) * c->slot_bytes ++ byte_offset;+- data_wr.wr.rdma.rkey = c->peer_rkey[h][p];++ data_wr.wr.rdma.rkey = c->peer_rkey[s][p];+ first_wr = &data_wr;+ }+ struct ibv_send_wr *bad = NULL;+diff --git tensorfold/cuda/shares.py tensorfold/cuda/shares.py+new file mode 100644+index 0000000..3a836ab+--- /dev/null++++ tensorfold/cuda/shares.py+@@ -0,0 +1,41 @@++"""How a dimension splits over tensor-parallel ranks: whole units (a head, a 128-column Hadamard block, 64 vocabulary++rows), as even as they go, the remainder to the lowest ranks. Two ranks of an even count get exact halves."""++++from __future__ import annotations++++++def parts(total: int, world: int, unit: int = 1) -> list[int]:++ """Each rank's share of ``total`` (a multiple of ``unit``) in rank order: e.g. 64 heads over 3 ranks 22, 21, 21;++ 2048 columns in units of 128 over 3 ranks 768, 640, 640."""++++ total, world, unit = int(total), int(world), int(unit)++ if world < 1 or unit < 1:++ raise ValueError(f"shares of {total} over {world} ranks in units of {unit}")++ if total % unit:++ raise ValueError(f"{total} is not a whole number of {unit}-wide units")++ units = total // unit++ if units < world:++ raise ValueError(f"{total} ({units} units of {unit}) cannot give each of {world} ranks a unit")++ base, extra = divmod(units, world)++ return [(base + (r < extra)) * unit for r in range(world)]++++++def share(total: int, world: int, rank: int, unit: int = 1) -> tuple[int, int]:++ """Rank ``rank``'s [start, stop) of ``total`` (``parts``)."""++++ sizes = parts(total, world, unit)++ if not 0 <= rank < world:++ raise ValueError(f"rank {rank} of {world}")++ start = sum(sizes[:rank])++ return start, start + sizes[rank]++++++def scaled(total: int, world: int, rank: int, unit: int, length: int) -> tuple[int, int]:++ """Rank ``rank``'s [start, stop) of an axis of ``length`` elements that holds the ``total`` (e.g. a trellis's++ 128 tile columns for 2,048 expert columns, a packed row's words): the share of ``total`` scaled to the axis,++ which must land on whole elements."""++++ a, b = share(total, world, rank, unit)++ if (a * length) % total or (b * length) % total:++ raise ValueError(f"rank {rank} of {world}: [{a}, {b}) of {total} is not whole on an axis of {length}")++ return a * length // total, b * length // total+diff --git tensorfold/families/glm5_next/__init__.py tensorfold/families/glm5_next/__init__.py+index 90cb8f3..5701341 100644+--- tensorfold/families/glm5_next/__init__.py++++ tensorfold/families/glm5_next/__init__.py+@@ -200,17 +200,21 @@ def memory_fraction(ram_bytes: int) -> float | None:++ # the CUDA engine's kernels read MLX affine weights of this (bits, group size); EXL3 checkpoints are checked above+ CUDA_QUANTIZATION = (4, 64)++CUDA_TP = (2, 3, 4) # GPUs (one per machine) the CUDA engine splits over+++ def cuda_engine(model_dir: str | Path, *, drafter: str = "", tp: int = 1, rank: int = 0, master: str = "",+ master_port: int = 29551, no_drafts: bool = False, mtp_drafts: int | None = None, **options: Any):+- """Build the two-rank engine with adaptive drafting, reusable prompt state, or serial decoding when drafts are disabled."""++ """Build the N-rank engine (N = 2, 3 or 4) with adaptive drafting, reusable prompt state, or serial decoding when drafts are disabled."""++- if int(tp) != 2:+- raise ValueError("GLM-5.3-Flash needs two GPUs, one per machine: run the same `tensorfold serve` command "+- "with --tp 2 --rank R --master ADDRESS on both (rank 1 first)")++ tp = int(tp)++ if tp not in CUDA_TP:++ raise ValueError("GLM-5.3-Flash needs two GPUs or more (2, 3 or 4), one per machine: run the same "++ "`tensorfold serve` command with --tp N --rank R --master ADDRESS on each (rank 0 last)")+ if not master:+- raise ValueError("--tp 2 needs --master: rank 0's address on the link between the two machines")++ raise ValueError(f"--tp {tp} needs --master: rank 0's address on the link between the machines")++ if not 0 <= int(rank) < tp:++ raise ValueError(f"--rank {rank}: 0 to {tp - 1} with --tp {tp}")+ from .cuda.engine import DEFAULT_POLICY, DFLASH_POLICY, GlmEngine++ if mtp_drafts is None:+@@ -219,7 +223,7 @@ def cuda_engine(model_dir: str | Path, *, drafter: str = "", tp: int = 1, rank:+ policy = DFLASH_POLICY # no MTP drafts: every round still verifies DFlash2's drafts+ else:+ policy = str(int(mtp_drafts))+- return GlmEngine(Path(model_dir), rank=int(rank), master=master, port=int(master_port), policy=policy,++ return GlmEngine(Path(model_dir), rank=int(rank), world=tp, master=master, port=int(master_port), policy=policy,+ drafter=Path(drafter) if drafter and not no_drafts else None,+ context=options.get("context"), context_explicit=options.get("context_explicit"),+ serial_only=bool(no_drafts), vision=bool(options.get("vision", False)),+diff --git tensorfold/families/glm5_next/cuda/decode.py tensorfold/families/glm5_next/cuda/decode.py+index be872ae..d355e85 100644+--- tensorfold/families/glm5_next/cuda/decode.py++++ tensorfold/families/glm5_next/cuda/decode.py+@@ -12,7 +12,7 @@ import torch+ from tensorfold.cuda.sampling import comm_gather, nucleus_rows, one_rank+ from tensorfold.engine.exact_sampling import MARGIN, Sampling, choose_rows++-from . import glue, prof, qmm++from . import glue, prof, qmm, tp+ from .forward import Buffers, State, chunks_for, commit, compute, stage+ from .mtp import mtp_compute, mtp_forward, mtp_stage+ from .sparse import pool_bucket+@@ -111,7 +111,7 @@ class Engine:+ if any(l.kind == "kda" for l in w.layers): # the wide KDA chain's scratch, before any capture+ from . import kda as kda_mod++- kda_mod.reserve(max(max_rows, prefill_rows), w.cfg.lin_heads // w.world, w.device)++ kda_mod.reserve(max(max_rows, prefill_rows), tp.of(w).lin_heads, w.device)+ self.buf = Buffers(w, max_rows, capacity)+ self.pbuf = Buffers(w, prefill_rows, capacity, prefill=True)+ if taps:+diff --git tensorfold/families/glm5_next/cuda/dflash2.py tensorfold/families/glm5_next/cuda/dflash2.py+index b5dcd26..69d2268 100644+--- tensorfold/families/glm5_next/cuda/dflash2.py++++ tensorfold/families/glm5_next/cuda/dflash2.py+@@ -233,9 +233,13 @@ class Drafter:+ self.D = int(cfg["hidden_size"])+ self.hd = int(cfg["head_dim"])+ heads, kv_heads = int(cfg["num_attention_heads"]), int(cfg["num_key_value_heads"])+- if heads % self.world or kv_heads % self.world:+- raise ValueError("drafter heads must split evenly over the ranks")+- self.heads, self.kvh = heads // self.world, kv_heads // self.world++ from .tp import draft_parts++++ # KV heads in whole query groups over the ranks (32 / 8 over 3: 12/12/8 query heads, 3/3/2 KV heads), the MLP++ # in units of 128 (``tp.draft_parts``); two ranks: halves++ qs, kvs, mlps = draft_parts(heads, kv_heads, int(cfg["intermediate_size"]), self.world)++ self.heads, self.kvh = qs[self.rank], kvs[self.rank]++ q0, kv0 = sum(qs[:self.rank]), sum(kvs[:self.rank])+ self.eps = float(cfg["rms_norm_eps"])+ theta = float(cfg["rope_parameters"]["rope_theta"])+ self.mask_id = int(dc["mask_token_id"])+@@ -247,11 +251,9 @@ class Drafter:+ self.tap_layers = tuple(int(i) for i in dc["target_layer_ids"])+ self.window = int(cfg["sliding_window"]) - 1+ self.causal = bool(cfg.get("is_causal", True))+- inter = int(cfg["intermediate_size"])+- if inter % self.world:+- raise ValueError("drafter MLP must split evenly over the ranks")+- self.inter = inter // self.world+- r, H, KV, hd = self.rank, self.heads, self.kvh, self.hd++ self.inter = mlps[self.rank]++ m0 = sum(mlps[:self.rank])++ H, KV, hd = self.heads, self.kvh, self.hd+ dev = self.dev++ def gpu(t: torch.Tensor) -> torch.Tensor:+@@ -272,13 +274,13 @@ class Drafter:+ self.layers: list[DraftLayer] = []+ for i in range(int(cfg["num_hidden_layers"])):+ p = f"layers.{i}."+- q = get(p + "self_attn.q_proj.weight")[r * H * hd:(r + 1) * H * hd]+- k = get(p + "self_attn.k_proj.weight")[r * KV * hd:(r + 1) * KV * hd]+- v = get(p + "self_attn.v_proj.weight")[r * KV * hd:(r + 1) * KV * hd]+- o = get(p + "self_attn.o_proj.weight")[:, r * H * hd:(r + 1) * H * hd]+- g = get(p + "mlp.gate_proj.weight")[r * self.inter:(r + 1) * self.inter]+- u = get(p + "mlp.up_proj.weight")[r * self.inter:(r + 1) * self.inter]+- dn = get(p + "mlp.down_proj.weight")[:, r * self.inter:(r + 1) * self.inter]++ q = get(p + "self_attn.q_proj.weight")[q0 * hd:(q0 + H) * hd]++ k = get(p + "self_attn.k_proj.weight")[kv0 * hd:(kv0 + KV) * hd]++ v = get(p + "self_attn.v_proj.weight")[kv0 * hd:(kv0 + KV) * hd]++ o = get(p + "self_attn.o_proj.weight")[:, q0 * hd:(q0 + H) * hd]++ g = get(p + "mlp.gate_proj.weight")[m0:m0 + self.inter]++ u = get(p + "mlp.up_proj.weight")[m0:m0 + self.inter]++ dn = get(p + "mlp.down_proj.weight")[:, m0:m0 + self.inter]+ for conv in ("attention_conv", "mlp_conv"):+ if tuple(get(p + conv + ".base_kernel").shape) != (2, 2, self.D):+ raise ValueError(f"unexpected {conv} base kernel shape")+diff --git tensorfold/families/glm5_next/cuda/engine.py tensorfold/families/glm5_next/cuda/engine.py+index 87f265f..7aa889c 100644+--- tensorfold/families/glm5_next/cuda/engine.py++++ tensorfold/families/glm5_next/cuda/engine.py+@@ -1,4 +1,4 @@+-"""GLM-5.3-Flash on two NCCL ranks; both sample by one keyed rule from the same gathered candidates, so no broadcast."""++"""GLM-5.3-Flash on N NCCL ranks (2, 3 or 4); all sample by one keyed rule from the same gathered candidates, so no broadcast."""++ from __future__ import annotations++@@ -308,15 +308,18 @@ PARALLEL_MOST = 4 # --parallel: concurrent requests at most+ MULTI_WINDOW = 32 # --parallel: rows of every stream's verify windows together (multi.MAX_WINDOW)+++-def slot_bytes(t: dict, world: int = 2, rows: int = MAX_ROWS) -> int:+- """What one more stream slot (``forward.Slots``) takes on each rank, from the text config: every KDA layer's+- recurrent states (two parities), conv window, a decode window's projections and replay scratch."""++def slot_bytes(t: dict, world: int = 2, rows: int = MAX_ROWS, rank: int = 0) -> int:++ """What one more stream slot (``forward.Slots``) takes on rank ``rank`` of ``world``, from the text config:++ every KDA layer's recurrent states (two parities), conv window, a decode window's projections and replay++ scratch."""++ from tensorfold.cuda.geometry import layer_counts+++ from .tp import UNITS, split_sizes+++ linear, _ = layer_counts(t)+ lin = t.get("linear_attn_config") or {}+- lh = int(lin.get("num_heads", t.get("linear_num_heads", 64))) // world++ lh = split_sizes(int(lin.get("num_heads", t.get("linear_num_heads", 64))), world, UNITS["lin"])[rank]+ ld = int(lin.get("head_dim", t.get("linear_head_dim", 128)))+ conv = int(lin.get("short_conv_kernel_size", t.get("linear_conv_kernel_dim", 4)))+ width = 3 * lh * ld + 2 * ld + lh # the KDA input projection's rows (q, k, v, f_a, g_a, beta)+@@ -325,14 +328,16 @@ def slot_bytes(t: dict, world: int = 2, rows: int = MAX_ROWS) -> int:+++ def multi_draft_bytes(t: dict, streams: int, world: int = 2, *, ring: bool, capacity: int,+- tap_rows: int = MAX_ROWS) -> int:+- """``dflash2_multi.MultiDrafter``'s context pool on each rank: ``streams`` rings (or flat contexts of capacity ++- block rows) and the padded context updates' trash rows, keys and values per draft layer."""++ tap_rows: int = MAX_ROWS, rank: int = 0) -> int:++ """``dflash2_multi.MultiDrafter``'s context pool on rank ``rank``: ``streams`` rings (or flat contexts of++ capacity + block rows) and the padded context updates' trash rows, keys and values per draft layer."""++ from tensorfold.cuda.geometry import draft_ring_rows+++ from .tp import split_sizes+++ layers = int(t["num_hidden_layers"])+- heads = int(t["num_key_value_heads"]) // world++ heads = split_sizes(int(t["num_key_value_heads"]), world, 1)[rank]+ hd = int(t["head_dim"])+ block = int((t.get("dflash_config") or {}).get("block_size", 16))+ window = int(t.get("sliding_window", 0))+@@ -342,6 +347,27 @@ def multi_draft_bytes(t: dict, streams: int, world: int = 2, *, ring: bool, capa+ return 2 * layers * heads * hd * (streams * cap + trash) * 2++++def draft_fraction(draft_dir, rank: int, world: int):++ """``geometry.dflash2_weights``'s per-rank rows of the drafter at ``draft_dir`` (``tp.draft_parts``)."""++++ from tensorfold.cuda.capacity import config as read_config++++ from .tp import draft_parts++++ t = read_config(draft_dir)++ heads, kv_heads, inter = int(t["num_attention_heads"]), int(t["num_key_value_heads"]), int(t["intermediate_size"])++ qs, kvs, mlps = draft_parts(heads, kv_heads, inter, world)++ hd = int(t.get("head_dim") or int(t["hidden_size"]) // heads)++ rows = {"q": qs[rank] * hd, "kv": kvs[rank] * hd, "mlp": mlps[rank]}++ totals = {"q": heads * hd, "kv": kv_heads * hd, "mlp": inter}++++ def fraction(kind: str, n: int) -> int:++ if n != totals[kind]:++ raise ValueError(f"drafter {kind} rows {n}, config {totals[kind]}")++ return rows[kind]++ return fraction+++++ def _f64_ints(x: float) -> list[int]:+ return list(struct.unpack("<2i", struct.pack("<d", float(x))))++@@ -372,9 +398,16 @@ def without_mtp(transform, layers: int):+ return lambda name, info: (0, 0) if name.startswith(prefix) else transform(name, info)++++def bell_key(rank: int, n: int) -> str:++ """The store key that wakes follower ``rank`` for request ``n`` (rank 1's is the two-rank engine's name)."""++++ return f"tf_glm_request_{n}" if rank == 1 else f"tf_glm_request_r{rank}_{n}"+++++ class GlmEngine:+- """GLM-5.3-Flash on two ranks (this one ``rank``): weights, MTP and DFlash2 drafting, per-request policies."""++ """GLM-5.3-Flash on ``world`` ranks (this one ``rank``): weights, MTP and DFlash2 drafting, per-request policies."""+++ world = 2 # ranks the model is split over (``tp.Layout``; set by __init__)+ shared = 0 # TF_GLM_SHARED_PREFIX (``shared_prefix``): 0 off, else the fewest tokens it adds+ opener = None # rank 0, shared on: ``<|user|>``'s id, whose first appearance ends the system block+ parallel = 1 # --parallel N: requests decoded together (``multi``); 1 serves one at a time+@@ -382,14 +415,17 @@ class GlmEngine:+ multi = None # --parallel > 1: the ``multi.MultiDecoder`` (both ranks)+ scheduler = None # ... and rank 0's ``multi.GlmScheduler``++- def __init__(self, model_dir: Path, *, rank: int, master: str, port: int, policy: str = DEFAULT_POLICY,++ def __init__(self, model_dir: Path, *, rank: int, master: str, port: int, world: int = 2,++ policy: str = DEFAULT_POLICY,+ drafter: Path | None = None, context: int | None = None, context_explicit: bool | None = None, serial_only: bool = False, comm=None,+ prefill_rows: int | None = None, vision: bool = False, vision_urls: bool = False,+- split=None, parallel: int = 1) -> None:++ split=None, parallel: int = 1, graphs: bool = True) -> None:+ """``comm``: a communicator with ``all_gather`` and ``barrier`` instead of NCCL between two machines (tests);+ ``vision``: rank 0 runs the image tower (rank 1 only takes its rows); ``split``: a ``hcsplit.SplitSettings``+ instead of TF_GLM_HC_SPLIT / TF_GLM_PREFILL_OVERLAP (tests); ``parallel``: requests decoded together+- (``multi``: their caches share one pool, each stream up to the context window; DFlash2 drafts only)."""++ (``multi``: their caches share one pool, each stream up to the context window; DFlash2 drafts only);++ ``world``: the ranks the model is split over (2, 3 or 4; ``tp.Layout``); ``graphs``: False runs every window++ eagerly (tests whose communicator cannot be captured)."""++ import torch++@@ -414,26 +450,34 @@ class GlmEngine:+ # TF_GLM_HC_SPLIT=1 / TF_GLM_PREFILL_OVERLAP=1: prompt chunks' hyper-connection glue split by rows between the+ # ranks (and its exchanges overlapped); the same bits, both ranks must agree (the comparison below)+ self.split = SplitSettings.from_env() if split is None else split++ world = int(world) if comm is None else int(getattr(comm, "world", world))++ from .tp import SIZES++++ if world not in SIZES:++ raise ValueError(f"GLM-5.3-Flash's CUDA engine runs on {', '.join(map(str, SIZES))} ranks, not {world}")+ torch.cuda.set_device(0)+ self.torch = torch+- self.rank = rank++ self.rank, self.world = rank, world+ parallel = int(parallel)+ if not 1 <= parallel <= PARALLEL_MOST:+ raise ValueError(f"--parallel: 1 to {PARALLEL_MOST} requests at once for GLM-5.3-Flash, not {parallel}")+ self.parallel = parallel+ self.policy = "0" if serial_only else policy+ self.serial_only = serial_only+- self.comm = comm if comm is not None else NCCL(rank, 2, master, port)++ self.comm = comm if comm is not None else NCCL(rank, world, master, port)+ self.comm.barrier()+ if comm is None and os.environ.get("TF_GLM_COMM", "nccl") == "roce":+ # small all-gathers (a decode round's partials, the samplers) over b12x's one-shot RoCE transport+ from tensorfold.cuda.roce import RoceComm++- self.comm = RoceComm(self.comm, rank, 2)++ self.comm = RoceComm(self.comm, rank, world)+ if rank == 0:+- print(f"[tensorfold] all-gathers up to {self.comm.roce.max_bytes >> 10} KiB over RoCE "+- f"({', '.join(self.comm.roce.hcas)}; b12x's RoCEnante transport), larger ones over NCCL",+- flush=True)++ roce = self.comm.roce++ routes = getattr(roce, "routes", None)++ via = ", ".join(roce.hcas) if routes is None else "; ".join(++ f"rank {p} over {'+'.join(roce.hcas[h] for h, _ in pairs)}" for p, pairs in sorted(routes.items()))++ print(f"[tensorfold] all-gathers up to {roce.max_bytes >> 10} KiB over RoCE ({via}; b12x's RoCEnante "++ "transport), larger ones over NCCL", flush=True)+ cfg = Config.read(model_dir)+ # Without --context the window stays dense, attending every key without indexer work.+ explicit = context is not None if context_explicit is None else bool(context_explicit)+@@ -442,7 +486,28 @@ class GlmEngine:+ from .qmm import KVB_KINDS, dense_kind, fp8_weights, kvb_kind, kvb_weights, q4_weights++ # TF_GLM_DENSE=fp8 (an EXL3 checkpoint): its BF16 matrices take a byte a value, which the estimate counts+- weights_estimate = split_weights(rule)++ from . import tp as tp_mod++ from .split import rank_cut++++ lay = tp_mod.Layout.from_config(cfg, rank, world)++ self.tp = lay++++ def cut(name: str, shape: list[int], kind: str) -> tuple[int, int]:++ """This rank's share of a split tensor (``split.rank_cut``) or of lm_head's rows, for the estimate."""++ if kind == "vocab":++ if "vocab" not in lay.totals:++ return 0, shape[0] // world++ return lay.vocab_offset, lay.vocab_offset + lay.vocab++ got = rank_cut(lay, name, shape, kind)++ if got is None: # a family the config does not size (two ranks): halves++ n = shape[{"row": 0, "col": -1, "dim1": 1}[kind]]++ return 0, n // world++ return got++++ def share(family: str, total: int) -> int:++ """This rank's width of a split dimension, for the estimate."""++ return lay.size(family) if family in lay.totals else int(total) // world++ weights_estimate = split_weights(rule, world, cut)+ if cfg.quant == "exl3" and dense_kind() == "fp8":+ weights_estimate = fp8_weights(weights_estimate)+ elif cfg.quant == "exl3" and dense_kind() == "q4":+@@ -488,13 +553,13 @@ class GlmEngine:+ def geometry(text):+ from tensorfold.cuda.capacity import Geometry++- g = mla_geometry(text, 2, MAX_ROWS, minimum_slots=DENSE_CAPACITY, latent=LATENT, prefill_rows=prefill_rows,++ g = mla_geometry(text, world, MAX_ROWS, share=share, minimum_slots=DENSE_CAPACITY, latent=LATENT, prefill_rows=prefill_rows,+ mtp=self.mtp_on, onepass=SPARSE_ONEPASS, exl3_prompt=prompt_kernels(),+ prompt_split_k=cfg.quant == "exl3" and dense_kind() != "q4", kv=kv)+ # --parallel: every stream slot past the first (KDA states, conv windows, window scratch); the batched+ # verify window's buffers fit the decode rows the estimate sizes (MLA_DECODE_ROWS), its token selection's+ # fp32 scores (MAX_WINDOW rows x a pool of 4 tokens) grow with the pool+- extra = workspace + (parallel - 1) * (slot_bytes(text) + mla_ring_bytes(text, prefill_rows))++ extra = workspace + (parallel - 1) * (slot_bytes(text, world, rank=rank) + mla_ring_bytes(text, prefill_rows))+ per = 4 * MULTI_WINDOW // 4 if parallel > 1 else 0+ if not extra and not per:+ return g+@@ -503,16 +568,17 @@ class GlmEngine:+ def draft_geometry(text):+ from tensorfold.cuda.capacity import Geometry++- g = dflash2_geometry(text, 2, MAX_ROWS, ring=DRAFT_RING)++ g = dflash2_geometry(text, world, MAX_ROWS, ring=DRAFT_RING,++ kv_heads=tp_mod.split_sizes(int(text["num_key_value_heads"]), world, 1)[rank])+ if parallel == 1:+ return g+ # --parallel: the multi-stream drafter's own pool of contexts beside the solo drafter's+- return Geometry(lambda slots: g.bytes_at(slots) + multi_draft_bytes(text, parallel, ring=DRAFT_RING,++ return Geometry(lambda slots: g.bytes_at(slots) + multi_draft_bytes(text, parallel, world, rank=rank, ring=DRAFT_RING,+ capacity=slots), g.reserve)+ self.capacity_plan = admit(model_dir, context if explicit else cfg.dense_limit, explicit, torch,+ geometry,+- weights_estimate, rank=rank, world=2, gather=self._gather_ints,+- draft_dir=drafter, draft_weights=lambda d: dflash2_weights(d, 2),++ weights_estimate, rank=rank, world=world, gather=self._gather_ints,++ draft_dir=drafter, draft_weights=lambda d: dflash2_weights(d, world, draft_fraction(d, rank, world)),+ draft_geometry=draft_geometry)+ self.limit = self.capacity_plan["context_window"]+ capacity = self.capacity_plan["cache_slots"]+@@ -538,7 +604,7 @@ class GlmEngine:+ verify_code = [verify_code] + MultiSettings.from_env().code() + _f64_ints(budget_ms())+ else:+ verify_code = [verify_code]+- # both ranks must run the same calls: refuse to start when they were given different settings++ # every rank must run the same calls: refuse to start when they were given different settings+ mine = [int(drafter is not None), capacity, int(long_context), int(serial_only), int(LATENT),+ prefill_rows, self.grid, KVB_KINDS.index(kvb)] + (self.copy.code() if self.copy is not None else [0, 0, 0, 0]) + \+ self.split.code() + [int(self.dump is not None), quant_code, self.shared, int(DRAFT_RING), int(self.mtp_on),+@@ -549,17 +615,19 @@ class GlmEngine:+ plan = self.capacity_plan+ wanted = int(float(os.environ.get("TF_GLM_CACHE_GIB", "3")) * 2 ** 30)+ spare = max(0, min(wanted, plan["budget_bytes"] - plan["total_bytes_estimate"]))+- both = self._gather_ints(mine + [spare >> 20])+- if both[0][:-1] != both[1][:-1]:+- raise RuntimeError("the two ranks were started with different settings (draft model, context, drafts, "++ rows = self._gather_ints(mine + [spare >> 20])++ odd = [r for r, row in enumerate(rows) if row[:-1] != rows[0][:-1]]++ if odd:++ raise RuntimeError("the ranks were started with different settings (draft model, context, drafts, "+ "TF_GLM_LATENT, TF_GLM_PREFILL_ROWS, TF_GLM_PROMPT_GRID, TF_GLM_KVB, TF_GLM_COPY_*, "+ "TF_GLM_HC_SPLIT*, TF_GLM_PREFILL_OVERLAP, TF_GLM_OVERLAP_PIECES, TF_GLM_DRAFT_DUMP, "+ "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, "+ "TENSORFOLD_NUCLEUS_UNION, TF_GLM_MAX_ROWS, TF_GLM_WIDE_GRAPHS, TF_GLM_KV): "+- f"rank 0 {both[0][:-1]}, rank 1 {both[1][:-1]}; pull the draft model on both machines "+- "(or pass --drafter none to both) and give both the same flags")+- self.cache_bytes = min(both[0][-1], both[1][-1]) << 20++ 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")++ self.cache_bytes = min(row[-1] for row in rows) << 20+ plan["kept_bytes"] = self.cache_bytes+ for key in ("serving_peak_bytes_estimate", "total_bytes_estimate"):+ plan[key] = plan[key] + self.cache_bytes+@@ -575,7 +643,8 @@ class GlmEngine:+ text = read_config(model_dir)+ g = geometry(text)+ 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, rows=0) // 2 + (22 << 20))++ 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+ if pool_rows < ALIGN:+ raise ValueError(f"--parallel {parallel}: a pool of {pool_rows} tokens is less than one {ALIGN}-token "+@@ -590,15 +659,20 @@ class GlmEngine:+ raise ValueError(("TF_GLM_MTP=0 leaves" if cfg.mtp_layers else "this checkpoint has") + " no MTP head and "+ "no DFlash2 draft model was given, so every round would decode one token: pull the draft "+ "model on both machines (--drafter), or pass --no-drafts to both for the serial reference")+- if self.split.split and self.split.exchange == "p2p" and getattr(self.comm, "world", 2) == 2 \+- and hasattr(self.comm, "exchange"):+- # both ranks: open the split's send/receive connection before the weights and the cache pool take the++ if self.split.split and self.split.exchange == "p2p" and hasattr(self.comm, "exchange" if world == 2++ else "exchange_all"):++ # every rank: open the split's send/receive connections before the weights and the cache pool take the+ # memory; opened at the split's warm-up (after the pool), NCCL's buffer registration could fail with+- # ENOMEM (ibv_reg_mr, issue #36). The connection stays open; nothing it sends changes++ # ENOMEM (ibv_reg_mr, issue #36). The connections stay open; nothing they send changes. Past two ranks,++ # one to every peer, as ``hcsplit.RowSplit.warm`` opens them+ a = torch.zeros((1,), dtype=torch.float32, device="cuda")+- self.comm.exchange([a], [torch.empty_like(a)], 1 - rank)++ if world == 2:++ self.comm.exchange([a], [torch.empty_like(a)], 1 - rank)++ else:++ peers = [p for p in range(world) if p != rank]++ self.comm.exchange_all({p: [a] for p in peers}, {p: [torch.empty_like(a)] for p in peers})+ torch.cuda.synchronize()+- w = load(model_dir, rank=rank, mtp=self.mtp_on)++ w = load(model_dir, rank=rank, world=world, mtp=self.mtp_on)+ w.comm = self.comm+ self.comm.ready("loading") # a peer stuck loading is named, not waited on in NCCL+ self.comm.barrier()+@@ -612,7 +686,7 @@ class GlmEngine:+ from .dflash2 import Drafter++ self.drafter = Drafter(drafter, w, capacity=pool_rows or capacity, tap_rows=MAX_ROWS, ring=DRAFT_RING)+- self.e = Engine(w, capacity=pool_rows or capacity, max_rows=MAX_ROWS, prefill_rows=prefill_rows, graphs=True,++ 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)+@@ -649,7 +723,8 @@ class GlmEngine:+ print(f"[tensorfold] shared-prefix prompt states: kept where a prompt stops sharing another and at the end "+ f"of its system block, when they add {self.shared}+ tokens (TF_GLM_SHARED_PREFIX)", flush=True)+ if self.drafter is not None:+- self.drafter.capture()++ if graphs:++ self.drafter.capture()+ self.costs = self._calibrate()+ if rank == 0:+ c = self.costs+@@ -759,9 +834,9 @@ class GlmEngine:+ back()+ names = list(best)+ mine = torch.tensor([best[n] for n in names], dtype=torch.float32, device="cuda")+- got = torch.empty((2 * mine.numel(),), dtype=torch.float32, device="cuda")++ got = torch.empty((self.world * mine.numel(),), dtype=torch.float32, device="cuda")+ self.comm.all_gather(mine, got)+- both = dict(zip(names, got.view(2, -1).max(dim=0).values.tolist()))++ both = dict(zip(names, got.view(self.world, -1).max(dim=0).values.tolist()))+ e.reset()+ if self.drafter is not None:+ self.drafter.reset()+@@ -779,11 +854,12 @@ class GlmEngine:+ def _gather_ints(self, values: list[int]) -> list[list[int]]:+ torch = self.torch+ mine = torch.tensor(values, dtype=torch.int32, device="cuda")+- got = torch.empty((2 * len(values),), dtype=torch.int32, device="cuda")++ got = torch.empty((self.world * len(values),), dtype=torch.int32, device="cuda")+ self.comm.all_gather(mine, got)+- return [got[:len(values)].tolist(), got[len(values):].tolist()]++ return got.view(self.world, len(values)).tolist()++- # the idle doorbell: rank 1 waits for each request on the rendezvous store (no store: no doorbell), not in NCCL++ # the idle doorbell: the followers wait for each request on the rendezvous store (no store: no doorbell), not in++ # NCCL; a key a follower and request, which only that follower deletes+ def _store(self):+ return getattr(self.comm, "store", None)++@@ -791,7 +867,8 @@ class GlmEngine:+ store = self._store()+ if store is not None:+ self._bell = getattr(self, "_bell", 0) + 1+- store.set(f"tf_glm_request_{self._bell}", b"1")++ for r in range(1, getattr(self, "world", 2)):++ store.set(bell_key(r, self._bell), b"1")++ def _await_bell(self) -> None:+ store = self._store()+@@ -799,7 +876,7 @@ class GlmEngine:+ return+ from datetime import timedelta++- key = f"tf_glm_request_{getattr(self, '_bell', 0) + 1}"++ key = bell_key(getattr(self, "rank", 1), getattr(self, "_bell", 0) + 1)+ while True:+ try:+ store.wait([key], timedelta(hours=1))+@@ -815,12 +892,12 @@ class GlmEngine:++ torch = self.torch+ n = torch.tensor([len(values) if self.rank == 0 else 0], dtype=torch.int32, device="cuda")+- got = torch.empty((2,), dtype=torch.int32, device="cuda")++ got = torch.empty((self.world,), dtype=torch.int32, device="cuda")+ self.comm.all_gather(n, got)+ count = int(got[0].item())+ buf = (torch.tensor(values, dtype=torch.int32, device="cuda") if self.rank == 0+ else torch.zeros((count,), dtype=torch.int32, device="cuda"))+- allv = torch.empty((2 * count,), dtype=torch.int32, device="cuda")++ allv = torch.empty((self.world * count,), dtype=torch.int32, device="cuda")+ self.comm.all_gather(buf, allv)+ return [int(v) for v in allv[:count].tolist()]++@@ -1120,7 +1197,7 @@ class GlmEngine:+ return stats++ def follow(self) -> None:+- """Rank 1: mirror every request rank 0 serves, forever."""++ """Ranks past 0: mirror every request rank 0 serves, forever."""++ if self.multi is not None:+ self.multi.follow()+@@ -1129,7 +1206,7 @@ class GlmEngine:+ self.follow_one()++ def follow_one(self) -> None:+- """Rank 1: mirror one request rank 0 serves."""++ """A rank past 0: mirror one request rank 0 serves."""++ from tensorfold.engine.exact_sampling import Sampling++@@ -1153,7 +1230,7 @@ class GlmEngine:+ if cached:+ hit = next((c for c in self.cache if len(c.ids) == cached and prompt[:cached] == c.ids), None)+ if hit is None:+- raise RuntimeError(f"rank 1 has no snapshot of the {cached} tokens rank 0 resumes from")++ raise RuntimeError(f"rank {self.rank} has no snapshot of the {cached} tokens rank 0 resumes from")+ self._run(prompt, max_tokens, sampling, bool(stop_eos), lambda new: None, code, hit, bool(draft),+ constraint, feed, shared)+ if hasattr(self.comm, "check"):+@@ -1162,7 +1239,7 @@ class GlmEngine:++ class VisionFeed:+ """An image prompt's feature rows for each prefill chunk: rank 0 holds them all, and hands a chunk's rows to+- rank 1 through the all-gather as the chunk comes (rank 1 sends zeros), so neither rank holds a second copy."""++ the other ranks through the all-gather as the chunk comes (they send zeros), so no rank holds a second copy."""++ def __init__(self, engine: GlmEngine, positions: list[int], rows) -> None:+ self.engine, self.positions, self.rows = engine, positions, rows+@@ -1182,7 +1259,7 @@ class VisionFeed:+ n = hi - lo+ mine = (self.rows[lo:hi].contiguous() if self.rows is not None else+ torch.zeros((n, self.width), dtype=torch.bfloat16, device="cuda"))+- both = torch.empty((2 * n, self.width), dtype=torch.bfloat16, device="cuda")++ both = torch.empty((self.engine.world * n, self.width), dtype=torch.bfloat16, device="cuda")+ self.engine.comm.all_gather(mine, both)+ index = torch.tensor([p - start for p in self.positions[lo:hi]], dtype=torch.int64, device="cuda")+ return index, both[:n]+diff --git tensorfold/families/glm5_next/cuda/exl3.cu tensorfold/families/glm5_next/cuda/exl3.cu+index 38824db..5ef3fa0 100644+--- tensorfold/families/glm5_next/cuda/exl3.cu++++ tensorfold/families/glm5_next/cuda/exl3.cu+@@ -989,20 +989,19 @@ void exl3_down_epilogue_cuda(const at::Tensor& Z, const at::Tensor& pick, const+ C10_CUDA_KERNEL_LAUNCH_CHECK();+ }++-// Decode windows (items of up to 16 pairs): ``dec_kernel`` with NT 8, 4 warps and 16 k steps a warp (both of GLM's+-// expert matmuls: gate/up K 4096 in 4 splits, down K 1024 in 1). fuse 0: Z as exl3_grouped_cuda; 1: Y (down); 2: Xd+-// (gate/up; ``done`` holds max_items * N / 128 zeroed ints).+-void exl3_dec_cuda(const at::Tensor& X0, const at::Tensor& X1, const at::Tensor& T0, const at::Tensor& T1,+- const at::Tensor& items, const at::Tensor& counts, const at::Tensor& members, at::Tensor& Z,+- int64_t mats, int64_t K, int64_t N, int64_t P, int64_t SK, int64_t max_items, int64_t E,+- int64_t slots, int64_t fuse, bool xrow, const at::Tensor& sv0, const at::Tensor& sv1,+- const at::Tensor& su2, at::Tensor& out, double limit, at::Tensor& done, int64_t ld) {+- constexpr int NT = 8, W = 4, STEPS = 16;+- TORCH_CHECK(ld >= 0 && ld <= 3, "decode expert kernel: loads 0 (32-bit), 1 / 2 / 3 (16-byte, 1 / 2 / 4 steps ahead)");+- TORCH_CHECK(K % (16 * SK * W) == 0 && K / (16 * SK * W) == STEPS && N % (16 * NT) == 0,+- "decode expert kernel: 16 k steps a warp");+- TORCH_CHECK(fuse != 1 || (SK == 1 && mats == 1), "the fused down epilogue takes one split of one matrix");+- TORCH_CHECK(fuse != 2 || mats == 2, "the fused gate/up epilogue takes gate and up");++// Decode windows (items of up to 16 pairs): ``dec_kernel`` with NT 8, 4 warps and K / 64 k steps a warp: gate/up K++// 4096 in 4 splits (16 steps), down K = the rank's expert width in 1 (16 steps at two ranks' 1024; 8, 10 and 12 for++// the 512 / 640 / 768 of three and four ranks: the grouped kernel's chains at that width, so the same bits as++// TF_GLM_EXL3_DEC=0). fuse 0: Z as exl3_grouped_cuda; 1: Y (down); 2: Xd (gate/up; ``done`` holds max_items * N / 128++// zeroed ints). The 16-byte loads run PD steps ahead where PD divides the steps (10 steps: at most 2).++template <int STEPS>++static void dec_launch(const at::Tensor& X0, const at::Tensor& X1, const at::Tensor& T0, const at::Tensor& T1,++ const at::Tensor& items, const at::Tensor& counts, const at::Tensor& members, at::Tensor& Z,++ int64_t mats, int64_t K, int64_t N, int64_t P, int64_t SK, int64_t max_items, int64_t E,++ int64_t slots, int64_t fuse, bool xrow, const at::Tensor& sv0, const at::Tensor& sv1,++ const at::Tensor& su2, at::Tensor& out, double limit, at::Tensor& done, int64_t ld) {++ constexpr int NT = 8, W = 4;++ constexpr int PD4 = STEPS % 4 == 0 ? 4 : 2;+ dim3 grid((unsigned)max_items, (unsigned)(N / (16 * NT)), (unsigned)(mats * SK));+ auto stream = at::cuda::getCurrentCUDAStream();+ auto h = [](const at::Tensor& t) { return reinterpret_cast<const half*>(t.data_ptr()); };+@@ -1016,12 +1015,39 @@ void exl3_dec_cuda(const at::Tensor& X0, const at::Tensor& X1, const at::Tensor&+ if (ld == 0) DEC1(F_, XR_, 0, 1); \+ else if (ld == 1) DEC1(F_, XR_, 1, 1); \+ else if (ld == 2) DEC1(F_, XR_, 1, 2); \+- else DEC1(F_, XR_, 1, 4)+- if (fuse == 0) { if (xrow) { DEC(0, true); } else { DEC(0, false); } }+- else if (fuse == 1) { if (xrow) { DEC(1, true); } else { DEC(1, false); } }+- else { if (xrow) { DEC(2, true); } else { DEC(2, false); } }++ else DEC1(F_, XR_, 1, PD4)++ if constexpr (STEPS == 16) { // every matrix: gate/up (fuse 0 / 2, xrow) and two ranks' down++ if (fuse == 0) { if (xrow) { DEC(0, true); } else { DEC(0, false); } }++ else if (fuse == 1) { if (xrow) { DEC(1, true); } else { DEC(1, false); } }++ else { if (xrow) { DEC(2, true); } else { DEC(2, false); } }++ } else { // only the down projection of 3 or 4 ranks (one matrix)++ TORCH_CHECK(mats == 1 && !xrow && fuse != 2, "decode expert kernel: ", STEPS,++ " k steps a warp only for the down projection");++ if (fuse == 0) { DEC(0, false); } else { DEC(1, false); }++ }+ #undef DEC+ #undef DEC1++}++++void exl3_dec_cuda(const at::Tensor& X0, const at::Tensor& X1, const at::Tensor& T0, const at::Tensor& T1,++ const at::Tensor& items, const at::Tensor& counts, const at::Tensor& members, at::Tensor& Z,++ int64_t mats, int64_t K, int64_t N, int64_t P, int64_t SK, int64_t max_items, int64_t E,++ int64_t slots, int64_t fuse, bool xrow, const at::Tensor& sv0, const at::Tensor& sv1,++ const at::Tensor& su2, at::Tensor& out, double limit, at::Tensor& done, int64_t ld) {++ constexpr int NT = 8, W = 4;++ TORCH_CHECK(ld >= 0 && ld <= 3, "decode expert kernel: loads 0 (32-bit), 1 / 2 / 3 (16-byte, 1 / 2 / 4 steps ahead)");++ TORCH_CHECK(K % (16 * SK * W) == 0 && N % (16 * NT) == 0, "decode expert kernel: whole k steps a warp");++ TORCH_CHECK(fuse != 1 || (SK == 1 && mats == 1), "the fused down epilogue takes one split of one matrix");++ TORCH_CHECK(fuse != 2 || mats == 2, "the fused gate/up epilogue takes gate and up");++ const int64_t steps = K / (16 * SK * W);++#define ARGS X0, X1, T0, T1, items, counts, members, Z, mats, K, N, P, SK, max_items, E, slots, fuse, xrow, sv0, sv1, \++ su2, out, limit, done, ld++ if (steps == 16) dec_launch<16>(ARGS);++ else if (steps == 12) dec_launch<12>(ARGS);++ else if (steps == 10) dec_launch<10>(ARGS);++ else if (steps == 8) dec_launch<8>(ARGS);++ else TORCH_CHECK(false, "decode expert kernel: 8, 10, 12 or 16 k steps a warp, not ", steps);++#undef ARGS+ C10_CUDA_KERNEL_LAUNCH_CHECK();+ }++diff --git tensorfold/families/glm5_next/cuda/exl3_mm.py tensorfold/families/glm5_next/cuda/exl3_mm.py+index d79bfb2..2bc0b6b 100644+--- tensorfold/families/glm5_next/cuda/exl3_mm.py++++ tensorfold/families/glm5_next/cuda/exl3_mm.py+@@ -11,6 +11,9 @@ import torch++ from tensorfold.cuda import experts as grouped+++# a rank's expert widths the decode kernel (``dec``) takes: two ranks' 1024, four ranks' 512, three ranks' 768 / 640++# (its down projection's K / 64 k steps a warp: 16, 8, 12, 10); others run the grouped kernel (the same bits)++DEC_WIDTHS = (1024, 768, 640, 512)+ # Gate/up and down tile counts, warps, and K splits stay fixed across row counts to preserve each row's bits.+ GATEUP_CFG = (8, 4, 4)+ DOWN_CFG = (8, 4, 1)+@@ -73,7 +76,7 @@ def _ext():+ from tensorfold.cuda.build import load++ here = Path(__file__).parent+- return load(name="tensorfold_glm_exl3_v19", sources=[str(here / "exl3.cpp"), str(here / "exl3.cu")],++ return load(name="tensorfold_glm_exl3_v20", sources=[str(here / "exl3.cpp"), str(here / "exl3.cu")],+ extra_cuda_cflags=["-O3"], verbose=False)+++@@ -204,7 +207,7 @@ def routed(x: torch.Tensor, pick: torch.Tensor, plan: grouped.Plan, ex: Exl3Expe+ raise ValueError("the EXL3 kernel takes items of 16 pairs")+ items = grouped.max_items(R * slots, plan.experts)+ dec, fuse, xrow = dec_settings()+- if dec and R < PROMPT_ROWS and GATEUP_CFG == (8, 4, 4) and DOWN_CFG == (8, 4, 1) and D == 4096 and NI == 1024:++ if dec and R < PROMPT_ROWS and GATEUP_CFG == (8, 4, 4) and DOWN_CFG == (8, 4, 1) and D == 4096 and NI in DEC_WIDTHS:+ xrow = xrow and ex.shared_suh is not None+ if xrow: # one rotated input a row, read by all its pairs' gate and up+ ext.rot_rows(x, x.stride(0), ex.shared_suh, s.xg, R, D)+diff --git tensorfold/families/glm5_next/cuda/forward.py tensorfold/families/glm5_next/cuda/forward.py+index f1c4d14..1af69e5 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++from . import glue, kda as kda_mod, kv8, l2pf, latent, prof, qmm, sparse, tp+ from .attention import AttnScratch, attention, kv_write+ from .weights import LayerW, Weights++@@ -40,8 +40,8 @@ class Buffers:+ dev = w.device+ bf, f32 = torch.bfloat16, torch.float32+ D, S = c.hidden, c.streams+- HL = c.heads // w.world+- LL = c.lin_heads // w.world++ HL = tp.of(w).heads++ LL = tp.of(w).lin_heads+ self.rows, self.prefill = rows, prefill+ head_rows = 1 if prefill else rows+ self.world = w.world+@@ -93,13 +93,13 @@ class Buffers:+ self.igr = torch.empty((rows, c.index_dim), dtype=f32, device=dev)+ self.qi = torch.empty((rows, c.index_heads * c.index_dim), dtype=bf, device=dev)+ # dense MLP+- dl = c.dense_width // w.world++ dl = tp.of(w).dense+ self.gu = torch.empty((rows, 2 * dl), dtype=bf, device=dev)+ self.act = torch.empty((rows, dl), dtype=bf, device=dev)+ self.xs_act = torch.empty((rows, dl // 64), dtype=f32, device=dev)+ # MoE+ slots = c.top_k + 1+- ml = c.moe_width // w.world++ ml = tp.of(w).moe+ self.mlog = torch.empty((rows, c.experts), dtype=f32, device=dev)+ self.pick = torch.empty((rows, slots), dtype=torch.int32, device=dev)+ self.wts = torch.empty((rows, slots), dtype=f32, device=dev)+@@ -112,7 +112,7 @@ class Buffers:+ from .exl3_mm import Scratch, prompt_kernels, prompt_pass++ prompt = prefill and prompt_kernels()+- sl = c.shared_width // w.world++ sl = tp.of(w).shared+ self.exl3 = Scratch(rows, slots, D, ml, dev, prompt=prompt)+ self.sgu = torch.empty((rows, 2 * sl), dtype=bf, device=dev)+ self.sact = torch.empty((rows, sl), dtype=bf, device=dev)+@@ -187,7 +187,7 @@ class Caches:++ c = w.cfg+ dev = w.device+- HL = c.heads // w.world++ HL = tp.of(w).heads+ dsa = len([l for l in w.layers if l.kind == "dsa"])+ self.latent = latent.ENABLED+ if kv not in kv8.KINDS or (kv != "bf16" and not self.latent):+@@ -276,7 +276,7 @@ class Slots:+ def __init__(self, w: Weights, count: int, rows: int) -> None:+ c = w.cfg+ dev = w.device+- LL = c.lin_heads // w.world++ LL = tp.of(w).lin_heads+ kda_layers = [l for l in w.layers if l.kind == "kda"]+ n = len(kda_layers)+ width = kda_layers[0].kda.proj.n if kda_layers else 0+@@ -298,7 +298,7 @@ def slot_bytes(w: Weights, rows: int) -> int:+ """Device bytes one more stream slot takes (``Slots``), without allocating it."""++ c = w.cfg+- LL = c.lin_heads // w.world++ LL = tp.of(w).lin_heads+ kda_layers = [l for l in w.layers if l.kind == "kda"]+ n = len(kda_layers)+ width = kda_layers[0].kda.proj.n if kda_layers else 0+diff --git tensorfold/families/glm5_next/cuda/glue.py tensorfold/families/glm5_next/cuda/glue.py+index ae13bb7..993b71a 100644+--- tensorfold/families/glm5_next/cuda/glue.py++++ tensorfold/families/glm5_next/cuda/glue.py+@@ -280,6 +280,23 @@ def hc_post_pair(x: torch.Tensor, xout: torch.Tensor, g0: torch.Tensor, g1: torc+ _hc_post[(rows, d // block)](x, xout, g0, post, comb, rs, D=d, S=s, WORLD=2, BLOCK=block, num_warps=4)++++def hc_post_ranks(x: torch.Tensor, xout: torch.Tensor, first: torch.Tensor, stride: int, world: int,++ post: torch.Tensor, comb: torch.Tensor) -> None:++ """``hc_post`` of ``world`` ranks' fp32 partials [R, D] that sit ``stride`` elements apart from rank 0's++ (``first``): rows of one all-gathered [world, R', D] buffer (stride R' x D), the sum rank 0 first and every bit++ hc_post's (TF_GLM_HC_SPLIT past two ranks)."""++++ rows, d = first.shape++ if first.dtype != torch.float32 or not first.is_contiguous():++ raise ValueError("hc_post_ranks: contiguous fp32 partials")++ if not rows:++ return++ s = x.shape[1] // d++ block = min(1024, d)++ _hc_post[(rows, d // block)](x, xout, first, post, comb, int(stride), D=d, S=s, WORLD=int(world), BLOCK=block,++ num_warps=4)+++++ @triton.jit+ def _residual_add(X, XOUT, G, RS, D: tl.constexpr, WORLD: tl.constexpr, BLOCK: tl.constexpr):+ """Plain residual (the MTP block): X = bf16(X + bf16(partials summed rank 0 first))."""+diff --git tensorfold/families/glm5_next/cuda/hcsplit.py tensorfold/families/glm5_next/cuda/hcsplit.py+index 5426bb7..7a44e73 100644+--- tensorfold/families/glm5_next/cuda/hcsplit.py++++ tensorfold/families/glm5_next/cuda/hcsplit.py+@@ -1,4 +1,4 @@+-"""TF_GLM_HC_SPLIT=1: a prompt chunk's hyper-connection glue split by rows between the two ranks (decode untouched).++"""TF_GLM_HC_SPLIT=1: a prompt chunk's hyper-connection glue split by rows between the ranks (decode untouched).++ Unsplit, each exchange site (after the attention block and after the MLP/MoE block) all-gathers both ranks' fp32+ partials [R, D], and both ranks run hc_post and the next hc_pre over all R rows. Split, rank r owns rows+@@ -109,15 +109,29 @@ class SplitSettings:+++ class HcSplit:+- """One prompt buffer's row split: rows, pieces, the second stream and its events."""++ """One prompt buffer's row split: rows, pieces, the second stream and its events.++++ Past two ranks (``world`` N): rank r owns rows [r H, r H + H), H = ceil(R / N) (pad rows zero, never read).++ p2p: each rank sends every peer its partial of that peer's rows and receives each peer's partial of its own rows++ into a [N, n, D] staging block a piece (its own partial copied into its slot), summed rank 0 first by hc_post++ (``exchange_all``: one NCCL group, every pair a send and a receive, so it needs every pair connected); its glued++ rows go to every peer the same way. gather (for fabrics without every pair, e.g. a ring): the unsplit all-gather++ of every rank's whole partial, glue on own rows (``glue.hc_post_ranks``), then the in-place all-gather of the++ rows. Either way the partial sums are hc_post's, rank 0 first: the unsplit bits."""++ def __init__(self, w, b, settings: SplitSettings) -> None:+- if w.world != 2 or w.comm is None or (settings.exchange == "p2p" and not hasattr(w.comm, "exchange")):+- raise ValueError("TF_GLM_HC_SPLIT needs two ranks and a communicator with exchange (send/receive), "+- "or TF_GLM_HC_EXCHANGE=gather")++ world = int(getattr(w, "world", 2))++ two = world == 2++ p2p = settings.exchange == "p2p"++ if world < 2 or w.comm is None or (p2p and not hasattr(w.comm, "exchange" if two else "exchange_all")):++ raise ValueError("TF_GLM_HC_SPLIT needs two ranks or more and a communicator with exchange "++ "(send/receive), or TF_GLM_HC_EXCHANGE=gather")+ self.w, self.b, self.settings = w, b, settings+- self.rank, self.peer = w.rank, 1 - w.rank+- self.gather = settings.exchange == "gather"++ self.world = world++ self.rank = w.rank++ self.peer = 1 - w.rank if two else None++ self.peers = [r for r in range(world) if r != w.rank]++ self.gather = not p2p+ # the plain NCCL all-gather (RoceComm sends small gathers over RoCE, whose kernel is not written for in place)+ self.all_gather = getattr(w.comm, "nccl", w.comm).all_gather+ self.active = False+@@ -136,38 +150,52 @@ class HcSplit:+ self.ev_glue = [torch.cuda.Event() for _ in range(n)]+ self.ev_done = torch.cuda.Event()+++ def padded(self, R: int) -> int:++ """R rounded up to a whole share a rank (two ranks: an odd chunk gets one pad row)."""++ return -(-R // self.world) * self.world+++ def applies(self, R: int) -> bool:+- return R >= self.settings.min_rows and R + (R & 1) <= self.b.rows++ return R >= self.settings.min_rows and self.padded(R) <= self.b.rows++ def warm(self) -> None:+- """Open the NCCL send/receive connection to the peer at startup (both ranks call this together)."""++ """Open the NCCL send/receive connections to the peers at startup (every rank calls this together)."""++ if self.gather:+ return+ a = torch.zeros((1,), dtype=torch.float32, device="cuda")+ z = torch.empty_like(a)+- self.w.comm.exchange([a], [z], self.peer)++ if self.world == 2:++ self.w.comm.exchange([a], [z], self.peer)++ else:++ outs = {p: [torch.empty_like(a)] for p in self.peers}++ self.w.comm.exchange_all({p: [a] for p in self.peers}, outs)+ torch.cuda.synchronize()++ # -- per chunk ------------------------------------------------------------------------------------------------+ def begin(self, R: int) -> None:+ b = self.b+- self.R, self.Rp = R, R + (R & 1)+- self.H = H = self.Rp // 2++ self.R, self.Rp = R, self.padded(R)++ self.H = H = self.Rp // self.world+ n = self.settings.piece_count()+ size = -(-H // n)+ if size > 64: # whole 64-row tiles for the glue kernels where possible+ size = min(H, -(-size // 64) * 64)+ self.pieces = [(off, min(size, H - off)) for off in range(0, H, size)]+- # where the peer's partial of each piece of this rank's rows lands: [n, D] fp32 in the all-gather buffer,+- # unused while split (gather: the peer's slot of the piece's [2, n, D])++ # where the peers' partials of each piece of this rank's rows land, in the all-gather buffer (unused while++ # split). Two ranks: [n, D] fp32 a piece (gather: the peer's slot of the piece's [2, n, D]); more: a [N, n, D]++ # block a piece (p2p), or every rank's whole partial [N, Rp, D] (gather, one piece)+ d = b.part.shape[1]+- if self.gather:++ N = self.world++ if N == 2 and self.gather:+ self.got = [b.gath[(2 * off + self.peer * n) * d:(2 * off + self.peer * n + n) * d].view(n, d)+ for off, n in self.pieces]+- else:++ elif N == 2:+ self.got = [b.gath[off * d:(off + n) * d].view(n, d) for off, n in self.pieces]+- if self.Rp > R: # the pad row: zero streams and partials, never read++ elif self.gather:++ self.got = [b.gath[:N * self.Rp * d].view(N, self.Rp, d)]++ else:++ self.got = [b.gath[N * off * d:N * (off + n) * d].view(N, n, d) for off, n in self.pieces]++ if self.Rp > R: # the pad rows: zero streams and partials, never read+ b.x[R:self.Rp].zero_()+ b.part[R:self.Rp].zero_()+ if self.stream is not None:+@@ -191,41 +219,64 @@ class HcSplit:+ fill(lo, hi)++ def _swap_partial(self, j: int) -> None:+- """Piece j: this rank's partial of the peer's rows out, the peer's partial of this rank's rows in."""++ """Piece j: this rank's partial of the peers' rows out, the peers' partials of this rank's rows in."""++ off, n = self.pieces[j]++ b = self.b++ if self.world > 2:++ if self.gather: # every rank's whole partial (one piece)++ self.all_gather(b.part[:self.Rp].reshape(-1), self.got[0].reshape(-1))++ return++ self.w.comm.exchange_all({p: [b.part[p * self.H + off:p * self.H + off + n]] for p in self.peers},++ {p: [self.got[j][p]] for p in self.peers})++ return+ lo = self.theirs() + off+- send = self.b.part[lo:lo + n]++ send = b.part[lo:lo + n]+ if self.gather:+ d = send.shape[1]+- self.all_gather(send.reshape(-1), self.b.gath[2 * off * d:2 * (off + n) * d])++ self.all_gather(send.reshape(-1), b.gath[2 * off * d:2 * (off + n) * d])+ else:+ self.w.comm.exchange([send], [self.got[j]], self.peer)++ def _swap_rows(self, j: int, outs: list[torch.Tensor]) -> None:+- """Piece j of bf16 row buffers: this rank's rows out, the peer's rows in (gather: in place, whole halves)."""++ """Piece j of bf16 row buffers: this rank's rows out, the peers' rows in (gather: in place, whole shares)."""++ off, n = self.pieces[j]+- mine, theirs = self.mine() + off, self.theirs() + off++ mine = self.mine() + off+ if self.gather: # one piece: rank order is row order+ for t in outs:+ self.all_gather(t[mine:mine + n].reshape(-1), t[:self.Rp].reshape(-1))+ return++ if self.world > 2:++ self.w.comm.exchange_all({p: [t[mine:mine + n] for t in outs] for p in self.peers},++ {p: [t[p * self.H + off:p * self.H + off + n] for t in outs] for p in self.peers})++ return++ theirs = self.theirs() + off+ self.w.comm.exchange([t[mine:mine + n] for t in outs], [t[theirs:theirs + n] for t in outs], self.peer)++ def partial(self, fill: Callable[[int, int], None]) -> None:+- """This rank's fp32 partial rows (``fill(lo, hi)`` writes b.part[lo:hi]), the peer's rows sent to it and its+- partial of this rank's rows received (``got``)."""++ """This rank's fp32 partial rows (``fill(lo, hi)`` writes b.part[lo:hi]), the peers' rows sent to them and++ their partials of this rank's rows received (``got``)."""++- theirs, mine = self.theirs(), self.mine()+- if self.stream is None:++ mine = self.mine()++ if self.stream is None or (self.world > 2 and self.gather):+ fill(0, self.R)+- for j in range(len(self.pieces)):+- self._swap_partial(j)++ if self.stream is None:++ for j in range(len(self.pieces)):++ self._swap_partial(j)++ return++ main = torch.cuda.current_stream() # past two ranks, gather: the whole partial, then its gather++ self.ev_fill[0].record(main)++ with torch.cuda.stream(self.stream):++ self.stream.wait_event(self.ev_fill[0])++ self._swap_partial(0)++ self.ev_part[0].record(self.stream)+ return+ main = torch.cuda.current_stream()++ others = [self.theirs()] if self.world == 2 else [p * self.H for p in self.peers]+ for j, (off, n) in enumerate(self.pieces):+- self._fill(fill, theirs + off, theirs + off + n)++ for start in others:++ self._fill(fill, start + off, start + off + n)+ self.ev_fill[j].record(main)+ with torch.cuda.stream(self.stream):+ self.stream.wait_event(self.ev_fill[j])+@@ -234,17 +285,36 @@ class HcSplit:+ self._fill(fill, mine, mine + self.H)++ def own(self) -> tuple[int, int]:+- """This rank's rows of the chunk, [lo, hi) (the pad row left out)."""++ """This rank's rows of the chunk, [lo, hi) (the pad rows left out)."""++ return self.mine(), min(self.mine() + self.H, self.R)+++ def _post(self, j: int, lo: int, hi: int) -> None:++ """hc_post of this rank's rows lo .. hi (piece j): every rank's partial of them summed rank 0 first."""++++ b = self.b++ x = b.x[lo:hi]++ own = b.part[lo:hi]++ if self.world == 2:++ got = self.got[j]++ g0, g1 = (own, got) if self.rank == 0 else (got, own)++ glue.hc_post_pair(x, x, g0, g1, b.post[lo:hi], b.comb[lo:hi])++ elif self.gather:++ whole = self.got[0]++ glue.hc_post_ranks(x, x, whole[0, lo:hi], self.Rp * whole.shape[2], self.world, b.post[lo:hi],++ b.comb[lo:hi])++ else:++ block = self.got[j]++ block[self.rank].copy_(own)++ glue.hc_post(x, x, block, b.post[lo:hi], b.comb[lo:hi])+++ def glue(self, hc=None, norm=None, taps: tuple[int, ...] = (), final: bool = False,+ front: Callable[[int, int], None] | None = None) -> None:+ """hc_post of this rank's rows, then (in order) the layer's DFlash2 taps, the final stream mean (``final``)+- and the next hc_pre (``hc``, ``norm``); their rows swapped with the peer's. ``front(lo, hi)``++ and the next hc_pre (``hc``, ``norm``); their rows swapped with the peers'. ``front(lo, hi)``+ (TF_GLM_PREFILL_OVERLAP=2): the next block's row-independent start on this rank's rows of each piece, on the+ main stream right after the piece's glue, while its swap (and the later pieces' partials) are on the wire;+- the caller runs it on the peer's rows (``own`` is what was done) after this returns."""++ the caller runs it on the peers' rows (``own`` is what was done) after this returns."""++ b, c = self.b, self.w.cfg+ mine = self.mine()+@@ -253,11 +323,9 @@ class HcSplit:+ for j, (off, n) in enumerate(self.pieces):+ lo, hi = mine + off, mine + off + n+ if self.stream is not None:+- main.wait_event(self.ev_part[j])+- own, got = b.part[lo:hi], self.got[j]+- g0, g1 = (own, got) if self.rank == 0 else (got, own)++ main.wait_event(self.ev_part[0 if self.world > 2 and self.gather else j])++ self._post(j, lo, hi)+ x = b.x[lo:hi]+- glue.hc_post_pair(x, x, g0, g1, b.post[lo:hi], b.comb[lo:hi])+ for slot in taps:+ glue.stream_mean(x, b.taps[slot][lo:hi])+ if final:+diff --git tensorfold/families/glm5_next/cuda/multi.py tensorfold/families/glm5_next/cuda/multi.py+index 4c7f64e..bfc06e2 100644+--- tensorfold/families/glm5_next/cuda/multi.py++++ tensorfold/families/glm5_next/cuda/multi.py+@@ -116,18 +116,19 @@ def digest(msg: Sequence[int], seq: int) -> int:+ return int((int((a * w % SEAL_MOD).sum()) + seq * 1_000_003) % SEAL_MOD)+++-def unseal(msg: Sequence[int], seq: int) -> list[int]:+- """Rank 1: the message rank 0 sealed as number ``seq``, or a RuntimeError naming what differs: the ranks would+- otherwise apply different ops and wait on each other's collectives forever (issue #29's hangs had no error)."""++def unseal(msg: Sequence[int], seq: int, rank: int = 1) -> list[int]:++ """A follower (rank ``rank``, 1 or more): the message rank 0 sealed as number ``seq``, or a RuntimeError naming++ what differs: the ranks would otherwise apply different ops and wait on each other's collectives forever (issue++ #29's hangs had no error)."""++ if len(msg) < 2:+- raise RuntimeError(f"rank 1: message {seq} from rank 0 is {len(msg)} values long, too short to be sealed; "+- "the ranks are out of step: restart both")++ raise RuntimeError(f"rank {rank}: message {seq} from rank 0 is {len(msg)} values long, too short to be sealed; "++ "the ranks are out of step: restart them all")+ body, got_seq, got = list(msg[:-2]), int(msg[-2]), int(msg[-1])+ if got_seq != seq or got != digest(body, got_seq):+- raise RuntimeError(f"rank 1: expected rank 0's message {seq}, received number {got_seq} "++ raise RuntimeError(f"rank {rank}: expected rank 0's message {seq}, received number {got_seq} "+ f"({'checksum matches' if got == digest(body, got_seq) else 'checksum differs'}, "+- f"{len(body)} values): the ranks are out of step: restart both")++ f"{len(body)} values): the ranks are out of step: restart them all")+ return body+++@@ -548,9 +549,10 @@ class MultiDecoder:+ if ready is not None:+ ready.record()+ comm = self.g.comm+- got = torch.empty((2,), dtype=torch.int32, device=dev)++ world = self.g.world++ got = torch.empty((world,), dtype=torch.int32, device=dev)+ comm.all_gather(length, got)+- allv = torch.empty((2 * n,), dtype=torch.int32, device=dev)++ allv = torch.empty((world * n,), dtype=torch.int32, device=dev)+ comm.all_gather(vals[:n], allv)++ def _time_rows(self, reps: int = 5) -> list[float]:+@@ -562,9 +564,10 @@ class MultiDecoder:+ raise ValueError("TF_GLM_MULTI_DEPTH=joint needs the batched verify window's graphs "+ "(TF_GLM_MULTI_VERIFY=batched, TF_GLM_MULTI_GRAPHS=1)")+ mine = torch.tensor(v.time_rows(reps), dtype=torch.float32, device=self.w.device)+- got = torch.empty((2 * mine.numel(),), dtype=torch.float32, device=self.w.device)++ world = self.g.world++ got = torch.empty((world * mine.numel(),), dtype=torch.float32, device=self.w.device)+ self.g.comm.all_gather(mine, got)+- return [float(x) for x in got.view(2, -1).max(dim=0).values.tolist()]++ return [float(x) for x in got.view(world, -1).max(dim=0).values.tolist()]++ @torch.no_grad()+ def _time_prompt_layers(self):+@@ -1659,8 +1662,8 @@ class MultiDecoder:+ if self.idle:+ self.g._await_bell()+ self.idle = False+- _watch(self.watchdog, "rank 1 message") # busy: rank 0's next message is due within a round+- self.apply(unseal(self.g._share(None), self.received))++ _watch(self.watchdog, f"rank {self.rank} message") # busy: rank 0's next message is due within a round++ self.apply(unseal(self.g._share(None), self.received, self.rank))+ self.received = (self.received + 1) % SEAL_MOD+ _unwatch(self.watchdog)+ if once:+diff --git tensorfold/families/glm5_next/cuda/split.py tensorfold/families/glm5_next/cuda/split.py+index 8f51c55..a973b31 100644+--- tensorfold/families/glm5_next/cuda/split.py++++ tensorfold/families/glm5_next/cuda/split.py+@@ -71,54 +71,84 @@ def read_header(path: str | Path) -> tuple[dict, int]:+ return header, 8 + n+++-def split_bytes(raw: np.ndarray, shape: list[int], itemsize: int, kind: str, rank: int) -> tuple[np.ndarray, list[int]]:+- """A tensor's bytes -> rank's part of them and its shape."""++AXIS = {"row": 0, "col": 1, "dim1": 1}++++++def _cut(shape: list[int], kind: str, rank: int, cut: tuple[int, int] | None) -> tuple[int, int]:++ """[start, stop) of the split axis: ``cut`` (``tp.Layout.cut``), or rank's half of an even axis (two ranks)."""++++ if kind == "col" and len(shape) != 2:++ raise ValueError(f"column split needs a 2-D shape, got {shape}")++ if kind == "dim1" and len(shape) < 2:++ raise ValueError(f"split of the second axis needs a second dim, got {shape}")++ n = shape[AXIS[kind]]++ if cut is None:++ if n % 2:++ raise ValueError(f"{kind} split of an odd dim {shape}")++ return rank * (n // 2), (rank + 1) * (n // 2)++ a, b = int(cut[0]), int(cut[1])++ if not 0 <= a < b <= n:++ raise ValueError(f"{kind} split [{a}, {b}) outside {shape}")++ return a, b++++++def split_bytes(raw: np.ndarray, shape: list[int], itemsize: int, kind: str, rank: int,++ cut: tuple[int, int] | None = None) -> tuple[np.ndarray, list[int]]:++ """A tensor's bytes -> rank's part of them and its shape; ``cut``: the rank's [start, stop) of the split axis++ (``tp.Layout.cut``; default rank's half, the two-rank split)."""++ if kind == "rep":+ return raw, list(shape)++ if kind not in AXIS:++ raise ValueError(kind)++ a, b = _cut(shape, kind, rank, cut)+ if kind == "row":+- rows = shape[0]+- if rows % 2:+- raise ValueError(f"row split of odd leading dim {shape}")+- per = raw.size // rows+- half = rows // 2+- return raw[rank * half * per:(rank + 1) * half * per], [half] + list(shape[1:])+- if kind == "col":+- if len(shape) != 2 or shape[1] % 2:+- raise ValueError(f"column split needs an even 2-D shape, got {shape}")+- view = raw.reshape(shape[0], shape[1] * itemsize)+- half = shape[1] // 2+- part = np.ascontiguousarray(view[:, rank * half * itemsize:(rank + 1) * half * itemsize])+- return part.reshape(-1), [shape[0], half]+- if kind == "dim1": # the second axis of a 2-D or higher tensor+- if len(shape) < 2 or shape[1] % 2:+- raise ValueError(f"split of the second axis needs an even second dim, got {shape}")+- inner = int(np.prod(shape[2:])) * itemsize+- view = raw.reshape(shape[0], shape[1] * inner)+- half = shape[1] // 2+- part = np.ascontiguousarray(view[:, rank * half * inner:(rank + 1) * half * inner])+- return part.reshape(-1), [shape[0], half] + list(shape[2:])+- raise ValueError(kind)+-+-+-def split_device(raw, shape: list[int], itemsize: int, kind: str, rank: int):++ per = raw.size // shape[0]++ return raw[a * per:b * per], [b - a] + list(shape[1:])++ inner = int(np.prod(shape[2:])) * itemsize++ view = raw.reshape(shape[0], shape[1] * inner)++ part = np.ascontiguousarray(view[:, a * inner:b * inner])++ return part.reshape(-1), [shape[0], b - a] + list(shape[2:])++++++def split_device(raw, shape: list[int], itemsize: int, kind: str, rank: int, cut: tuple[int, int] | None = None):+ """``split_bytes`` for a uint8 tensor on the GPU: the rank's part (a new contiguous tensor) and its shape."""++ if kind == "rep":+ return raw.clone(), list(shape)++ if kind not in AXIS:++ raise ValueError(kind)++ a, b = _cut(shape, kind, rank, cut)+ if kind == "row":+- if shape[0] % 2:+- raise ValueError(f"row split of odd leading dim {shape}")+- per, half = raw.numel() // shape[0], shape[0] // 2+- return raw[rank * half * per:(rank + 1) * half * per].clone(), [half] + list(shape[1:])+- if kind in ("col", "dim1"):+- if len(shape) < 2 or shape[1] % 2 or (kind == "col" and len(shape) != 2):+- raise ValueError(f"{kind} split needs an even second dim, got {shape}")+- inner = int(np.prod(shape[2:])) * itemsize+- half = shape[1] // 2+- part = raw.view(shape[0], shape[1] * inner)[:, rank * half * inner:(rank + 1) * half * inner]+- return part.contiguous().reshape(-1), [shape[0], half] + list(shape[2:])+- raise ValueError(kind)++ per = raw.numel() // shape[0]++ return raw[a * per:b * per].clone(), [b - a] + list(shape[1:])++ inner = int(np.prod(shape[2:])) * itemsize++ part = raw.view(shape[0], shape[1] * inner)[:, a * inner:b * inner]++ return part.contiguous().reshape(-1), [shape[0], b - a] + list(shape[2:])++++++def layout_for(model_dir: str | Path, rank: int, world: int):++ """``tp.Layout`` of rank ``rank`` of ``world`` from the checkpoint's config."""++++ from .tp import Layout++++ raw = json.loads((Path(model_dir) / "config.json").read_text())++ return Layout.from_text(dict(raw.get("text_config") or raw), rank, world)++++++def rank_cut(layout, name: str, shape: list[int], kind: str) -> tuple[int, int] | None:++ """The rank's [start, stop) of ``name``'s split axis by ``layout`` (None for a replicated tensor)."""++++ if kind in ("rep", "drop"):++ return None++ if layout is None: # two ranks without a config: halves++ return None++ family = layout.family(name)++ if family is None or family not in layout.totals:++ if layout.world == 2: # a family the config does not size: halves, as ever++ return None++ raise ValueError(f"{name}: split ({kind}) but the config sizes no tensor-parallel family for it")++ return layout.cut(family, shape[AXIS[kind]])+++ def torch_dtype(dtype: str):+@@ -133,19 +163,37 @@ def rank_files(model_dir: str | Path, rank: int) -> list[Path]:+ return sorted(Path(model_dir).glob(f"*.rank{rank}.safetensors"))++++def folder_world(files: list[Path]) -> int:++ """The tensor-parallel size a rank folder was split for (its ``tf_tp`` metadata; none: the two-rank split)."""++++ worlds = set()++ for path in files:++ meta = read_header(path)[0].get("__metadata__") or {}++ worlds.add(int(meta.get("tf_tp", 2)))++ if len(worlds) > 1:++ raise ValueError(f"rank files split for different sizes: {sorted(worlds)}")++ return worlds.pop() if worlds else 2+++++ class RankReader:+ """Read stored-dtype CPU tensors for one rank from the full checkpoint or its pre-split folder."""++- def __init__(self, model_dir: str | Path, rank: int) -> None:++ def __init__(self, model_dir: str | Path, rank: int, world: int = 2) -> None:+ from tensorfold.cuda.direct_read import ReadAhead, Reader, SafeTensors++- self.dir, self.rank = Path(model_dir), rank+- self.io = Reader() # O_DIRECT reads where the file system allows them+- self.reads = ReadAhead(self.io, READERS, RUN, GAP)+- mine, other = rank_files(self.dir, rank), rank_files(self.dir, 1 - rank)++ self.dir, self.rank, self.world = Path(model_dir), rank, int(world)++ mine = rank_files(self.dir, rank)++ other = sorted(p for p in self.dir.glob("*.rank*.safetensors") if p not in mine)+ if other and not mine:+- raise ValueError(f"{self.dir} holds rank {1 - rank}'s share: give rank {rank} its own folder or the "++ raise ValueError(f"{self.dir} holds another rank's share ({other[0].name}): give rank {rank} its own "++ "folder or the full checkpoint")++ if mine and folder_world(mine) != self.world:++ raise ValueError(f"{self.dir} holds rank {rank}'s share for --tp {folder_world(mine)}, not --tp "++ f"{self.world}: split it again (python -m {__name__} --tp {self.world}) or give the "+ "full checkpoint")++ self._layout = False # read from config.json at the first split tensor++ self.io = Reader() # O_DIRECT reads where the file system allows them++ self.reads = ReadAhead(self.io, READERS, RUN, GAP)+ self.split = bool(mine)+ if self.split:+ self.folder = SafeTensors(mine, self.io)+@@ -169,6 +217,17 @@ class RankReader:+ items.append((name, span[0], span[1], span[2], span))+ self.reads.queue(items, device, self._cut)+++ @property++ def layout(self):++ """This rank's ``tp.Layout`` (None without a config.json at two ranks: plain halves)."""++++ if self._layout is False:++ if self.world == 2 and not (self.dir / "config.json").exists():++ self._layout = None++ else:++ self._layout = layout_for(self.dir, self.rank, self.world)++ return self._layout+++ @property+ def ahead(self) -> dict:+ return self.reads.ahead+@@ -180,12 +239,13 @@ class RankReader:+ def close(self) -> None:+ self.reads.close()++- def _span(self, name: str) -> tuple[str, int, int, str, list[int], str]:+- """(file, first byte, end byte, split kind, shape, dtype) of the bytes this rank reads for ``name``."""++ def _span(self, name: str) -> tuple:++ """(file, first byte, end byte, split kind, shape, dtype, cut) of the bytes this rank reads for ``name``;++ ``cut``: the rank's [start, stop) of the split axis."""++ if self.split: # a rank folder holds the rank's tensors as they are+ path, begin, n, dtype, shape = self.folder.where[name]+- return str(path), begin, begin + n, "rep", list(shape), dtype++ return str(path), begin, begin + n, "rep", list(shape), dtype, None+ file = str(self.dir / self.index[name])+ if file not in self.files:+ self.files[file] = read_header(file)+@@ -196,18 +256,22 @@ class RankReader:+ raise KeyError(f"{name} is not used by the engine")+ a, b = info["data_offsets"]+ shape = list(info["shape"])+- if kind == "row" and shape and shape[0] % 2 == 0: # the rank's rows are one run: read only those+- per = (b - a) // shape[0] * (shape[0] // 2)+- a, b, kind, shape = a + self.rank * per, a + (self.rank + 1) * per, "rep", [shape[0] // 2] + shape[1:]+- return file, base + a, base + b, kind, shape, info["dtype"]++ cut = rank_cut(self.layout, name, shape, kind)++ if kind == "row" and cut is None and shape and shape[0] % 2 == 0:++ cut = _cut(shape, kind, self.rank, None)++ if kind == "row" and cut is not None: # the rank's rows are one run: read only those++ per = (b - a) // shape[0]++ a, b = a + cut[0] * per, a + cut[1] * per++ kind, shape, cut = "rep", [cut[1] - cut[0]] + shape[1:], None++ return file, base + a, base + b, kind, shape, info["dtype"], cut++ def _tensor(self, raw: np.ndarray, span: tuple, own: bool):+ """The rank's tensor from the span's bytes; ``own``: never a view of ``raw`` (a shared read's buffer)."""++ import torch++- _, _, _, kind, shape, dtype = span+- data, shape = split_bytes(raw, shape, DTYPE_BYTES[dtype], kind, self.rank)++ _, _, _, kind, shape, dtype, cut = span++ data, shape = split_bytes(raw, shape, DTYPE_BYTES[dtype], kind, self.rank, cut)+ if own and np.may_share_memory(data, raw):+ data = data.copy()+ return torch.from_numpy(data).view(torch_dtype(dtype)).reshape(shape)+@@ -223,8 +287,8 @@ class RankReader:++ if not raw.is_cuda:+ return self._tensor(raw.numpy(), span, own=True)+- _, _, _, kind, shape, dtype = span+- data, shape = split_device(raw, shape, DTYPE_BYTES[dtype], kind, self.rank)++ _, _, _, kind, shape, dtype, cut = span++ data, shape = split_device(raw, shape, DTYPE_BYTES[dtype], kind, self.rank, cut)+ return data.view(torch_dtype(dtype)).reshape(shape)++ def write(path: str, tensors: list[tuple[str, str, list[int], np.ndarray]], metadata: dict | None) -> None:+@@ -246,11 +310,16 @@ def write(path: str, tensors: list[tuple[str, str, list[int], np.ndarray]], meta+ os.replace(tmp, path)+++-def split_file(src: str | Path, out: str | Path, rank: int) -> dict:+- """One checkpoint file -> OUT/<stem>.rank<R>.safetensors with the rank's part of every tensor it keeps."""++def split_file(src: str | Path, out: str | Path, rank: int, world: int = 2, layout=None) -> dict:++ """One checkpoint file -> OUT/<stem>.rank<R>.safetensors with the rank's part of every tensor it keeps (of++ ``world`` ranks by ``layout``, a ``tp.Layout``; the metadata names a size past 2 as ``tf_tp``)."""++ header, base = read_header(src)+ metadata = header.pop("__metadata__", None)++ if layout is None and (int(world) != 2 or (Path(src).parent / "config.json").exists()):++ layout = layout_for(Path(src).parent, rank, world)++ if int(world) != 2:++ metadata = {**(metadata or {}), "tf_tp": str(int(world))}+ mm = np.memmap(src, dtype=np.uint8, mode="r")+ stem = os.path.basename(str(src)).replace(".safetensors", "")+ summary = {"rep": 0, "row": 0, "col": 0, "dim1": 0, "drop": 0}+@@ -263,7 +332,8 @@ def split_file(src: str | Path, out: str | Path, rank: int) -> dict:+ continue+ a, b = info["data_offsets"]+ itemsize = DTYPE_BYTES[info["dtype"]]+- data, shape = split_bytes(mm[base + a:base + b], info["shape"], itemsize, kind, rank)++ data, shape = split_bytes(mm[base + a:base + b], info["shape"], itemsize, kind, rank,++ rank_cut(layout, name, list(info["shape"]), kind))+ if int(np.prod(shape)) * itemsize != data.size:+ raise ValueError(f"{name}: {shape} does not match {data.size} bytes")+ part.append((name, info["dtype"], shape, data))+@@ -276,9 +346,13 @@ def split_file(src: str | Path, out: str | Path, rank: int) -> dict:+ def main(argv: list[str] | None = None) -> int:+ p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ p.add_argument("model_dir", type=Path, help="the checkpoint (e.g. the snapshot `tensorfold pull` downloaded)")+- p.add_argument("--rank", type=int, choices=(0, 1), required=True, help="the rank this machine serves")+- p.add_argument("out", type=Path, help="the folder to write (then: tensorfold serve OUT --tp 2 --rank R ...)")++ p.add_argument("--tp", type=int, choices=(2, 3, 4), default=2, help="ranks the model is split over")++ p.add_argument("--rank", type=int, choices=(0, 1, 2, 3), required=True, help="the rank this machine serves")++ p.add_argument("out", type=Path, help="the folder to write (then: tensorfold serve OUT --tp N --rank R ...)")+ args = p.parse_args(argv)++ if args.rank >= args.tp:++ p.error(f"--rank {args.rank} needs --tp {args.rank + 1} or more")++ layout = layout_for(args.model_dir, args.rank, args.tp)+ files = sorted(args.model_dir.glob("model-*.safetensors"))+ if not files:+ raise SystemExit(f"{args.model_dir}: no model-*.safetensors files")+@@ -290,7 +364,7 @@ def main(argv: list[str] | None = None) -> int:+ stem = src.name.replace(".safetensors", "")+ if (args.out / f"{stem}.rank{args.rank}.safetensors").exists():+ continue+- print(src.name, split_file(src, args.out, args.rank), flush=True)++ print(src.name, split_file(src, args.out, args.rank, args.tp, layout), flush=True)+ print(f"rank {args.rank}'s share of {len(files)} files in {args.out}", flush=True)+ return 0++diff --git tensorfold/families/glm5_next/cuda/tp.py tensorfold/families/glm5_next/cuda/tp.py+new file mode 100644+index 0000000..5eec3b1+--- /dev/null++++ tensorfold/families/glm5_next/cuda/tp.py+@@ -0,0 +1,178 @@++"""GLM-5.3-Flash's tensor-parallel layout over N ranks (N = 2, 3, 4): which share of each split dimension a rank++holds. Every family splits in whole units (``tensorfold.cuda.shares``), the remainder to the lowest ranks, so two++ranks hold exact halves (the two-rank engine's split) and three hold e.g. 22/21/21 heads and 6/5/5 of an expert's++16 Hadamard blocks. Nothing is padded: no exchanged tensor is per-head or per-column (the ranks gather full-width++fp32 partials and top-k candidates), so ranks may hold different shapes.++++Families (the split checkpoint tensors, ``split.ROW`` / ``COL`` / EXL3 rules):++ heads MLA attention heads: q_b and kv_b rows, a DSA layer's o_proj columns unit 1 head++ lin KDA heads: q/k/v (and their convs), f_b, g_b, b, A_log, dt_bias rows, o_proj unit 1 head++ dense the dense MLP's intermediate (layers before first_k_dense_replace) unit 128++ moe a routed expert's intermediate (EXL3: whole 128-column Hadamard blocks) unit 128++ shared the shared expert's intermediate unit 128++ vocab lm_head rows unit 64++"""++++from __future__ import annotations++++import re++from dataclasses import dataclass, field++++from tensorfold.cuda.shares import parts++++UNITS = {"heads": 1, "lin": 1, "dense": 128, "moe": 128, "shared": 128, "vocab": 64}++SIZES = (2, 3, 4) # the engine's tensor-parallel sizes++++_LAYER = re.compile(r"(?:^|\.)layers\.(\d+)\.")++_FAMILIES = (++ (re.compile(r"\.mlp\.experts\.\d+\."), "moe"),++ (re.compile(r"\.mlp\.shared_experts\."), "shared"),++ (re.compile(r"\.mlp\.(gate|up|down)_proj\."), "dense"),++ (re.compile(r"\.self_attn\.(q_b|kv_b)_proj\."), "heads"),++ (re.compile(r"\.self_attn\.((q|k|v)_proj|(q|k|v)_conv1d|f_b_proj|g_b_proj|b_proj)\."), "lin"),++ (re.compile(r"\.self_attn\.(A_log|dt_bias)$"), "lin"),++ (re.compile(r"^lm_head\."), "vocab"),++)++_O_PROJ = re.compile(r"\.self_attn\.o_proj\.")++++++@dataclass(frozen=True)++class Layout:++ """Rank ``rank`` of ``world``: the totals of every family and this rank's [start, stop) of each."""++++ rank: int++ world: int++ totals: dict = field(hash=False)++ kinds: tuple = () # per layer "kda" / "dsa" (an o_proj's family); past them: the MTP layer (dsa)++++ def __post_init__(self) -> None:++ if not 0 <= self.rank < self.world:++ raise ValueError(f"rank {self.rank} of {self.world}")++ for name in self.totals:++ self.sizes(name) # every family must split whole++++ @classmethod++ def from_config(cls, cfg, rank: int, world: int) -> "Layout":++ """From ``weights.Config``."""++++ names = {"heads": "heads", "lin": "lin_heads", "dense": "dense_width", "moe": "moe_width",++ "shared": "shared_width", "vocab": "vocab"}++ totals = {f: int(getattr(cfg, a)) for f, a in names.items() if getattr(cfg, a, None) is not None}++ return cls(int(rank), int(world), totals, tuple(getattr(cfg, "kinds", ()) or ()))++++ @classmethod++ def from_text(cls, t: dict, rank: int, world: int) -> "Layout":++ """From a checkpoint's text config (``config.json``'s text_config or the whole of it)."""++++ lin = t.get("linear_attn_config") or {}++ kinds = tuple("kda" if k == "linear_attention" else "dsa" for k in t.get("layer_types", ()))++ totals = {}++ if "num_attention_heads" in t:++ totals["heads"] = int(t["num_attention_heads"])++ if "num_heads" in lin or "linear_num_heads" in t:++ totals["lin"] = int(lin.get("num_heads", t.get("linear_num_heads", 0)))++ if "intermediate_size" in t:++ totals["dense"] = int(t["intermediate_size"])++ if "moe_intermediate_size" in t:++ moe = int(t["moe_intermediate_size"])++ totals.update(moe=moe, shared=moe * int(t.get("n_shared_experts", 1)))++ if "vocab_size" in t:++ totals["vocab"] = int(t["vocab_size"])++ return cls(int(rank), int(world), totals, kinds)++++ def sizes(self, family: str) -> list[int]:++ return split_sizes(self.totals[family], self.world, UNITS[family])++++ def size(self, family: str) -> int:++ return self.sizes(family)[self.rank]++++ def start(self, family: str) -> int:++ return sum(self.sizes(family)[:self.rank])++++ def largest(self, family: str) -> int:++ """The largest share any rank holds (rank 0's): what a buffer every rank sizes alike must take."""++ return max(self.sizes(family))++++ def cut(self, family: str, length: int) -> tuple[int, int]:++ """This rank's [start, stop) of an axis of ``length`` elements holding ``family``'s total (rows of a weight,++ packed words, trellis tiles, group scales)."""++++ total, a = self.totals[family], self.start(family)++ b = a + self.size(family)++ if (a * length) % total or (b * length) % total:++ raise ValueError(f"rank {self.rank} of {self.world}: [{a}, {b}) of {family}'s {total} is not whole on an "++ f"axis of {length}")++ return a * length // total, b * length // total++++ def at(self, rank: int) -> "Layout":++ return Layout(rank, self.world, self.totals, self.kinds)++++ # the per-rank widths the engine sizes its weights and buffers by++ @property++ def heads(self) -> int:++ return self.size("heads")++++ @property++ def lin_heads(self) -> int:++ return self.size("lin")++++ @property++ def dense(self) -> int:++ return self.size("dense")++++ @property++ def moe(self) -> int:++ return self.size("moe")++++ @property++ def shared(self) -> int:++ return self.size("shared")++++ @property++ def vocab(self) -> int:++ return self.size("vocab")++++ @property++ def vocab_offset(self) -> int:++ return self.start("vocab")++++ def family(self, name: str) -> str | None:++ """The family a split checkpoint tensor belongs to (None: not one this layout splits)."""++++ if _O_PROJ.search(name):++ m = _LAYER.search(name)++ layer = int(m.group(1)) if m else -1++ return "lin" if 0 <= layer < len(self.kinds) and self.kinds[layer] == "kda" else "heads"++ for pattern, family in _FAMILIES:++ if pattern.search(name):++ return family++ return None++++++def split_sizes(total: int, world: int, unit: int) -> list[int]:++ """Each rank's share of a family's ``total``: halves at two ranks whenever the total is even (the two-rank++ engine's split, whatever the unit), else whole ``unit``s as even as they go (``shares.parts``)."""++++ if world == 2 and total % 2 == 0:++ return [total // 2, total // 2]++ return parts(total, world, unit)++++++def of(w) -> Layout:++ """The layout of a ``weights.Weights`` (or a stand-in with cfg, rank and world)."""++++ lay = getattr(w, "tp", None)++ if lay is None:++ lay = Layout.from_config(w.cfg, getattr(w, "rank", 0), getattr(w, "world", 1))++ return lay++++++def draft_parts(heads: int, kv_heads: int, inter: int, world: int) -> tuple[list[int], list[int], list[int]]:++ """DFlash2's split: KV heads in whole groups (each with its heads // kv_heads query heads), the MLP in units of++ 128 -> (query heads, KV heads, MLP width) per rank. 32 / 8 over 3 ranks: KV 3/3/2, queries 12/12/8."""++++ if heads % kv_heads:++ raise ValueError(f"drafter: {heads} query heads over {kv_heads} KV heads")++ group = heads // kv_heads++ kv = split_sizes(kv_heads, world, 1)++ return [k * group for k in kv], kv, split_sizes(inter, world, 128 if inter % 128 == 0 else 1)+diff --git tensorfold/families/glm5_next/cuda/verify.py tensorfold/families/glm5_next/cuda/verify.py+index f359bc9..64dbc7c 100644+--- tensorfold/families/glm5_next/cuda/verify.py++++ tensorfold/families/glm5_next/cuda/verify.py+@@ -97,7 +97,9 @@ class BatchedVerify:+ self.sel = SelectScratch(rows, e.caches.rows, dev) if e.caches.index is not None else None+ kda_layers = [l for l in w.layers if l.kind == "kda"]+ n = len(kda_layers)+- LL = c.lin_heads // w.world++ from .tp import of as layout_of++++ LL = layout_of(w).lin_heads+ width = kda_layers[0].kda.proj.n if kda_layers else 0+ self.kda_index = {l.index: i for i, l in enumerate(kda_layers)}+ self.dsa_index = {l.index: i for i, l in enumerate(l for l in w.layers if l.kind == "dsa")}+diff --git tensorfold/families/glm5_next/cuda/weights.py tensorfold/families/glm5_next/cuda/weights.py+index 783bd39..b768c7d 100644+--- tensorfold/families/glm5_next/cuda/weights.py++++ tensorfold/families/glm5_next/cuda/weights.py+@@ -213,10 +213,17 @@ class Weights:+ comm: Any = None+ meta: dict = field(default_factory=dict)+ draft_head: Q4 | None = None # BF16 heads: a 4-bit copy the draft steps read (drafts only propose)++ tp: Any = None # the rank's ``tp.Layout`` (None: made from cfg, rank and world)++++ def __post_init__(self) -> None:++ if self.tp is None:++ from .tp import Layout++++ self.tp = Layout.from_config(self.cfg, self.rank, self.world)++ @property+ def vocab_offset(self) -> int:+- return self.rank * (self.cfg.vocab // self.world)++ return self.tp.vocab_offset++ def nbytes(self) -> int:+ total = 0+@@ -247,20 +254,22 @@ class Weights:+ return total+++-def load(model_dir: str | Path, *, rank: int, device: str = "cuda", mtp: bool = True) -> Weights:+- """One of two ranks from a checkpoint or rank folder, MTP included unless ``mtp`` is False, with its head half."""++def load(model_dir: str | Path, *, rank: int, world: int = 2, device: str = "cuda", mtp: bool = True) -> Weights:++ """Rank ``rank`` of ``world`` from a checkpoint or rank folder (``tp.Layout``'s shares), MTP included unless++ ``mtp`` is False, with its rows of the head."""++ from .split import RankReader++ from .tp import Layout++- world = 2+ cfg = Config.read(model_dir)++ lay = Layout.from_config(cfg, rank, world)+ if cfg.quant not in ("mlx", "exl3"):+ raise ValueError(f"GLM-5.3-Flash's CUDA engine reads MLX 4-bit or EXL3 checkpoints, not {cfg.quant}")+ exl3 = cfg.quant == "exl3"+ dev = torch.device(device)+- rd = RankReader(model_dir, rank)+- HL = cfg.heads // world+- LL = cfg.lin_heads // world++ rd = RankReader(model_dir, rank, world)++ HL = lay.heads++ LL = lay.lin_heads++ def t(name: str, dtype: torch.dtype | None = None) -> torch.Tensor:+ x = rd.get(PREFIX + name)+@@ -432,23 +441,22 @@ def load(model_dir: str | Path, *, rank: int, device: str = "cuda", mtp: bool =+ try: # a failed load still cancels the reads queued ahead+ which = list(range(cfg.layers))+ built = [layer(i) for i in which]+- vl = cfg.vocab // world++ v0, v1 = lay.vocab_offset, lay.vocab_offset + lay.vocab+ draft_head = None+ if exl3:+- raw = rd.get("lm_head.weight")[rank * vl:(rank + 1) * vl].to(dev)++ raw = rd.get("lm_head.weight")[v0:v1].to(dev)+ head = dense(raw)+ # Draft steps use a 4-bit copy (TF_GLM_DRAFT_QUANT: minmax or mse ranges); verification keeps the head.+ draft_head = draft_quantize4(raw)+ else:+ hw, hs, hb = (rd.get("lm_head." + x) for x in ("weight", "scales", "biases"))+- head = make_q4(as_i32(hw[rank * vl:(rank + 1) * vl]).to(dev), hs[rank * vl:(rank + 1) * vl].to(dev),+- hb[rank * vl:(rank + 1) * vl].to(dev))++ head = make_q4(as_i32(hw[v0:v1]).to(dev), hs[v0:v1].to(dev), hb[v0:v1].to(dev))+ mtpw = None+ if cfg.mtp_layers and mtp:+ i = cfg.layers+ mtpw = MTPW(t(f"layers.{i}.enorm.weight"), t(f"layers.{i}.hnorm.weight"), q4(f"layers.{i}.eh_proj"),+ t(f"layers.{i}.shared_head.norm.weight"), layer(i, plain=True))+- w = Weights(cfg, embed, built, t("norm.weight"), head, mtpw, rank, world, dev, draft_head=draft_head)++ w = Weights(cfg, embed, built, t("norm.weight"), head, mtpw, rank, world, dev, draft_head=draft_head, tp=lay)+ w.meta.update(layers=which)+ finally:+ rd.close()diff --git a/patches/0067-glm-tp3-split-pad.patch b/patches/0067-glm-tp3-split-pad.patchnew file mode 100644index 0000000..f05ee7e--- /dev/null+++ b/patches/0067-glm-tp3-split-pad.patch@@ -0,0 +1,97 @@+diff --git tensorfold/families/glm5_next/cuda/decode.py tensorfold/families/glm5_next/cuda/decode.py+index d355e85..1e6d712 100644+--- tensorfold/families/glm5_next/cuda/decode.py++++ tensorfold/families/glm5_next/cuda/decode.py+@@ -113,7 +113,13 @@ class Engine:++ kda_mod.reserve(max(max_rows, prefill_rows), tp.of(w).lin_heads, w.device)+ self.buf = Buffers(w, max_rows, capacity)+- self.pbuf = Buffers(w, prefill_rows, capacity, prefill=True)++ # the row split's pad rows past a full chunk (three ranks: 1; ``hcsplit.pad_rows``)++ pad = 0++ if split is not None and split.split:++ from .hcsplit import pad_rows++++ pad = pad_rows(prefill_rows, w.world)++ self.pbuf = Buffers(w, prefill_rows, capacity, prefill=True, pad=pad)+ if taps:+ self.buf.set_taps(tuple(taps), w.cfg.hidden) # before any graph capture+ self.pbuf.set_taps(tuple(taps), w.cfg.hidden)+diff --git tensorfold/families/glm5_next/cuda/engine.py tensorfold/families/glm5_next/cuda/engine.py+index 7aa889c..96ee202 100644+--- tensorfold/families/glm5_next/cuda/engine.py++++ tensorfold/families/glm5_next/cuda/engine.py+@@ -694,6 +694,9 @@ class GlmEngine:+ self.e.pbuf.split.warm() # both ranks: open the send/receive connection now+ if rank == 0:+ print(f"[tensorfold] {self.split.describe()}", flush=True)++ if not self.e.pbuf.split.applies(prefill_rows): # e.g. TF_GLM_HC_SPLIT_MIN_ROWS past a chunk++ print(f"[tensorfold] note: a full {prefill_rows}-row prompt chunk runs unsplit at {world} ranks "++ "(only shorter ones split)", flush=True)+ c = self.copy+ if rank == 0 and (WIDE_GRAPHS or MAX_ROWS != 16 or (c is not None and (c.reply_match or c.miss_most))):+ print(f"[tensorfold] verify windows up to {MAX_ROWS} rows, CUDA graphs for "+diff --git tensorfold/families/glm5_next/cuda/forward.py tensorfold/families/glm5_next/cuda/forward.py+index 1af69e5..4d6499e 100644+--- tensorfold/families/glm5_next/cuda/forward.py++++ tensorfold/families/glm5_next/cuda/forward.py+@@ -35,7 +35,7 @@ def prompt_split_k(w: Weights) -> bool:+ class Buffers:+ """Scratch for windows of up to ``rows`` rows, sliced [:R] for smaller ones; ``prefill`` for prompt chunks."""++- def __init__(self, w: Weights, rows: int, capacity: int = 2560, *, prefill: bool = False) -> None:++ def __init__(self, w: Weights, rows: int, capacity: int = 2560, *, prefill: bool = False, pad: int = 0) -> None:+ c = w.cfg+ dev = w.device+ bf, f32 = torch.bfloat16, torch.float32+@@ -43,6 +43,9 @@ class Buffers:+ HL = tp.of(w).heads+ LL = tp.of(w).lin_heads+ self.rows, self.prefill = rows, prefill++ # ``pad``: rows held past the largest window, for the row split's pad rows (TF_GLM_HC_SPLIT past two ranks: a++ # chunk rounded up to whole shares a rank, ``hcsplit.pad_rows``); every buffer below holds them++ self.alloc_rows = rows = rows + int(pad)+ head_rows = 1 if prefill else rows+ self.world = w.world+ self.ids = torch.zeros((rows,), dtype=torch.int32, device=dev)+@@ -151,7 +154,8 @@ class Buffers:+ self.tap_at = {}+ for i, layer in enumerate(layers):+ self.tap_at.setdefault(layer, []).append(i)+- self.taps = [torch.empty((self.rows, hidden), dtype=torch.bfloat16, device=self.ids.device) for _ in layers]++ self.taps = [torch.empty((self.alloc_rows, hidden), dtype=torch.bfloat16, device=self.ids.device)++ for _ in layers]++ def parents(self, R: int) -> torch.Tensor:+ p = self._parents.get(R)+diff --git tensorfold/families/glm5_next/cuda/hcsplit.py tensorfold/families/glm5_next/cuda/hcsplit.py+index 7a44e73..3c14726 100644+--- tensorfold/families/glm5_next/cuda/hcsplit.py++++ tensorfold/families/glm5_next/cuda/hcsplit.py+@@ -56,6 +56,16 @@ def _int(env, name: str, default: int, lo: int, hi: int) -> int:+ return int(value)++++def pad_rows(rows: int, world: int) -> int:++ """Rows a prompt buffer of ``rows`` rows holds past them for the split's pad rows: a chunk of ``rows`` rows rounded++ up to whole shares a rank (``HcSplit.padded``). 0 at two and four ranks (prompt chunks are a multiple of 64 rows);++ 1 at three, where a 2,048-row chunk splits as 3 x 683 = 2,049 rows: without that row every full chunk failed++ ``applies`` and ran unsplit (an all-gather of every rank's whole partial at each of the 90 sites, the glue on++ every row, no overlap)."""++++ return -int(rows) % int(world)+++++ @dataclass(frozen=True)+ class SplitSettings:+ """What TF_GLM_HC_SPLIT / TF_GLM_PREFILL_OVERLAP ask for; both ranks must agree (the startup comparison)."""+@@ -155,7 +165,8 @@ class HcSplit:+ return -(-R // self.world) * self.world++ def applies(self, R: int) -> bool:+- return R >= self.settings.min_rows and self.padded(R) <= self.b.rows++ """Whether a chunk of R rows runs split: long enough, and its pad rows fit the buffers (``pad_rows``)."""++ return R >= self.settings.min_rows and self.padded(R) <= getattr(self.b, "alloc_rows", self.b.rows)++ def warm(self) -> None:+ """Open the NCCL send/receive connections to the peers at startup (every rank calls this together)."""diff --git a/patches/0068-glm-tpn-split-buffer-rows.patch b/patches/0068-glm-tpn-split-buffer-rows.patchnew file mode 100644index 0000000..e80ad14--- /dev/null+++ b/patches/0068-glm-tpn-split-buffer-rows.patch@@ -0,0 +1,78 @@+diff --git tensorfold/families/glm5_next/cuda/decode.py tensorfold/families/glm5_next/cuda/decode.py+index 1e6d712..40aa44e 100644+--- tensorfold/families/glm5_next/cuda/decode.py++++ tensorfold/families/glm5_next/cuda/decode.py+@@ -113,12 +113,10 @@ class Engine:++ kda_mod.reserve(max(max_rows, prefill_rows), tp.of(w).lin_heads, w.device)+ self.buf = Buffers(w, max_rows, capacity)+- # the row split's pad rows past a full chunk (three ranks: 1; ``hcsplit.pad_rows``)+- pad = 0+- if split is not None and split.split:+- from .hcsplit import pad_rows++ # the row split's pad rows past a full chunk (``hcsplit.pad_rows``: 0 at two and four ranks, 1 at three)++ from .hcsplit import buffer_rows++- pad = pad_rows(prefill_rows, w.world)++ pad = buffer_rows(prefill_rows, w.world, split) - prefill_rows+ self.pbuf = Buffers(w, prefill_rows, capacity, prefill=True, pad=pad)+ if taps:+ self.buf.set_taps(tuple(taps), w.cfg.hidden) # before any graph capture+diff --git tensorfold/families/glm5_next/cuda/engine.py tensorfold/families/glm5_next/cuda/engine.py+index 96ee202..a6332ba 100644+--- tensorfold/families/glm5_next/cuda/engine.py++++ tensorfold/families/glm5_next/cuda/engine.py+@@ -548,12 +548,18 @@ class GlmEngine:+ if name.startswith("model.visual.") else text_weights(name, info))++ from .exl3_mm import prompt_kernels++ from .hcsplit import buffer_rows+ from .latent import SPARSE_ONEPASS+++ # the prompt buffers' rows, the split's pad rows included (``hcsplit.buffer_rows``; the prompt chunk's rows at++ # two and four ranks)++ prompt_buffer_rows = buffer_rows(prefill_rows, world, self.split)+++ def geometry(text):+ from tensorfold.cuda.capacity import Geometry++- g = mla_geometry(text, world, MAX_ROWS, share=share, minimum_slots=DENSE_CAPACITY, latent=LATENT, prefill_rows=prefill_rows,++ g = mla_geometry(text, world, MAX_ROWS, share=share, minimum_slots=DENSE_CAPACITY, latent=LATENT,++ prefill_rows=prompt_buffer_rows,+ mtp=self.mtp_on, onepass=SPARSE_ONEPASS, exl3_prompt=prompt_kernels(),+ prompt_split_k=cfg.quant == "exl3" and dense_kind() != "q4", kv=kv)+ # --parallel: every stream slot past the first (KDA states, conv windows, window scratch); the batched+diff --git tensorfold/families/glm5_next/cuda/hcsplit.py tensorfold/families/glm5_next/cuda/hcsplit.py+index 3c14726..79b4f8c 100644+--- tensorfold/families/glm5_next/cuda/hcsplit.py++++ tensorfold/families/glm5_next/cuda/hcsplit.py+@@ -58,14 +58,25 @@ def _int(env, name: str, default: int, lo: int, hi: int) -> int:++ def pad_rows(rows: int, world: int) -> int:+ """Rows a prompt buffer of ``rows`` rows holds past them for the split's pad rows: a chunk of ``rows`` rows rounded+- up to whole shares a rank (``HcSplit.padded``). 0 at two and four ranks (prompt chunks are a multiple of 64 rows);+- 1 at three, where a 2,048-row chunk splits as 3 x 683 = 2,049 rows: without that row every full chunk failed+- ``applies`` and ran unsplit (an all-gather of every rank's whole partial at each of the 90 sites, the glue on+- every row, no overlap)."""++ up to whole shares a rank (``HcSplit.padded``), so that a full chunk, and every shorter one, runs split at any++ world size. Prompt chunks are a multiple of 64 rows (TF_GLM_PREFILL_ROWS), so this is 0 wherever the world size++ divides 64 (two and four ranks: 2,048 = 2 x 1,024 = 4 x 512) and ``-rows % 3`` at three (2,048 = 3 x 683 - 1:++ one row; 2,112: none). Without that row every full chunk at three ranks failed ``applies`` and ran unsplit (an++ all-gather of every rank's whole partial at each of the 90 sites, the glue on every row, no overlap)."""++ return -int(rows) % int(world)++++def buffer_rows(rows: int, world: int, settings: "SplitSettings | None") -> int:++ """Rows the prompt buffers of ``rows``-row chunks hold (``forward.Buffers``' ``rows + pad``): ``rows`` plus the++ split's pad rows when TF_GLM_HC_SPLIT is on past one rank, else ``rows``. The engine's buffers and its memory++ estimate both take it, so they agree; at two and four ranks it is ``rows`` (the same buffers and estimate)."""++++ if settings is None or not settings.split or int(world) < 2:++ return int(rows)++ return int(rows) + pad_rows(rows, world)+++++ @dataclass(frozen=True)+ class SplitSettings:+ """What TF_GLM_HC_SPLIT / TF_GLM_PREFILL_OVERLAP ask for; both ranks must agree (the startup comparison)."""diff --git a/scripts/config.sh b/scripts/config.shindex 4d72089..24eb570 100644--- a/scripts/config.sh+++ b/scripts/config.sh@@ -26,17 +26,38 @@ if [[ -f "$_cfg_root/.env" ]]; thenfiunset _n _line _key _value-# The two Sparks: this machine serves rank 0 and the API; WORKER (ssh target, key-based) runs rank 1.+# The Sparks: this machine serves rank 0 and the API; WORKER (ssh target, key-based) runs rank 1. TP: how many Sparks+# (2, the default; 3 through ./start-tp3.sh, experimental: README "3 Sparks"), with WORKER2 (rank 2); a start uses+# WORKER .. WORKER<TP-1> and leaves later ones out (stop.sh stops every configured one).+TP="${TP:-2}"WORKER="${WORKER:-}" # e.g. user@<worker address>; set it in scripts/local.shFABRIC_PEER="${FABRIC_PEER:-}" # the worker's CX7 address when WORKER is reached over another network+WORKER_HF_CACHE="${WORKER_HF_CACHE:-}" # the worker's Hugging Face cache when it is not its HF_HOME (absolute path)+WORKER2="${WORKER2:-}"; FABRIC_PEER2="${FABRIC_PEER2:-}"; WORKER_HF_CACHE2="${WORKER_HF_CACHE2:-}" # rank 2, as WORKER / FABRIC_PEER / WORKER_HF_CACHEMASTER_PORT="${MASTER_PORT:-29551}" # TensorFold's rendezvous port between the ranks (keep it on the private link)+# The rendezvous address (rank 0's, --master): at TP=2 the head's address on the link to the worker; at TP>2 this+# node's LAN address (what its hostname resolves to), which every worker reaches. SOCKET_IFNAME (TP>2): the netdev of+# NCCL's bootstrap socket on every node (default: each node's default-route netdev).+_ma=""+if [[ "$TP" != 2 ]]; then+ # (|| true: a hostname that does not resolve fails getent, and under pipefail that ended the script silently)+ _ma=$(getent ahostsv4 "$(hostname)" 2>/dev/null | awk '$1 !~ /^127\./ {print $1; exit}' || true)+ [[ -n "$_ma" ]] || _ma=$(hostname -I 2>/dev/null | awk '{print $1}' || true)+fi+MASTER_ADDR="${MASTER_ADDR:-$_ma}"+SOCKET_IFNAME="${SOCKET_IFNAME:-}"-MODEL_ID="${MODEL_ID:-Mia-AiLab/GLM-5.3-Flash-EXL3-TR3-4bpw}" # EXL3 routed experts (4 bpw), BF16 elsewhere+MODEL_ID="${MODEL_ID:-Mia-AiLab/GLM-5.3-Flash-EXL3-4bpw-TensorFold}" # EXL3 routed experts (4 bpw), BF16 elsewhere+# (Mia-AiLab/GLM-5.3-Flash-EXL3-TR3-4bpw, the default before v1.3.3, still works: MODEL_ID=... in scripts/local.sh)# The checkpoint's revision (a Hugging Face commit sha; DFLASH2_REVISION below is DFlash2's): the one this recipe was# measured with. prepare.sh downloads exactly it, start.sh serves that snapshot from the local cache (no network), and# a new upstream commit changes nothing here until the pin does. Empty: the Hub's main when first downloaded. The pin-# belongs to the default MODEL_ID; another MODEL_ID gets no pin unless you set one.-_rev=""; [[ "$MODEL_ID" == Mia-AiLab/GLM-5.3-Flash-EXL3-TR3-4bpw ]] && _rev=9eaebb7c4e96d983dcd538e18624622ba5b820a8+# belongs to the two checkpoints above; another MODEL_ID gets no pin unless you set one.+case "$MODEL_ID" in+ Mia-AiLab/GLM-5.3-Flash-EXL3-4bpw-TensorFold) _rev=078455ffe6472f9a52fbc1139f58b9db2881b25c ;;+ Mia-AiLab/GLM-5.3-Flash-EXL3-TR3-4bpw) _rev=9eaebb7c4e96d983dcd538e18624622ba5b820a8 ;;+ *) _rev="" ;;+esacMODEL_REVISION="${MODEL_REVISION-$_rev}"TF_VERSION="${TF_VERSION:-v0.6.0}"TF_REPO="${TF_REPO:-https://github.com/ashhart/TensorFold.git}"@@ -50,8 +71,9 @@ GHCR_IMAGE="${GHCR_IMAGE:-ghcr.io/miaai-lab/glm-5.3-flash-exl3-2x-dgx-sparks-ten# The published image of this release's patches, pinned: prepare.sh pulls it by digest (a tag can be moved, a digest# cannot) while patches/*.patch and IMAGE_EXTRAS still hash to IMAGE_TAG's hash. Other patches pull# $GHCR_IMAGE:<TF_VERSION>-<hash> when one is published, else build locally. scripts/publish-image.sh prints both.-IMAGE_TAG="${IMAGE_TAG:-v0.6.0-ae8d1c789b47}"-IMAGE_DIGEST="${IMAGE_DIGEST:-sha256:22789f0cb3dc308f0b2ce52a33961b88bd624af1725e91e8aba0a74a671bb969}"+# The same image serves two and three Sparks.+IMAGE_TAG="${IMAGE_TAG:-v0.6.0-5e01f1bb74d8}"+IMAGE_DIGEST="${IMAGE_DIGEST:-sha256:14f15591eae5d6a540f09218d3852068962fe5381371bbfefe0e9194cd834529}"# the registry reference prepare.sh pulls for these patches: the pinned digest, or the hash's tagprebuilt_image() {local tag="${TF_VERSION}-$(image_hash)"@@ -109,7 +131,8 @@ export TF_GLM_DENSE="$DENSE"# The ranks' all-gathers. roce (default): the small ones (a decode round's partials, the samplers; up to# TF_ROCE_MAX_KB below) as one-shot RDMA writes over the Sparks' RoCE link, b12x's transport (patch 0006): 11 us a# 16 KiB gather against NCCL's 45; decode +6% (prose 44.2 -> 46.9, code 48.7 -> 51.6). NCCL keeps the rest. nccl: NCCL-# for all. Same bits.+# for all. Same bits. start-tp3.sh defaults to nccl; with roce there, each peer goes over the devices that share its+# subnet (the TP-N engine's RoCE; TF_ROCE_HCA lists them all, the GID is found per device).COMM="${COMM:-roce}"export TF_GLM_COMM="$COMM"# The largest all-gather in KiB that goes over RoCE (patch 0006 reads it; a setting, no patch of its own): 512 (default;@@ -156,12 +179,30 @@ export TF_GLM_MULTI_LONE="${TF_GLM_MULTI_LONE:-0}"# or four alternating conversations push each other out (issue #17). Each entry reserves its fixed state (~45 MiB) at# start: 32 takes ~1 GiB more than 8.export TF_GLM_CACHE_ENTRIES="${TF_GLM_CACHE_ENTRIES:-32}"+# Earlier turns keep their reasoning in the prompt (patch 0060), as in zai-org's current template. 1: drop it, as the+# checkpoint's template does; agents then prefill the previous turn's tool loop again at each new user message.+export TF_GLM_CLEAR_THINKING="${TF_GLM_CLEAR_THINKING:-0}"# Waiting prompts filled together in one forward (patch 0049): shared work (expert weights, glue, projections) runs once# for every waiting prompt, attention per prompt on its own state, so each gets the bits it gets alone. sparkDash, prose at# 4 at once: 103.4 -> 108.8 tok/s, time to first token 590 -> 340 ms; structured at 3 / 4 at once: 175.2 -> 196.3 and# 196.3 -> 227.9 tok/s; one request unchanged. Exact. MULTI_PREFILL=0 turns it off.MULTI_PREFILL="${MULTI_PREFILL:-1}"export TF_GLM_MULTI_PREFILL="$MULTI_PREFILL"+# Smooth streaming (patch 0061): with drafts a round accepts ~3 tokens at once, so a streamed reply arrives in bursts+# (every ~50 ms alone, ~100 ms with 4 streams), and pauses while another request's prompt fills. 1 (default): tokens+# go out one event each at a steady pace from a playout buffer of STREAM_SMOOTH_MS (text appears that much later; the+# reply still ends when it did); the same text, tool calls in place. 0: one event a round, as soon as it is decoded.+STREAM_SMOOTH="${STREAM_SMOOTH:-1}"+STREAM_SMOOTH_MS="${STREAM_SMOOTH_MS:-400}"+export TF_GLM_STREAM_SMOOTH="$STREAM_SMOOTH" TF_GLM_STREAM_SMOOTH_MS="$STREAM_SMOOTH_MS"+# Concurrent prompt fills in layer slices (patch 0062): while other requests decode, a new prompt's 1,024-row chunks+# run a few layers at a time (about FILL_BUDGET_MS each) with a decode round between slices, instead of freezing the+# other replies for a whole chunk. FILL_DRAFTS=1 (default): those rounds draft as usual (~3 tokens a stream);+# 0: one token a stream (the new prompt's first token sooner, the others slower while it fills). FILL_BUDGET_MS=0:+# whole chunks, as before. A request alone fills at full speed either way. Same replies.+FILL_BUDGET_MS="${FILL_BUDGET_MS:-200}"+FILL_DRAFTS="${FILL_DRAFTS:-1}"+export TF_GLM_FILL_BUDGET_MS="$FILL_BUDGET_MS" TF_GLM_FILL_DRAFTS="$FILL_DRAFTS"# L2 prefetch in decode windows (patch 0046, adapted from jayleaton/glm53-tensorfold-spark's patch 0460): a side stream# brings the weights the next kernels read into L2 during each layer's all-gathers. 1 (default): one request's prose# 48.36 -> 49.46 tok/s, code 59.54 -> 61.08 (two boots each). Same bits. 0: off.@@ -184,7 +225,11 @@ export TF_GLM_SHARED_PREFIX="$SHARED_PREFIX"# the Sparks' memory.MEMORY_RESERVE_GIB="${MEMORY_RESERVE_GIB:-14.5}"export TENSORFOLD_MEMORY_RESERVE_GIB="$MEMORY_RESERVE_GIB"-KV_POOL_GIB="${KV_POOL_GIB:-12.5}"+# With more Sparks each holds fewer weights, so the pool can take more (the per-token KV cost is the same on every+# rank: the latent cache is replicated). TP=3: 32 GiB leaves rank 0, the busiest, ~5 GiB under a 1M-token prompt+# (at 27: 10.6 GiB lowest on rank 0, pool 5,257,216 tokens; at 32: 5,959,680).+case "$TP" in 3) _pool=32 ;; *) _pool=12.5 ;; esac+KV_POOL_GIB="${KV_POOL_GIB:-$_pool}"export TF_GLM_CACHE_GIB="$KV_POOL_GIB"export TENSORFOLD_NO_UPDATE_CHECK="${TENSORFOLD_NO_UPDATE_CHECK:-1}"@@ -197,12 +242,23 @@ HF_CACHE="${HF_CACHE:-${HF_HOME:-$HOME/.cache/huggingface}}"WORKER_WEIGHTS="${WORKER_WEIGHTS:-copy}"NFS_PATH="${NFS_PATH:-$HF_CACHE}"NFS_SERVER="${NFS_SERVER:-}"+# The third Spark (TP=3): WORKER_WEIGHTS2 (default: WORKER_WEIGHTS) and NFS_SERVER2 (default: the head's address on+# that worker's link); NFS_PATH and NFS_VOLUME are the same for all.+WORKER_WEIGHTS2="${WORKER_WEIGHTS2:-}"; NFS_SERVER2="${NFS_SERVER2:-}"NFS_VOLUME="${NFS_VOLUME:-glm53-hf}"KERNEL_CACHE="${KERNEL_CACHE:-$HOME/.cache/tensorfold-glm53}" # compiled CUDA kernels, a folder per image's patches hashSTATE_DIR="${STATE_DIR:-$HOME/.local/state/glm53-tensorfold}" # this recipe's locks and setup marker-# Free disk prepare.sh asks for before it downloads or copies: the checkpoint (~176 GB) under HF_CACHE (on the worker,-# the copy is checked against its size instead), and an image build or copy (~25 GB) under Docker's root on each Spark;-# both together when they share a filesystem.+# Server logs: stop.sh (and start.sh, before it removes a stopped container left from an earlier run) saves each rank's+# container log, stdout and stderr with timestamps, gzipped, as <date>-<time>-rank<N>.log.gz in LOG_DIR here and in+# ~/.cache/tensorfold-glm53/logs on each worker, and keeps the newest LOG_KEEP (0: saves none). docker rm deletes a+# container's own log, so without this a crash's log is gone at the next stop or start.+LOG_DIR="${LOG_DIR:-$HOME/.cache/tensorfold-glm53/logs}"+LOG_KEEP="${LOG_KEEP:-10}"+# Free disk prepare.sh asks for before it downloads or copies: under HF_CACHE, what the download still needs (the+# revisions' files whose blobs are not cached yet, from the Hub's file list, plus 5 GB), or MIN_FREE_GB for the+# checkpoint (~176 GB) when that list cannot be read (no huggingface_hub on the host, or no network); on each worker,+# what rsync must send plus 5 GB; and an image build or copy (~25 GB) under Docker's root on each Spark; both together+# when they share a filesystem.MIN_FREE_GB="${MIN_FREE_GB:-180}"IMAGE_FREE_GB="${IMAGE_FREE_GB:-35}"@@ -218,14 +274,20 @@ model_revision() { if [[ "$1" == "$MODEL_ID" ]]; then echo "$MODEL_REVISION"; el# snapshot_rev <id>: the snapshot this setup serves: the pin, else what refs/main names on this Sparksnapshot_rev() { local rev; rev=$(model_revision "$1"); [[ -n "$rev" ]] || rev=$(cat "$(model_cache_dir "$1")/refs/main" 2>/dev/null); echo "$rev"; }-# What scripts/prepare.sh last left ready on both Sparks (it writes this line to PREPARED_MARKER when it succeeds);-# start.sh runs prepare.sh again whenever the current line differs: a missing or different image on either Spark, new-# patches, another model, drafter or revision, another worker. Needs scripts/nodes.sh (the worker's image).+# What scripts/prepare.sh last left ready on every Spark (it writes this line to PREPARED_MARKER when it succeeds);+# start.sh runs prepare.sh again whenever the current line differs: a missing or different image on any Spark, new+# patches, another model, drafter or revision, other workers. Needs scripts/nodes.sh (the workers' images). At TP=2 the+# line is the one it always was.PREPARED_MARKER="$STATE_DIR/prepared"prepared_state() {- local hash label wlabel+ local hash label wlabel i linehash=$(image_hash)label=$(docker image inspect -f '{{.Id}}' "$IMAGE" 2>/dev/null || echo missing)- wlabel=$(worker docker image inspect -f '{{.Id}}' "$IMAGE" 2>/dev/null || echo missing)- echo "model=$MODEL_ID@$MODEL_REVISION drafter=$DRAFTER@$DFLASH2_REVISION image=$label worker=$wlabel patches=$hash worker_host=$WORKER weights=$WORKER_WEIGHTS"+ wlabel=$(worker 1 docker image inspect -f '{{.Id}}' "$IMAGE" 2>/dev/null || echo missing)+ line="model=$MODEL_ID@$MODEL_REVISION drafter=$DRAFTER@$DFLASH2_REVISION image=$label worker=$wlabel patches=$hash worker_host=$WORKER weights=$WORKER_WEIGHTS"+ for (( i = 2; i < TP; i++ )); do+ wlabel=$(worker "$i" docker image inspect -f '{{.Id}}' "$IMAGE" 2>/dev/null || echo missing)+ line+=" worker$i=$wlabel worker${i}_host=$(worker_host "$i") weights$i=$(worker_weights "$i") nfs$i=$(wval NFS_SERVER "$i")"+ done+ echo "$line"}diff --git a/scripts/local.sh.example b/scripts/local.sh.exampleindex 5a25e35..02236cb 100644--- a/scripts/local.sh.example+++ b/scripts/local.sh.example@@ -1,3 +1,7 @@# Copy to scripts/local.sh (not in git) and fill in this setup's values; scripts/config.sh reads it first.[email protected] # ssh target of the second Spark (key-based: ssh-copy-id [email protected])# FABRIC_PEER=192.0.2.12 # the worker's CX7 address, when WORKER is reached over another network+# A third Spark (./start-tp3.sh, experimental; README "3 Sparks"):+# [email protected] # rank 2+# WORKER_WEIGHTS2=nfs # per worker: copy or nfs (default: WORKER_WEIGHTS)+# WORKER_HF_CACHE2=/models/hf # per worker: its Hugging Face cache when it is not its HF_HOMEdiff --git a/scripts/nodes.sh b/scripts/nodes.shindex cf8cf63..52b5d1b 100644--- a/scripts/nodes.sh+++ b/scripts/nodes.sh@@ -1,46 +1,104 @@-# The two Sparks: the worker over ssh, and each node's RoCE link found from the route between them.+# The Sparks: this machine (rank 0), and the workers over ssh: WORKER (rank 1), WORKER2 (rank 2).+# Each node's links to the others are found from the routes and subnets between them.# Sourced by start.sh, stop.sh and prepare.sh after config.sh.-# Run a command on the worker (rank 1). Key-based ssh only, no prompts.-worker() { ssh -o BatchMode=yes -o ConnectTimeout=10 -o ServerAliveInterval=15 "$WORKER" "$@"; }+# wvar <NAME> <i>: the name of worker i's own setting: NAME for worker 1 (WORKER, FABRIC_PEER, NFS_SERVER,+# WORKER_WEIGHTS, WORKER_HF_CACHE), NAME<i> for the others (WORKER2, FABRIC_PEER2, NFS_SERVER2, WORKER_WEIGHTS2,+# WORKER_HF_CACHE2).+wvar() { if (( $2 == 1 )); then echo "$1"; else echo "$1$2"; fi; }+wval() { local v; v=$(wvar "$1" "$2"); echo "${!v:-}"; }+worker_host() { wval WORKER "$1"; }+# The workers this start uses (1 .. TP-1), and every worker configured at all (stop.sh stops them all).+worker_ids() { seq 1 $((TP - 1)); }+configured_workers() { local i; for i in 1 2; do [[ -z "$(worker_host "$i")" ]] || echo "$i"; done; }+# worker i's weights: WORKER_WEIGHTS for worker 1, WORKER_WEIGHTS<i> (default: WORKER_WEIGHTS) for the others+worker_weights() { local w; w=$(wval WORKER_WEIGHTS "$1"); echo "${w:-$WORKER_WEIGHTS}"; }-# The worker's Hugging Face cache: its own HF_HOME, else ~/.cache/huggingface there. prepare.sh copies the checkpoint-# into it and start.sh mounts it into rank 1.-worker_hf_cache() { # WORKER_HF_CACHE wins: a worker whose cache is not its HF_HOME (e.g. a shared models disk)- if [[ -n "${WORKER_HF_CACHE:-}" ]]; then echo "$WORKER_HF_CACHE"; return; fi- worker 'echo "${HF_HOME:-$HOME/.cache/huggingface}"'+# check_workers: TP is 2 or 3, and WORKER .. WORKER<TP-1> are set and distinct (later ones are left out).+check_workers() {+ local i j h+ [[ "$TP" =~ ^[23]$ ]] || die "TP is 2 (./start.sh) or 3 (./start-tp3.sh, experimental) Sparks, not $TP"+ for i in $(worker_ids); do+ h=$(worker_host "$i")+ [[ -n "$h" ]] || die "TP=$TP needs $((TP - 1)) workers: set $(wvar WORKER "$i")=user@<address of rank $i> in scripts/local.sh (see scripts/local.sh.example)"+ [[ "$(worker_weights "$i")" =~ ^(copy|nfs)$ ]] || die "$(wvar WORKER_WEIGHTS "$i") is copy or nfs, not $(worker_weights "$i")"+ for (( j = 1; j < i; j++ )); do+ [[ "$h" != "$(worker_host "$j")" ]] || die "$(wvar WORKER "$i") and $(wvar WORKER "$j") are the same node ($h)"+ done+ done}-# An image's identity by content (its layers' diffIDs and runtime config), the same under Docker's overlay2 and-# containerd image stores: .Id is the config digest under one and the manifest digest under the other, so it never-# matches across a mixed pair (issue #8). The template holds no spaces: worker() passes it through ssh, which-# re-splits arguments. A missing image is "missing".-IMAGE_IDENT='{{.RootFS.Layers}}{{.Config.Env}}{{.Config.Entrypoint}}{{.Config.Cmd}}{{.Config.WorkingDir}}'-image_ident() { local s; s=$(docker image inspect -f "$IMAGE_IDENT" "$1" 2>/dev/null) && sha256sum <<<"$s" | cut -c1-64 || echo missing; }-worker_image_ident() {- local s; s=$(worker docker image inspect -f "$IMAGE_IDENT" "$1" 2>/dev/null) && sha256sum <<<"$s" | cut -c1-64 || echo missing+# DRY_RUN=1 goes on without workers it cannot reach (a fictitious WORKER2): their values print as <WORKER2:...>.+declare -A WORKER_DOWN=()+# worker <i> <command...>: run a command on worker i (rank i). Key-based ssh only, no prompts.+worker() {+ local i=$1; shift+ [[ -z "${WORKER_DOWN[$i]:-}" ]] || return 255+ ssh -o BatchMode=yes -o ConnectTimeout=10 -o ServerAliveInterval=15 "$(worker_host "$i")" "$@"+}++# save_log <dir> <rank> <container> <keep>: the container's log (stdout and stderr, with timestamps) gzipped into+# <dir>/<date>-<time>-rank<N>.log.gz before the container is removed (docker rm deletes it), keeping the newest <keep>+# of that rank; prints the file. Runs on the worker too (its definition is sent over ssh): no config.sh there.+save_log() {+ local dir=$1 rank=$2 c=$3 keep=$4 stamp f i=0+ [[ "$keep" =~ ^[0-9]+$ ]] && (( keep > 0 )) || return 0+ docker inspect "$c" >/dev/null 2>&1 || return 0+ mkdir -p "$dir" || return 1+ stamp=$(date +%Y%m%d-%H%M%S); f="$dir/$stamp-rank$rank.log.gz"+ while [[ -e "$f" ]]; do f="$dir/$stamp.$((++i))-rank$rank.log.gz"; done # same second: still sorts as newer+ if ! docker logs --timestamps "$c" 2>&1 | gzip > "$f"; then rm -f "$f"; return 1; fi+ ls -1 "$dir"/*-rank"$rank".log.gz 2>/dev/null | { grep -vxF "$f" || true; } | LC_ALL=C sort -r | tail -n +"$keep" | xargs -r rm -f --+ echo "$f"+}+# worker_save_log <i>: the same, for rank i on worker i (into ~/.cache/tensorfold-glm53/logs there)+worker_save_log() {+ worker "$1" "$(declare -f save_log); save_log \"\$HOME/.cache/tensorfold-glm53/logs\" $1 '$CONTAINER_NAME' '$LOG_KEEP'"}-# WORKER_WEIGHTS=nfs: rank 1 mounts the head's HF_CACHE read-only through the docker volume NFS_VOLUME on the worker.-# ensure_nfs_volume creates it (or checks the one there names the same export); worker_nfs <cmd...> runs a command in-# a throwaway container with the volume at /hf.+need_worker() {+ local i=$1 v h+ v=$(wvar WORKER "$i"); h=$(worker_host "$i")+ [[ -n "$h" ]] || die "$v is not set: put $v=user@<worker address> in scripts/local.sh (see scripts/local.sh.example)"+ worker "$i" true 2>/dev/null && return 0+ if [[ "${DRY_RUN:-0}" == 1 ]]; then+ warn "DRY_RUN: cannot ssh to $h ($v): its values print as <$v:...>"+ WORKER_DOWN[$i]=1+ return 0+ fi+ die "cannot ssh to $h without a password: set up key-based ssh (ssh-copy-id $h)"+}+need_workers() { local i; for i in $(worker_ids); do need_worker "$i"; done; }++# Worker i's Hugging Face cache: its own HF_HOME, else ~/.cache/huggingface there. prepare.sh copies the checkpoint+# into it and start.sh mounts it into rank i. WORKER_HF_CACHE (worker 1) / WORKER_HF_CACHE<i> wins: a worker whose+# cache is not its HF_HOME (e.g. a shared models disk).+worker_hf_cache() {+ local c; c=$(wval WORKER_HF_CACHE "$1")+ if [[ -n "$c" ]]; then echo "$c"; return; fi+ [[ -z "${WORKER_DOWN[$1]:-}" ]] || { echo "<$(wvar WORKER "$1"):hf-cache>"; return 0; }+ worker "$1" 'echo "${HF_HOME:-$HOME/.cache/huggingface}"'+}++# Weights over NFS: rank i mounts the head's HF_CACHE read-only through the docker volume NFS_VOLUME on worker i, from+# nfs_server i: NFS_SERVER (worker 1) / NFS_SERVER<i>, else the head's address on that worker's link (detect_links).+# ensure_nfs_volume i creates it (or checks the one there names the same export); worker_nfs i <cmd...> runs a command+# in a throwaway container on worker i with the volume at /hf.+nfs_server() { local s; s=$(wval NFS_SERVER "$1"); echo "${s:-${LINK_HEAD_ADDR[$1]:-}}"; }ensure_nfs_volume() {- local server="${NFS_SERVER:-$HEAD_ADDR}" have- have=$(worker "docker volume inspect -f '{{index .Options \"device\"}} {{index .Options \"o\"}}' '$NFS_VOLUME'" 2>/dev/null || true)+ local i=$1 server have h+ server=$(nfs_server "$i"); h=$(worker_host "$i")+ [[ -n "$server" ]] || die "no NFS server address for $h: set $(wvar NFS_SERVER "$i") to the head's address on that worker's link"+ have=$(worker "$i" "docker volume inspect -f '{{index .Options \"device\"}} {{index .Options \"o\"}}' '$NFS_VOLUME'" 2>/dev/null || true)if [[ -z "$have" ]]; then- worker "docker volume create --driver local --opt type=nfs --opt device=':$NFS_PATH' \+ worker "$i" "docker volume create --driver local --opt type=nfs --opt device=':$NFS_PATH' \--opt o='addr=$server,nfsvers=4.2,ro,nconnect=8,rsize=1048576,wsize=1048576,hard,timeo=600' '$NFS_VOLUME'" >/dev/null ||- die "could not create the docker volume $NFS_VOLUME on the worker"+ die "could not create the docker volume $NFS_VOLUME on $h"elif [[ "${have%% *}" != ":$NFS_PATH" || "$have" != *"addr=$server,"* ]]; then- die "the worker's docker volume $NFS_VOLUME is ${have%% *} from ${have#* }, not :$NFS_PATH from $server: remove it there (docker volume rm $NFS_VOLUME) or set NFS_VOLUME / NFS_PATH"+ die "$h's docker volume $NFS_VOLUME is ${have%% *} from ${have#* }, not :$NFS_PATH from $server: remove it there (docker volume rm $NFS_VOLUME) or set NFS_VOLUME / NFS_PATH / $(wvar NFS_SERVER "$i")"fi}-worker_nfs() { worker "docker run --rm --entrypoint '$1' -v '$NFS_VOLUME:/hf:ro' '$IMAGE' $(printf '%q ' "${@:2}")"; }--need_worker() {- [[ -n "${WORKER:-}" ]] || die "WORKER is not set: put WORKER=user@<worker address> in scripts/local.sh (see scripts/local.sh.example)"- worker true 2>/dev/null || die "cannot ssh to $WORKER without a password: set up key-based ssh (ssh-copy-id $WORKER)"-}+worker_nfs() { local i=$1; shift; worker "$i" "docker run --rm --entrypoint '$1' -v '$NFS_VOLUME:/hf:ro' '$IMAGE' $(printf '%q ' "${@:2}")"; }# link_info <peer address>: this node's side of the link to <peer>: "<address> <netdev> <rdma device> <gid index>".# The netdev and source address come from the route to the peer; the RDMA device from sysfs; the GID index is the@@ -88,30 +146,46 @@ rails() {# twins different subnets - so the scan above never sees the twin and NCCL gets one x4: ~112 Gb/s of the port's 200.# Pair the twin by name instead of by subnet: same fN/npM tail, different PCIe prefix. Same conditions as above# (link up, a RoCE v2 GID at $gid), and never add a device twice.+ # (only for Spark-style names, <prefix>f<N>np<M>; the check below compares whole comma-separated names, so a twin the+ # subnet scan already added, as when both twins share the link's subnet, is not listed twice)local tail=${dev##*f} other2 ib2+ [[ "$dev" =~ f[0-9]+np[0-9]+$ ]] || { echo "$hcas"; return 0; }for n in /sys/class/net/*; doother2=${n##*/}[[ "$other2" == "$dev" || "$other2" != *f"$tail" ]] && continue[[ -d $n/device/infiniband && "$(cat $n/operstate 2>/dev/null)" == up ]] || continueib2=$(ls $n/device/infiniband | head -1)- [[ -n "$ib2" && ","$hcas"," != *","$ib2,","* ]] || continue+ [[ -n "$ib2" && ",$hcas," != *",$ib2,"* ]] || continue[[ "$(cat /sys/class/infiniband/$ib2/ports/1/gid_attrs/types/$gid 2>/dev/null)" == *v2* ]] || continuehcas+=",$ib2"doneecho "$hcas"}-# The same function on the worker (its definition is sent over ssh).-worker_link_info() { worker "$(declare -f link_info); link_info $1"; }+# The same function on worker i (its definition is sent over ssh).+worker_link_info() { worker "$1" "$(declare -f link_info); link_info $2"; }-# HEAD_ADDR / HEAD_DEV / HEAD_HCA / HEAD_GID and WORKER_ADDR / WORKER_DEV / WORKER_HCA / WORKER_GID: the link the two-# ranks talk over (NCCL and the rendezvous). FABRIC_PEER overrides the worker's link address when WORKER is reached-# over another network.-# cx7_peer: the worker's address on a CX7 port that one of this node's CX7 ports reaches directly (same subnet, no-# gateway), for a WORKER given by its LAN address (issue #9). Empty when there is none.+# Per rank r, filled by detect_links: NODE_DEV[r] (the netdev of NCCL's bootstrap socket), NODE_HCAS[r] (its RoCE+# devices toward its peers), NODE_GID[r] (their RoCE v2 GID index; empty at TP>2 when they differ: NCCL then picks+# each device's own); LINK_HEAD_ADDR[i] / LINK_WORKER_ADDR[i]: the head's and worker i's addresses on their link (the+# head's is worker i's NFS server).+declare -a NODE_DEV=() NODE_HCAS=() NODE_GID=() LINK_HEAD_ADDR=() LINK_WORKER_ADDR=()++# An image's identity by content (its layers' diffIDs and runtime config), the same under Docker's overlay2 and+# containerd image stores: .Id is the config digest under one and the manifest digest under the other, so it never+# matches across a mixed pair (issue #8). The template holds no spaces: worker() passes it through ssh, which+# re-splits arguments. A missing image is "missing". worker_image_ident <i> <image>: on worker i.+IMAGE_IDENT='{{.RootFS.Layers}}{{.Config.Env}}{{.Config.Entrypoint}}{{.Config.Cmd}}{{.Config.WorkingDir}}'+image_ident() { local s; s=$(docker image inspect -f "$IMAGE_IDENT" "$1" 2>/dev/null) && sha256sum <<<"$s" | cut -c1-64 || echo missing; }+worker_image_ident() {+ local s; s=$(worker "$1" docker image inspect -f "$IMAGE_IDENT" "$2" 2>/dev/null) && sha256sum <<<"$s" | cut -c1-64 || echo missing+}++# cx7_peer <i>: worker i's address on a CX7 port that one of this node's CX7 ports reaches directly (same subnet, no+# gateway), for a worker given by its LAN address (issue #9). Empty when there is none.cx7_peer() {local a route dev- for a in $(worker 'for d in /sys/class/net/*; do [ -d "$d/device/infiniband" ] && ip -o -4 addr show dev "${d##*/}"; done' 2>/dev/null |+ for a in $(worker "$1" 'for d in /sys/class/net/*; do [ -d "$d/device/infiniband" ] && ip -o -4 addr show dev "${d##*/}"; done' 2>/dev/null |awk '{print $4}' | cut -d/ -f1); doroute=$(ip -o -4 route get "$a" 2>/dev/null) || continue[[ "$route" == *" via "* ]] && continue@@ -120,6 +194,10 @@ cx7_peer() {donereturn 1}++# TP=2: HEAD_ADDR / HEAD_DEV / HEAD_HCA / HEAD_GID and WORKER_ADDR / WORKER_DEV / WORKER_HCA / WORKER_GID: the link the+# two ranks talk over (NCCL and the rendezvous). FABRIC_PEER overrides the worker's link address when WORKER is reached+# over another network.detect_link() {local peer=${FABRIC_PEER:-${WORKER#*@}} cx7# a host name (an /etc/hosts alias of the CX7 address, say) is resolved first: ``ip route get`` takes addresses only@@ -130,25 +208,151 @@ detect_link() {read -r HEAD_ADDR HEAD_DEV HEAD_HCA HEAD_GID <<<"$(link_info "$peer")" || true[[ -n "${HEAD_ADDR:-}" ]] || die "no route from this node to $peer"# WORKER given by a LAN address (the route goes out a port without RoCE): use the worker's CX7 address instead- if [[ -z "${FABRIC_PEER:-}" && "${HEAD_HCA:--}" == "-" ]] && cx7=$(cx7_peer); then+ if [[ -z "${FABRIC_PEER:-}" && "${HEAD_HCA:--}" == "-" ]] && cx7=$(cx7_peer 1); thenlog "$peer is reached over $HEAD_DEV, not a CX7 port: using the worker's CX7 address $cx7 for the link (FABRIC_PEER)"peer=$cx7read -r HEAD_ADDR HEAD_DEV HEAD_HCA HEAD_GID <<<"$(link_info "$peer")" || truefi- read -r WORKER_ADDR WORKER_DEV WORKER_HCA WORKER_GID <<<"$(worker_link_info "$HEAD_ADDR")" || true+ read -r WORKER_ADDR WORKER_DEV WORKER_HCA WORKER_GID <<<"$(worker_link_info 1 "$HEAD_ADDR")" || true[[ -n "${WORKER_ADDR:-}" ]] || die "the worker has no route back to $HEAD_ADDR"- # both CX7 ports when both are cabled and addressed: a prompt chunk's all-gather is ~1.8x faster on two rails+ # every rail (both PCIe twins of the cabled port, a second cabled port): a chunk's all-gather is ~1.8x faster on twoHEAD_HCAS=$(rails "$HEAD_DEV" "$HEAD_GID")- WORKER_HCAS=$(worker "$(declare -f rails); rails $WORKER_DEV $WORKER_GID")+ WORKER_HCAS=$(worker 1 "$(declare -f rails); rails $WORKER_DEV $WORKER_GID")[[ "${NCCL_RAILS:-2}" == 1 ]] && { HEAD_HCAS=$HEAD_HCA; WORKER_HCAS=$WORKER_HCA; }[[ "$(tr ',' '\n' <<<"$HEAD_HCAS" | wc -l)" == "$(tr ',' '\n' <<<"$WORKER_HCAS" | wc -l)" ]] ||{ HEAD_HCAS=$HEAD_HCA; WORKER_HCAS=$WORKER_HCA; }for v in HEAD_HCA HEAD_GID WORKER_HCA WORKER_GID; do[[ "${!v}" != "-" ]] || die "no RoCE device or RoCE v2 GID for the link ($v): is $HEAD_DEV / $WORKER_DEV the CX7 port between the Sparks? Set FABRIC_PEER to the worker's CX7 address"done+ NODE_DEV=("$HEAD_DEV" "$WORKER_DEV"); NODE_HCAS=("$HEAD_HCAS" "$WORKER_HCAS"); NODE_GID=("$HEAD_GID" "$WORKER_GID")+ LINK_HEAD_ADDR[1]=$HEAD_ADDR; LINK_WORKER_ADDR[1]=$WORKER_ADDR+ MASTER_ADDR=${MASTER_ADDR:-$HEAD_ADDR}+}++# node_inventory [master]: this node's default-route netdev ("default <netdev>"), whether it routes to <master>+# ("master ok|none"), and one line per RoCE netdev that is up with an IPv4 address: "<netdev> <rdma device>+# <address/prefix> <RoCE v2 GID index of that address, or ->". Read-only (ip and sysfs).+node_inventory() {+ local n dev hca cidr want idx f+ echo "default $(ip -o -4 route show default 2>/dev/null | sed -n 's/.* dev \([^ ]*\).*/\1/p' | head -1)"+ [[ -z "${1:-}" ]] || { ip -o -4 route get "$1" >/dev/null 2>&1 && echo "master ok" || echo "master none"; }+ for n in /sys/class/net/*; do+ dev=${n##*/}+ [[ -d $n/device/infiniband && "$(cat "$n/operstate" 2>/dev/null)" == up ]] || continue+ hca=$(ls "$n/device/infiniband" | head -1)+ for cidr in $(ip -o -4 addr show dev "$dev" | awk '{print $4}'); do+ want=$(printf '0000:0000:0000:0000:0000:ffff:%02x%02x:%02x%02x' $(tr '.' ' ' <<<"${cidr%/*}"))+ idx=-+ for f in /sys/class/infiniband/"$hca"/ports/1/gids/*; do+ [[ "$(cat "$f" 2>/dev/null)" == "$want" ]] || continue+ [[ "$(cat /sys/class/infiniband/"$hca"/ports/1/gid_attrs/types/"${f##*/}" 2>/dev/null)" == *v2* ]] && { idx=${f##*/}; break; }+ done+ echo "$dev $hca $cidr $idx"+ done+ done}-# NCCL over the RoCE link, per rank: that rank's netdev, RoCE devices (both rails) and GID index, 4 channels.+# pair_links <ranks...> (stdin: node_inventory lines, each prefixed with its rank): two nodes are linked where they+# have addresses in one subnet (a direct cable, or a switch). Prints "rank <r> <default netdev> <hcas> <gid or ->" (a+# node's RoCE devices toward all its peers, in its sysfs order; the GID index when it is one for all of them), "peer <i>+# <worker i's lowest address on its link to the head>" and "missing <a> <b>" for two ranks without a common subnet.+pair_links() {+ python3 -c '+import ipaddress, sys+nodes, default = {}, {}+for line in sys.stdin:+ f = line.split()+ if len(f) == 3 and f[1] == "default":+ default[int(f[0])] = f[2]+ elif len(f) == 5:+ nodes.setdefault(int(f[0]), []).append((f[1], f[2], ipaddress.ip_interface(f[3]), f[4]))+ranks = [int(x) for x in sys.argv[1:]]+linked = lambda e, others: any(e[2].network == o[2].network for o in others)+for r in ranks:+ used = set()+ for s in ranks:+ if s == r:+ continue+ mine = [e for e in nodes.get(r, []) if linked(e, nodes.get(s, []))]+ if not mine:+ if r < s:+ print("missing", r, s)+ continue+ used.update(id(e) for e in mine)+ if r == 0:+ print("peer", s, min(o[2].ip for o in nodes[s] if linked(o, mine)))+ hcas, gids = [], set()+ for e in nodes.get(r, []): # in the node sysfs order+ if id(e) in used and e[1] not in hcas:+ hcas.append(e[1]); gids.add(e[3])+ print("rank", r, default.get(r) or "-", ",".join(hcas) or "-", gids.pop() if len(gids) == 1 else "-")+' "$@"+}++# TP>2: every node's RoCE netdevs, paired by subnet (pair_links); a node's NCCL devices are the union of its devices+# toward all its peers. NCCL's bootstrap socket goes over each node's default-route netdev (SOCKET_IFNAME overrides+# it): on a triangle every pair has its own subnet, so no CX7 netdev reaches both peers, and the 10.0.0.x-style+# addresses some setups route over the cables sit on lo. The rendezvous is MASTER_ADDR (config.sh).+detect_links() {+ if (( TP == 2 )); then detect_link; return; fi+ local r i peer kind a b c d pairs line missing="" names+ [[ -n "$MASTER_ADDR" ]] || die "no MASTER_ADDR: set it to an address of this node that every worker reaches (its LAN address)"+ local -a inv=()+ inv[0]=$(node_inventory)+ for i in $(worker_ids); do+ inv[i]=$(worker "$i" "$(declare -f node_inventory); node_inventory $MASTER_ADDR" 2>/dev/null || true)+ [[ "${inv[i]}" != *"master none"* ]] ||+ die "$(worker_host "$i") has no route to MASTER_ADDR $MASTER_ADDR: set MASTER_ADDR to an address of this node it reaches"+ done+ pairs=$(for r in "${!inv[@]}"; do sed "s/^/$r /" <<<"${inv[r]}"; done | pair_links 0 $(worker_ids)) ||+ die "could not pair the nodes' links"+ while read -r kind a b c d; do+ case "$kind" in+ rank)+ NODE_DEV[a]=${SOCKET_IFNAME:-$b}; NODE_HCAS[a]=$c; NODE_GID[a]=$d+ [[ "$d" != - ]] || NODE_GID[a]="" ;;+ peer)+ # the head's side of that link from its route to the worker's address there (FABRIC_PEER<i> overrides it)+ peer=$(wval FABRIC_PEER "$a"); peer=${peer:-$b}+ # a host name (an /etc/hosts alias of the CX7 address, say) is resolved first, as at TP=2+ if [[ ! "$peer" =~ ^[0-9]+(\.[0-9]+){3}$ ]]; then+ c=$(getent ahostsv4 "$peer" | awk 'NR == 1 {print $1}') || true+ [[ -n "$c" ]] || die "cannot resolve $peer ($(wvar FABRIC_PEER "$a")) to an IPv4 address"+ peer=$c+ fi+ read -r LINK_HEAD_ADDR[a] _ <<<"$(link_info "$peer")" || true+ LINK_WORKER_ADDR[a]=$peer ;;+ missing) missing+=" $a-$b" ;;+ esac+ done <<<"$pairs"+ for r in 0 $(worker_ids); do+ if [[ -n "${WORKER_DOWN[$r]:-}" ]]; then+ names=$(wvar WORKER "$r")+ NODE_DEV[r]="<$names:netdev>"; NODE_HCAS[r]="<$names:hcas>"; NODE_GID[r]="<$names:gid>"+ LINK_HEAD_ADDR[r]="<head address toward $names>"; LINK_WORKER_ADDR[r]="<$names:address>"+ continue+ fi+ names="this node"; (( r == 0 )) || names=$(worker_host "$r")+ [[ -n "${NODE_DEV[r]:-}" && "${NODE_DEV[r]}" != - ]] ||+ die "rank $r ($names) has no default route: set SOCKET_IFNAME to the netdev of the network all the Sparks share"+ [[ -n "${NODE_HCAS[r]:-}" && "${NODE_HCAS[r]}" != - ]] ||+ die "rank $r ($names) shares no RoCE subnet with any other rank: check the CX7 cabling and addresses (ip -4 addr)"+ done+ for line in $missing; do+ a=${line%-*}; b=${line#*-}+ if [[ -n "${WORKER_DOWN[$a]:-}${WORKER_DOWN[$b]:-}" ]]; then+ warn "DRY_RUN: the link between ranks $a and $b is unknown (a worker that cannot be reached)"+ continue+ fi+ die "ranks $a and $b share no RoCE subnet: $TP Sparks need a link between every pair (a triangle of direct cables; see README)"+ done+ return 0+}++# The NCCL settings of rank r's container (docker -e arguments).+# TP=2: the RoCE link's netdev, RoCE devices (both rails) and GID index, 4 channels. The RoCE all-gathers (patch 0006)+# take the same devices from NCCL_IB_HCA, as TF_ROCE_HCA is not set here (the command is v1.4's); TP>2 sets TF_ROCE_HCA+# per node (nccl_env_n).# Measured between the Sparks: a decode-sized all-gather 32 us (80 with NCCL's defaults) and a prompt chunk's 32 MB# 1.9 ms on two rails (3.5 on one). NCCL's other knobs (protocols, buffer sizes, QPs, NCCL_NET=IB and the like) were no# better, and some of them kept NCCL on one rail.@@ -158,3 +362,21 @@ nccl_env() {"-e NCCL_MIN_NCHANNELS=${NCCL_CHANNELS:-4} -e NCCL_MAX_NCHANNELS=${NCCL_CHANNELS:-4}" \${NCCL_DEBUG:+-e NCCL_DEBUG=$NCCL_DEBUG}}+# TP>2, from the owner's 3-Spark vLLM recipe on this triangle: the bootstrap socket on the network every node shares;+# every RoCE device toward every peer; NCCL_CROSS_NIC=1 and subnet-aware routing (the image's NCCL 2.30.7 has it): each+# cable joins port 0 of one node to port 1 of the next, and NCCL otherwise pairs device index with device index+# (ibv_modify_qp ... Connection timed out); no P2P or SHM transport (one GPU a node). The GID index only when it is the+# same on all of a node's devices; else NCCL picks each device's RoCE v2 IPv4 entry itself.+nccl_env_n() {+ local dev=$1 hcas=$2 gid=$3+ echo "-e NCCL_SOCKET_IFNAME=$dev -e NCCL_IB_HCA=$hcas ${gid:+-e NCCL_IB_GID_INDEX=$gid}" \+ "-e NCCL_CROSS_NIC=${NCCL_CROSS_NIC:-1} -e NCCL_IB_SUBNET_AWARE_ROUTING=${NCCL_IB_SUBNET_AWARE_ROUTING:-1}" \+ "-e NCCL_P2P_DISABLE=1 -e NCCL_SHM_DISABLE=1" \+ "-e NCCL_MIN_NCHANNELS=${NCCL_CHANNELS:-4} -e NCCL_MAX_NCHANNELS=${NCCL_CHANNELS:-4}" \+ "-e TF_ROCE_HCA=$hcas" \+ ${NCCL_DEBUG:+-e NCCL_DEBUG=$NCCL_DEBUG}+}+rank_nccl_env() {+ if (( TP == 2 )); then nccl_env "${NODE_DEV[$1]}" "${NODE_HCAS[$1]}" "${NODE_GID[$1]}"+ else nccl_env_n "${NODE_DEV[$1]}" "${NODE_HCAS[$1]}" "${NODE_GID[$1]}"; fi+}diff --git a/scripts/prepare.sh b/scripts/prepare.shindex 37b6a16..fe0d364 100755--- a/scripts/prepare.sh+++ b/scripts/prepare.sh@@ -1,5 +1,6 @@#!/usr/bin/env bash-# Prepare both Sparks to serve Mia-AiLab/GLM-5.3-Flash-EXL3-TR3-4bpw with TensorFold (two ranks):+# Prepare both Sparks to serve Mia-AiLab/GLM-5.3-Flash-EXL3-4bpw-TensorFold with TensorFold (two ranks; with TP=3,+# both workers the same way, each per its own WORKER_WEIGHTS / WORKER_WEIGHTS2):# 1. preflight checks: docker and the GPU on both nodes, key-based ssh to the worker, the RoCE link, disk space# 2. the image on the head: TensorFold plus patches/*.patch on NVIDIA's PyTorch container, pulled prebuilt from# $GHCR_IMAGE when a matching tag is reachable (PULL=0 skips that), else built locally@@ -7,7 +8,8 @@# 4. download the checkpoint on the head into the Hugging Face cache (~164 GiB, resumable), and DFlash2 too when# DRAFTER=dflash2, at their pinned revisions (MODEL_REVISION, DFLASH2_REVISION)# 5. verify the checkpoint with `tensorfold info`-# 6. the same files on the worker, copied from the head over the Sparks' link (rsync), checked file by file+# 6. the same files on the worker, copied from the head over the Sparks' link (rsync), checked file by file; or, with+# WORKER_WEIGHTS=nfs, a read-only NFS volume of the head's cache on the worker, checked the same way# ./start.sh runs this by itself when needed. Safe to re-run: every step skips work that is already done.# Pass --rebuild to rebuild the image from scratch.set -euo pipefail@@ -28,44 +30,106 @@ donemkdir -p "$KERNEL_CACHE" "$STATE_DIR" "$HF_CACHE/hub"exec 9>"$STATE_DIR/prepare.lock"flock -n 9 || die "another prepare.sh is already running (it holds the download locks); wait for it or stop it: pgrep -af prepare.sh"-log "Preflight checks on both Sparks"+SPARKS="both Sparks"; (( TP == 2 )) || SPARKS="all $TP Sparks"+log "Preflight checks on $SPARKS"command -v docker >/dev/null || die "docker is not installed"command -v rsync >/dev/null || die "rsync is not installed on this node (sudo apt install rsync)"docker info >/dev/null 2>&1 || die "cannot talk to the docker daemon (is your user in the docker group?)"if ! command -v nvidia-smi >/dev/null; then warn "nvidia-smi not found on this node"elif ! nvidia-smi -L >/dev/null 2>&1; then warn "nvidia-smi failed on this node: is the NVIDIA driver working?"; fidocker info 2>/dev/null | grep -qi nvidia || warn "docker does not list an nvidia runtime on this node; --gpus all may fail"-need_worker-worker 'docker info >/dev/null 2>&1' || die "the worker ($WORKER) cannot talk to its docker daemon (docker group?)"-worker 'nvidia-smi -L >/dev/null 2>&1' || warn "nvidia-smi failed on the worker: is the NVIDIA driver working?"-worker 'docker info 2>/dev/null | grep -qi nvidia' || warn "docker does not list an nvidia runtime on the worker; --gpus all may fail"-worker 'command -v rsync >/dev/null' || die "rsync is not installed on the worker (sudo apt install rsync)"-detect_link-log "Link: head $HEAD_ADDR ($HEAD_DEV, $HEAD_HCA, GID $HEAD_GID) <-> worker $WORKER_ADDR ($WORKER_DEV, $WORKER_HCA, GID $WORKER_GID)"-WORKER_HF=$(worker_hf_cache)-[[ "$WORKER_WEIGHTS" == nfs ]] || worker "mkdir -p '$WORKER_HF/hub' && test -w '$WORKER_HF/hub'" ||- die "the worker's $WORKER_HF/hub is not writable (left root-owned by a container? fix its ownership there)"+check_workers+# "the worker" at TP=2, "worker 2 (user@host)" beyond+wname() { if (( TP == 2 )); then echo "the worker"; else echo "worker $1 ($(worker_host "$1"))"; fi; }+declare -a WORKER_HF=()+for i in $(worker_ids); do+ need_worker "$i"+ w=$(wname "$i")+ worker "$i" 'docker info >/dev/null 2>&1' || die "$w ($(worker_host "$i")) cannot talk to its docker daemon (docker group?)"+ worker "$i" 'nvidia-smi -L >/dev/null 2>&1' || warn "nvidia-smi failed on $w: is the NVIDIA driver working?"+ worker "$i" 'docker info 2>/dev/null | grep -qi nvidia' || warn "docker does not list an nvidia runtime on $w; --gpus all may fail"+ [[ "$(worker_weights "$i")" == nfs ]] || worker "$i" 'command -v rsync >/dev/null' ||+ die "rsync is not installed on $w (sudo apt install rsync)"+done+detect_links+if (( TP == 2 )); then+ log "Link: head $HEAD_ADDR ($HEAD_DEV, $HEAD_HCA, GID $HEAD_GID) <-> worker $WORKER_ADDR ($WORKER_DEV, $WORKER_HCA, GID $WORKER_GID)"+else+ for i in $(worker_ids); do+ log "Link to worker $i: head ${LINK_HEAD_ADDR[i]:-?} <-> ${LINK_WORKER_ADDR[i]:-?}; RoCE ${NODE_HCAS[i]}"+ done+fi+for i in $(worker_ids); do+ WORKER_HF[i]=$(worker_hf_cache "$i")+ [[ "$(worker_weights "$i")" == nfs ]] || worker "$i" "mkdir -p '${WORKER_HF[i]}/hub' && test -w '${WORKER_HF[i]}/hub'" ||+ die "$(wname "$i")'s ${WORKER_HF[i]}/hub is not writable (left root-owned by a container? fix its ownership there)"+donePATCHES_HASH=$(image_hash)built_hash=$(docker image inspect -f '{{index .Config.Labels "tf.patches"}}' "$IMAGE" 2>/dev/null || true)free_gb() { df -BG --output=avail "$1" 2>/dev/null | tail -1 | tr -dc '0-9'; }-worker_free_gb() { worker "df -BG --output=avail '$1' | tail -1 | tr -dc '0-9'"; }-# Disk on the head: the checkpoint download (unless its snapshot is here) and the image (unless built from these-# patches), both on one filesystem when Docker's root shares it with HF_CACHE+worker_free_gb() { worker "$1" "df -BG --output=avail '$2' | tail -1 | tr -dc '0-9'"; }+models=("$MODEL_ID"); [[ "$DRAFTER" == dflash2 ]] && models+=("$DFLASH2_ID")+# hub_missing_gb: GB (GiB, as df counts) the download still needs on the head: the files of each revision to serve+# whose blob is not in the cache yet (by name, the LFS sha256 or else the git blob id, and by size), from the Hub's+# file list. A new pin that shares its blobs with a cached revision needs next to nothing (issue #24). Asked with+# huggingface_hub from this host's python3 or the hf CLI's own; fails without either, or without the Hub.+HUB_MISSING_PY='+import math, os, sys+from huggingface_hub import HfApi+hub, args, missing = sys.argv[1], sys.argv[2:], 0+for repo, rev in zip(args[::2], args[1::2]):+ blobs = os.path.join(hub, "models--" + repo.replace("/", "--"), "blobs")+ for f in HfApi().model_info(repo, revision=rev or None, files_metadata=True).siblings:+ lfs = f.lfs+ name = (getattr(lfs, "sha256", None) or lfs["sha256"]) if lfs else f.blob_id+ size = (getattr(lfs, "size", None) or lfs["size"]) if lfs else (f.size or 0)+ p = os.path.join(blobs, name)+ missing += 0 if os.path.isfile(p) and os.path.getsize(p) == size else size+print(math.ceil(missing / 2**30))'+hub_missing_gb() {+ local py id args=() out tried=""+ for id in "${models[@]}"; do args+=("$id" "$(model_revision "$id")"); done+ for py in "$(command -v python3)" "$(sed -n '1s/^#! *\(\/[^ ]*python[0-9.]*\)$/\1/p' "$(command -v hf || echo /dev/null)" 2>/dev/null)"; do+ [[ -n "$py" && -x "$py" && "$py" != "${tried:-}" ]] || continue+ tried=$py+ out=$(timeout 30 "$py" -c "$HUB_MISSING_PY" "$HF_CACHE/hub" "${args[@]}" 2>/dev/null) && [[ "$out" =~ ^[0-9]+$ ]] &&+ { echo "$out"; return 0; }+ done+ return 1+}+# Disk on the head: what the download still needs (plus 5 GB), and the image (unless built from these patches), both+# on one filesystem when Docker's root shares it with HF_CACHE. Without the Hub's file list: MIN_FREE_GB, unless every+# snapshot to serve is already here (as before).DOCKER_ROOT=$(docker info -f '{{.DockerRootDir}}' 2>/dev/null || echo /var/lib/docker)-need_ckpt=0; [[ -d "$(model_cache_dir)/snapshots/$(snapshot_rev "$MODEL_ID")" ]] || need_ckpt=$MIN_FREE_GB+if missing=$(hub_missing_gb); then+ need_ckpt=0; (( missing == 0 )) || need_ckpt=$((missing + 5))+ ckpt_what="the download needs ~${missing} GB that the cache does not hold yet"+else+ need_ckpt=0+ for id in "${models[@]}"; do [[ -d "$(model_cache_dir "$id")/snapshots/$(snapshot_rev "$id")" ]] || need_ckpt=$MIN_FREE_GB; done+ ckpt_what="the checkpoint needs MIN_FREE_GB (the Hub's file list could not be read to count what is missing)"+fi+(( need_ckpt )) || ckpt_what="nothing to download"need_img=0; [[ $REBUILD -eq 0 && "$built_hash" == "$PATCHES_HASH" ]] || need_img=$IMAGE_FREE_GBif [[ "$(stat -c %d "$HF_CACHE")" == "$(stat -c %d "$DOCKER_ROOT" 2>/dev/null)" ]]; thenhave=$(free_gb "$HF_CACHE"); (( have >= need_ckpt + need_img )) ||- die "only ${have} GB free under $HF_CACHE (also Docker's root); the checkpoint and the image need ~$((need_ckpt + need_img)) GB (MIN_FREE_GB, IMAGE_FREE_GB)"+ die "only ${have} GB free under $HF_CACHE (also Docker's root), ~$((need_ckpt + need_img)) GB needed: $ckpt_what; the image needs ${need_img} GB (IMAGE_FREE_GB)"elsehave=$(free_gb "$HF_CACHE"); (( have >= need_ckpt )) ||- die "only ${have} GB free under $HF_CACHE; the checkpoint needs ~${need_ckpt} GB (MIN_FREE_GB)"+ die "only ${have} GB free under $HF_CACHE, ~${need_ckpt} GB needed: $ckpt_what"have=$(free_gb "$DOCKER_ROOT"); (( have >= need_img )) ||die "only ${have} GB free under Docker's root ($DOCKER_ROOT); the image needs ~${need_img} GB (IMAGE_FREE_GB)"fi-WORKER_DOCKER_ROOT=$(worker "docker info -f '{{.DockerRootDir}}'" 2>/dev/null || echo /var/lib/docker)-log "Disk: $(free_gb "$HF_CACHE") GB free under $HF_CACHE here, $(worker_free_gb "$WORKER_HF") GB under $WORKER_HF on the worker"+declare -a WORKER_DOCKER_ROOT=()+disk=""+for i in $(worker_ids); do+ WORKER_DOCKER_ROOT[i]=$(worker "$i" "docker info -f '{{.DockerRootDir}}'" 2>/dev/null || echo /var/lib/docker)+ if [[ "$(worker_weights "$i")" == nfs ]]; then d=${WORKER_DOCKER_ROOT[i]}; else d=${WORKER_HF[i]}; fi+ if (( TP == 2 )); then disk+=", $(worker_free_gb "$i" "$d") GB under $d on the worker"+ else disk+=", $(worker_free_gb "$i" "$d") GB under $d on worker $i"; fi+done+log "Disk: $(free_gb "$HF_CACHE") GB free under $HF_CACHE here$disk"# ---------------------------------------------------------------- 2. image (head)# Local fixes in ./patches (unified diffs against site-packages, applied with patch -p0) are baked into the image.@@ -107,23 +171,25 @@ elsefidocker run --rm --entrypoint tensorfold "$IMAGE" --version 2>/dev/null | tail -1-# ---------------------------------------------------------------- 3. image (worker)+# ---------------------------------------------------------------- 3. image (workers)image_id=$(image_ident "$IMAGE") # by content: .Id differs between image stores (issue #8)-if [[ "$(worker_image_ident "$IMAGE")" != "$image_id" ]]; then- wfree=$(worker_free_gb "$WORKER_DOCKER_ROOT")+for i in $(worker_ids); do+ w=$(wname "$i")+ [[ "$(worker_image_ident "$i" "$IMAGE")" != "$image_id" ]] || continue+ wfree=$(worker_free_gb "$i" "${WORKER_DOCKER_ROOT[i]}")(( wfree >= IMAGE_FREE_GB )) ||- die "only ${wfree} GB free under the worker's Docker root ($WORKER_DOCKER_ROOT); the image needs ~${IMAGE_FREE_GB} GB (IMAGE_FREE_GB)"- if [[ "${PULL:-1}" == 1 ]] && worker docker pull "$prebuilt" >/dev/null 2>&1 &&- [[ "$(worker_image_ident "$prebuilt")" == "$image_id" ]]; then- worker docker tag "$prebuilt" "$IMAGE"- log "Using $prebuilt as $IMAGE on the worker"+ die "only ${wfree} GB free under $w's Docker root (${WORKER_DOCKER_ROOT[i]}); the image needs ~${IMAGE_FREE_GB} GB (IMAGE_FREE_GB)"+ if [[ "${PULL:-1}" == 1 ]] && worker "$i" docker pull "$prebuilt" >/dev/null 2>&1 &&+ [[ "$(worker_image_ident "$i" "$prebuilt")" == "$image_id" ]]; then+ worker "$i" docker tag "$prebuilt" "$IMAGE"+ log "Using $prebuilt as $IMAGE on $w"else- log "Copying $IMAGE to the worker (docker save | docker load; only missing layers are stored)"- docker save "$IMAGE" | worker docker load >/dev/null+ log "Copying $IMAGE to $w (docker save | docker load; only missing layers are stored)"+ docker save "$IMAGE" | worker "$i" docker load >/dev/nullfi- [[ "$(worker_image_ident "$IMAGE")" == "$image_id" ]] || die "the worker's $IMAGE differs from the head's"-fi-log "Image $IMAGE identical on both Sparks"+ [[ "$(worker_image_ident "$i" "$IMAGE")" == "$image_id" ]] || die "$w's $IMAGE differs from the head's"+done+log "Image $IMAGE identical on $SPARKS"# ---------------------------------------------------------------- 4. download (head)# One revision on both ranks: MODEL_REVISION / DFLASH2_REVISION (config.sh; empty: what the Hub calls main when first@@ -134,12 +200,12 @@ download() { # <repo id> <revision or empty># Host CLI: resumable, parallel, writes the standard HF cache layout.hf download "$1" ${2:+--revision "$2"} --cache-dir "$HF_CACHE/hub" >/dev/nullelse- docker run --rm --network host --entrypoint python ${HF_TOKEN:+-e HF_TOKEN} \- -v "$HF_CACHE":/root/.cache/huggingface "$IMAGE" -c \+ # Keep downloads owned by the host user, in the same HF_CACHE/hub layout as the host CLI.+ docker run --rm --user "$(id -u):$(id -g)" --network host --entrypoint python ${HF_TOKEN:+-e HF_TOKEN} \+ -v "$HF_CACHE":/hf -e HF_HOME=/hf -e HOME=/tmp "$IMAGE" -c \'import sys; from huggingface_hub import snapshot_download; snapshot_download(sys.argv[1], revision=sys.argv[2] or None)' "$1" "$2"fi}-models=("$MODEL_ID"); [[ "$DRAFTER" == dflash2 ]] && models+=("$DFLASH2_ID")for id in "${models[@]}"; dopin=$(model_revision "$id"); dir=$(model_cache_dir "$id")log "Downloading $id${pin:+ @ ${pin:0:8}} into $HF_CACHE/hub (resumes if interrupted)"@@ -164,47 +230,76 @@ info=$(docker run --rm --entrypoint tensorfold -e HF_HUB_OFFLINE=1 -v "$HF_CACHEdie "tensorfold info cannot read the checkpoint: $info"printf '%s\n' "$info" | grep -v "EXL3 support is experimental" || true-# ---------------------------------------------------------------- 6. the same files on the worker-if [[ "$WORKER_WEIGHTS" == nfs ]]; then # no copy: rank 1 reads the head's cache over NFS- ensure_nfs_volume+# ---------------------------------------------------------------- 6. the same files on the workers+# The manifests below ("<file> <size>" a line) are sorted in byte order on both sides (LC_ALL=C, also inside the+# commands sent over ssh, which carries no locale of ours): each host's own collation would order the same files+# differently (issue #21). On a mismatch, the first differing lines show what differs.+manifest_diff() { # <head's manifest> <worker's manifest>+ warn "first differences (< head, > worker):"+ diff <(printf '%s\n' "$1") <(printf '%s\n' "$2") | head -20 >&2 || true+}+for i in $(worker_ids); do+ [[ "$(worker_weights "$i")" == nfs ]] || continue # no copy: rank i reads the head's cache over NFS+ w=$(wname "$i"); server=$(nfs_server "$i")+ ensure_nfs_volume "$i"+ # the mount first: a refused export says so here, not as a missing file below+ if ! out=$(worker_nfs "$i" true 2>&1); then+ die "$w cannot mount the head's :$NFS_PATH from $server over NFS ($NFS_VOLUME): $(tail -1 <<<"$out")+ The head must export $NFS_PATH to that worker's address on its link (${LINK_WORKER_ADDR[i]:-its CX7 address}, or its subnet), read-only;+ or set $(wvar NFS_SERVER "$i") to a head address the export allows, or $(wvar WORKER_WEIGHTS "$i")=copy (README: Worker weights over NFS)"+ fifor id in "${models[@]}"; dodir=$(model_cache_dir "$id"); rev=$(snapshot_rev "$id")- manifest=$(cd "$dir/snapshots/$rev" && find -L . -type f -printf '%P %s\n' | sort)- have=$(worker_nfs find -L "/hf/hub/${dir##*/}/snapshots/$rev" -type f -printf '%P %s\n' 2>/dev/null | sort || true)- [[ "$have" == "$manifest" ]] ||- die "the worker does not see $id @ ${rev:0:8} over NFS ($NFS_VOLUME: :$NFS_PATH from ${NFS_SERVER:-$HEAD_ADDR}); is HF_CACHE exported to it? (README: Worker weights over NFS)"- log "Worker reads $id @ ${rev:0:8} from the head over NFS ($NFS_VOLUME)"+ manifest=$(cd "$dir/snapshots/$rev" && find -L . -type f -printf '%P %s\n' | LC_ALL=C sort)+ have=$(worker_nfs "$i" find -L "/hf/hub/${dir##*/}/snapshots/$rev" -type f -printf '%P %s\n' 2>/dev/null | LC_ALL=C sort || true)+ [[ "$have" == "$manifest" ]] || { manifest_diff "$manifest" "$have"+ die "$w does not see $id @ ${rev:0:8} over NFS ($NFS_VOLUME: :$NFS_PATH from $server); is HF_CACHE exported to it? (README: Worker weights over NFS)"; }+ if (( TP == 2 )); then log "Worker reads $id @ ${rev:0:8} from the head over NFS ($NFS_VOLUME)"+ else log "Worker $i reads $id @ ${rev:0:8} from the head over NFS ($NFS_VOLUME from $server)"; fidone-fi+done+for i in $(worker_ids); dofor id in "${models[@]}"; do- [[ "$WORKER_WEIGHTS" == nfs ]] && break+ [[ "$(worker_weights "$i")" == nfs ]] && break+ w=$(wname "$i"); WHOST=$(worker_host "$i"); WHF=${WORKER_HF[i]}dir=$(model_cache_dir "$id"); rev=$(snapshot_rev "$id")# every file of the snapshot, with its size (links followed), as the head has it- manifest=$(cd "$dir/snapshots/$rev" && find -L . -type f -printf '%P %s\n' | sort)- wdir="$WORKER_HF/hub/${dir##*/}"- have=$(worker "cd '$wdir/snapshots/$rev' 2>/dev/null && find -L . -type f -printf '%P %s\n' | sort" || true)+ manifest=$(cd "$dir/snapshots/$rev" && find -L . -type f -printf '%P %s\n' | LC_ALL=C sort)+ wdir="$WHF/hub/${dir##*/}"+ have=$(worker "$i" "cd '$wdir/snapshots/$rev' 2>/dev/null && find -L . -type f -printf '%P %s\n' | LC_ALL=C sort" || true)if [[ "$have" == "$manifest" ]]; then- log "Worker has $id @ ${rev:0:8}"+ if (( TP == 2 )); then log "Worker has $id @ ${rev:0:8}"; else log "Worker $i has $id @ ${rev:0:8}"; ficontinuefi- need=$(( $(du -sLB1G "$dir/snapshots/$rev" | cut -f1) + 5 ))- wfree=$(worker_free_gb "$WORKER_HF")- (( wfree >= need )) || die "only ${wfree} GB free under $WORKER_HF on the worker, $id needs ~${need} GB"- log "Copying $id @ ${rev:0:8} to the worker over the Sparks' link (~${need} GB, resumes)"- worker "mkdir -p '$wdir/refs' '$wdir/snapshots'"- # the blobs this revision uses, then its snapshot links and refs/main (the cache layout huggingface_hub keeps)- (cd "$dir" && find "snapshots/$rev" -type l -printf '%l\n' | sed 's#^\(\.\./\)*##' | sort -u) > "$STATE_DIR/blobs"+ # the blobs this revision uses (the cache layout huggingface_hub keeps), and how much rsync must send: the blobs (and+ # any plain file in the snapshot) that the worker lacks or holds at another size (issue #24; an earlier revision+ # may have brought it the rest)+ (cd "$dir" && find "snapshots/$rev" -type l -printf '%l\n' | sed 's#^\(\.\./\)*##' | LC_ALL=C sort -u) > "$STATE_DIR/blobs"+ (cat "$STATE_DIR/blobs"; cd "$dir" && find "snapshots/$rev" -type f) > "$STATE_DIR/files"+ send=$(awk 'FILENAME == ARGV[1] { w[$2] = $1; next } w[$2] != $1 { s += $1 } END { printf "%d", (s + 2^30 - 1) / 2^30 }' \+ <(worker "$i" "cd '$wdir' 2>/dev/null && xargs -r stat -Lc '%s %n' 2>/dev/null; true" < "$STATE_DIR/files") \+ <(cd "$dir" && xargs -r stat -Lc '%s %n' < "$STATE_DIR/files"))+ need=0; (( send == 0 )) || need=$((send + 5))+ wfree=$(worker_free_gb "$i" "$WHF")+ (( wfree >= need )) ||+ die "only ${wfree} GB free under $WHF on $w; $id needs ~${need} GB there (~${send} GB to send; or set $(wvar WORKER_WEIGHTS "$i")=nfs)"+ log "Copying $id @ ${rev:0:8} to $w over the Sparks' link (~${send} GB to send, resumes)"+ worker "$i" "mkdir -p '$wdir/refs' '$wdir/snapshots'"+ # the blobs, then the snapshot's links and refs/main# -L: a blob may itself be a link into the cache root's blobs/ (huggingface_hub's xet backend, issue #15)- rsync -a -L --partial --files-from="$STATE_DIR/blobs" "$dir/" "$WORKER:$wdir/" \+ rsync -a -L --partial --files-from="$STATE_DIR/blobs" "$dir/" "$WHOST:$wdir/" \-e "ssh -o BatchMode=yes" ${RSYNC_OPTS:-}- rsync -a "$dir/snapshots/$rev" "$WORKER:$wdir/snapshots/" -e "ssh -o BatchMode=yes"+ rsync -a "$dir/snapshots/$rev" "$WHOST:$wdir/snapshots/" -e "ssh -o BatchMode=yes"# refs/main as the head has it (with a pin: only when the worker has none)- if [[ -z "$(model_revision "$id")" ]]; then worker "printf %s '$rev' > '$wdir/refs/main'"- else worker "test -f '$wdir/refs/main' || printf %s '$rev' > '$wdir/refs/main'"; fi- have=$(worker "cd '$wdir/snapshots/$rev' && find -L . -type f -printf '%P %s\n' | sort")- [[ "$have" == "$manifest" ]] || die "the worker's copy of $id differs from the head's after the copy"+ if [[ -z "$(model_revision "$id")" ]]; then worker "$i" "printf %s '$rev' > '$wdir/refs/main'"+ else worker "$i" "test -f '$wdir/refs/main' || printf %s '$rev' > '$wdir/refs/main'"; fi+ have=$(worker "$i" "cd '$wdir/snapshots/$rev' && find -L . -type f -printf '%P %s\n' | LC_ALL=C sort")+ [[ "$have" == "$manifest" ]] ||+ { manifest_diff "$manifest" "$have"; die "$w's copy of $id differs from the head's after the copy"; }+donedoneprepared_state > "$PREPARED_MARKER"-log "Done: both Sparks are ready. Start the server with ./start.sh (port $PORT)."-log "The first start compiles CUDA kernels for GB10 (a few minutes); they are cached in $KERNEL_CACHE/<image hash> here and under ~/.cache/tensorfold-glm53 on the worker (a folder per image)."+if (( TP == 2 )); then log "Done: both Sparks are ready. Start the server with ./start.sh (port $PORT)."+else log "Done: all $TP Sparks are ready. Start the server with ./start-tp$TP.sh (port $PORT)."; fi+log "The first start compiles CUDA kernels for GB10 (a few minutes); they are cached in $KERNEL_CACHE/<image hash> here and under ~/.cache/tensorfold-glm53 on $( (( TP == 2 )) && echo "the worker" || echo "each worker") (a folder per image)."diff --git a/start-tp3.sh b/start-tp3.shnew file mode 100755index 0000000..b55a238--- /dev/null+++ b/start-tp3.sh@@ -0,0 +1,17 @@+#!/usr/bin/env bash+# Serve GLM-5.3 Flash EXL3 on three DGX Sparks (TP=3, experimental): ./start.sh with TP=3, COMM=nccl by default.+# Needs the TP-N GLM engine (patches 0066-0068; prepare.sh builds the image on the first start), WORKER and WORKER2 in+# scripts/local.sh, and a triangle of direct CX7 cables, one per pair (one subnet per cable).+# README: "3 Sparks (experimental)".+#+# Usage: ./start-tp3.sh [restart] [extra tensorfold serve args] (as ./start.sh; ./stop.sh stops it)+# DRY_RUN=1 ./start-tp3.sh # print every rank's docker command, change nothing+# COMM defaults to nccl here (NCCL for every all-gather); COMM=roce ./start-tp3.sh sends the small ones over RoCE,+# each peer on the devices that share its subnet (needs the TP-N engine's RoCE). COMM in scripts/local.sh or .env is+# not read here: set it on the command line.+set -euo pipefail+case "${1:-}" in+ help|-h|--help) awk 'NR > 1 && /^#/ { sub(/^# ?/, ""); print; next } NR > 1 { exit }' "$0"; echo; echo "./start.sh's options:"; echo ;;+esac+export TP=3 COMM="${COMM:-nccl}"+exec "$(dirname "$(readlink -f "$0")")/start.sh" "$@"diff --git a/start.sh b/start.shindex 250abbc..909e1ab 100755--- a/start.sh+++ b/start.sh@@ -1,8 +1,8 @@#!/usr/bin/env bash-# Serve GLM-5.3 Flash EXL3 (Mia-AiLab/GLM-5.3-Flash-EXL3-TR3-4bpw) with TensorFold on two DGX Sparks, end to end:+# Serve GLM-5.3 Flash EXL3 (Mia-AiLab/GLM-5.3-Flash-EXL3-4bpw-TensorFold) with TensorFold on two DGX Sparks, end to end:# runs scripts/prepare.sh on both Sparks when the image or the checkpoint is not ready yet (first run, or after patches# change), starts rank 1 on the worker and rank 0 here, which serves the API on port 8888, waits until the OpenAI API-# answers, then runs a smoke test. Stop it with ./stop.sh.+# answers, then runs a smoke test. Stop it with ./stop.sh. (3 Sparks: ./start-tp3.sh, experimental.)## Usage: ./start.sh [restart] [extra tensorfold serve args]# ./start.sh # scripts/config.sh defaults: 4 requests at once, a 1,048,576-token window,@@ -14,22 +14,28 @@# CONTEXT=131072 ./start.sh restart# KV=bf16 ./start.sh restart # the exact bf16 KV cache (and a 196,608 window)# DRAFTER=mtp ./start.sh restart # the checkpoint's own MTP head instead of DFlash2 (one request at a time)+# DRY_RUN=1 ./start.sh # print every rank's docker command and exit, stopping and starting nothing# Extra arguments go to both ranks after the defaults, so they win (the last value of a flag counts).# Setup: WORKER=user@<worker address> in scripts/local.sh (key-based ssh).# Settings, from the environment, scripts/local.sh or ./.env (defaults and measured effects in scripts/config.sh):# serving CONTEXT, PARALLEL, KV, DENSE, DRAFTER, DRAFT_POLICY, COPY, COPY_MAX, COPY_CODE, SPLIT, KDA_CHUNKED,-# SHARED_PREFIX, MULTI_PREFILL, KV_POOL_GIB, MEMORY_RESERVE_GIB, MAX_TOKENS, THINKING, VISION, VISION_URLS, COMM, SERVED_NAME, HOST, PORT-# nodes WORKER, FABRIC_PEER, MASTER_PORT, NCCL_RAILS (1: one CX7 port), NCCL_CHANNELS, NCCL_DEBUG+# SHARED_PREFIX, MULTI_PREFILL, STREAM_SMOOTH, STREAM_SMOOTH_MS, FILL_BUDGET_MS, FILL_DRAFTS, KV_POOL_GIB,+# MEMORY_RESERVE_GIB, MAX_TOKENS, THINKING, VISION, VISION_URLS, COMM, SERVED_NAME, HOST, PORT+# nodes WORKER, FABRIC_PEER, WORKER_HF_CACHE, MASTER_PORT, NCCL_RAILS (1: one RoCE device), NCCL_CHANNELS,+# NCCL_DEBUG; TP (2), WORKER2, FABRIC_PEER2, WORKER_HF_CACHE2, MASTER_ADDR, SOCKET_IFNAME (3 Sparks)# files MODEL_ID, MODEL_REVISION, DFLASH2_ID, DFLASH2_REVISION, HF_CACHE (default: HF_HOME), KERNEL_CACHE,# WORKER_WEIGHTS (copy | nfs: rank 1 reads the head's HF_CACHE over NFS), NFS_PATH, NFS_SERVER, NFS_VOLUME,+# WORKER_WEIGHTS2, NFS_SERVER2,# STATE_DIR, HF_HUB_OFFLINE=0 (let TensorFold reach the Hub; default serves from the local cache only)# image IMAGE, TF_VERSION, TF_REPO, BASE_IMAGE, GHCR_IMAGE, IMAGE_TAG / IMAGE_DIGEST (the pinned published# image), CONTAINER_NAME# setup PREPARE (auto | 1 | 0), PULL, MIN_FREE_GB, IMAGE_FREE_GB, RSYNC_OPTS, HF_TOKEN (prepare.sh's downloads);# FOREGROUND=1 (stay attached to rank 0's log, exit with its code); WAIT_TIMEOUT (seconds, default 1800);-# STOP_TIMEOUT (stop.sh)-# decode TF_GLM_L2PF (1), TF_GLM_EXL3_LOADS (nc), TF_ROCE_MAX_KB (512), TF_GLM_MULTI_LONE (1)-# ranks every TENSORFOLD_*, TF_GLM_* and TF_ROCE_* variable goes to both ranks, e.g.+# DRY_RUN=1 (print the docker commands, change nothing);+# STOP_TIMEOUT (stop.sh); LOG_DIR, LOG_KEEP (saved server logs)+# decode TF_GLM_L2PF (1), TF_GLM_EXL3_LOADS (nc), TF_ROCE_MAX_KB (512), TF_GLM_MULTI_LONE (0)+# ranks every TENSORFOLD_*, TF_GLM_* and TF_ROCE_* variable goes to every rank (TP>2: TF_ROCE_HCA per node, found),+# e.g.# TENSORFOLD_GLM_IMAGE_TOKENS, TENSORFOLD_MEMORY_RESERVE_GIB, TF_GLM_KEEP_REASONING=0set -euo pipefailcd "$(dirname "$(readlink -f "$0")")"@@ -51,19 +57,22 @@ SERVE_ARGS=(--context "$CONTEXT" --parallel "$PARALLEL" --max-tokens "$MAX_TOKEN[[ "$DRAFTER" =~ ^(mtp|dflash2)$ ]] || die "DRAFTER is mtp or dflash2, not $DRAFTER"[[ "$DENSE" =~ ^(bf16|fp8|q4)$ ]] || die "DENSE is bf16, fp8 or q4, not $DENSE"[[ "$COMM" =~ ^(nccl|roce)$ ]] || die "COMM is nccl or roce, not $COMM"+check_workers[[ "$KV" =~ ^(bf16|fp8)$ ]] || die "KV is bf16 or fp8, not $KV"[[ "$CONTEXT" =~ ^[0-9]+$ && "$CONTEXT" -le 1048576 ]] || die "CONTEXT is a token count up to 1048576 (0: the largest that fits), not $CONTEXT"[[ "$PARALLEL" =~ ^[1-4]$ ]] || die "PARALLEL is 1 to 4, not $PARALLEL"[[ "$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; do [[ "${!v}" =~ ^[01]$ ]] || die "$v is 0 or 1, not ${!v}"; done+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[[ "$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"[[ "$MEMORY_RESERVE_GIB" =~ ^[0-9]+([.][0-9]+)?$ ]] || die "MEMORY_RESERVE_GIB is a number of GiB, not $MEMORY_RESERVE_GIB"[[ "$COPY_MAX" =~ ^([1-9]|1[0-5])$ ]] || die "COPY_MAX is 1 to 15, not $COPY_MAX"[[ "$DRAFT_POLICY" == f* ]] || die "DRAFT_POLICY is a DFlash2 policy (fc5:0.3, fnc7:0.3, fcost7:noisy ...), not $DRAFT_POLICY"# decode settings the ranks read at load (scripts/config.sh): checked here so a typo fails before anything is stopped[[ "$TF_GLM_MULTI_LONE" =~ ^[01]$ ]] || die "TF_GLM_MULTI_LONE is 0 or 1, not $TF_GLM_MULTI_LONE"+[[ "$TF_GLM_CLEAR_THINKING" =~ ^[01]$ ]] || die "TF_GLM_CLEAR_THINKING is 0 or 1, not $TF_GLM_CLEAR_THINKING"[[ "$TF_GLM_L2PF" =~ ^(0|off|1|bulk|lines|touch)$ ]] || die "TF_GLM_L2PF is 0, 1 (bulk), lines or touch, not $TF_GLM_L2PF"[[ "$TF_GLM_EXL3_LOADS" =~ ^(0|ldg|1|nc|nc1|nc2|nc4)$ ]] || die "TF_GLM_EXL3_LOADS is 0, nc, nc2 or nc4, not $TF_GLM_EXL3_LOADS"[[ "$TF_ROCE_MAX_KB" =~ ^[1-9][0-9]*$ ]] || die "TF_ROCE_MAX_KB is a size in KiB (512: up to 32-row windows over RoCE), not $TF_ROCE_MAX_KB"@@ -88,7 +97,10 @@ API_HOST="$HOST"; [[ "$HOST" == 0.0.0.0 || "$HOST" == "::" ]] && API_HOST=127.0.URL="http://$API_HOST:$PORT"running_here() { [[ "$(docker inspect -f '{{.State.Running}}' "$CONTAINER_NAME" 2>/dev/null)" == true ]]; }-running_worker() { [[ "$(worker docker inspect -f '{{.State.Running}}' "$CONTAINER_NAME" 2>/dev/null)" == true ]]; }+running_worker() { [[ "$(worker "$1" docker inspect -f '{{.State.Running}}' "$CONTAINER_NAME" 2>/dev/null)" == true ]]; }+# Words for the nodes: "both Sparks" / "the worker" at TP=2, "all 3 Sparks" / "rank 2 (user@host)" beyond.+SPARKS="both Sparks"; (( TP == 2 )) || SPARKS="all $TP Sparks"+wname() { if (( TP == 2 )); then echo "the worker"; else echo "rank $1 ($(worker_host "$1"))"; fi; }served_name() {curl -s --max-time 5 "$URL/v1/models" 2>/dev/null |python3 -c 'import json,sys; print(json.load(sys.stdin)["data"][0]["id"])' 2>/dev/null@@ -101,7 +113,7 @@ source ./scripts/banner.shechobanner # the TensorFold ribbon and MIA AI LAB (terminals only)printf '\n%s Mia'"'"'s TensorFold Start Script%s\n' "$M" "$R"-printf '%s %s · 2 x DGX Spark · %s at once · %s-token window · %s KV · %s drafts · port %s%s\n\n' "$D" "$MODEL_ID" \+printf '%s %s · %s x DGX Spark · %s at once · %s-token window · %s KV · %s drafts · port %s%s\n\n' "$D" "$MODEL_ID" "$TP" \"$(arg_value --parallel)" "$(arg_value --context)" "$KV" "$DRAFTER" "$PORT" "$R"STEPS=5step() { printf '%s[%s/%s]%s %s%s%s\n' "$M" "$1" "$STEPS" "$R" "$B" "$2" "$R"; }@@ -110,11 +122,13 @@ command -v docker >/dev/null || die "docker is not installed"mkdir -p "$KERNEL_CACHE" "$STATE_DIR"exec 8>"$STATE_DIR/start.lock"flock -n 8 || die "another ./start.sh is already running; wait for it to finish"-need_worker+need_workers+(( DRY )) && log "DRY_RUN=1: printing the docker commands; nothing is stopped, started or prepared"# ---------------------------------------------------------------- already running?-if [[ "$MODE" == start ]] && running_here && running_worker; then- log "$CONTAINER_NAME is already running on both Sparks (model: $(served_name || echo "not answering yet"), port $PORT): nothing to do."+all_running() { local i; running_here || return 1; for i in $(worker_ids); do running_worker "$i" || return 1; done; }+if (( ! DRY )) && [[ "$MODE" == start ]] && all_running; then+ log "$CONTAINER_NAME is already running on $SPARKS (model: $(served_name || echo "not answering yet"), port $PORT): nothing to do."log "Use ./start.sh restart to restart it (e.g. with new settings), or ./stop.sh to stop it."exit 0fi@@ -122,39 +136,54 @@ fi# ---------------------------------------------------------------- 1. setup# scripts/prepare.sh (image and checkpoint on both Sparks) runs whenever what it last prepared differs from now: the# first run, new patches, another model, drafter or worker. PREPARE=1 forces it, PREPARE=0 skips it.-step 1 "Setup: image and checkpoint on both Sparks"+step 1 "Setup: image and checkpoint on $SPARKS"if [[ "${PREPARE:-auto}" == 1 || ( "${PREPARE:-auto}" != 0 && "$(prepared_state 2>/dev/null)" != "$(cat "$PREPARED_MARKER" 2>/dev/null)" ) ]]; then- log "Not ready yet: running scripts/prepare.sh (the first time this pulls the image, downloads ~166 GiB and copies both to the worker)"- ./scripts/prepare.sh+ if (( DRY )); then log "DRY_RUN: scripts/prepare.sh would run now (not ready yet)"+ else+ log "Not ready yet: running scripts/prepare.sh (the first time this pulls the image, downloads ~166 GiB and copies both to the worker)"+ ./scripts/prepare.sh+ fielse- log "Ready: $IMAGE (patches $(image_hash)) and $MODEL_ID on both Sparks${PREPARE:+ (PREPARE=$PREPARE)}"+ log "Ready: $IMAGE (patches $(image_hash)) and $MODEL_ID on $SPARKS${PREPARE:+ (PREPARE=$PREPARE)}"fiwhy="scripts/prepare.sh did not"; [[ "${PREPARE:-auto}" == 0 ]] && why="PREPARE=0 skipped scripts/prepare.sh, which would"+(( DRY )) && why="DRY_RUN: scripts/prepare.sh would"docker image inspect "$IMAGE" >/dev/null 2>&1 || die "image $IMAGE missing: $why build it"-worker docker image inspect "$IMAGE" >/dev/null 2>&1 || die "image $IMAGE missing on the worker: $why copy it there"+for i in $(worker_ids); do+ [[ -z "${WORKER_DOWN[$i]:-}" ]] || continue+ worker "$i" docker image inspect "$IMAGE" >/dev/null 2>&1 || { (( DRY )) && warn "image $IMAGE missing on $(wname "$i"): $why copy it there"; } ||+ die "image $IMAGE missing on $(wname "$i"): $why copy it there"+done# Compiled kernels are kept per image (its patches hash): a build is found by its extension's name, so another image's# build of the same name, older or newer, must never be the one loadedKCACHE=$(docker image inspect -f '{{index .Config.Labels "tf.patches"}}' "$IMAGE" 2>/dev/null || true)[[ "$KCACHE" =~ ^[0-9a-f]{12}$ ]] || KCACHE=$(docker image inspect -f '{{.Id}}' "$IMAGE" | cut -d: -f2 | cut -c1-12)# (docker creates the folder at the mount: the cache is the containers', so it may not be writable from here)-# The snapshots both ranks serve (config.sh's pins, else refs/main), as paths under the containers' cache mount: the-# ranks read them offline, whatever the Hub's main is now. The worker's cache is its own HF_HOME (prepare.sh copies-# into the same place).-WORKER_HF=$(worker_hf_cache)-WORKER_MOUNT="$WORKER_HF:/root/.cache/huggingface" # rank 1's cache: its own copy, or the head's (nfs)-[[ "$WORKER_WEIGHTS" == nfs ]] && WORKER_MOUNT="$NFS_VOLUME:/root/.cache/huggingface:ro"-snapshot() { # <repo id>: its snapshot path in the container, checked on both Sparks- local id=$1 rev sub+# The snapshots every rank serves (config.sh's pins, else refs/main), as paths under the containers' cache mount: the+# ranks read them offline, whatever the Hub's main is now. A worker's cache is its own HF_HOME (prepare.sh copies+# into the same place), or the head's over NFS (WORKER_WEIGHTS / WORKER_WEIGHTS<i>=nfs).+declare -a WORKER_HF=() WORKER_MOUNT=()+for i in $(worker_ids); do+ WORKER_HF[i]=$(worker_hf_cache "$i")+ WORKER_MOUNT[i]="${WORKER_HF[i]}:/root/.cache/huggingface" # rank i's cache: its own copy, or the head's (nfs)+ [[ "$(worker_weights "$i")" == nfs ]] && WORKER_MOUNT[i]="$NFS_VOLUME:/root/.cache/huggingface:ro"+done+snapshot() { # <repo id>: its snapshot path in the container, checked on every Spark (DRY_RUN: here only)+ local id=$1 rev sub irev=$(snapshot_rev "$id")[[ -n "$rev" ]] || die "$id not in $HF_CACHE: $why download it"sub="hub/models--${id//\//--}/snapshots/$rev"[[ -f "$HF_CACHE/$sub/config.json" ]] || die "$id @ ${rev:0:8} not in $HF_CACHE: $why download it"- if [[ "$WORKER_WEIGHTS" == nfs ]]; then- worker_nfs test -f "/hf/$sub/config.json" ||- die "the worker does not see $id @ ${rev:0:8} over NFS ($NFS_VOLUME): $why set it up"- else- worker "test -f '$WORKER_HF/$sub/config.json'" || die "$id @ ${rev:0:8} not on the worker ($WORKER_HF): $why copy it there"- fi+ for i in $(worker_ids); do+ (( DRY )) && break+ if [[ "$(worker_weights "$i")" == nfs ]]; then+ worker_nfs "$i" test -f "/hf/$sub/config.json" ||+ die "$(wname "$i") does not see $id @ ${rev:0:8} over NFS ($NFS_VOLUME): $why set it up"+ else+ worker "$i" "test -f '${WORKER_HF[i]}/$sub/config.json'" ||+ die "$id @ ${rev:0:8} not on $(wname "$i") (${WORKER_HF[i]}): $why copy it there"+ fi+ doneecho "/root/.cache/huggingface/$sub"}MODEL_ARG=$(snapshot "$MODEL_ID")@@ -167,94 +196,152 @@ step 2 "Checks: arguments, link, previous server, port, memory"# tensorfold's own parser, in a throwaway container without the GPU: a typo fails here, before anything is stoppeddocker run --rm --entrypoint python "$IMAGE" -c \'import sys; from tensorfold.cli import build_parser; build_parser().parse_args(sys.argv[1:])' \- serve "$MODEL_ARG" --tp 2 --rank 0 --master 127.0.0.1 --host "$HOST" --port "$PORT" "${SERVE_ARGS[@]}" >/dev/null ||- die "tensorfold serve rejects these arguments (see above); nothing was changed"-detect_link-log "Link: $HEAD_ADDR ($HEAD_DEV) <-> $WORKER_ADDR ($WORKER_DEV), RoCE $HEAD_HCAS / $WORKER_HCAS"+ serve "$MODEL_ARG" --tp "$TP" --rank 0 --master 127.0.0.1 --host "$HOST" --port "$PORT" "${SERVE_ARGS[@]}" >/dev/null 2>"$STATE_DIR/args.err" ||+ if (( DRY )); then warn "DRY_RUN: tensorfold serve in $IMAGE rejects these arguments: $(tail -1 "$STATE_DIR/args.err")"+ else cat "$STATE_DIR/args.err" >&2; die "tensorfold serve rejects these arguments (see above); nothing was changed"; fi+detect_links+if (( TP == 2 )); then log "Link: $HEAD_ADDR ($HEAD_DEV) <-> $WORKER_ADDR ($WORKER_DEV), RoCE $HEAD_HCAS / $WORKER_HCAS"+else+ log "Rendezvous: $MASTER_ADDR:$MASTER_PORT; NCCL bootstrap over ${NODE_DEV[*]} (rank 0 to $((TP - 1)))"+ for r in 0 $(worker_ids); do+ log " rank $r: RoCE ${NODE_HCAS[r]} (GID ${NODE_GID[r]:-per device})$( (( r == 0 )) || echo ", link to the head ${LINK_WORKER_ADDR[r]:-?} <-> ${LINK_HEAD_ADDR[r]:-?}")"+ done+fihere_up=0; running_here && here_up=1-worker_up=0; running_worker && worker_up=1-if (( here_up || worker_up )); then # after the setup and the checks: down only while restarting,- if [[ "$MODE" == start ]]; then # or when a start that failed halfway left one rank up- if (( here_up )); then log "Only rank 0 is running (here): stopping it, then starting both ranks"+declare -a worker_up=() left_worker=() there_gb=()+any_worker_up=0+for i in $(worker_ids); do worker_up[i]=0; running_worker "$i" && { worker_up[i]=1; any_worker_up=1; }; done+if (( DRY )); then+ (( here_up || any_worker_up )) && log "DRY_RUN: $CONTAINER_NAME is running; a real start would stop it first (./stop.sh)"+elif (( here_up || any_worker_up )); then # after the setup and the checks: down only while restarting,+ if [[ "$MODE" == start ]]; then # or when a start that failed halfway left some ranks up+ if (( TP > 2 )); then log "Only some ranks are running: stopping them, then starting all $TP ranks"+ elif (( here_up )); then log "Only rank 0 is running (here): stopping it, then starting both ranks"else log "Only rank 1 is running (on $WORKER): stopping it, then starting both ranks"; fifi./stop.shfileft_here=0; docker ps -a --format '{{.Names}}' | grep -qx "$CONTAINER_NAME" && left_here=1-left_worker=0; worker "docker ps -a --format '{{.Names}}' | grep -qx '$CONTAINER_NAME'" 2>/dev/null && left_worker=1-if (( left_here || left_worker )); then- where="on both Sparks"; (( left_worker )) || where="here"; (( left_here )) || where="on the worker"- log "Removing the previous (stopped) container $CONTAINER_NAME $where"- (( left_here == 0 )) || docker rm -f "$CONTAINER_NAME" >/dev/null- (( left_worker == 0 )) || worker "docker rm -f '$CONTAINER_NAME' >/dev/null"+any_left=0+for i in $(worker_ids); do+ left_worker[i]=0+ worker "$i" "docker ps -a --format '{{.Names}}' | grep -qx '$CONTAINER_NAME'" 2>/dev/null && { left_worker[i]=1; any_left=1; }+done+if (( ! DRY && ( left_here || any_left ) )); then+ if (( TP == 2 )); then+ where="on both Sparks"; (( left_worker[1] )) || where="here"; (( left_here )) || where="on the worker"+ else+ where=$(if (( left_here )); then echo "here"; fi; for i in $(worker_ids); do if (( left_worker[i] )); then echo "on $(worker_host "$i")"; fi; done)+ where=$(paste -sd, <<<"$where" | sed 's/,/, /g')+ fi+ log "Removing the previous (stopped) container $CONTAINER_NAME $where, its log saved first (a crash's evidence)"+ if (( left_here )); then+ saved=$(save_log "$LOG_DIR" 0 "$CONTAINER_NAME" "$LOG_KEEP") || warn "could not save rank 0's log to $LOG_DIR"+ [[ -z "${saved:-}" ]] || log "Rank 0's log: $saved"+ docker rm -f "$CONTAINER_NAME" >/dev/null+ fi+ for i in $(worker_ids); do+ (( left_worker[i] )) || continue+ saved=$(worker_save_log "$i") || warn "could not save rank $i's log on $(worker_host "$i")"+ [[ -z "${saved:-}" ]] || log "Rank $i's log (on $(worker_host "$i")): $saved"+ worker "$i" "docker rm -f '$CONTAINER_NAME' >/dev/null"+ donefiif ss -ltn "sport = :$PORT" 2>/dev/null | grep -q LISTEN; then- die "port $PORT is already in use: $(ss -ltnp "sport = :$PORT" 2>/dev/null | tail -n +2)"+ (( DRY )) && log "DRY_RUN: port $PORT is in use now" ||+ die "port $PORT is already in use: $(ss -ltnp "sport = :$PORT" 2>/dev/null | tail -n +2)"fi# TensorFold budgets each Spark's free memory minus MEMORY_RESERVE_GIB (14.5); the defaults want ~110 GiB free at start on each.# With less, rank 0 refuses the window and names one that fits, which the load below then starts again with.here_gb=$(free -g | awk '/^Mem:/ {print $7}')-there_gb=$(worker "free -g | awk '/^Mem:/ {print \$7}'")-if (( here_gb >= 110 && there_gb >= 110 )); then- log "Arguments OK, port $PORT free, ${here_gb} GiB memory available here, ${there_gb} GiB on the worker"+low=0; (( here_gb >= 110 )) || low=1+for i in $(worker_ids); do+ there_gb[i]=$(worker "$i" "free -g | awk '/^Mem:/ {print \$7}'" 2>/dev/null || echo 0)+ (( there_gb[i] >= 110 )) || low=1+done+if (( ! low )); then+ if (( TP == 2 )); then log "Arguments OK, port $PORT free, ${here_gb} GiB memory available here, ${there_gb[1]} GiB on the worker"+ else log "Arguments OK, port $PORT free, ${here_gb} GiB memory available here, $(for i in $(worker_ids); do printf '%s on rank %s, ' "${there_gb[i]}" "$i"; done | sed 's/, $//')"; fielse(( here_gb >= 110 )) ||warn "only ${here_gb} GiB memory available here (the default needs ~110): stop other GPU workloads (docker ps), or lower CONTEXT"- (( there_gb >= 110 )) ||- warn "only ${there_gb} GiB memory available on the worker (the default needs ~110): stop other GPU workloads there (ssh $WORKER docker ps), or lower CONTEXT"+ for i in $(worker_ids); do+ [[ -z "${WORKER_DOWN[$i]:-}" ]] || continue+ (( there_gb[i] >= 110 )) ||+ warn "only ${there_gb[i]} GiB memory available on $(wname "$i") (the default needs ~110): stop other GPU workloads there (ssh $(worker_host "$i") docker ps), or lower CONTEXT"+ donefi-# TensorFold's own switches (TENSORFOLD_*, TF_GLM_*, TF_ROCE_*) reach both ranks with their values: rank 1's docker-# command runs over ssh, where this shell's environment does not reach. None of them is a secret.+# TensorFold's own switches (TENSORFOLD_*, TF_GLM_*, TF_ROCE_*) reach every rank with the same values: the workers'+# 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}")-while IFS='=' read -r name _; do ENV_ARGS+=(-e "$name=${!name}"); done < <(env | grep -E '^(TENSORFOLD|TF_GLM|TF_ROCE)_[A-Z0-9_]+=' || true)+_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)RUN_ARGS=(--gpus all --ipc=host --network host --shm-size 16g --device /dev/infiniband --cap-add IPC_LOCK--ulimit memlock=-1 --ulimit stack=67108864)# ---------------------------------------------------------------- 3. launch, 4. load (a second try when the window does not fit)# No token goes into the containers: the ranks read only the local cache (HF_HUB_OFFLINE=1), and with HF_HUB_OFFLINE=0# huggingface_hub finds the token file in the mounted cache.+# Ranks TP-1 .. 1 on their workers first, then rank 0 here, which serves the API. DRY_RUN=1 prints each rank's+# command exactly as it would run (a worker's as the string ssh sends) and exits.launch() {- local rank1 rank0 worker_cmd remote a- rank1=(tensorfold serve "$MODEL_ARG" --tp 2 --rank 1 --master "$HEAD_ADDR" --master-port "$MASTER_PORT" "${SERVE_ARGS[@]}")- rank0=(tensorfold serve "$MODEL_ARG" --tp 2 --rank 0 --master "$HEAD_ADDR" --master-port "$MASTER_PORT"+ local rank0 rankw worker_cmd remote a i+ local -a here_cmd+ for (( i = TP - 1; i >= 1; i-- )); do+ rankw=(tensorfold serve "$MODEL_ARG" --tp "$TP" --rank "$i" --master "$MASTER_ADDR" --master-port "$MASTER_PORT" "${SERVE_ARGS[@]}")+ log "Rank $i on $(worker_host "$i"): ${rankw[*]}"+ worker_cmd=(docker run -d --name "$CONTAINER_NAME" "${RUN_ARGS[@]}" "${ENV_ARGS[@]}"+ $(rank_nccl_env "$i")+ -v "${WORKER_MOUNT[i]}" -v "\$HOME/.cache/tensorfold-glm53/$KCACHE:/cache"+ "$IMAGE" "${rankw[@]}")+ remote=""; for a in "${worker_cmd[@]}"; do+ case "$a" in '$HOME'*) remote+=" \"$a\"" ;; *) remote+=" $(printf '%q' "$a")" ;; esac+ done+ if (( DRY )); then+ printf '[dry-run] rank %s on %s:\n %s\n' "$i" "$(worker_host "$i")" "mkdir -p \$HOME/.cache/tensorfold-glm53 &&$remote"+ continue+ fi+ worker "$i" "mkdir -p \$HOME/.cache/tensorfold-glm53 &&$remote" >/dev/null || die "could not start rank $i on $(worker_host "$i")"+ done+ rank0=(tensorfold serve "$MODEL_ARG" --tp "$TP" --rank 0 --master "$MASTER_ADDR" --master-port "$MASTER_PORT"--name "$SERVED_NAME" --host "$HOST" --port "$PORT" "${SERVE_ARGS[@]}")- log "Rank 1 on $WORKER: ${rank1[*]}"log "Rank 0 here: ${rank0[*]}"- worker_cmd=(docker run -d --name "$CONTAINER_NAME" "${RUN_ARGS[@]}" "${ENV_ARGS[@]}"- $(nccl_env "$WORKER_DEV" "$WORKER_HCAS" "$WORKER_GID")- -v "$WORKER_MOUNT" -v "\$HOME/.cache/tensorfold-glm53/$KCACHE:/cache"- "$IMAGE" "${rank1[@]}")- remote=""; for a in "${worker_cmd[@]}"; do- case "$a" in '$HOME'*) remote+=" \"$a\"" ;; *) remote+=" $(printf '%q' "$a")" ;; esac- done- worker "mkdir -p \$HOME/.cache/tensorfold-glm53 &&$remote" >/dev/null || die "could not start rank 1 on $WORKER"- docker run -d --name "$CONTAINER_NAME" "${RUN_ARGS[@]}" "${ENV_ARGS[@]}" \- $(nccl_env "$HEAD_DEV" "$HEAD_HCAS" "$HEAD_GID") \- -v "$HF_CACHE":/root/.cache/huggingface -v "$KERNEL_CACHE/$KCACHE":/cache \- "$IMAGE" "${rank0[@]}" >/dev/null+ here_cmd=(docker run -d --name "$CONTAINER_NAME" "${RUN_ARGS[@]}" "${ENV_ARGS[@]}"+ $(rank_nccl_env 0)+ -v "$HF_CACHE":/root/.cache/huggingface -v "$KERNEL_CACHE/$KCACHE":/cache+ "$IMAGE" "${rank0[@]}")+ if (( DRY )); then+ printf '[dry-run] rank 0 here:\n %s\n' "$(printf '%q ' "${here_cmd[@]}" | sed 's/ $//')"+ exit 0+ fi+ "${here_cmd[@]}" >/dev/null}# FOREGROUND=1: stay attached to rank 0's log and exit with its code (systemd's Restart=on-failure). Either rank ending# takes the other one down: a lone rank would wait for its peer forever.foreground() {- local watch w code+ local watch w code itrap './stop.sh; exit 130' INT TERM( exec 8>&- # not holding start.sh's lock once start.sh has exitedwhile sleep 30; dorunning_here || exit 0- worker true 2>/dev/null || continue # the worker out of reach for a moment says nothing about rank 1- running_worker && continue- warn "rank 1 on $WORKER exited: stopping rank 0"- docker stop -t "${STOP_TIMEOUT:-30}" "$CONTAINER_NAME" >/dev/null 2>&1- exit 1+ for i in $(worker_ids); do+ worker "$i" true 2>/dev/null || continue # a worker out of reach for a moment says nothing about its rank+ running_worker "$i" && continue+ warn "rank $i on $(worker_host "$i") exited: stopping rank 0"+ docker stop -t "${STOP_TIMEOUT:-30}" "$CONTAINER_NAME" >/dev/null 2>&1+ exit 1+ donedone ) &watch=$!docker logs -f "$CONTAINER_NAME" || truekill "$watch" 2>/dev/null || truew=0; wait "$watch" || w=$?code=$(docker inspect -f '{{.State.ExitCode}}' "$CONTAINER_NAME" 2>/dev/null || echo 1)- [[ "$w" != 1 || "$code" != 0 ]] || code=1 # rank 1 failed, even if rank 0 then shut down cleanly- worker "docker stop -t ${STOP_TIMEOUT:-30} '$CONTAINER_NAME'" >/dev/null 2>&1 || true+ [[ "$w" != 1 || "$code" != 0 ]] || code=1 # a worker's rank failed, even if rank 0 then shut down cleanly+ for i in $(worker_ids); do worker "$i" "docker stop -t ${STOP_TIMEOUT:-30} '$CONTAINER_NAME'" >/dev/null 2>&1 || true; doneexit "$code"}# NVIDIA's container banner, without its license notice (GOVERNING TERMS ...), which stays visible@@ -274,15 +361,21 @@ fail() {sleep 0.5printf '\n%s── rank 0 (here): last server log lines ──%s\n' "$D" "$R"docker logs --tail 25 "$CONTAINER_NAME" 2>&1 | sed 's/^/ │ /'- printf '%s── rank 1 (%s): last server log lines ──%s\n' "$D" "$WORKER" "$R"- worker docker logs --tail 25 "$CONTAINER_NAME" 2>&1 | sed 's/^/ │ /'+ for i in $(worker_ids); do+ printf '%s── rank %s (%s): last server log lines ──%s\n' "$D" "$i" "$(worker_host "$i")" "$R"+ worker "$i" docker logs --tail 25 "$CONTAINER_NAME" 2>&1 | sed 's/^/ │ /'+ donedie "$1"}for attempt in 1 2; do- step 3 "Launch: container $CONTAINER_NAME, rank 1 on $WORKER, then rank 0 here"+ if (( 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[[ "${FOREGROUND:-0}" == 1 ]] && foreground- step 4 "Loading: ~80 GiB of weights on each Spark (2-6 min; the very first start also compiles CUDA kernels)"+ case "$TP" in+ 3) step 4 "Loading: the weights on each Spark (~60 GiB on rank 0, ~50 on the others) (2-6 min; the very first start also compiles CUDA kernels)" ;;+ *) step 4 "Loading: ~80 GiB of weights on each Spark (2-6 min; the very first start also compiles CUDA kernels)" ;;+ esac# 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=$!@@ -295,14 +388,20 @@ for attempt in 1 2; dofail "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); both ranks are still running: docker logs -f $CONTAINER_NAME"+ fail "not ready after ${WAIT_TIMEOUT}s (WAIT_TIMEOUT); the ranks are still running: docker logs -f $CONTAINER_NAME"if (( SECONDS - start >= next_beat )); then- running_worker ||- fail "rank 1 on $WORKER exited (code $(worker docker inspect -f '{{.State.ExitCode}}' "$CONTAINER_NAME" 2>/dev/null || echo "?")) before the server was ready"+ for 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"+ doneestimate=$(docker logs "$CONTAINER_NAME" 2>&1 | sed -n 's/.*startup estimate \([0-9.]*\) GiB.*/\1/p' | tail -1)- printf ' %s⋯ %ss elapsed, %s%s GiB on the GPU here, %s on the worker%s\n' "$D" "$((SECONDS - start))" \- "$(gpu_gib "$CONTAINER_NAME")" "${estimate:+ of ~$estimate}" \- "$(worker "$(declare -f gpu_gib); gpu_gib $CONTAINER_NAME" 2>/dev/null || echo "?")" "$R"+ there=""+ for i in $(worker_ids); do+ g=$(worker "$i" "$(declare -f gpu_gib); gpu_gib $CONTAINER_NAME" 2>/dev/null || echo "?")+ if (( TP == 2 )); then there+=", $g on the worker"; else there+=", $g on rank $i"; fi+ done+ printf ' %s⋯ %ss elapsed, %s%s GiB on the GPU here%s%s\n' "$D" "$((SECONDS - start))" \+ "$(gpu_gib "$CONTAINER_NAME")" "${estimate:+ of ~$estimate}" "$there" "$R"next_beat=$((next_beat + 15))fisleep 3@@ -319,14 +418,14 @@ log "Server answered after $((SECONDS - start))s"# ---------------------------------------------------------------- 5. smoke test# Thinking off and greedy, so that a short reply has text (the model thinks first otherwise); no text fails the start.-step 5 "Smoke test: one chat completion through both ranks"+step 5 "Smoke test: one chat completion through $( (( TP == 2 )) && echo "both" || echo "all $TP") ranks"SERVED=$(served_name || echo "$SERVED_NAME")if smoke=$(curl -s --max-time 180 "$URL/v1/chat/completions" -H 'Content-Type: application/json' \-d "{\"model\": \"$SERVED\", \"max_tokens\": 32, \"temperature\": 0, \"chat_template_kwargs\": {\"enable_thinking\": false}, \"messages\": [{\"role\": \"user\", \"content\": \"Reply with OK.\"}]}" |python3 -c 'import json,sys; r = json.load(sys.stdin); c = r["choices"][0]["message"].get("content") or ""; assert c.strip(); print(repr(c.strip()[:40]) + ",", r["usage"]["completion_tokens"], "tokens,", r.get("tensorfold", {}).get("decode_s"), "s")' 2>/dev/null); thenlog "OK: $smoke"else- fail "the smoke test request failed (no reply text); both ranks are still running"+ fail "the smoke test request failed (no reply text); the ranks are still running"fiIP=$(hostname -I 2>/dev/null | awk '{print $1}')@@ -334,9 +433,9 @@ IP=$(hostname -I 2>/dev/null | awk '{print $1}')printf '\n%s ✔ %s is now LIVE! on port %s%s\n\n' "$G" "$SERVED" "$PORT" "$R"cat <<EOFAPI http://${IP:-<spark-address>}:$PORT/v1 (model: $SERVED)- Window $(arg_value --context) tokens · $(arg_value --parallel) at once · $KV KV · $DRAFTER drafts · $DENSE dense weights$( [[ "$VISION" == 1 ]] && echo " · images and video")$( [[ "$COMM" == roce ]] && echo " · RoCE all-gathers")$( [[ "$SPLIT" == 1 ]] && echo " · split prefill")$( [[ "$KDA_CHUNKED" == 1 ]] && echo " · chunked KDA")+ Window $(arg_value --context) tokens$( (( TP == 2 )) || echo " · $TP Sparks (experimental)") · $(arg_value --parallel) at once · $KV KV · $DRAFTER drafts · $DENSE dense weights$( [[ "$VISION" == 1 ]] && echo " · images and video")$( [[ "$COMM" == roce ]] && echo " · RoCE all-gathers")$( [[ "$SPLIT" == 1 ]] && echo " · split prefill")$( [[ "$KDA_CHUNKED" == 1 ]] && echo " · chunked KDA")Drafts $DRAFT_POLICY · copy drafts $( [[ "$COPY" == 1 ]] && echo "up to $COPY_MAX$( [[ "$COPY_CODE" == 1 ]] && echo ", code rules")" || echo off) · shared system prompts $( [[ "$SHARED_PREFIX" == 1 ]] && echo on || echo off)- Logs docker logs -f $CONTAINER_NAME (rank 1: ssh $WORKER docker logs -f $CONTAINER_NAME)+ Logs docker logs -f $CONTAINER_NAME$(for i in $(worker_ids); do printf ' (rank %s: ssh %s docker logs -f %s)' "$i" "$(worker_host "$i")" "$CONTAINER_NAME"; done)Restart ./start.sh restartStop ./stop.shdiff --git a/stop.sh b/stop.shindex 9d3a937..0455015 100755--- a/stop.sh+++ b/stop.sh@@ -1,28 +1,45 @@#!/usr/bin/env bash-# Stop the server that ./start.sh started on both Sparks and remove its containers, freeing their GPU memory. The-# ranks get STOP_TIMEOUT seconds (default 30) to shut down; requests still running are cut off (it does not drain-# them), so stop.sh says when there are any.-# Usage: ./stop.sh Env: CONTAINER_NAME, PORT, WORKER (see scripts/config.sh), STOP_TIMEOUT+# Stop the server that ./start.sh (or ./start-tp3.sh) started and remove its containers on every Spark,+# freeing their GPU memory: here (rank 0) and on every configured worker (WORKER, WORKER2), whatever TP is.+# The ranks get STOP_TIMEOUT seconds (default 30) to shut down; requests still running are cut off (it does not drain+# them), so stop.sh says when there are any. Each rank's log is saved first (docker rm deletes it), gzipped, in LOG_DIR+# here (~/.cache/tensorfold-glm53/logs) and ~/.cache/tensorfold-glm53/logs on each worker; the newest LOG_KEEP (10) of+# each rank stay.+# Usage: ./stop.sh Env: CONTAINER_NAME, PORT, WORKER, WORKER2 (see scripts/config.sh), STOP_TIMEOUT,+# LOG_DIR, LOG_KEEP+# DRY_RUN=1 ./stop.sh says what it would stop, and on which Spark, and stops nothingset -euo pipefailcd "$(dirname "$(readlink -f "$0")")"source ./scripts/config.shsource ./scripts/nodes.sh-# Where the containers are: here (rank 0) and on the worker (rank 1)+# Where the containers are: here (rank 0) and on the workers (rank i on worker i)here=0; docker ps -a --format '{{.Names}}' | grep -qx "$CONTAINER_NAME" && here=1-there=0-if [[ -z "${WORKER:-}" ]]; then- warn "WORKER is not set (scripts/local.sh): rank 1 was left alone"-elif ! worker true 2>/dev/null; then- warn "cannot reach the worker ($WORKER) over ssh: rank 1 was left alone"-elif worker "docker ps -a --format '{{.Names}}' | grep -qx '$CONTAINER_NAME'"; then- there=1-fi-if (( here == 0 && there == 0 )); then- log "No container named $CONTAINER_NAME on either Spark: nothing to stop"+workers=$(configured_workers)+nw=$(wc -w <<<"$workers")+declare -a there=()+any=0+[[ -n "$workers" ]] || warn "WORKER is not set (scripts/local.sh): rank 1 was left alone"+for i in $workers; do+ there[i]=0+ if ! worker "$i" true 2>/dev/null; then+ warn "cannot reach the worker ($(worker_host "$i")) over ssh: rank $i was left alone"+ elif worker "$i" "docker ps -a --format '{{.Names}}' | grep -qx '$CONTAINER_NAME'"; then+ there[i]=1; any=1+ fi+done+if (( here == 0 && any == 0 )); then+ if (( nw <= 1 )); then log "No container named $CONTAINER_NAME on either Spark: nothing to stop"+ else log "No container named $CONTAINER_NAME on any Spark: nothing to stop"; fiexit 0fi-where="on both Sparks"; (( there )) || where="here"; (( here )) || where="on the worker"+if (( nw <= 1 )); then+ where="on both Sparks"; (( any )) || where="here"; (( here )) || where="on the worker"+else+ # (if, not &&: a last false test would be the substitution's status and stop the script under set -e)+ where=$(if (( here )); then echo "here"; fi; for i in $workers; do if (( there[i] )); then echo "on $(worker_host "$i")"; fi; done)+ where=$(paste -sd, <<<"$where" | sed 's/,/, /g')+fiif [[ "$(docker inspect -f '{{.State.Running}}' "$CONTAINER_NAME" 2>/dev/null)" == true ]]; thenapi_host="$HOST"; [[ "$HOST" == 0.0.0.0 || "$HOST" == "::" ]] && api_host=127.0.0.1@@ -31,19 +48,36 @@ if [[ "$(docker inspect -f '{{.State.Running}}' "$CONTAINER_NAME" 2>/dev/null)"python3 -c 'import json,sys; print(json.load(sys.stdin).get("requests_running", 0))' 2>/dev/null || echo 0)(( busy == 0 )) || warn "$busy request(s) still running will be cut off"fi+if [[ "${DRY_RUN:-0}" == 1 ]]; then+ log "DRY_RUN=1: would stop and remove $CONTAINER_NAME $where (up to ${STOP_TIMEOUT:-30}s); nothing is stopped"+ if (( here )); then printf '[dry-run] rank 0 here:\n docker stop -t %s %s; (its log saved to %s); docker rm -f %s\n' "${STOP_TIMEOUT:-30}" "$CONTAINER_NAME" "$LOG_DIR" "$CONTAINER_NAME"; fi+ for i in $workers; do+ if (( there[i] )); then printf '[dry-run] rank %s on %s:\n docker stop -t %s %s; (its log saved to ~/.cache/tensorfold-glm53/logs there); docker rm -f %s\n' "$i" "$(worker_host "$i")" "${STOP_TIMEOUT:-30}" "$CONTAINER_NAME" "$CONTAINER_NAME"; fi+ done+ exit 0+filog "Stopping $CONTAINER_NAME $where (up to ${STOP_TIMEOUT:-30}s)"+# each rank: stop, save its log (with the shutdown lines), then remove the containerstop_here() {+ local saveddocker stop -t "${STOP_TIMEOUT:-30}" "$CONTAINER_NAME" >/dev/null 2>&1 || true+ saved=$(save_log "$LOG_DIR" 0 "$CONTAINER_NAME" "$LOG_KEEP") || warn "could not save rank 0's log to $LOG_DIR"docker rm -f "$CONTAINER_NAME" >/dev/null- log "Stopped and removed rank 0 here"+ log "Stopped and removed rank 0 here${saved:+; its log: $saved}"}stop_worker() {- worker "docker stop -t ${STOP_TIMEOUT:-30} '$CONTAINER_NAME' >/dev/null 2>&1; docker rm -f '$CONTAINER_NAME' >/dev/null" ||- { warn "could not stop rank 1 on $WORKER"; return 1; }- log "Stopped and removed rank 1 on $WORKER"+ local saved h+ h=$(worker_host "$1")+ worker "$1" "docker stop -t ${STOP_TIMEOUT:-30} '$CONTAINER_NAME' >/dev/null 2>&1" || true+ saved=$(worker_save_log "$1") || warn "could not save rank $1's log on $h"+ worker "$1" "docker rm -f '$CONTAINER_NAME' >/dev/null" || { warn "could not stop rank $1 on $h"; return 1; }+ log "Stopped and removed rank $1 on $h${saved:+; its log there: $saved}"}-wpid=""; if (( there )); then stop_worker & wpid=$!; fi+wpids=()+for i in $workers; do if (( there[i] )); then stop_worker "$i" & wpids+=($!); fi; doneif (( here )); then stop_here; fi-[[ -z "$wpid" ]] || wait "$wpid" || exit 0 # a warning above said what is left+failed=0+for p in "${wpids[@]}"; do wait "$p" || failed=1; done+(( failed == 0 )) || exit 0 # a warning above said what is leftlog "Stopped and removed $CONTAINER_NAME $where; its GPU memory is free again"