Skip to content

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

Python

v1.3: TensorFold v0.6.0, fixes for #2 and #6, whole tool calls, 32k default replies

MiaAI-Lab6eba2cd5d57a
diff --git a/.github/ISSUE_TEMPLATE/1_bug.md b/.github/ISSUE_TEMPLATE/1_bug.md
index b9e5b49..46a3250 100644
--- a/.github/ISSUE_TEMPLATE/1_bug.md
+++ b/.github/ISSUE_TEMPLATE/1_bug.md
@@ -99,7 +99,7 @@ curl -s http://<head-address>:8888/v1/chat/completions \
network: set FABRIC_PEER to the worker's CX7 address.
* `start.sh` refuses port 8888 -> something else listens there; set PORT.
* prepare.sh fails applying a patch -> TF_VERSION was changed; the patches are
- made for v0.5.0.
+ made for v0.6.0.
* First start takes long -> the CUDA kernels compile once on each Spark (cached in
~/.cache/tensorfold-glm53); that is expected, not a hang.
-->
diff --git a/CHANGELOG.md b/CHANGELOG.md
index de9c827..e1ab691 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -3,6 +3,44 @@
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.3 (2026-10-01): TensorFold v0.6.0, issue fixes #2 and #6, whole tool calls
+
+Image `v0.6.0-ae8d1c789b47` (`sha256:22789f0cb3dc308f0b2ce52a33961b88bd624af1725e91e8aba0a74a671bb969`), 53 patches.
+
+### Changed
+- **TensorFold v0.6.0** (was v0.5.0). The patches are rebased onto it. Three of ours are now part of TensorFold
+ itself and were dropped: the idle doorbell, `TENSORFOLD_MEMORY_RESERVE_GIB` and `TF_GLM_MTP`. The others keep
+ their names, renumbered (0024 -> 0023 ... 0053 -> 0050; the README's patch table lists them). TensorFold is
+ Apache-2.0 from v0.6.0; `NOTICE` and `CREDITS.md` say so.
+- `TF_GLM_MTP=auto` is now set explicitly: v0.6.0's own default (`1`) would load the MTP head (1.77 GiB a Spark)
+ with `PARALLEL=1`.
+- **Default reply budget 4,096 -> 32,768 tokens** (`MAX_TOKENS`) for a request that sets no `max_tokens`, as agents
+ such as Codex do. GLM thinks at Max by default and could run out of budget inside a tool call. A request's own
+ value still wins; the default is cut to what the window has left, never refused.
+- **Compiled kernels are kept per image** (`~/.cache/tensorfold-glm53/<image hash>`): another image's build of the
+ same extension can no longer be loaded by mistake. A new image compiles once (a few minutes on its first start).
+- From v0.6.0 itself: `reasoning_effort: "medium"` is heard as `high`; `logprobs`, `top_logprobs` and `n` other than
+ 1 get HTTP 400 (they were ignored).
+
+### Fixed
+- **#6, `COMM=roce` first start dying at the first all-gather.** On a first start each rank builds its CUDA kernels on
+ its own and could drift past the ~20 s a RoCE wait allows. Until startup is over, each RoCE gather first waits for
+ the peer in an NCCL barrier; the RoCE kernel builds during setup. New `TF_ROCE_WAIT_S` (default 20 s); a failure
+ now prints the proxy's counters. Patch `0052-cuda-roce-startup`.
+- **#2, one malformed tool call in the history blocking a conversation for good.** A past tool call whose arguments
+ are not a JSON object is left out of the prompt with its result, and logged, instead of HTTP 400 on every later
+ turn. Patch `0051-glm-tool-history-recovery`.
+- **Cut-off tool calls are never sent.** A tool call now goes out whole once it is written; a reply that ends inside
+ a call (its token limit) ends with `length` and never sends that call, streamed or not, so a client cannot store
+ or run cut arguments. While a call is written, an empty delta goes out every 2 s for clients with an idle timeout.
+ Patch `0053-glm-whole-tool-calls`.
+
+### Unchanged
+- Replies: the exactness checks (reference shas, drafted == serial 6/6, concurrency 22/22, images and videos, tool
+ calls) equal v1.2's. Prefill speed is unchanged (sparkDash, 8k-256k).
+- Memory: KV pool **2,922,496 tokens** at the measured start (the 12.5 GiB cap); lowest free memory under a 1M-token
+ prompt 5.6 GiB on the head, 9.5 GiB on the worker (needle found).
+
## v1.2 (2026-10-01): bigger KV pool, worker weights over NFS
Image unchanged: `v0.5.0-cb7c56f7f921` (`sha256:6ee3c6e0430040b69ddcb0c96c7fbbcb94a5bed47d48a8ba092626369ae533b9`),
diff --git a/CREDITS.md b/CREDITS.md
index bfafc8b..b681fa2 100644
--- a/CREDITS.md
+++ b/CREDITS.md
@@ -28,12 +28,12 @@ checkpoint's ShapleyMcg attribution and the drafter's license).
## Inference engine
- **[TensorFold](https://github.com/ashhart/TensorFold)** by Ash Hart ([ashhart](https://github.com/ashhart)) and the
- TensorFold contributors (MIT License; Apache 2.0 from v0.6.0, which patches 0047 and 0048 port code from): the
- engine that serves the model, including the two-rank CUDA engine for GLM-5.3-Flash, its EXL3 expert kernels, DFlash2
- and MTP drafting with exact verification and the OpenAI-compatible server. Every file in `patches/` is a
- modification of TensorFold v0.5.0.
+ TensorFold contributors (Apache 2.0 from v0.6.0; releases up to v0.5.0 were MIT, and code written before v0.6.0
+ keeps its MIT notice): the engine that serves the model, including the two-rank CUDA engine for GLM-5.3-Flash, its
+ EXL3 expert kernels, DFlash2 and MTP drafting with exact verification and the OpenAI-compatible server. Every file
+ in `patches/` is a modification of TensorFold v0.6.0.
- TensorFold itself builds on, and credits in its
- [third-party notices](https://github.com/ashhart/TensorFold/blob/v0.5.0/THIRD_PARTY_NOTICES.md):
+ [third-party notices](https://github.com/ashhart/TensorFold/blob/v0.6.0/THIRD_PARTY_NOTICES.md):
[ExLlamaV3](https://github.com/turboderp-org/exllamav3) (turboderp, MIT), whose EXL3 format the routed experts are
stored in, the GLM-5.3-Flash modeling code in Hugging Face
[transformers](https://github.com/huggingface/transformers) (Apache 2.0), and
@@ -47,38 +47,38 @@ checkpoint's ShapleyMcg attribution and the drafter's license).
- `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`).
-- `0012-glm-kda-chunked`, `0014-glm-kda-chunked-gb10`, `0042-glm-kda-chunked-kernel` (`KDA_CHUNKED`, on by default):
+- `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 delta
networks and Kimi Delta Attention, as implemented in
[flash-linear-attention](https://github.com/fla-org/flash-linear-attention) (MIT); the kernels are written anew.
- `0013-glm-decode-rounds`: verify windows of up to 16 rows so copy drafts can run long, after the wider copy windows
proposed in [TensorFold PR #115](https://github.com/ashhart/TensorFold/pull/115) by Ash Hart.
-- `0039-glm-tool-calls` (tool calling for agent clients): the rule that tool calls written inside the think block
+- `0036-glm-tool-calls` (tool calling for agent clients): the rule that tool calls written inside the think block
count when they end the reply, the store that gives back a step's reasoning to clients that drop it, and null /
`const` typing of tool arguments are adapted from patch 0620 of
[jayleaton/glm53-tensorfold-spark](https://github.com/jayleaton/glm53-tensorfold-spark) (Apache 2.0); the rest of
that patch's fixes are our own implementation.
-- `0040-cuda-tokenize`: the `/tokenize` and `/detokenize` endpoints take and return what
+- `0037-cuda-tokenize`: the `/tokenize` and `/detokenize` endpoints take and return what
[vLLM](https://github.com/vllm-project/vllm)'s (Apache 2.0) do, so clients written for vLLM work unchanged;
the code is our own.
-- `0046-glm-visible-pools`: the idea of bounding decode token selection to the pools a row can see follows
- [TensorFold PR #140](https://github.com/ashhart/TensorFold/pull/140) by mikolaj92; the implementation is our own.
-- `0047-cuda-context-errors`: ported from [TensorFold](https://github.com/ashhart/TensorFold) v0.6.0 (commit 68c6e35,
- Apache 2.0) by Ash Hart: context-window refusals in OpenAI's wording with code `context_length_exceeded`
- (`ContextLengthError`, `refusal`, `error_body` and the `App.check` messages). The `param` field and the GLM app's
- and GLM image refusals are our own.
-- `0048-cuda-metrics`: ported from TensorFold v0.6.0 (commit 4447ac3, "Prometheus /metrics on both servers (#110)",
- Apache 2.0) by Ash Hart: the CUDA server's `/metrics` (`server/metrics.py`, request clocks in `cuda/health.py`,
- `Turns.parked`). The `tensorfold_health:` metrics are our own.
-- `0049-glm-l2-prefetch` (L2 prefetch in decode, `TF_GLM_L2PF`): adapted from patch 0460 of
+- `0043-glm-visible-pools`: the idea of bounding decode token selection to the pools a row can see follows
+ [TensorFold PR #140](https://github.com/ashhart/TensorFold/pull/140) by mikolaj92, which TensorFold v0.6.0 has for
+ its selection kernel; this patch's bound on the decode scoring and the split selection is our own.
+- `0044-cuda-context-errors`: TensorFold v0.6.0's context-window refusals (commit 68c6e35 by Ash Hart) extended: the
+ `param` field, and the same wording and `context_length_exceeded` code for the GLM app's window check and image
+ prompts.
+- `0045-cuda-metrics`: TensorFold v0.6.0's Prometheus `/metrics` (commit 4447ac3, #110, by Ash Hart) extended with
+ `/health`'s figures as `tensorfold_health:` metrics.
+- `0046-glm-l2-prefetch` (L2 prefetch in decode, `TF_GLM_L2PF`): adapted from patch 0460 of
[jayleaton/glm53-tensorfold-spark](https://github.com/jayleaton/glm53-tensorfold-spark) (Apache 2.0); changes listed
in `NOTICE`.
-- `0050-glm-exl3-decode-loads` (routed-expert decode loads, `TF_GLM_EXL3_LOADS`): adapted from patch 0580 of
+- `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 listed
in `NOTICE`.
- 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 or
- quote as context stays under TensorFold's MIT License (see `NOTICE`).
+ quote as context stays under TensorFold's licenses (Apache 2.0, and MIT for code written before v0.6.0; see
+ `NOTICE`).
## Runtime stack
diff --git a/NOTICE b/NOTICE
index 13d63f1..2d1f9f2 100644
--- a/NOTICE
+++ b/NOTICE
@@ -9,11 +9,16 @@ This project builds on third-party work that keeps its own license:
TensorFold
https://github.com/ashhart/TensorFold
- Copyright (c) 2026 TensorFold contributors. MIT License.
- The files in patches/ modify TensorFold v0.5.0 source; scripts/prepare.sh applies them to TensorFold's installed
+ Copyright 2026 TensorFold contributors. Apache License, Version 2.0 from 0.6.0; code written before 0.6.0 keeps its
+ MIT notice (below). TensorFold's NOTICE reads: "TensorFold / Copyright 2026 TensorFold contributors /
+ https://github.com/ashhart/TensorFold".
+ The files in patches/ modify TensorFold v0.6.0 source; scripts/prepare.sh applies them to TensorFold's installed
package when it builds the image. The changes in patches/ are this project's work under Apache-2.0 (except the
- parts credited below); the TensorFold code they modify, and quote as diff context, stays under TensorFold's MIT
- License, so keep TensorFold's copyright and permission notice with any copy of a patched tree:
+ parts credited below); the TensorFold code they modify, and quote as diff context, stays under TensorFold's
+ licenses: Apache-2.0, and for code written before 0.6.0 also its MIT notice (TensorFold's LICENSES/MIT.txt), so keep
+ TensorFold's NOTICE and this copyright and permission notice with any copy of a patched tree:
+
+ Copyright (c) 2026 TensorFold contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
@@ -33,14 +38,11 @@ TensorFold
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
- From 0.6.0 TensorFold is licensed under the Apache License, Version 2.0 (code written before 0.6.0 keeps its MIT
- notice). Its NOTICE reads: "TensorFold / Copyright 2026 TensorFold contributors / https://github.com/ashhart/TensorFold".
- patches/0047-cuda-context-errors.patch and patches/0048-cuda-metrics.patch port code from TensorFold v0.6.0 under
- Apache-2.0: commit 68c6e35 (tensorfold/server/errors.py ContextLengthError, CONTEXT_LIMIT, refusal, error_body; the
- context messages in tensorfold/cuda/server.py) and commit 4447ac3 (tensorfold/server/metrics.py, the request clocks in
- tensorfold/cuda/health.py, Turns.parked in tensorfold/cuda/turns.py, the /metrics route in tensorfold/cuda/http.py).
- Changed here: the Mac server's hooks left out, an OpenAI "param" field added, and GLM-specific refusals and
- /health-derived metrics added. Ported code carries a comment naming its upstream commit.
+ patches/0044-cuda-context-errors.patch and patches/0045-cuda-metrics.patch extend code TensorFold v0.6.0 has
+ itself: 0044 gives context-window errors OpenAI's "param" field and the same wording and code
+ (context_length_exceeded) for GLM's own window check and image prompts; 0045 adds the CUDA server's /health
+ figures to /metrics as tensorfold_health:* families. Two comments in 0044 still name the upstream commit (68c6e35)
+ whose wording they reuse.
b12x
https://github.com/local-inference-lab/b12x
@@ -54,7 +56,7 @@ glm53-tensorfold-spark
https://github.com/jayleaton/glm53-tensorfold-spark
Copyright 2026 Jay Leaton (https://x.com/jayleaton)
Apache License, Version 2.0.
- patches/0039-glm-tool-calls.patch adapts parts of that project's patch 0620:
+ patches/0036-glm-tool-calls.patch adapts parts of that project's patch 0620:
- tensorfold/cuda/reply_text.py: the rule that tool calls written inside the think block are the reply's calls
when they end it (its trailing_calls), applied in ThinkSplit.
- tensorfold/families/glm5_next/cuda/kept_reasoning.py: its reasoning store (the ReasoningMemory LRU, keyed by the
@@ -63,11 +65,12 @@ glm53-tensorfold-spark
was written for.
- tensorfold/tool_parameters.py: const schemas, and null read as None for a nullable string (its typed_value),
moved into the shared decoder that every parser and both streamers use. Its coercions that change what a
- resent history renders (quoted scalars, Python literals, integral floats) were not taken.
- The rest of patch 0039 is this project's own implementation.
+ resent history renders (quoted scalars, Python literals, integral floats) were not taken. (TensorFold v0.6.0's
+ own decoder reads Python literals for Qwen's parsers; GLM's parsers keep values as written.)
+ The rest of patch 0036 is this project's own implementation.
Decode code adapted from that project's patches (Apache-2.0, Copyright 2026 Jay Leaton), in
- patches/0049-glm-l2-prefetch.patch and patches/0050-glm-exl3-decode-loads.patch:
- - patches/0049-glm-l2-prefetch.patch: tensorfold/families/glm5_next/cuda/l2pf.cu, l2pf.cpp, l2pf.py
+ patches/0046-glm-l2-prefetch.patch and patches/0047-glm-exl3-decode-loads.patch:
+ - patches/0046-glm-l2-prefetch.patch: tensorfold/families/glm5_next/cuda/l2pf.cu, l2pf.cpp, l2pf.py
(TF_GLM_L2PF): adapted from patch 0460's L2 prefetch (its l2pf.cu / l2pf.py; not its RoCE changes): a
side-stream kernel that issues cp.async.bulk.prefetch.L2 (or line prefetches, or loads) for the weights the next
kernels read, forked at a layer's attention and FFN all-gathers and after its attention projections and joined
@@ -78,7 +81,7 @@ glm53-tensorfold-spark
DSA's output site placed after the query absorb, prefetching kv_b's value half (this project's latent layout)
before the output projection; the next layer's small KDA / DSA / indexer weights added to the FFN site; no
expert or MTP sites; 8 MiB a site by default.
- - patches/0050-glm-exl3-decode-loads.patch: tensorfold/families/glm5_next/cuda/exl3.cu (dec_kernel's second load
+ - patches/0047-glm-exl3-decode-loads.patch: tensorfold/families/glm5_next/cuda/exl3.cu (dec_kernel's second load
path, TF_GLM_EXL3_LOADS=nc), with its setting in exl3.cpp and exl3_mm.py: adapted from patch 0580 (its
exl3_ld.cu ld_kernel, LD_NC): 16-byte ld.global.nc.L1::no_allocate loads of the trellis a k step ahead through a
staging area in the warp's slice of the reduction buffer, and the item read with its count in one round trip,
diff --git a/README.md b/README.md
index 4c60663..23412f8 100644
--- a/README.md
+++ b/README.md
@@ -13,7 +13,7 @@
Serve **GLM-5.3-Flash** from two NVIDIA DGX Sparks (GB10, 128 GB each, linked by their ConnectX-7 ports) through an
OpenAI-compatible API, with **4 concurrent requests**, the model's full **1,048,576-token context** and **image and
-video input**. It runs [TensorFold](https://github.com/ashhart/TensorFold) v0.5.0 on both Sparks (one rank on each)
+video 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,
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`.
@@ -24,7 +24,7 @@ vision, tool calling, `/tokenize` and `/metrics`.
- Drafter: [`incoai/GLM-5.3-Flash-DFlash2`](https://huggingface.co/incoai/GLM-5.3-Flash-DFlash2), or the checkpoint's
own MTP head (`DRAFTER`, see [Configuration](#configuration))
- API model id: `GLM-5.3-Flash-EXL3`
-- Context: **1,048,576 tokens** a request; the 4 requests share an FP8 KV pool of about **2.9M tokens** (2,852,864 at the measured start)
+- Context: **1,048,576 tokens** a request; the 4 requests share an FP8 KV pool of about **2.9M tokens** (2,922,496 at the measured start)
- Tool calling, structured outputs (xgrammar), `/tokenize`, and `reasoning_effort` `low` / `high` / `max`
- One command on the first Spark: `./start.sh` sets up both Sparks and starts both ranks; `./stop.sh` stops them
@@ -110,7 +110,7 @@ cp scripts/local.sh.example scripts/local.sh # set [email protected] in
set `FABRIC_PEER` to the worker's CX7 address. The worker needs no copy of this repository.
The first run sets up both Sparks (see below): the image (~25 GB) on each, the checkpoint (~176 GB) and DFlash2
-downloaded on the head and copied to the worker, then the CUDA kernels compile once (into `~/.cache/tensorfold-glm53`).
+downloaded on the head and copied to the worker, then the CUDA kernels compile once per image (into `~/.cache/tensorfold-glm53/<image hash>`).
Later starts take 2 to 6 minutes to load ~80 GiB of weights on each Spark. `start.sh` shows each step and the server's
log, runs a smoke test through both ranks, and prints `GLM-5.3-Flash-EXL3 is now LIVE! on port 8888` with the endpoint.
@@ -191,9 +191,9 @@ the progress lines, the window retry or the smoke test; when either rank ends, i
**`scripts/prepare.sh`** does the one-time setup, and is safe to re-run (each step skips work already done):
1. Preflight on both Sparks: Docker, the GPU, `rsync`, key-based ssh, the RoCE link, disk space.
-2. The image `tensorfold-glm53:v0.5.0` on the head: TensorFold v0.5.0 with every `patches/*.patch` applied, plus PyAV
+2. The image `tensorfold-glm53:v0.6.0` on the head: TensorFold v0.6.0 with every `patches/*.patch` applied, plus PyAV
(video decoding) and xgrammar (structured outputs), on NVIDIA's `nvcr.io/nvidia/pytorch:26.07-py3`. It first
- pulls the published image `ghcr.io/miaai-lab/glm-5.3-flash-exl3-2x-dgx-sparks-tensorfold:v0.5.0-<image hash>`,
+ pulls the published image `ghcr.io/miaai-lab/glm-5.3-flash-exl3-2x-dgx-sparks-tensorfold:v0.6.0-<image hash>`,
by the digest pinned in `scripts/config.sh` (`IMAGE_TAG` / `IMAGE_DIGEST`) while the patches are this release's
(the hash covers the patches and those pip packages); after you change `patches/`, it pulls that hash's tag if
one is published, else (or with `PULL=0`) it builds.
@@ -209,7 +209,7 @@ PREPARE=1 ./start.sh restart # force prepare.sh, then restart; PREPARE=0 skips
```
After changing `patches/`, `scripts/publish-image.sh` pushes the new image to GitHub Container Registry (`latest` and
-`v0.5.0-<image hash>`, the tag `prepare.sh` looks for).
+`v0.6.0-<image hash>`, the tag `prepare.sh` looks for).
## KV pool and memory
@@ -222,21 +222,21 @@ caches from **one shared pool**:
| Requests at once (`PARALLEL`) | 4 |
| Window per request (`CONTEXT`, the model's native maximum) | 1,048,576 tokens |
| KV precision (`KV`) | FP8 (e4m3 rows with a power-of-two scale each: half of bf16's bytes) |
-| **Shared pool** (what is free at start minus `MEMORY_RESERVE_GIB` 14.5, at most `KV_POOL_GIB` 12.5 GiB a Spark beyond the window) | **2,852,864 tokens** at the measured start (~2.1-2.9M depending on free memory) |
+| **Shared pool** (what is free at start minus `MEMORY_RESERVE_GIB` 14.5, at most `KV_POOL_GIB` 12.5 GiB a Spark beyond the window) | **2,922,496 tokens** at the measured start, the 12.5 GiB cap (~2.1-2.9M depending on free memory) |
| Rank 0's startup estimate | 88.09 GiB |
-| Free memory (`MemAvailable`) at idle | 7.8 GiB on rank 0, 10.8 GiB on rank 1 |
-| Lowest free memory under a 1M-token prompt | 4.7 GiB on rank 0, 8.8 GiB on rank 1 |
+| Free memory (`MemAvailable`) at idle | 7.0 GiB on rank 0, 10.5 GiB on rank 1 |
+| Lowest free memory under a 1M-token prompt | 5.6 GiB on rank 0, 9.5 GiB on rank 1 |
Any one request can grow to the full window, and the four together share the pool: e.g. one 1M-token conversation
-next to one more of 1M, or next to three of ~600k. A request the pool cannot place yet waits until others finish (kept prompt states give way
+next to one more of 1M, or next to three of ~640k. A request the pool cannot place yet waits until others finish (kept prompt states give way
first); `/health` shows `pool_tokens`, `pool_free_tokens` and the streams decoding, filling and paused.
TensorFold's budget on each Spark is `MemAvailable` at start minus a host reserve (`MEMORY_RESERVE_GIB`, 14.5 GiB here;
TensorFold's own default is a tenth of RAM). The server uses about 10 GiB beyond its own estimate at its peak, so the
-reserve also sets the lowest free memory. On the Spark's unified memory, running out tends to freeze the machine rather than
-fail an allocation. A setting that does not fit is refused before any weights load, with the largest window that
-fits; `start.sh` then restarts once with that window and says so (free memory on both Sparks for the full one).
-Other settings' windows:
+reserve also sets the lowest free memory.
+On the Spark's unified memory, running out tends to freeze the machine rather than fail an allocation. A setting that
+does not fit is refused before any weights load, with the largest window that fits; `start.sh` then restarts once
+with that window and says so (free memory on both Sparks for the full one). Other settings' windows:
| Setting | Window | Note |
| --- | ---: | --- |
@@ -283,10 +283,12 @@ sets a value wins: the environment, then `scripts/local.sh`, then `.env`, then t
| `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 |
| `DENSE` | `q4` | the checkpoint's BF16 weights (attention, shared experts, dense layers, head): `q4` (4-bit groups of 64, head and kv_b in FP8), `fp8` or `bf16` |
| `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 |
| `DRAFT_POLICY` | `fnc7:0.3` | how many DFlash2 drafts a round verifies: up to 7, until the drafts' chance under the request's own sampling noise drops below 0.3 |
| `COPY` / `COPY_MAX` | `1` / `15` | copy drafts: when the reply's last 8 tokens occurred before, the tokens that followed are verified ahead of DFlash2's, up to 15 a round |
| `COPY_CODE` | `1` | 16-row verify windows as CUDA graphs, and copies from the reply itself only after a 16-token match |
| `SHARED_PREFIX` | `1` | conversations that share a system prompt reuse its prompt state |
+| `MAX_TOKENS` | `32768` | the reply budget (reasoning and answer) of a request that sets no `max_tokens`; TensorFold's own default is 4,096 |
| `THINKING` | `1` | think before answering by default; `0` answers directly unless a request asks to think |
| `VISION` / `VISION_URLS` | `1` / `0` | image and video input; `1` also accepts public `https://` URLs |
| `COMM` | `roce` | the ranks' small all-gathers as one-shot RDMA writes over the RoCE link; `nccl`: NCCL for all |
@@ -295,6 +297,7 @@ sets a value wins: the environment, then `scripts/local.sh`, then `.env`, then t
| `TF_GLM_L2PF` | `1` | L2 prefetch in decode: the weights the next kernels read brought into L2 during each layer's all-gathers; `0`: off |
| `TF_GLM_EXL3_LOADS` | `nc` | the decode expert kernel's trellis as 16-byte non-coherent loads a step ahead (`nc2` / `nc4`: 2 or 4 steps); `0`: TensorFold's 32-bit loads |
| `TF_ROCE_MAX_KB` | `512` | the largest all-gather (KiB) sent over RoCE with `COMM=roce` (TensorFold's default: 256); 512 covers the 17-32-row verify windows of concurrent requests |
+| `TF_ROCE_WAIT_S` | `20` | seconds a RoCE all-gather waits for the other Spark before it fails (1 to 3600); until the engine is built, each gather first meets the peer in an NCCL barrier, so a long first start (kernels compiling) does not run into it |
| `TF_GLM_MULTI_LONE` | `1` | with `PARALLEL` above 1, a request decoding alone runs on the one-stream graphs; `0`: on the batched ones |
| `MULTI_PREFILL` | `1` | prompts that arrive together are filled in one forward (each with the bits it gets alone); `0`: one after another |
| `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 |
@@ -312,7 +315,7 @@ Speed settings' measured effects: [What the patches change](#what-the-patches-ch
changes nothing until the pin does. Set one empty to take the Hub's `main` when first downloaded.
Less common settings are described in `scripts/config.sh` and `scripts/nodes.sh`: `MODEL_ID`, `DFLASH2_ID`,
-`TF_VERSION`, `TF_REPO`, `BASE_IMAGE` (the patches are made for TensorFold v0.5.0; after changing any of these run
+`TF_VERSION`, `TF_REPO`, `BASE_IMAGE` (the patches are made for TensorFold v0.6.0; after changing any of these run
`scripts/prepare.sh --rebuild`), `IMAGE`, `CONTAINER_NAME`, `GHCR_IMAGE`, `HF_CACHE` (default `$HF_HOME` or
`~/.cache/huggingface`), `KERNEL_CACHE`, `STATE_DIR`, `MIN_FREE_GB`, `IMAGE_FREE_GB`, `NCCL_RAILS` (`1`: one CX7
port even when both are up), `NCCL_CHANNELS` (4), `NCCL_DEBUG`, `RSYNC_OPTS`. `start.sh` also takes `HF_HUB_OFFLINE=0` (let the
@@ -324,10 +327,11 @@ The checkpoint's own sampling defaults apply (temperature 1.0, top_p 0.95). Per
- `temperature`, `top_p`, `top_k`, `min_p` and `seed` override them (`temperature: 0` decodes greedily). Without a
`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`. Without it, GLM's
- template uses `max`; `"none"` (or `"chat_template_kwargs": {"enable_thinking": false}`) answers without thinking.
+- `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.
- The reasoning comes back in `reasoning_content`, the answer in `content`. A request without `max_tokens` gets
- 4,096 tokens (`./start.sh restart --max-tokens 16384` changes the default). An empty `content` means the model
+ 32,768 tokens for both (`MAX_TOKENS`; cut to what the window has left, never refused). An empty `content` means the model
thought until `max_tokens`: give more, or use `reasoning_effort: "low"`.
### API notes
@@ -338,41 +342,45 @@ The checkpoint's own sampling defaults apply (temperature 1.0, top_p 0.95). Per
`/v1/messages`.
- **Context limits:** a request whose prompt plus `max_tokens` does not fit the window is refused with HTTP 400 in
OpenAI's wording, `"code": "context_length_exceeded"` and `param` naming the field (`messages` or `prompt`).
-- **Tool calling:** `tools` / `tool_calls`, streamed, with arguments typed by their schema (an array as a JSON array,
+- **Tool calling:** `tools` / `tool_calls`, each call streamed whole once it is written (empty deltas every 2 s
+ meanwhile, 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,
`null` and `const` values as such). Calls written inside the think block count when the reply ends on them, and a
tool-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).
+ (`TF_GLM_KEEP_REASONING=0` turns that off). A past tool call whose arguments are not a JSON object is left out of
+ the prompt with its result (and logged) instead of failing the request.
- **Structured outputs:** `response_format` (`json_object` or `json_schema`) and the `guided_json` / `guided_regex` /
`guided_choice` / `guided_grammar` / `structured_outputs` fields, enforced with xgrammar (after the think block).
- **`/tokenize` / `/detokenize`:** vLLM's fields; a `prompt` or `messages` (rendered as the chat route does) to token
ids with their `count` and `max_model_len`, and back.
-- Accepted but ignored, with no error: `logprobs` / `top_logprobs`, `n` (one choice), `logit_bias`, and the
- presence, frequency and repetition penalties. `priority: "background"` serves a request after the others.
+- 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 repetition
+ penalties. `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`).
## What the patches change
-`scripts/prepare.sh` bakes every `patches/*.patch` into the image (diffs against TensorFold v0.5.0's site-packages,
+`scripts/prepare.sh` bakes every `patches/*.patch` into the image (diffs against TensorFold v0.6.0's site-packages,
applied with `patch -p0` in filename order); `start.sh` rebuilds or re-pulls the image when the patches change.
| Area | Patches | Change | Effect |
| --- | --- | --- | --- |
| 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 | `0041-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`, `0026-glm-prompt-select-rows`, `0031-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`, `0036-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, KDA | `0012-glm-kda-chunked`, `0014-glm-kda-chunked-gb10`, `0042-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`, `0045-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) |
-| Decode | `0013-glm-decode-rounds`, `0016-glm-decode-kernels`, `0019-glm-decode-kernels2`, `0034-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 | `0049-glm-l2-prefetch`, `0050-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 | `0046-glm-visible-pools` | a decode row's token selection bounded to the pools it can see (after TensorFold PR #140) | the same tokens |
-| Link | `0006-cuda-roce-allgather`, `0023-glm-idle-doorbell` | 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%); an idle rank 1 waits on a socket instead of a spinning NCCL kernel | 11 us a 16 KiB gather against NCCL's 45, decode +6%; an idle server holds no GPU or CPU core |
-| Drafts | `0007-glm-copy-drafts`, `0035-glm-code-copy-drafts`, `0018-glm-noise-policies`, `0021-glm-dflash-policy-env`, `0027-glm-dflash2-ring`, `0030-glm-mtp-off` | copy (prompt-lookup) drafts ahead of DFlash2's (`COPY`, `COPY_CODE`); DFlash2 stop rules aware of the sampling noise (`DRAFT_POLICY`); DFlash2's context as a ring; the MTP head 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 |
+| 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, 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) |
+| 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 | `0028-glm-multi-kda`, `0029-glm-multi-dflash2`, `0032-glm-multi-dsa`, `0033-glm-multi-stream-engine`, `0038-glm-multi-rounds`, `0043-glm-parallel-deadlocks`, `0044-glm-parallel-ring-base`, `0051-glm-timing-tokens`, `0052-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`: +0.6-0.9%); the startup timings of verify windows on distinct tokens | 4 requests at once ([Performance](#performance)) |
-| Sampling | `0037-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`, `0053-glm-many-media`, `0039-glm-tool-calls`, `0040-cuda-tokenize`, `0024-server-effort-max`, `0025-cuda-memory-reserve`, `0047-cuda-context-errors`, `0048-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; `/tokenize` and `/detokenize`; `reasoning_effort: "max"`; a settable host reserve; context-window refusals with code `context_length_exceeded` and Prometheus `/metrics` (both ported from TensorFold v0.6.0) | the API features above |
+| 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`: +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 |
## Checks
@@ -412,9 +420,10 @@ NOTICE third-party notices (TensorFold's MIT and Apache-2.0 notices, b12x
## License
Apache License 2.0, see [`LICENSE`](LICENSE). [`NOTICE`](NOTICE) carries the third-party notices that go with it: the
-files in `patches/` modify TensorFold, and the TensorFold code they change or quote as context stays under TensorFold's
-MIT License (its notice is in `NOTICE`); parts of patches 0006 (b12x), 0039, 0049 and 0050 (glm53-tensorfold-spark)
-and 0047 and 0048 (TensorFold v0.6.0) come from Apache-2.0 projects, credited there and in [`CREDITS.md`](CREDITS.md). The model
+files in `patches/` modify TensorFold v0.6.0, and the TensorFold code they change or quote as context stays under
+TensorFold's licenses (Apache 2.0 from v0.6.0, and the MIT notice of code written before it, both in `NOTICE`); parts
+of patches 0006 (b12x), 0036, 0046 and 0047 (glm53-tensorfold-spark) come from Apache-2.0 projects, credited there and
+in [`CREDITS.md`](CREDITS.md). The model
files 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
diff --git a/patches/0002-glm-dense-fp8.patch b/patches/0002-glm-dense-fp8.patch
index f600569..5c53c5a 100644
--- a/patches/0002-glm-dense-fp8.patch
+++ b/patches/0002-glm-dense-fp8.patch
@@ -1,8 +1,8 @@
diff --git tensorfold/families/glm5_next/cuda/engine.py tensorfold/families/glm5_next/cuda/engine.py
-index 43c1af4..3393fa0 100644
+index b98d846..b29529c 100644
--- tensorfold/families/glm5_next/cuda/engine.py
+++ tensorfold/families/glm5_next/cuda/engine.py
-@@ -111,10 +111,16 @@ class GlmEngine:
+@@ -136,9 +136,14 @@ class GlmEngine:
explicit = context is not None if context_explicit is None else bool(context_explicit)
from . import LATENT
@@ -12,19 +12,17 @@ index 43c1af4..3393fa0 100644
+ weights_estimate = split_weights(rule)
+ if cfg.quant == "exl3" and dense_kind() == "fp8":
+ weights_estimate = fp8_weights(weights_estimate)
+ # TF_GLM_MTP off: the MTP layer's tensors, caches and buffers are neither loaded nor estimated
+ self.mtp_on = mtp_head(drafter is not None, serial_only, cfg.mtp_layers)
+- weights_estimate = split_weights(rule)
+ if not self.mtp_on:
+ weights_estimate = without_mtp(weights_estimate, cfg.layers)
self.capacity_plan = admit(model_dir, context if explicit else cfg.dense_limit, explicit, torch,
- lambda text: mla_geometry(text, 2, MAX_ROWS, minimum_slots=DENSE_CAPACITY,
- latent=LATENT),
-- split_weights(rule), rank=rank, world=2, gather=self._gather_ints,
-+ weights_estimate, rank=rank, world=2, gather=self._gather_ints,
- draft_dir=drafter, draft_geometry=lambda text: draft_geometry(text, 2, MAX_ROWS))
- self.limit = self.capacity_plan["context_window"]
- capacity = self.capacity_plan["cache_slots"]
diff --git tensorfold/families/glm5_next/cuda/forward.py tensorfold/families/glm5_next/cuda/forward.py
-index 40f1fd1..cd3cfc8 100644
+index 01a173c..f73f253 100644
--- tensorfold/families/glm5_next/cuda/forward.py
+++ tensorfold/families/glm5_next/cuda/forward.py
-@@ -248,19 +248,23 @@ def kda_block(layer: LayerW, w: Weights, st: State, b: Buffers, R: int) -> torch
+@@ -260,29 +260,32 @@ def kda_block(layer: LayerW, w: Weights, st: State, b: Buffers, R: int, cut: Cut
k = layer.kda
li = st.kda_index[layer.index]
p = b.kproj[0, :R] if b.prefill else st.proj[li, :R]
@@ -41,12 +39,31 @@ index 40f1fd1..cd3cfc8 100644
+ mm(b, fa, k.fb, None if pre else qmm.group_sums(fa, b.xs_fa[:R]), b.ka[:R])
+ mm(b, ga, k.gb, None if pre else qmm.group_sums(ga, b.xs_ga[:R]), b.kg[:R])
cur = st.cur[li]
-- out = kda_mod.chain(p, k.b_off, b.ka[:R], b.kg[:R], st.conv[li], k.conv, st.rec[cur, li], k.a_log, k.dt_bias,
-- k.norm, c.eps, c.lower, R, b.kscratch if pre else st.scratch[li], st.rec[1 - cur, li])
+- if cut is None:
+- out = kda_mod.chain(p, k.b_off, b.ka[:R], b.kg[:R], st.conv[li], k.conv, st.rec[cur, li], k.a_log,
+- k.dt_bias, k.norm, c.eps, c.lower, R, b.kscratch if pre else st.scratch[li],
+- st.rec[1 - cur, li])
+- else:
+- n = cut.point
+- first = kda_mod.chain(p[:n], k.b_off, b.ka[:n], b.kg[:n], st.conv[li], k.conv, st.rec[cur, li],
+- k.a_log, k.dt_bias, k.norm, c.eps, c.lower, n, b.kscratch, cut.rec[li]).clone()
+- _shift_conv(cut.conv[li:li + 1], b.kproj[:, :n], n)
+- rest = kda_mod.chain(p[n:], k.b_off, b.ka[n:R], b.kg[n:R], cut.conv[li], k.conv, cut.rec[li],
+- k.a_log, k.dt_bias, k.norm, c.eps, c.lower, R - n, b.kscratch, st.rec[1 - cur, li])
+- out = torch.cat((first, rest))
+ with prof.timed("kda: recurrence"):
-+ out = kda_mod.chain(p, k.b_off, b.ka[:R], b.kg[:R], st.conv[li], k.conv, st.rec[cur, li], k.a_log,
-+ k.dt_bias, k.norm, c.eps, c.lower, R, b.kscratch if pre else st.scratch[li],
-+ st.rec[1 - cur, li])
++ if cut is None:
++ out = kda_mod.chain(p, k.b_off, b.ka[:R], b.kg[:R], st.conv[li], k.conv, st.rec[cur, li], k.a_log,
++ k.dt_bias, k.norm, c.eps, c.lower, R, b.kscratch if pre else st.scratch[li],
++ st.rec[1 - cur, li])
++ else:
++ n = cut.point
++ first = kda_mod.chain(p[:n], k.b_off, b.ka[:n], b.kg[:n], st.conv[li], k.conv, st.rec[cur, li],
++ k.a_log, k.dt_bias, k.norm, c.eps, c.lower, n, b.kscratch, cut.rec[li]).clone()
++ _shift_conv(cut.conv[li:li + 1], b.kproj[:, :n], n)
++ rest = kda_mod.chain(p[n:], k.b_off, b.ka[n:R], b.kg[n:R], cut.conv[li], k.conv, cut.rec[li],
++ k.a_log, k.dt_bias, k.norm, c.eps, c.lower, R - n, b.kscratch, st.rec[1 - cur, li])
++ out = torch.cat((first, rest))
if pre: # a prompt chunk keeps every row: the layer commits now
st.cur[li] = 1 - cur
_shift_conv(st.conv[li:li + 1], b.kproj[:, :R], R)
@@ -56,7 +73,7 @@ index 40f1fd1..cd3cfc8 100644
def dsa_block(layer: LayerW, w: Weights, kc: torch.Tensor, vc: torch.Tensor, pos_dev: torch.Tensor, b: Buffers,
-@@ -361,14 +365,18 @@ def moe_block(layer: LayerW, w: Weights, b: Buffers, R: int) -> torch.Tensor:
+@@ -398,14 +401,18 @@ def moe_block(layer: LayerW, w: Weights, b: Buffers, R: int) -> torch.Tensor:
# EXL3: the routed slots through the trellis kernels, the shared expert (last slot) through BF16 matmuls
from . import exl3_mm
@@ -243,7 +260,7 @@ index a366806..827db2b 100644
+ return total, extra
+ return transform
diff --git tensorfold/families/glm5_next/cuda/weights.py tensorfold/families/glm5_next/cuda/weights.py
-index bc0b47f..f2d3cb8 100644
+index 48c4190..fd9db9d 100644
--- tensorfold/families/glm5_next/cuda/weights.py
+++ tensorfold/families/glm5_next/cuda/weights.py
@@ -13,7 +13,7 @@ from tensorfold.cuda import experts as grouped
@@ -255,7 +272,7 @@ index bc0b47f..f2d3cb8 100644
PREFIX = "model.language_model."
-@@ -199,7 +199,7 @@ class Weights:
+@@ -204,7 +204,7 @@ class Weights:
embed: tuple[torch.Tensor, torch.Tensor, torch.Tensor]
layers: list[LayerW]
norm: torch.Tensor
@@ -264,7 +281,7 @@ index bc0b47f..f2d3cb8 100644
mtp: MTPW | None
rank: int
world: int
-@@ -221,7 +221,7 @@ class Weights:
+@@ -226,7 +226,7 @@ class Weights:
if isinstance(t, torch.Tensor) and t.data_ptr() not in seen:
seen.add(t.data_ptr())
total += t.numel() * t.element_size()
@@ -273,7 +290,7 @@ index bc0b47f..f2d3cb8 100644
for v in vars(t).values():
add(v)
elif isinstance(t, (list, tuple)):
-@@ -264,12 +264,16 @@ def load(model_dir: str | Path, *, rank: int, device: str = "cuda") -> Weights:
+@@ -269,12 +269,16 @@ def load(model_dir: str | Path, *, rank: int, device: str = "cuda", mtp: bool =
def trip(name: str) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
return (as_i32(t(name + ".weight")), t(name + ".scales"), t(name + ".biases"))
@@ -294,7 +311,7 @@ index bc0b47f..f2d3cb8 100644
return stack_q4([trip(n) for n in names])
def hc(i: int, site: str) -> HCW:
-@@ -290,7 +294,7 @@ def load(model_dir: str | Path, *, rank: int, device: str = "cuda") -> Weights:
+@@ -295,7 +299,7 @@ def load(model_dir: str | Path, *, rank: int, device: str = "cuda", mtp: bool =
krows, vrows = rows[:, :cfg.qk_dim].reshape(-1), rows[:, cfg.qk_dim:].reshape(-1)
if exl3:
w = t(p + "kv_b_proj.weight")
@@ -303,7 +320,7 @@ index bc0b47f..f2d3cb8 100644
full_k, full_v = (lambda: w[krows].float()), (lambda: w[vrows].float())
else:
w, s, b = trip(p + "kv_b_proj")
-@@ -412,9 +416,9 @@ def load(model_dir: str | Path, *, rank: int, device: str = "cuda") -> Weights:
+@@ -417,9 +421,9 @@ def load(model_dir: str | Path, *, rank: int, device: str = "cuda", mtp: bool =
vl = cfg.vocab // world
draft_head = None
if exl3:
diff --git a/patches/0003-glm-vision.patch b/patches/0003-glm-vision.patch
index 2b73e2c..2b4046a 100644
--- a/patches/0003-glm-vision.patch
+++ b/patches/0003-glm-vision.patch
@@ -1,22 +1,8 @@
-diff --git tensorfold/cli.py tensorfold/cli.py
-index 6a3a9d2..72b1ec4 100644
---- tensorfold/cli.py
-+++ tensorfold/cli.py
-@@ -36,7 +36,8 @@ def build_parser() -> argparse.ArgumentParser:
- endpoint.add_argument("--port", type=int, default=8080)
- endpoint.add_argument("--name", default="", help="model id clients ask for (default: the model's name)")
- endpoint.add_argument("--alias", action="append", default=[], help="another model id to answer to")
-- endpoint.add_argument("--vision", action="store_true", help="enable image input for Qwen3.5/3.8 dense vision checkpoints")
-+ endpoint.add_argument("--vision", action="store_true", help="enable image input for Qwen3.5/3.8 dense vision checkpoints, and "
-+ "image and video input for GLM-5.3 Flash")
- endpoint.add_argument("--vision-urls", action="store_true",
- help="with --vision, accept public HTTP(S) image URLs (default: data URLs only)")
-
diff --git tensorfold/cuda/server.py tensorfold/cuda/server.py
-index eef1b5f..31e0268 100644
+index 552720d..3707349 100644
--- tensorfold/cuda/server.py
+++ tensorfold/cuda/server.py
-@@ -353,11 +353,15 @@ class App:
+@@ -408,11 +408,15 @@ class App:
end = None if think_end is None or think_end in ids[len(prompt):] else think_end
extra["constraint"] = self._grammars().constraint(compiled, think_end=end, spec=spec)
if prepared.vision is not None: # a gate's continuation keeps the images, positions extended
@@ -37,10 +23,10 @@ index eef1b5f..31e0268 100644
if not cached:
cached.append(int((stats or {}).get("cached") or 0))
diff --git tensorfold/families/glm5_next/__init__.py tensorfold/families/glm5_next/__init__.py
-index f95a051..7076545 100644
+index 5d8cac3..a2f4a6f 100644
--- tensorfold/families/glm5_next/__init__.py
+++ tensorfold/families/glm5_next/__init__.py
-@@ -192,7 +192,8 @@ def cuda_engine(model_dir: str | Path, *, drafter: str = "", tp: int = 1, rank:
+@@ -222,7 +222,8 @@ def cuda_engine(model_dir: str | Path, *, drafter: str = "", tp: int = 1, rank:
return GlmEngine(Path(model_dir), rank=int(rank), 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"),
@@ -51,7 +37,7 @@ index f95a051..7076545 100644
def __getattr__(name: str) -> Any:
diff --git tensorfold/families/glm5_next/cuda/app.py tensorfold/families/glm5_next/cuda/app.py
-index 62d3d38..f46b66c 100644
+index 0b6d35e..350e5b0 100644
--- tensorfold/families/glm5_next/cuda/app.py
+++ tensorfold/families/glm5_next/cuda/app.py
@@ -2,6 +2,7 @@
@@ -62,7 +48,7 @@ index 62d3d38..f46b66c 100644
from typing import Any, Callable
from tensorfold.cuda.server import App, PreparedRequest, RequestError
-@@ -16,16 +17,38 @@ class ThinkingOffTemplate:
+@@ -15,16 +16,38 @@ class ThinkingOffTemplate:
self.inner = inner
self.efforts = getattr(inner, "efforts", frozenset())
@@ -104,38 +90,39 @@ index 62d3d38..f46b66c 100644
def check(self, body: dict[str, Any], *, prepared: PreparedRequest | None = None) -> str | None:
diff --git tensorfold/families/glm5_next/cuda/decode.py tensorfold/families/glm5_next/cuda/decode.py
-index 6a01236..1df65cf 100644
+index f8b4ec4..4850d92 100644
--- tensorfold/families/glm5_next/cuda/decode.py
+++ tensorfold/families/glm5_next/cuda/decode.py
-@@ -310,8 +310,8 @@ def restore(e: Engine, snap: Snapshot, drafter=None) -> None:
+@@ -341,8 +341,8 @@ def restore(e: Engine, snap: Snapshot, drafter=None) -> None:
# -- prefill ----------------------------------------------------------------------------------------------------
@torch.no_grad()
def prefill(e: Engine, prompt: Sequence[int], sampling: Sampling | None, *, mtp: bool = True, drafter=None,
-- resume: Snapshot | None = None) -> int:
+- resume: Snapshot | None = None, keep_at: int | None = None, keep=None) -> int:
- """Commit the prompt in chunks and sample its first token; a resumed prompt ends in a fresh prefill's state."""
-+ resume: Snapshot | None = None, feed=None) -> int:
++ resume: Snapshot | None = None, keep_at: int | None = None, keep=None, feed=None) -> int:
+ """Commit the prompt in chunks and sample its first token; a resumed prompt ends in a fresh prefill's state; ``feed``: an image prompt's feature rows (``engine.VisionFeed``)."""
if not prompt:
raise ValueError("prefill requires at least one token")
-@@ -337,7 +337,8 @@ def prefill(e: Engine, prompt: Sequence[int], sampling: Sampling | None, *, mtp:
- for start in range(begin, len(prompt), e.prefill_rows):
- chunk = list(prompt[start:start + e.prefill_rows])
+@@ -375,7 +375,9 @@ def prefill(e: Engine, prompt: Sequence[int], sampling: Sampling | None, *, mtp:
R = len(chunk)
-- last = compute(w, st, b, stage(w, st, b, chunk), nch=chunks_for(st, R), host_pos=st.pos).clone()
+ point = keep_at - start if keep_at is not None else 0
+ cut = Cut(point, torch.empty_like(st.rec[0]), st.conv.clone()) if 0 < point < R else None
+- last = compute(w, st, b, stage(w, st, b, chunk), nch=chunks_for(st, R), host_pos=st.pos, cut=cut).clone()
+ inject = feed.chunk(start, R) if feed is not None else None
-+ last = compute(w, st, b, stage(w, st, b, chunk), nch=chunks_for(st, R), host_pos=st.pos, inject=inject).clone()
++ last = compute(w, st, b, stage(w, st, b, chunk), nch=chunks_for(st, R), host_pos=st.pos, cut=cut,
++ inject=inject).clone()
e.last_hidden = b.fnormed[R - 1:R].clone()
- if drafter is not None:
- drafter.add_taps(e.tap_rows(R, b))
+ if 0 < point <= R:
+ rec = cut.rec if cut is not None else st.rec[st.cur[0] if st.cur else 0].clone()
diff --git tensorfold/families/glm5_next/cuda/engine.py tensorfold/families/glm5_next/cuda/engine.py
-index 3393fa0..c46aa52 100644
+index b29529c..47d2a02 100644
--- tensorfold/families/glm5_next/cuda/engine.py
+++ tensorfold/families/glm5_next/cuda/engine.py
-@@ -17,6 +17,22 @@ EXL3_AUTO = DFLASH_POLICY # what auto runs on an EXL3 checkpoint wit
- GRAPH_ROWS = (1, 2, 3, 4, 5, 6) # verify windows captured as CUDA graphs
- MAX_ROWS = 8 # the widest verify window (a pending token and up to 7 drafts)
+@@ -19,6 +19,22 @@ MAX_ROWS = 8 # the widest verify window (a pending toke
DENSE_CAPACITY = 2560 # cache slots while DSA attention stays dense (contexts up to 2,051 tokens)
+ # TF_GLM_DRAFT_RING=0: DFlash2's context in a flat buffer of the whole window, not a 2,176-row ring (the same drafts)
+ DRAFT_RING = os.environ.get("TF_GLM_DRAFT_RING", "1").strip() != "0"
+# --vision (rank 0): what startup reserves beside the tower's 1.05 GiB of bf16 weights for an encode and its
+# prompt's feature rows. Measured peaks: 0.47 GiB (a 2,048-token picture), 0.56 (four), 1.08 (a 16,384-token clip,
+# 16,384 patches a pass), 1.73 (an 8,000-token picture, one 31,724-patch pass). A picture cap past 4,096 tokens
@@ -155,7 +142,7 @@ index 3393fa0..c46aa52 100644
def encode_policy(spec: str) -> list[int]:
-@@ -86,8 +102,9 @@ class GlmEngine:
+@@ -110,8 +126,9 @@ class GlmEngine:
def __init__(self, model_dir: Path, *, rank: int, master: str, port: int, policy: str = DEFAULT_POLICY,
drafter: Path | None = None, context: int | None = None, context_explicit: bool | None = None, serial_only: bool = False, comm=None,
@@ -167,10 +154,10 @@ index 3393fa0..c46aa52 100644
import torch
-@@ -117,9 +134,22 @@ class GlmEngine:
- weights_estimate = split_weights(rule)
- if cfg.quant == "exl3" and dense_kind() == "fp8":
- weights_estimate = fp8_weights(weights_estimate)
+@@ -146,9 +163,22 @@ class GlmEngine:
+ self.mtp_on = mtp_head(drafter is not None, serial_only, cfg.mtp_layers)
+ if not self.mtp_on:
+ weights_estimate = without_mtp(weights_estimate, cfg.layers)
+ vision = bool(vision) and rank == 0
+ workspace = vision_workspace() if vision else 0
+ if vision: # the tower's bf16 weights, which the split rule drops
@@ -183,19 +170,19 @@ index 3393fa0..c46aa52 100644
+ def geometry(text):
+ from tensorfold.cuda.capacity import Geometry
+
-+ g = mla_geometry(text, 2, MAX_ROWS, minimum_slots=DENSE_CAPACITY, latent=LATENT)
++ g = mla_geometry(text, 2, MAX_ROWS, minimum_slots=DENSE_CAPACITY, latent=LATENT, mtp=self.mtp_on)
+ return Geometry(lambda slots: g.bytes_at(slots) + workspace, g.reserve, g.minimum_slots) if workspace else g
self.capacity_plan = admit(model_dir, context if explicit else cfg.dense_limit, explicit, torch,
- lambda text: mla_geometry(text, 2, MAX_ROWS, minimum_slots=DENSE_CAPACITY,
-- latent=LATENT),
+- latent=LATENT, mtp=self.mtp_on),
+ geometry,
weights_estimate, rank=rank, world=2, gather=self._gather_ints,
- draft_dir=drafter, draft_geometry=lambda text: draft_geometry(text, 2, MAX_ROWS))
- self.limit = self.capacity_plan["context_window"]
-@@ -170,6 +200,18 @@ class GlmEngine:
- print("[tensorfold] drafter costs (ms): verify " + " ".join(f"{v:.1f}" for v in c["verify"]) +
- f"; MTP draft {c['mtp']:.2f} (+{c['mtp_step']:.2f} a chained draft, +{c['mtp_row']:.2f} a row); "
- f"DFlash2 block {c['block']:.2f} (+{c['taps_row']:.3f} a tap row)", flush=True)
+ draft_dir=drafter, draft_weights=lambda d: dflash2_weights(d, 2),
+ draft_geometry=lambda text: dflash2_geometry(text, 2, MAX_ROWS, ring=DRAFT_RING))
+@@ -206,6 +236,18 @@ class GlmEngine:
+ if w.mtp is not None else "")
+ print("[tensorfold] drafter costs (ms): verify " + " ".join(f"{v:.1f}" for v in c["verify"]) + mtp +
+ f"; DFlash2 block {c['block']:.2f} (+{c['taps_row']:.3f} a tap row)", flush=True)
+ self.vision = None # rank 0's image tower (``tensorfold.vision.glm.GlmVision``), --vision
+ if vision:
+ from tensorfold.vision.glm import GlmVision
@@ -211,7 +198,7 @@ index 3393fa0..c46aa52 100644
self.eos = tuple(w.cfg.eos)
self.model_dir = Path(model_dir)
self.request = threading.local() # the calling request's policy and stop-at-EOS (``app.GlmApp``)
-@@ -361,15 +403,16 @@ class GlmEngine:
+@@ -424,15 +466,16 @@ class GlmEngine:
return sum(snapshot_bytes(c) for c in self.cache)
def _run(self, prompt: list[int], max_tokens: int, sampling, stop_eos: bool, on_tokens: Callable[[list[int]], Any],
@@ -228,25 +215,24 @@ index 3393fa0..c46aa52 100644
- on_tokens: Callable[[list[int]], Any], code: list[int], hit, draft: bool) -> dict[str, Any]:
+ on_tokens: Callable[[list[int]], Any], code: list[int], hit, draft: bool,
+ feed=None) -> dict[str, Any]:
- from .decode import DepthPolicy, dflash_decode, mtp_decode, prefill, serial_decode, take_snapshot
+ from .decode import DepthPolicy, dflash_decode, mtp_decode, prefill, serial_decode
from .drafter_choice import DrafterChoice, auto_decode
-@@ -384,10 +427,11 @@ class GlmEngine:
+@@ -447,9 +490,10 @@ class GlmEngine:
if hit is not None and hit.rows is not None:
load_rows(self.e, hit)
hit.rows, hit.nbytes = None, 0 # live again
- self.live = list(prompt)
-- first = prefill(self.e, prompt, sampling, mtp=use_mtp, drafter=drafter, resume=hit)
+- first = prefill(self.e, prompt, sampling, mtp=use_mtp, drafter=drafter, resume=hit,
+- keep_at=max(1, len(prompt) - 1) if draft else None, keep=self._remember)
+ # an image prompt's rows are not its token ids' rows: nothing resumes from them, and they are not kept
+ self.live = list(prompt) if feed is None else []
-+ first = prefill(self.e, prompt, sampling, mtp=use_mtp, drafter=drafter, resume=hit, feed=feed)
++ first = prefill(self.e, prompt, sampling, mtp=use_mtp, drafter=drafter, resume=hit, feed=feed,
++ keep_at=max(1, len(prompt) - 1) if draft and feed is None else None, keep=self._remember)
prefill_s = time.perf_counter() - t0
-- if draft:
-+ if draft and feed is None:
- self._remember(take_snapshot(self.e, prompt, self.e.last_hidden if use_mtp else None, mtp=use_mtp,
- drafter=drafter))
stats: dict[str, Any] = {"prefill_s": prefill_s, "cached": cut}
-@@ -415,7 +459,8 @@ class GlmEngine:
+ on_tokens([first])
+@@ -476,7 +520,8 @@ class GlmEngine:
res = mtp_decode(self.e, first, max_tokens, sampling, policy=policy, stop_eos=stop_eos,
on_tokens=on_tokens)
# the caches now hold prompt and reply; only prompts are snapshotted, since a later prompt prefills the reply again
@@ -256,7 +242,7 @@ index 3393fa0..c46aa52 100644
stats.update(decode_s=res.seconds, rounds=res.rounds, min_rows=1 + min(res.depths, default=0),
tokens_per_round=round((len(res.tokens) - 1) / max(res.rounds, 1), 3),
sha256=hashlib.sha256(json.dumps(res.tokens).encode()).hexdigest()[:16])
-@@ -426,8 +471,8 @@ class GlmEngine:
+@@ -487,8 +532,8 @@ class GlmEngine:
return stats
def generate(self, prompt: list[int], max_tokens: int, sampling, on_tokens, draft: bool = True,
@@ -267,7 +253,7 @@ index 3393fa0..c46aa52 100644
if len(prompt) >= self.limit:
raise ValueError(f"prompt of {len(prompt)} tokens: this engine serves contexts up to {self.limit}")
-@@ -438,21 +483,39 @@ class GlmEngine:
+@@ -499,13 +544,27 @@ class GlmEngine:
spec = getattr(self.request, "policy", None) or self.policy
code = self._effective(encode_policy(spec))
stop_eos = bool(getattr(self.request, "stop_eos", True))
@@ -296,7 +282,8 @@ index 3393fa0..c46aa52 100644
+ int(constraint is not None), len(positions)] + code
from tensorfold.engine.grammar import pack
- self._share(header)
+ self._ring() # wakes rank 1, which idles on the store, not in the all-gather
+@@ -513,8 +572,12 @@ class GlmEngine:
self._share(list(prompt))
if constraint is not None: # the request's grammar: rank 1 compiles the same
self._share(pack(constraint))
@@ -310,16 +297,16 @@ index 3393fa0..c46aa52 100644
return stats
def follow(self) -> None:
-@@ -462,7 +525,7 @@ class GlmEngine:
-
+@@ -525,7 +588,7 @@ class GlmEngine:
while True:
+ self._await_bell()
(max_tokens, stop_eos, draft, cached, s_lo, s_hi, s_top, t_lo, t_hi, top_k, p_lo, p_hi, m_lo, m_hi, shaped,
- *code) = self._share(None)
+ images, *code) = self._share(None)
prompt = self._share(None)
packed = self._share(None) if shaped else []
constraint = None
-@@ -470,6 +533,7 @@ class GlmEngine:
+@@ -533,6 +596,7 @@ class GlmEngine:
from tensorfold.engine import grammar
constraint = grammar.compiler(self, self.model_dir, self.eos).follow(packed)
@@ -327,7 +314,7 @@ index 3393fa0..c46aa52 100644
temperature = _ints_f64(t_lo, t_hi)
seed = (s_top << 62) | (s_hi << 31) | s_lo
sampling = (Sampling(seed, temperature, top_k, _ints_f64(p_lo, p_hi), _ints_f64(m_lo, m_hi))
-@@ -480,4 +544,32 @@ class GlmEngine:
+@@ -543,4 +607,32 @@ class GlmEngine:
if hit is None:
raise RuntimeError(f"rank 1 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),
@@ -362,26 +349,41 @@ index 3393fa0..c46aa52 100644
+ 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/forward.py tensorfold/families/glm5_next/cuda/forward.py
-index cd3cfc8..f5f6179 100644
+index f73f253..225109f 100644
--- tensorfold/families/glm5_next/cuda/forward.py
+++ tensorfold/families/glm5_next/cuda/forward.py
-@@ -436,11 +436,14 @@ def stage(w: Weights, st: State, b: Buffers, tokens: Sequence[int]) -> int:
+@@ -472,13 +472,16 @@ def stage(w: Weights, st: State, b: Buffers, tokens: Sequence[int]) -> int:
def compute(w: Weights, st: State, b: Buffers, R: int, *, logits: bool = True, nch: int | None = None,
-- host_pos: int | None = None, sparse_np: int | None = None):
+- host_pos: int | None = None, sparse_np: int | None = None, cut: Cut | None = None):
- """Run capturable GPU work on static buffers and device positions; eager long contexts use host_pos (graphs sparse_np) to select sparse attention."""
-+ host_pos: int | None = None, sparse_np: int | None = None, inject=None):
++ host_pos: int | None = None, sparse_np: int | None = None, cut: Cut | None = None, inject=None):
+ """Run capturable GPU work on static buffers and device positions; eager long contexts use host_pos (graphs sparse_np) to select sparse attention; ``inject``: (rows, features) replacing those rows' embeddings (an image prompt's tower output, on every hyper-connection stream)."""
+ if cut is not None and (not b.prefill or not 0 < cut.point < R):
+ raise ValueError("a prompt cut must lie inside a prefill chunk")
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))
for layer in w.layers:
- layer_forward(layer, w, st, b, R, nch, host_pos, sparse_np)
+ layer_forward(layer, w, st, b, R, nch, host_pos, sparse_np, cut)
for slot in b.tap_at.get(layer.index, ()):
+diff --git tensorfold/serve_options.py tensorfold/serve_options.py
+index 658f828..f36736e 100644
+--- tensorfold/serve_options.py
++++ tensorfold/serve_options.py
+@@ -13,8 +13,6 @@ def check(args: argparse.Namespace, family: Any, backend: str, config_dir: Any =
+ if getattr(args, "vision_urls", False) and not getattr(args, "vision", False):
+ raise ValueError("--vision-urls needs --vision")
+ if getattr(args, "vision", False): # only --vision reads the config here
+- if family.model_type == "glm5_next" and backend != "mlx":
+- raise ValueError("GLM-5.3-Flash image input is currently MLX-only")
+ from tensorfold.families import read_config
+ from tensorfold.vision.config import validate_vision_config
+
diff --git tensorfold/server/messages.py tensorfold/server/messages.py
index 24bbd82..dde2b67 100644
--- tensorfold/server/messages.py
@@ -414,7 +416,7 @@ index 24bbd82..dde2b67 100644
raise RequestError("a text content part must contain a text string")
out.append({**message, "content": list(content)})
diff --git tensorfold/server/prompts.py tensorfold/server/prompts.py
-index ebf64e7..52e8009 100644
+index 1b709a7..ee19680 100644
--- tensorfold/server/prompts.py
+++ tensorfold/server/prompts.py
@@ -18,7 +18,7 @@ class RenderedPrompt:
@@ -457,26 +459,6 @@ index ebf64e7..52e8009 100644
except (ImageInputError, ValueError, ImportError) as exc:
raise RequestError(str(exc)) from exc
finally:
-diff --git tensorfold/vision/config.py tensorfold/vision/config.py
-index ef30d5a..3ce4733 100644
---- tensorfold/vision/config.py
-+++ tensorfold/vision/config.py
-@@ -2,9 +2,13 @@
- from __future__ import annotations
-
-
-+FAMILIES = ('qwen3_5', 'glm5_next') # the Qwen3.5/3.8 dense models, and GLM-5.3 Flash (rank 0's tower) on CUDA
-+
-+
- def validate_vision_config(config, family):
-- if family != 'qwen3_5':
-- raise ValueError('--vision currently supports Qwen3.5/3.8 dense checkpoints with their vision tower')
-+ if family not in FAMILIES:
-+ raise ValueError('--vision currently supports Qwen3.5/3.8 dense and GLM-5.3 Flash checkpoints with their '
-+ 'vision tower')
- vision = config.get('vision_config')
- text = config.get('text_config', config)
- if not isinstance(vision, dict) or not vision:
diff --git tensorfold/vision/glm.py tensorfold/vision/glm.py
new file mode 100644
index 0000000..77a96f9
diff --git a/patches/0004-glm-prompt-kernels.patch b/patches/0004-glm-prompt-kernels.patch
index b7c902b..de296c3 100644
--- a/patches/0004-glm-prompt-kernels.patch
+++ b/patches/0004-glm-prompt-kernels.patch
@@ -12,7 +12,7 @@ index 85c2887..c036c64 100644
}
diff --git tensorfold/cuda/experts.py tensorfold/cuda/experts.py
-index 1a39067..450503c 100644
+index 54fd7ee..9e0fdb6 100644
--- tensorfold/cuda/experts.py
+++ tensorfold/cuda/experts.py
@@ -20,7 +20,7 @@ def _ext():
@@ -32,49 +32,53 @@ index 1a39067..450503c 100644
+ prefill: bool = False, tile: int | None = None) -> None:
pairs = rows * slots
self.rows, self.slots, self.experts, self.prefill = rows, slots, experts, prefill
-- self.tile = PREFILL_TILE if prefill else TILE
-+ self.tile = tile or (PREFILL_TILE if prefill else TILE)
+- self.tile = PREFILL_TILE if prefill else TILE # ``route`` sets a prompt plan's to its consumer's
++ self.tile = tile or (PREFILL_TILE if prefill else TILE) # ``route`` sets a prompt plan's to its consumer's
self.members = torch.zeros((pairs,), dtype=torch.int32, device=device)
- self.items = torch.zeros((max_items(pairs, experts, self.tile), 3), dtype=torch.int32, device=device)
+ self.items = torch.zeros((max_items(pairs, experts, TILE), 3), dtype=torch.int32, device=device)
self.counts = torch.zeros((2,), dtype=torch.int32, device=device)
diff --git tensorfold/cuda/geometry.py tensorfold/cuda/geometry.py
-index ee444c2..908f94e 100644
+index 44d7994..9a1b8d5 100644
--- tensorfold/cuda/geometry.py
+++ tensorfold/cuda/geometry.py
-@@ -193,7 +193,8 @@ def _indexed_prefill_row(t: dict, world: int, h: int, hk: int, hd: int, nv: int,
- + 12 * streams + 64)
+@@ -227,7 +227,7 @@ def exl3_expert_scratch(rows: int, slots: int, d: int, width: int) -> int:
--def mla_geometry(t: dict, world: int, reserve: int, *, minimum_slots: int = 2560, latent: bool = False) -> Geometry:
-+def mla_geometry(t: dict, world: int, reserve: int, *, minimum_slots: int = 2560, latent: bool = False,
-+ prefill_rows: int = PREFILL_ROWS) -> Geometry:
+ def mla_geometry(t: dict, world: int, reserve: int, *, minimum_slots: int = 2560, latent: bool = False,
+- mtp: bool | None = None) -> Geometry:
++ prefill_rows: int = PREFILL_ROWS, mtp: bool | None = None) -> Geometry:
+ """GLM's engine; ``mtp``: whether it holds the MTP head's caches and buffers (None: when the checkpoint has one)."""
linear, attention = layer_counts(t)
lin = t.get("linear_attn_config") or {}
- heads = int(t["num_attention_heads"]) // world
-@@ -214,18 +215,18 @@ def mla_geometry(t: dict, world: int, reserve: int, *, minimum_slots: int = 2560
+@@ -249,21 +249,21 @@ def mla_geometry(t: dict, world: int, reserve: int, *, minimum_slots: int = 2560
extent += int(t.get("intermediate_size", width)) * 3 // world + 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 - int(t["vocab_size"]) // world)
if (t.get("_quantization") or {}).get("quant_method") == "exl3":
- fixed += 128 * rows * slots * max(width, d) * 4
+ # EXL3 experts' scratch (decode windows, the MTP head's, a prompt chunk) and the prompt's BF16 split-K partials
+ fixed += (2 if mtp else 1) * exl3_expert_scratch(rows, slots, d, width)
+- fixed += exl3_expert_scratch(PREFILL_ROWS, slots, d, width) + 8 * PREFILL_ROWS * 16384 * 4
++ fixed += exl3_expert_scratch(prefill_rows, slots, d, width) + 8 * prefill_rows * 16384 * 4
count = attention + int(mtp)
lw = int(t.get("kv_lora_rank", 512))
def bytes_at(capacity: int) -> int:
- scratch = mla_chunk_scratch(t, world, capacity, latent=latent)
+ scratch = mla_chunk_scratch(t, world, capacity, latent=latent, prefill_rows=prefill_rows)
if latent:
- # latent cache; one prompt chunk's latent partials and absorbed rows (the MTP absorbs through the same buffers)
+ # latent cache; a prompt chunk's partials (MLA_PROMPT_ATT_ROWS rows at a time) and absorbed rows (MTP's too)
cache = count * capacity * lw * 2
- dense = min(capacity, minimum_slots) + PREFILL_ROWS
-- scratch += ((dense + 511) // 512) * PREFILL_ROWS * heads * (lw + 2) * 4 + 4 * PREFILL_ROWS * heads * lw
+- scratch += (((dense + 511) // 512) * min(PREFILL_ROWS, MLA_PROMPT_ATT_ROWS) * heads * (lw + 2) * 4
+- + 4 * PREFILL_ROWS * heads * lw)
+ dense = min(capacity, minimum_slots) + prefill_rows
-+ scratch += ((dense + 511) // 512) * prefill_rows * heads * (lw + 2) * 4 + 4 * prefill_rows * heads * lw
++ scratch += (((dense + 511) // 512) * min(prefill_rows, MLA_PROMPT_ATT_ROWS) * heads * (lw + 2) * 4
++ + 4 * prefill_rows * heads * lw)
else:
cache = count * capacity * heads * (kd + vd) * 2
scratch += (2 if mtp else 1) * ((capacity + rows + 511) // 512) * rows * heads * (kd + 2) * 4
-@@ -234,13 +235,13 @@ def mla_geometry(t: dict, world: int, reserve: int, *, minimum_slots: int = 2560
+@@ -272,14 +272,14 @@ def mla_geometry(t: dict, world: int, reserve: int, *, minimum_slots: int = 2560
return Geometry(bytes_at, reserve, minimum_slots)
@@ -83,8 +87,9 @@ index ee444c2..908f94e 100644
"""A prompt chunk's transient bytes: token selection (fp32 pool scores, chosen pools, token lists), then sparse attention's partials."""
heads, topk = int(t["num_attention_heads"]) // world, int(t.get("index_topk", 2048))
-- select = PREFILL_ROWS * (4 * ((capacity + 3) // 4) + 16 * (topk + 3))
-+ select = prefill_rows * (4 * ((capacity + 3) // 4) + 16 * (topk + 3))
+ # 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)
++ select = min(prefill_rows, MLA_SELECT_ROWS) * 4 * ((capacity + 3) // 4) + prefill_rows * 16 * (topk + 3)
if latent:
- return select + ((topk + 515) // 512) * PREFILL_ROWS * heads * (int(t.get("kv_lora_rank", 512)) + 2) * 4
+ return select + ((topk + 515) // 512) * prefill_rows * heads * (int(t.get("kv_lora_rank", 512)) + 2) * 4
@@ -92,12 +97,12 @@ index ee444c2..908f94e 100644
return select + 128 * heads * (kd + 2) * 4 * ((topk + 515) // 512)
diff --git tensorfold/families/glm5_next/cuda/engine.py tensorfold/families/glm5_next/cuda/engine.py
-index c46aa52..ff49a2a 100644
+index 47d2a02..1c11a54 100644
--- tensorfold/families/glm5_next/cuda/engine.py
+++ tensorfold/families/glm5_next/cuda/engine.py
-@@ -18,10 +18,10 @@ GRAPH_ROWS = (1, 2, 3, 4, 5, 6) # verify windows captured as CUDA graphs
- MAX_ROWS = 8 # the widest verify window (a pending token and up to 7 drafts)
- DENSE_CAPACITY = 2560 # cache slots while DSA attention stays dense (contexts up to 2,051 tokens)
+@@ -20,10 +20,10 @@ DENSE_CAPACITY = 2560 # cache slots while DSA attention stays de
+ # TF_GLM_DRAFT_RING=0: DFlash2's context in a flat buffer of the whole window, not a 2,176-row ring (the same drafts)
+ DRAFT_RING = os.environ.get("TF_GLM_DRAFT_RING", "1").strip() != "0"
# --vision (rank 0): what startup reserves beside the tower's 1.05 GiB of bf16 weights for an encode and its
-# prompt's feature rows. Measured peaks: 0.47 GiB (a 2,048-token picture), 0.56 (four), 1.08 (a 16,384-token clip,
-# 16,384 patches a pass), 1.73 (an 8,000-token picture, one 31,724-patch pass). A picture cap past 4,096 tokens
@@ -110,10 +115,10 @@ index c46aa52..ff49a2a 100644
def vision_workspace() -> int:
-@@ -134,6 +134,13 @@ class GlmEngine:
- weights_estimate = split_weights(rule)
- if cfg.quant == "exl3" and dense_kind() == "fp8":
- weights_estimate = fp8_weights(weights_estimate)
+@@ -163,6 +163,13 @@ class GlmEngine:
+ self.mtp_on = mtp_head(drafter is not None, serial_only, cfg.mtp_layers)
+ if not self.mtp_on:
+ weights_estimate = without_mtp(weights_estimate, cfg.layers)
+ # rows a prompt chunk runs at once: TF_GLM_PREFILL_ROWS (both ranks alike), more amortizes each chunk's expert
+ # weight decode over more tokens and costs buffer memory
+ if prefill_rows is None:
@@ -124,24 +129,25 @@ index c46aa52..ff49a2a 100644
vision = bool(vision) and rank == 0
workspace = vision_workspace() if vision else 0
if vision: # the tower's bf16 weights, which the split rule drops
-@@ -146,7 +153,7 @@ class GlmEngine:
+@@ -175,7 +182,8 @@ class GlmEngine:
def geometry(text):
from tensorfold.cuda.capacity import Geometry
-- g = mla_geometry(text, 2, MAX_ROWS, minimum_slots=DENSE_CAPACITY, latent=LATENT)
-+ g = mla_geometry(text, 2, MAX_ROWS, minimum_slots=DENSE_CAPACITY, latent=LATENT, prefill_rows=prefill_rows)
+- g = mla_geometry(text, 2, MAX_ROWS, minimum_slots=DENSE_CAPACITY, latent=LATENT, mtp=self.mtp_on)
++ g = mla_geometry(text, 2, MAX_ROWS, minimum_slots=DENSE_CAPACITY, latent=LATENT, prefill_rows=prefill_rows,
++ mtp=self.mtp_on)
return Geometry(lambda slots: g.bytes_at(slots) + workspace, g.reserve, g.minimum_slots) if workspace else g
self.capacity_plan = admit(model_dir, context if explicit else cfg.dense_limit, explicit, torch,
geometry,
-@@ -156,7 +163,6 @@ class GlmEngine:
+@@ -186,7 +194,6 @@ class GlmEngine:
capacity = self.capacity_plan["cache_slots"]
long_context = self.limit > cfg.dense_limit
# both ranks must run the same calls: refuse to start when they were given different settings
- prefill_rows = PREFILL_ROWS if prefill_rows is None else int(prefill_rows)
mine = [int(drafter is not None), capacity, int(long_context), int(serial_only), int(LATENT),
- prefill_rows]
+ prefill_rows, int(self.mtp_on), int(DRAFT_RING)]
# other conversations' kept prompts get what the window leaves, at most TF_GLM_CACHE_GIB, the same on both ranks
-@@ -492,7 +498,11 @@ class GlmEngine:
+@@ -553,7 +560,11 @@ class GlmEngine:
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()
@@ -735,10 +741,10 @@ index 58e739d..71cd600 100644
+ w, nfirst, _pf(), nfirst and sk > 1 and _seq())
ext.down_epilogue(s.z, pick, ex.svh_d, y, R, P, D, sk, slots)
diff --git tensorfold/families/glm5_next/cuda/forward.py tensorfold/families/glm5_next/cuda/forward.py
-index f5f6179..31ff0ad 100644
+index 225109f..0e130f5 100644
--- tensorfold/families/glm5_next/cuda/forward.py
+++ tensorfold/families/glm5_next/cuda/forward.py
-@@ -86,17 +86,21 @@ class Buffers:
+@@ -98,17 +98,21 @@ class Buffers:
self.eact = torch.empty((rows * slots, ml), dtype=bf, device=dev)
exl3 = c.quant == "exl3"
self.ey = torch.empty((rows, slots, D), dtype=bf if prefill and not exl3 else f32, device=dev)
@@ -763,7 +769,7 @@ index f5f6179..31ff0ad 100644
# rank partials
self.part = torch.empty((rows, D), dtype=f32, device=dev)
self.gath = torch.empty((w.world * rows * D,), dtype=f32, device=dev)
-@@ -328,7 +332,7 @@ def _dsa_latent(a, w: Weights, lc: torch.Tensor, pos_dev: torch.Tensor, b: Buffe
+@@ -364,7 +368,7 @@ def _dsa_latent(a, w: Weights, lc: torch.Tensor, pos_dev: torch.Tensor, b: Buffe
glue.router(b.normed[:R], ix.gate, b.igr[:R])
sparse.index_update(b.ikr[:R, :c.index_dim], b.igr[:R], ix.ln_w, ix.ln_b, ix.ape, ik, ig, pk, pos_dev)
with prof.timed("dsa: absorb"):
@@ -772,7 +778,7 @@ index f5f6179..31ff0ad 100644
ol = s.ol[:R]
scale = c.qk_dim ** -0.5
if not all_sparse:
-@@ -343,7 +347,7 @@ def _dsa_latent(a, w: Weights, lc: torch.Tensor, pos_dev: torch.Tensor, b: Buffe
+@@ -379,7 +383,7 @@ def _dsa_latent(a, w: Weights, lc: torch.Tensor, pos_dev: torch.Tensor, b: Buffe
with prof.timed("dsa: sparse attention"):
latent.sparse_attention(qa, lc, tokens, counts, ol, scale)
with prof.timed("dsa: expand"):
@@ -781,7 +787,16 @@ index f5f6179..31ff0ad 100644
return out_proj(w, b, o, a.o, qmm.group_sums(o, b.xs_ao[:R]), R)
-@@ -393,7 +397,7 @@ def layer_forward(layer: LayerW, w: Weights, st: State, b: Buffers, R: int, nch:
+@@ -396,7 +400,7 @@ def moe_block(layer: LayerW, w: Weights, b: Buffers, R: int) -> torch.Tensor:
+ with prof.timed("moe: route"):
+ glue.router(b.normed[:R], m.router, b.mlog[:R])
+ glue.select(b.mlog[:R], m.bias, b.pick[:R], b.wts[:R], c.top_k, c.experts, c.routed_scale, c.norm_topk)
+- grouped.route(b.pick[:R], b.plan)
++ grouped.route(b.pick[:R], b.plan, b.plan.tile) # the plan keeps its pass (TF_GLM_EXL3_PASS)
+ if m.shared is not None:
+ # EXL3: the routed slots through the trellis kernels, the shared expert (last slot) through BF16 matmuls
+ from . import exl3_mm
+@@ -429,7 +433,7 @@ def layer_forward(layer: LayerW, w: Weights, st: State, b: Buffers, R: int, nch:
x = b.x[:R]
h = layer.attn_hc
glue.hc_pre(x, h.fn, h.base, h.scale, layer.in_norm, b.normed[:R], b.xs[:R], b.post[:R], b.comb[:R],
@@ -789,8 +804,8 @@ index f5f6179..31ff0ad 100644
+ b.hcpart[:R], c.eps, c.hc_eps, c.hc_iters, prompt=b.prefill)
if layer.kind == "kda":
with prof.timed("kda"):
- g = kda_block(layer, w, st, b, R)
-@@ -406,7 +410,7 @@ def layer_forward(layer: LayerW, w: Weights, st: State, b: Buffers, R: int, nch:
+ g = kda_block(layer, w, st, b, R, cut)
+@@ -442,7 +446,7 @@ 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])
h = layer.ffn_hc
glue.hc_pre(x, h.fn, h.base, h.scale, layer.post_norm, b.normed[:R], b.xs[:R], b.post[:R], b.comb[:R],
@@ -855,7 +870,7 @@ index 0a6a4f1..84f0dbe 100644
ITERS=iters, BLOCK=d, num_warps=8)
diff --git tensorfold/families/glm5_next/cuda/latent.py tensorfold/families/glm5_next/cuda/latent.py
-index d84b5c6..2e2a32e 100644
+index cec1ff1..1fac95e 100644
--- tensorfold/families/glm5_next/cuda/latent.py
+++ tensorfold/families/glm5_next/cuda/latent.py
@@ -154,14 +154,64 @@ def _expand_v4(OL, WW, WS, WB, OUT, R, H: tl.constexpr, DV: tl.constexpr, LW: tl
@@ -944,7 +959,7 @@ index d84b5c6..2e2a32e 100644
BN = 16
_expand_v4[(H, a.v_dim // BN)](o_lat, a.wvw, a.wvs, a.wvb, out, R, H=H, DV=a.v_dim, LW=a.lw, BN=BN,
diff --git tensorfold/families/glm5_next/cuda/qmm.py tensorfold/families/glm5_next/cuda/qmm.py
-index 827db2b..b845afa 100644
+index 827db2b..ca8a066 100644
--- tensorfold/families/glm5_next/cuda/qmm.py
+++ tensorfold/families/glm5_next/cuda/qmm.py
@@ -184,12 +184,38 @@ def stack_b16(parts: list[torch.Tensor]) -> B16:
diff --git a/patches/0005-glm-dense-q4.patch b/patches/0005-glm-dense-q4.patch
index 47e64a6..8ab6c8b 100644
--- a/patches/0005-glm-dense-q4.patch
+++ b/patches/0005-glm-dense-q4.patch
@@ -1,8 +1,8 @@
diff --git tensorfold/families/glm5_next/cuda/engine.py tensorfold/families/glm5_next/cuda/engine.py
-index ff49a2a..0ed6ec3 100644
+index 1c11a54..6492798 100644
--- tensorfold/families/glm5_next/cuda/engine.py
+++ tensorfold/families/glm5_next/cuda/engine.py
-@@ -128,12 +128,14 @@ class GlmEngine:
+@@ -153,12 +153,14 @@ class GlmEngine:
explicit = context is not None if context_explicit is None else bool(context_explicit)
from . import LATENT
@@ -15,11 +15,11 @@ index ff49a2a..0ed6ec3 100644
weights_estimate = fp8_weights(weights_estimate)
+ elif cfg.quant == "exl3" and dense_kind() == "q4":
+ weights_estimate = q4_weights(weights_estimate)
- # rows a prompt chunk runs at once: TF_GLM_PREFILL_ROWS (both ranks alike), more amortizes each chunk's expert
- # weight decode over more tokens and costs buffer memory
- if prefill_rows is None:
+ # TF_GLM_MTP off: the MTP layer's tensors, caches and buffers are neither loaded nor estimated
+ self.mtp_on = mtp_head(drafter is not None, serial_only, cfg.mtp_layers)
+ if not self.mtp_on:
diff --git tensorfold/families/glm5_next/cuda/qmm.py tensorfold/families/glm5_next/cuda/qmm.py
-index b845afa..ee83025 100644
+index ca8a066..6377c42 100644
--- tensorfold/families/glm5_next/cuda/qmm.py
+++ tensorfold/families/glm5_next/cuda/qmm.py
@@ -176,6 +176,49 @@ def quantize4(w: torch.Tensor, chunk: int = 8192) -> Q4:
@@ -109,10 +109,10 @@ index b845afa..ee83025 100644
"""A split_weights transform that counts the matrices held as FP8 at a byte a value plus their block scales."""
diff --git tensorfold/families/glm5_next/cuda/weights.py tensorfold/families/glm5_next/cuda/weights.py
-index f2d3cb8..2d6ab83 100644
+index fd9db9d..766a3b0 100644
--- tensorfold/families/glm5_next/cuda/weights.py
+++ tensorfold/families/glm5_next/cuda/weights.py
-@@ -265,15 +265,22 @@ def load(model_dir: str | Path, *, rank: int, device: str = "cuda") -> Weights:
+@@ -270,15 +270,22 @@ def load(model_dir: str | Path, *, rank: int, device: str = "cuda", mtp: bool =
return (as_i32(t(name + ".weight")), t(name + ".scales"), t(name + ".biases"))
# TF_GLM_DENSE=fp8: the BF16 matrices as FP8 with block scales (lossy, half the bytes a decode round reads)
diff --git a/patches/0006-cuda-roce-allgather.patch b/patches/0006-cuda-roce-allgather.patch
index eea9ecf..338aa2b 100644
--- a/patches/0006-cuda-roce-allgather.patch
+++ b/patches/0006-cuda-roce-allgather.patch
@@ -1010,10 +1010,10 @@ index 0000000..5e605ae
+ free(c);
+}
diff --git tensorfold/families/glm5_next/cuda/engine.py tensorfold/families/glm5_next/cuda/engine.py
-index 0ed6ec3..cb8d750 100644
+index 6492798..53ddda9 100644
--- tensorfold/families/glm5_next/cuda/engine.py
+++ tensorfold/families/glm5_next/cuda/engine.py
-@@ -123,6 +123,15 @@ class GlmEngine:
+@@ -148,6 +148,15 @@ class GlmEngine:
self.serial_only = serial_only
self.comm = comm if comm is not None else NCCL(rank, 2, master, port)
self.comm.barrier()
@@ -1029,7 +1029,7 @@ index 0ed6ec3..cb8d750 100644
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)
-@@ -526,6 +535,8 @@ class GlmEngine:
+@@ -589,6 +598,8 @@ class GlmEngine:
self._share(positions)
stats = self._run(list(prompt), max_tokens, sampling, stop_eos, on_tokens, code, hit, draft, constraint, feed)
stats.update(policy=spec, drafts=draft)
@@ -1038,7 +1038,7 @@ index 0ed6ec3..cb8d750 100644
if feed is not None:
stats.update(image_rows=len(positions), encode_s=round(feed.encode_s, 3))
return stats
-@@ -557,6 +568,8 @@ class GlmEngine:
+@@ -621,6 +632,8 @@ class GlmEngine:
raise RuntimeError(f"rank 1 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)
diff --git a/patches/0007-glm-copy-drafts.patch b/patches/0007-glm-copy-drafts.patch
index e015ffa..5334a82 100644
--- a/patches/0007-glm-copy-drafts.patch
+++ b/patches/0007-glm-copy-drafts.patch
@@ -120,10 +120,10 @@ index 0000000..25e4be7
+ s = int(full[-1]) if full.size else int(hits[0])
+ return self.buf[s + n:min(s + n + k, L)].tolist()
diff --git tensorfold/families/glm5_next/cuda/decode.py tensorfold/families/glm5_next/cuda/decode.py
-index 1df65cf..6bde10d 100644
+index 4850d92..7c7cf73 100644
--- tensorfold/families/glm5_next/cuda/decode.py
+++ tensorfold/families/glm5_next/cuda/decode.py
-@@ -377,8 +377,11 @@ class DecodeResult:
+@@ -430,8 +430,11 @@ class DecodeResult:
stages: dict[str, float] = field(default_factory=dict)
depths: list[int] = field(default_factory=list)
keeps: list[int] = field(default_factory=list)
@@ -136,7 +136,7 @@ index 1df65cf..6bde10d 100644
@property
def tokens_per_second(self) -> float:
-@@ -436,23 +439,35 @@ class DepthPolicy:
+@@ -489,23 +492,35 @@ class DepthPolicy:
return max(1, min(self.most, 1 if self.rate < self.low else 2 if self.rate < self.high else 3))
@@ -176,7 +176,7 @@ index 1df65cf..6bde10d 100644
stages["draft"] += time.perf_counter() - t0
while len(out) < count and not (stop_eos and out[-1] in w.cfg.eos):
t0 = time.perf_counter()
-@@ -474,10 +489,14 @@ def mtp_decode(e: Engine, pending: int, count: int, sampling: Sampling | None, *
+@@ -527,10 +542,14 @@ def mtp_decode(e: Engine, pending: int, count: int, sampling: Sampling | None, *
rounds += 1
drafted += len(drafts)
accepted += keep - 1
@@ -191,7 +191,7 @@ index 1df65cf..6bde10d 100644
if on_tokens is not None:
on_tokens(sampled[:keep][:max(0, count - (len(out) - keep))])
stages["forward"] += t1 - t0
-@@ -486,24 +505,33 @@ def mtp_decode(e: Engine, pending: int, count: int, sampling: Sampling | None, *
+@@ -539,24 +558,33 @@ def mtp_decode(e: Engine, pending: int, count: int, sampling: Sampling | None, *
if len(out) >= count or (stop_eos and out[-1] in w.cfg.eos):
break
t4 = time.perf_counter()
@@ -231,7 +231,7 @@ index 1df65cf..6bde10d 100644
depths: list[int] = []
keeps: list[int] = []
_sync(w)
-@@ -511,7 +539,11 @@ def dflash_decode(e: Engine, drafter, pending: int, count: int, sampling: Sampli
+@@ -564,7 +592,11 @@ def dflash_decode(e: Engine, drafter, pending: int, count: int, sampling: Sampli
depth = min(policy.next(0, 0), count - len(out))
while len(out) < count and not (stop_eos and out[-1] in w.cfg.eos):
t0 = time.perf_counter()
@@ -244,7 +244,7 @@ index 1df65cf..6bde10d 100644
t1 = time.perf_counter()
tokens = e.verify_window([out[-1]] + drafts)
drafts = tokens[1:]
-@@ -533,16 +565,22 @@ def dflash_decode(e: Engine, drafter, pending: int, count: int, sampling: Sampli
+@@ -586,16 +618,22 @@ def dflash_decode(e: Engine, drafter, pending: int, count: int, sampling: Sampli
rounds += 1
drafted += len(drafts)
accepted += keep - 1
@@ -349,11 +349,11 @@ index e018386..b14a7e9 100644
- m_rows[:len(m_next)])
+ m_rows[:len(m_next)], c_rounds, c_drafted, c_accepted)
diff --git tensorfold/families/glm5_next/cuda/engine.py tensorfold/families/glm5_next/cuda/engine.py
-index cb8d750..13d3262 100644
+index 53ddda9..62a1117 100644
--- tensorfold/families/glm5_next/cuda/engine.py
+++ tensorfold/families/glm5_next/cuda/engine.py
-@@ -116,6 +116,11 @@ class GlmEngine:
- from tensorfold.cuda.geometry import PREFILL_ROWS, draft_geometry, mla_geometry, split_weights
+@@ -141,6 +141,11 @@ class GlmEngine:
+ split_weights)
encode_policy(policy) # a bad default fails here, not in the first request
+ from .copy_drafts import CopySettings
@@ -364,25 +364,25 @@ index cb8d750..13d3262 100644
torch.cuda.set_device(0)
self.torch = torch
self.rank = rank
-@@ -175,7 +180,7 @@ class GlmEngine:
+@@ -206,7 +211,7 @@ class GlmEngine:
long_context = self.limit > cfg.dense_limit
# both ranks 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]
-+ prefill_rows] + (self.copy.code() if self.copy is not None else [0, 0])
+- prefill_rows, int(self.mtp_on), int(DRAFT_RING)]
++ prefill_rows] + (self.copy.code() if self.copy is not None else [0, 0]) + [int(self.mtp_on), int(DRAFT_RING)]
# other conversations' kept prompts get what the window leaves, at most TF_GLM_CACHE_GIB, the same on both ranks
plan = self.capacity_plan
wanted = int(float(os.environ.get("TF_GLM_CACHE_GIB", "3")) * 2 ** 30)
-@@ -183,7 +188,7 @@ class GlmEngine:
+@@ -214,7 +219,7 @@ class GlmEngine:
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, "
-- "TF_GLM_LATENT): "
-+ "TF_GLM_LATENT, TF_GLM_COPY_*): "
+- "TF_GLM_LATENT, TF_GLM_MTP, TF_GLM_DRAFT_RING): "
++ "TF_GLM_LATENT, TF_GLM_COPY_*, TF_GLM_MTP, TF_GLM_DRAFT_RING): "
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
-@@ -456,6 +461,11 @@ class GlmEngine:
+@@ -518,6 +523,11 @@ class GlmEngine:
if max_tokens <= 1 or (stop_eos and first in self.eos):
return stats
policy = decode_policy(code)
@@ -394,7 +394,7 @@ index cb8d750..13d3262 100644
if policy is None:
res = serial_decode(self.e, first, max_tokens, sampling, stop_eos=stop_eos, on_tokens=on_tokens)
elif auto:
-@@ -468,13 +478,13 @@ class GlmEngine:
+@@ -530,13 +540,13 @@ class GlmEngine:
margin=margin)
res = auto_decode(self.e, drafter, first, max_tokens, sampling, choice=choice, m_policy=m_policy,
f_policy=DepthPolicy(5, fixed=True, confidence=0.3), stop_eos=stop_eos,
@@ -411,7 +411,7 @@ index cb8d750..13d3262 100644
# the caches now hold prompt and reply; only prompts are snapshotted, since a later prompt prefills the reply again
if feed is None:
self.live = list(prompt) + res.tokens[:self.e.st.pos - len(prompt)]
-@@ -483,6 +493,10 @@ class GlmEngine:
+@@ -545,6 +555,10 @@ class GlmEngine:
sha256=hashlib.sha256(json.dumps(res.tokens).encode()).hexdigest()[:16])
if res.arms:
stats.update(drafters=res.arms, keeps=res.keeps)
diff --git a/patches/0008-glm-prompt-grid.patch b/patches/0008-glm-prompt-grid.patch
index fb5fb85..e8b0320 100644
--- a/patches/0008-glm-prompt-grid.patch
+++ b/patches/0008-glm-prompt-grid.patch
@@ -1,5 +1,5 @@
diff --git tensorfold/families/glm5_next/cuda/decode.py tensorfold/families/glm5_next/cuda/decode.py
-index 6bde10d..fdc7c53 100644
+index 7c7cf73..b16ad04 100644
--- tensorfold/families/glm5_next/cuda/decode.py
+++ tensorfold/families/glm5_next/cuda/decode.py
@@ -84,8 +84,13 @@ class Engine:
@@ -17,18 +17,18 @@ index 6bde10d..fdc7c53 100644
w.meta["long_context"] = long_context
self.rows, self.prefill_rows = max_rows, prefill_rows
self.buf = Buffers(w, max_rows, capacity)
-@@ -310,8 +315,8 @@ def restore(e: Engine, snap: Snapshot, drafter=None) -> None:
+@@ -341,8 +346,8 @@ def restore(e: Engine, snap: Snapshot, drafter=None) -> None:
# -- prefill ----------------------------------------------------------------------------------------------------
@torch.no_grad()
def prefill(e: Engine, prompt: Sequence[int], sampling: Sampling | None, *, mtp: bool = True, drafter=None,
-- resume: Snapshot | None = None, feed=None) -> int:
+- resume: Snapshot | None = None, keep_at: int | None = None, keep=None, feed=None) -> int:
- """Commit the prompt in chunks and sample its first token; a resumed prompt ends in a fresh prefill's state; ``feed``: an image prompt's feature rows (``engine.VisionFeed``)."""
+ resume: Snapshot | None = None, feed=None, sample: bool = True) -> int | None:
+ """Commit the prompt in chunks and sample its first token; a resumed prompt ends in a fresh prefill's state; ``feed``: an image prompt's feature rows (``engine.VisionFeed``); ``sample=False``: commit only (no head, no first token, None), leaving the state a prompt of this length leaves before its sample."""
if not prompt:
raise ValueError("prefill requires at least one token")
-@@ -324,6 +329,8 @@ def prefill(e: Engine, prompt: Sequence[int], sampling: Sampling | None, *, mtp:
+@@ -355,6 +360,8 @@ def prefill(e: Engine, prompt: Sequence[int], sampling: Sampling | None, *, mtp:
drafter.reset()
else:
begin = len(resume.ids)
@@ -37,19 +37,52 @@ index 6bde10d..fdc7c53 100644
if begin >= len(prompt) or list(prompt[:begin]) != resume.ids:
raise ValueError("a resumed prefill needs a snapshot of a strict prefix of the prompt")
if (use_mtp and resume.mtp_len < 0) or (drafter is not None and resume.drafter_end != begin):
-@@ -338,7 +345,9 @@ def prefill(e: Engine, prompt: Sequence[int], sampling: Sampling | None, *, mtp:
+@@ -363,36 +370,18 @@ def prefill(e: Engine, prompt: Sequence[int], sampling: Sampling | None, *, mtp:
+ if use_mtp:
+ k = resume.pending.shape[0]
+ _absorb_rows(e, resume.pending, list(prompt[begin - k + 1:begin + 1]))
+- from .forward import Cut
+-
+- if keep_at is not None and (keep is None or not max(1, begin) <= keep_at <= len(prompt)):
+- raise ValueError("a kept prefix needs a callback and a point in the prompt's prefill")
+- kept = resume if keep_at == begin else None
+ last = None
+ prof.active = True
+ for start in range(begin, len(prompt), e.prefill_rows):
chunk = list(prompt[start:start + e.prefill_rows])
R = len(chunk)
+- point = keep_at - start if keep_at is not None else 0
+- cut = Cut(point, torch.empty_like(st.rec[0]), st.conv.clone()) if 0 < point < R else None
inject = feed.chunk(start, R) if feed is not None else None
-- last = compute(w, st, b, stage(w, st, b, chunk), nch=chunks_for(st, R), host_pos=st.pos, inject=inject).clone()
+- last = compute(w, st, b, stage(w, st, b, chunk), nch=chunks_for(st, R), host_pos=st.pos, cut=cut,
+- inject=inject).clone()
+ out = compute(w, st, b, stage(w, st, b, chunk), nch=chunks_for(st, R), host_pos=st.pos, inject=inject,
+ head=sample)
+ last = out.clone() if sample else None
e.last_hidden = b.fnormed[R - 1:R].clone()
+- if 0 < point <= R:
+- rec = cut.rec if cut is not None else st.rec[st.cur[0] if st.cur else 0].clone()
+- conv = cut.conv if cut is not None else st.conv.clone()
+- kept = Snapshot(list(prompt[:keep_at]), rec, conv,
+- b.fnormed[point - 1:point].clone() if use_mtp else None,
+- keep_at - 1 if use_mtp else -1, keep_at if drafter is not None else -1)
if drafter is not None:
drafter.add_taps(e.tap_rows(R, b))
-@@ -351,6 +360,8 @@ def prefill(e: Engine, prompt: Sequence[int], sampling: Sampling | None, *, mtp:
+- if 0 < point <= R and getattr(drafter, "ring", 0):
+- # a ring keeps the kept point's window unless this chunk wrote past it by more than the ring's slack
+- if R - point < drafter.ring - drafter.window:
+- kept.drafter_rows = _ring_window(drafter, keep_at)
+- else:
+- kept.drafter_end = -1
+ if use_mtp:
+ nxt = list(prompt[start + 1:start + R + 1])
+ if nxt:
+@@ -400,10 +389,10 @@ def prefill(e: Engine, prompt: Sequence[int], sampling: Sampling | None, *, mtp:
+ _absorb_rows(e, b.fnormed[:len(nxt)], nxt)
+ with prof.timed("commit"):
commit(w, st, b, R, R)
+- if kept is not None:
+- keep(kept)
prof.active = False
prof.report(len(prompt) - begin)
+ if not sample:
@@ -58,10 +91,10 @@ index 6bde10d..fdc7c53 100644
e.window = e.constraint.window([0], [-1])
first = e.sample(last, [len(prompt)], sampling)[0]
diff --git tensorfold/families/glm5_next/cuda/engine.py tensorfold/families/glm5_next/cuda/engine.py
-index 13d3262..63c5dd2 100644
+index 62a1117..b508ba0 100644
--- tensorfold/families/glm5_next/cuda/engine.py
+++ tensorfold/families/glm5_next/cuda/engine.py
-@@ -35,6 +35,40 @@ def vision_workspace() -> int:
+@@ -37,6 +37,40 @@ def vision_workspace() -> int:
return int(value) * 2**20
@@ -102,7 +135,7 @@ index 13d3262..63c5dd2 100644
def encode_policy(spec: str) -> list[int]:
"""Encode policy kind, maximum drafts, and two parameters in millionths as four integers, with 10 added to kind for DFlash2."""
-@@ -157,6 +191,8 @@ class GlmEngine:
+@@ -186,6 +220,8 @@ class GlmEngine:
prefill_rows = int(prefill_rows)
if not 64 <= prefill_rows <= 16384 or prefill_rows % 64:
raise ValueError(f"prefill rows: a multiple of 64 from 64 to 16,384, not {prefill_rows}")
@@ -111,27 +144,29 @@ index 13d3262..63c5dd2 100644
vision = bool(vision) and rank == 0
workspace = vision_workspace() if vision else 0
if vision: # the tower's bf16 weights, which the split rule drops
-@@ -180,7 +216,7 @@ class GlmEngine:
+@@ -211,7 +247,8 @@ class GlmEngine:
long_context = self.limit > cfg.dense_limit
# both ranks 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.copy.code() if self.copy is not None else [0, 0])
-+ prefill_rows, self.grid] + (self.copy.code() if self.copy is not None else [0, 0])
+- prefill_rows] + (self.copy.code() if self.copy is not None else [0, 0]) + [int(self.mtp_on), int(DRAFT_RING)]
++ prefill_rows, self.grid] + (self.copy.code() if self.copy is not None else [0, 0]) + \
++ [int(self.mtp_on), int(DRAFT_RING)]
# other conversations' kept prompts get what the window leaves, at most TF_GLM_CACHE_GIB, the same on both ranks
plan = self.capacity_plan
wanted = int(float(os.environ.get("TF_GLM_CACHE_GIB", "3")) * 2 ** 30)
-@@ -188,7 +224,7 @@ class GlmEngine:
+@@ -219,7 +256,8 @@ class GlmEngine:
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, "
-- "TF_GLM_LATENT, TF_GLM_COPY_*): "
-+ "TF_GLM_LATENT, TF_GLM_PREFILL_ROWS, TF_GLM_PROMPT_GRID, TF_GLM_COPY_*): "
+- "TF_GLM_LATENT, TF_GLM_COPY_*, TF_GLM_MTP, TF_GLM_DRAFT_RING): "
++ "TF_GLM_LATENT, TF_GLM_PREFILL_ROWS, TF_GLM_PROMPT_GRID, TF_GLM_COPY_*, TF_GLM_MTP, "
++ "TF_GLM_DRAFT_RING): "
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
-@@ -212,7 +248,11 @@ class GlmEngine:
+@@ -248,7 +286,11 @@ class GlmEngine:
- self.drafter = Drafter(drafter, w, capacity=capacity)
+ self.drafter = Drafter(drafter, w, capacity=capacity, ring=DRAFT_RING)
self.e = Engine(w, capacity=capacity, max_rows=MAX_ROWS, prefill_rows=prefill_rows, graphs=True, graph_rows=GRAPH_ROWS,
- long_context=long_context, taps=self.drafter.tap_layers if self.drafter is not None else ())
+ long_context=long_context, taps=self.drafter.tap_layers if self.drafter is not None else (),
@@ -142,7 +177,7 @@ index 13d3262..63c5dd2 100644
if self.drafter is not None:
self.drafter.capture()
self.costs = self._calibrate()
-@@ -362,6 +402,7 @@ class GlmEngine:
+@@ -426,6 +468,7 @@ class GlmEngine:
best = None
for snap in self.cache:
fits = (not dflash or snap.drafter_end == len(snap.ids)) and (not mtp or snap.mtp_len >= 0)
@@ -150,11 +185,21 @@ index 13d3262..63c5dd2 100644
if fits and len(snap.ids) < len(prompt) and prompt[:len(snap.ids)] == snap.ids and (
best is None or len(snap.ids) > len(best.ids)):
best = snap
-@@ -451,11 +492,26 @@ class GlmEngine:
+@@ -499,7 +542,7 @@ class GlmEngine:
+ def _run_once(self, prompt: list[int], max_tokens: int, sampling, stop_eos: bool,
+ on_tokens: Callable[[list[int]], Any], code: list[int], hit, draft: bool,
+ feed=None) -> dict[str, Any]:
+- from .decode import DepthPolicy, dflash_decode, mtp_decode, prefill, serial_decode
++ from .decode import DepthPolicy, dflash_decode, mtp_decode, prefill, serial_decode, take_snapshot
+ from .drafter_choice import DrafterChoice, auto_decode
+
+ auto, use_mtp, use_dflash = self._drafters(code)
+@@ -515,9 +558,26 @@ class GlmEngine:
hit.rows, hit.nbytes = None, 0 # live again
# an image prompt's rows are not its token ids' rows: nothing resumes from them, and they are not kept
self.live = list(prompt) if feed is None else []
-- first = prefill(self.e, prompt, sampling, mtp=use_mtp, drafter=drafter, resume=hit, feed=feed)
+- first = prefill(self.e, prompt, sampling, mtp=use_mtp, drafter=drafter, resume=hit, feed=feed,
+- keep_at=max(1, len(prompt) - 1) if draft and feed is None else None, keep=self._remember)
+ # a drafted text prompt keeps its state at ``point``: its end, or with TF_GLM_PROMPT_GRID the last grid
+ # multiple in it. Short of the end, the prompt prefills to the point as a prompt of that length would (no
+ # first token), keeps that state, and resumes from it as a later request would: so any prompt extending
@@ -168,9 +213,6 @@ index 13d3262..63c5dd2 100644
+ drafter=drafter)
+ first = prefill(self.e, prompt, sampling, mtp=use_mtp, drafter=drafter, resume=resume, feed=feed)
prefill_s = time.perf_counter() - t0
-- if draft and feed is None:
-- self._remember(take_snapshot(self.e, prompt, self.e.last_hidden if use_mtp else None, mtp=use_mtp,
-- drafter=drafter))
+ if point == len(prompt):
+ kept = take_snapshot(self.e, prompt, self.e.last_hidden if use_mtp else None, mtp=use_mtp,
+ drafter=drafter)
@@ -182,19 +224,103 @@ index 13d3262..63c5dd2 100644
on_tokens([first])
if max_tokens <= 1 or (stop_eos and first in self.eos):
diff --git tensorfold/families/glm5_next/cuda/forward.py tensorfold/families/glm5_next/cuda/forward.py
-index 31ff0ad..cf16c8f 100644
+index 0e130f5..a5a4180 100644
--- tensorfold/families/glm5_next/cuda/forward.py
+++ tensorfold/families/glm5_next/cuda/forward.py
-@@ -440,7 +440,7 @@ def stage(w: Weights, st: State, b: Buffers, tokens: Sequence[int]) -> int:
+@@ -2,7 +2,6 @@
+
+ from __future__ import annotations
+
+-from dataclasses import dataclass
+ from typing import Sequence
+
+ import torch
+@@ -18,15 +17,6 @@ from .attention import AttnScratch, attention, kv_write
+ from .weights import LayerW, Weights
+
+
+-@dataclass
+-class Cut:
+- """The recurrent state and convolution windows at an interior prompt row."""
+-
+- point: int
+- rec: torch.Tensor
+- conv: torch.Tensor
+-
+-
+ class Buffers:
+ """Scratch for windows of up to ``rows`` rows, sliced [:R] for smaller ones; ``prefill`` for prompt chunks."""
+
+@@ -259,7 +249,7 @@ def out_proj(w: Weights, b: Buffers, x: torch.Tensor, q: qmm.Q4, xs: torch.Tenso
+ return gather(w, b, R)
+
+
+-def kda_block(layer: LayerW, w: Weights, st: State, b: Buffers, R: int, cut: Cut | None = None) -> torch.Tensor:
++def kda_block(layer: LayerW, w: Weights, st: State, b: Buffers, R: int) -> torch.Tensor:
+ c = w.cfg
+ k = layer.kda
+ li = st.kda_index[layer.index]
+@@ -273,18 +263,9 @@ def kda_block(layer: LayerW, w: Weights, st: State, b: Buffers, R: int, cut: Cut
+ mm(b, ga, k.gb, None if pre else qmm.group_sums(ga, b.xs_ga[:R]), b.kg[:R])
+ cur = st.cur[li]
+ with prof.timed("kda: recurrence"):
+- if cut is None:
+- out = kda_mod.chain(p, k.b_off, b.ka[:R], b.kg[:R], st.conv[li], k.conv, st.rec[cur, li], k.a_log,
+- k.dt_bias, k.norm, c.eps, c.lower, R, b.kscratch if pre else st.scratch[li],
+- st.rec[1 - cur, li])
+- else:
+- n = cut.point
+- first = kda_mod.chain(p[:n], k.b_off, b.ka[:n], b.kg[:n], st.conv[li], k.conv, st.rec[cur, li],
+- k.a_log, k.dt_bias, k.norm, c.eps, c.lower, n, b.kscratch, cut.rec[li]).clone()
+- _shift_conv(cut.conv[li:li + 1], b.kproj[:, :n], n)
+- rest = kda_mod.chain(p[n:], k.b_off, b.ka[n:R], b.kg[n:R], cut.conv[li], k.conv, cut.rec[li],
+- k.a_log, k.dt_bias, k.norm, c.eps, c.lower, R - n, b.kscratch, st.rec[1 - cur, li])
+- out = torch.cat((first, rest))
++ out = kda_mod.chain(p, k.b_off, b.ka[:R], b.kg[:R], st.conv[li], k.conv, st.rec[cur, li], k.a_log,
++ k.dt_bias, k.norm, c.eps, c.lower, R, b.kscratch if pre else st.scratch[li],
++ st.rec[1 - cur, li])
+ if pre: # a prompt chunk keeps every row: the layer commits now
+ st.cur[li] = 1 - cur
+ _shift_conv(st.conv[li:li + 1], b.kproj[:, :R], R)
+@@ -428,7 +409,7 @@ def moe_block(layer: LayerW, w: Weights, b: Buffers, R: int) -> torch.Tensor:
+
+
+ def layer_forward(layer: LayerW, w: Weights, st: State, b: Buffers, R: int, nch: int | None = None,
+- host_pos: int | None = None, sparse_np: int | None = None, cut: Cut | None = None) -> None:
++ host_pos: int | None = None, sparse_np: int | None = None) -> None:
+ c = w.cfg
+ x = b.x[:R]
+ h = layer.attn_hc
+@@ -436,7 +417,7 @@ def layer_forward(layer: LayerW, w: Weights, st: State, b: Buffers, R: int, nch:
+ b.hcpart[:R], c.eps, c.hc_eps, c.hc_iters, prompt=b.prefill)
+ if layer.kind == "kda":
+ with prof.timed("kda"):
+- g = kda_block(layer, w, st, b, R, cut)
++ g = kda_block(layer, w, st, b, R)
+ else:
+ di = st.dsa_index[layer.index]
+ with prof.timed("dsa (total)"):
+@@ -476,24 +457,24 @@ def stage(w: Weights, st: State, b: Buffers, tokens: Sequence[int]) -> int:
def compute(w: Weights, st: State, b: Buffers, R: int, *, logits: bool = True, nch: int | None = None,
-- host_pos: int | None = None, sparse_np: int | None = None, inject=None):
+- host_pos: int | None = None, sparse_np: int | None = None, cut: Cut | None = None, inject=None):
+ host_pos: int | None = None, sparse_np: int | None = None, inject=None, head: bool = True):
"""Run capturable GPU work on static buffers and device positions; eager long contexts use host_pos (graphs sparse_np) to select sparse attention; ``inject``: (rows, features) replacing those rows' embeddings (an image prompt's tower output, on every hyper-connection stream)."""
+- if cut is not None and (not b.prefill or not 0 < cut.point < R):
+- raise ValueError("a prompt cut must lie inside a prefill chunk")
c = w.cfg
-@@ -456,6 +456,8 @@ def compute(w: Weights, st: State, b: Buffers, R: int, *, logits: bool = True, n
+ 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))
+ for layer in w.layers:
+- layer_forward(layer, w, st, b, R, nch, host_pos, sparse_np, cut)
++ layer_forward(layer, w, st, b, R, nch, host_pos, sparse_np)
+ for slot in b.tap_at.get(layer.index, ()):
+ glue.stream_mean(b.x[:R], b.taps[slot][:R])
+ glue.stream_mean(b.x[:R], b.hidden[:R])
if not logits:
return None
glue.rmsnorm(b.hidden[:R], w.norm, c.eps, b.fnormed[:R], b.fxs[:R])
diff --git a/patches/0009-glm-prefill-kernels.patch b/patches/0009-glm-prefill-kernels.patch
index 1f88b28..fc095e2 100644
--- a/patches/0009-glm-prefill-kernels.patch
+++ b/patches/0009-glm-prefill-kernels.patch
@@ -373,10 +373,10 @@ index 71cd600..5e21f90 100644
if plan.tile != grouped.TILE:
raise ValueError("the EXL3 kernel takes items of 16 pairs")
diff --git tensorfold/families/glm5_next/cuda/forward.py tensorfold/families/glm5_next/cuda/forward.py
-index cf16c8f..6c81ba8 100644
+index a5a4180..a961a94 100644
--- tensorfold/families/glm5_next/cuda/forward.py
+++ tensorfold/families/glm5_next/cuda/forward.py
-@@ -312,6 +312,16 @@ def dsa_block(layer: LayerW, w: Weights, kc: torch.Tensor, vc: torch.Tensor, pos
+@@ -314,12 +314,23 @@ def dsa_block(layer: LayerW, w: Weights, kc: torch.Tensor, vc: torch.Tensor, pos
return out_proj(w, b, o, a.o, None if b.prefill else qmm.group_sums(o, b.xs_ao[:R]), R)
@@ -390,10 +390,20 @@ index cf16c8f..6c81ba8 100644
+ return min(R, max(0, sparse.SPARSE_FROM - host_pos))
+
+
- def _dsa_latent(a, w: Weights, lc: torch.Tensor, pos_dev: torch.Tensor, b: Buffers, R: int, nch: int | None,
- index, host_pos: int | None, sparse_np: int | None = None) -> torch.Tensor:
- """DSA on the latent cache: the same indexer and selection, attention over latents with kv_b's key blocks absorbed into the query."""
-@@ -336,16 +346,22 @@ def _dsa_latent(a, w: Weights, lc: torch.Tensor, pos_dev: torch.Tensor, b: Buffe
+ def dense_attention(qa: torch.Tensor, lc: torch.Tensor, pos_dev: torch.Tensor, s: latent.LatentScratch, *,
+- scale: float, nch: int, out: torch.Tensor) -> torch.Tensor:
+- """``latent.attention`` in blocks of ``part_rows`` rows, each at its first row's position: one call's bits a row."""
++ scale: float, nch: int, out: torch.Tensor, hb: int | None = None) -> torch.Tensor:
++ """``latent.attention`` in blocks of ``part_rows`` rows, each at its first row's position: one call's bits a row
++ (``hb``: the window's ``head_block``, which a window's first rows computed alone keep)."""
+
+ R, step = qa.shape[0], s.part_rows
+- hb = latent.head_block(R)
++ hb = latent.head_block(R) if hb is None else hb
+ if R <= step:
+ return latent.attention(qa, lc, pos_dev, s, scale=scale, nch=nch, out=out, hb=hb)
+ for r0 in range(0, R, step):
+@@ -353,16 +364,22 @@ def _dsa_latent(a, w: Weights, lc: torch.Tensor, pos_dev: torch.Tensor, b: Buffe
ol = s.ol[:R]
scale = c.qk_dim ** -0.5
if not all_sparse:
@@ -402,9 +412,9 @@ index cf16c8f..6c81ba8 100644
+ # and only the rows before it (a row's dense bits do not depend on the rows after it: latent.attention).
+ dense = dense_rows(c, R, host_pos) if sparse_rows else R
with prof.timed("dsa: dense attention"):
-- latent.attention(qa, lc, pos_dev, s, scale=scale, nch=min(nch or s.nch, s.nch), out=ol)
-+ latent.attention(qa[:dense], lc, pos_dev, s, scale=scale, nch=min(nch or s.nch, s.nch), out=ol[:dense],
-+ hb=latent.head_block(R))
+- dense_attention(qa, lc, pos_dev, s, scale=scale, nch=min(nch or s.nch, s.nch), out=ol)
++ dense_attention(qa[:dense], lc, pos_dev, s, scale=scale, nch=min(nch or s.nch, s.nch), out=ol[:dense],
++ hb=latent.head_block(R))
if sparse_rows:
with prof.timed("dsa: select tokens"):
mm(b, b.qr[:R], ix.qb, b.xs_qr[:R], b.qi[:R])
@@ -419,7 +429,7 @@ index cf16c8f..6c81ba8 100644
with prof.timed("dsa: expand"):
o = latent.expand_v(ol, a.absorb, b.vn[:R], prompt=b.prefill and latent.PROMPT_MMA).view(R, HL * c.v_dim)
return out_proj(w, b, o, a.o, qmm.group_sums(o, b.xs_ao[:R]), R)
-@@ -377,8 +393,11 @@ def moe_block(layer: LayerW, w: Weights, b: Buffers, R: int) -> torch.Tensor:
+@@ -394,8 +411,11 @@ def moe_block(layer: LayerW, w: Weights, b: Buffers, R: int) -> torch.Tensor:
glue.swiglu(b.sgu[:R], b.sact[:R], b.sxs[:R], c.limit)
mm(b, b.sact[:R], s.down, b.sxs[:R], b.sy[:R], f32=True)
with prof.timed("moe: combine"):
@@ -467,7 +477,7 @@ index 84f0dbe..dbde3f1 100644
+ block = min(1024, d)
+ _combine_sy[(rows, d // block)](y, sy, wts, out, D=d, SLOTS=wts.shape[1], BLOCK=block, num_warps=4)
diff --git tensorfold/families/glm5_next/cuda/latent.py tensorfold/families/glm5_next/cuda/latent.py
-index 2e2a32e..62cc861 100644
+index 1fac95e..55e7e77 100644
--- tensorfold/families/glm5_next/cuda/latent.py
+++ tensorfold/families/glm5_next/cuda/latent.py
@@ -273,6 +273,21 @@ def _tile(q, kv, m, l, o, valid, SCALE: tl.constexpr):
@@ -571,30 +581,28 @@ index 2e2a32e..62cc861 100644
@triton.jit
def _merge(PO, PM, PL, OUT, CNT, R, H: tl.constexpr, LW: tl.constexpr, NCH: tl.constexpr, SPARSE: tl.constexpr):
"""Program (row, head): the row's chunk partials in chunk order -> OUT[r, h] bf16. Sparse: rows with CNT 0 skip."""
-@@ -371,14 +458,19 @@ class LatentScratch:
-
+@@ -373,7 +460,10 @@ class LatentScratch:
def attention(qa: torch.Tensor, cache: torch.Tensor, pos: torch.Tensor, s: LatentScratch, *, scale: float,
-- nch: int, out: torch.Tensor) -> torch.Tensor:
-- """Dense causal attention of qa [R, H, 512] over the cache through pos + R - 1, visiting nch 512-key chunks (empty ones skipped) -> out [R, H, 512]."""
-+ nch: int, out: torch.Tensor, hb: int | None = None) -> torch.Tensor:
+ nch: int, out: torch.Tensor, hb: int | None = None) -> torch.Tensor:
+- """Dense causal attention of qa [R, H, 512] through pos + R - 1 in nch 512-key chunks; a row ignores the others."""
+ """Dense causal attention of qa [R, H, 512] over the cache through pos + R - 1, visiting nch 512-key chunks (empty ones skipped) -> out [R, H, 512].
+
+ Row r's programs read only its query, keys 0 .. pos + r and its own partials, so the first rows of a window
+ computed alone (``qa[:n]``, the same nch and ``hb``: the window's ``head_block``) get the window's bits."""
R, H, LW = qa.shape
- if nch > s.nch or R > s.rows or LW != s.lw:
+ if nch > s.nch or R > s.part_rows or LW != s.lw:
raise ValueError(f"latent attention: {R} rows, {nch} chunks, width {LW} past the scratch's "
- f"{s.rows}, {s.nch}, {s.lw}")
+@@ -381,7 +471,7 @@ def attention(qa: torch.Tensor, cache: torch.Tensor, pos: torch.Tensor, s: Laten
n = nch * R * H
-- hb = head_block(R)
-+ hb = head_block(R) if hb is None else hb
-+ if hb not in (HB, HB_WIDE):
+ hb = head_block(R) if hb is None else hb
+ if hb not in (HB, HB_WIDE):
+- raise ValueError(f"latent attention: {hb} heads a program, not {HB} or {HB_WIDE}")
+ raise ValueError(f"latent attention: {hb} heads a tile, not {HB} or {HB_WIDE}")
_dense_chunks[(R, triton.cdiv(H, hb), nch)](qa, cache, pos, s.po[:n * LW], s.pm[:n], s.pl[:n], R, H=H, LW=LW,
CH=CHUNK, SCALE=scale, HBT=hb, KTT=KT, num_warps=8, num_stages=1)
_merge[(R, H)](s.po, s.pm, s.pl, out, s.dummy, R, H=H, LW=LW, NCH=nch, SPARSE=False, num_warps=4)
-@@ -401,5 +493,32 @@ def sparse_attention(qa: torch.Tensor, cache: torch.Tensor, tokens: torch.Tensor
+@@ -404,5 +494,32 @@ def sparse_attention(qa: torch.Tensor, cache: torch.Tensor, tokens: torch.Tensor
_merge[(R, H)](po, pm, pl, out, counts, R, H=H, LW=LW, NCH=nch, SPARSE=True, num_warps=4)
@@ -628,10 +636,10 @@ index 2e2a32e..62cc861 100644
def chunks_for(length: int) -> int:
return triton.cdiv(length, CHUNK)
diff --git tensorfold/families/glm5_next/cuda/sparse.py tensorfold/families/glm5_next/cuda/sparse.py
-index 56582b8..124c75c 100644
+index a7930dd..a7a252d 100644
--- tensorfold/families/glm5_next/cuda/sparse.py
+++ tensorfold/families/glm5_next/cuda/sparse.py
-@@ -9,6 +9,8 @@ import triton.language as tl
+@@ -11,6 +11,8 @@ from tensorfold.cuda.geometry import MLA_SELECT_ROWS as SELECT_ROWS # a prompt
POOL = 4
TOPK_POOLS = 512
BR = 16
@@ -640,7 +648,7 @@ index 56582b8..124c75c 100644
@triton.jit
-@@ -165,12 +167,55 @@ def pool_bucket(pos: int, R: int, np_max: int) -> int:
+@@ -177,12 +179,55 @@ def pool_bucket(pos: int, R: int, np_max: int) -> int:
return min(np_max, max(1024, 1 << (visible - 1).bit_length()))
@@ -695,8 +703,8 @@ index 56582b8..124c75c 100644
+ return _select_prompt(qi, wts, pk, pos, R, np_max, pos_dev)
# score only visible pools, rounded up to a power of two so the allocator reuses a few sizes (exact sizes fragmented memory at 128k)
np_max = bucket if bucket is not None else pool_bucket(pos, R, np_max)
- scores = torch.empty((R, np_max), dtype=torch.float32, device=qi.device)
-@@ -195,6 +240,38 @@ def select_tokens(qi: torch.Tensor, wts: torch.Tensor, pk: torch.Tensor, pos: in
+ # rows scored SELECT_ROWS at a time over the window's np_max pools (the same columns, so the same bits a row)
+@@ -216,6 +261,38 @@ def select_tokens(qi: torch.Tensor, wts: torch.Tensor, pk: torch.Tensor, pos: in
return tokens, counts
diff --git a/patches/0010-glm-hc-split.patch b/patches/0010-glm-hc-split.patch
index f1c0cd3..d69ff18 100644
--- a/patches/0010-glm-hc-split.patch
+++ b/patches/0010-glm-hc-split.patch
@@ -1,5 +1,5 @@
diff --git tensorfold/cuda/comm.py tensorfold/cuda/comm.py
-index 31a92c1..eb7aa10 100644
+index 2e50cdc..b94a2ce 100644
--- tensorfold/cuda/comm.py
+++ tensorfold/cuda/comm.py
@@ -1,4 +1,5 @@
@@ -21,9 +21,9 @@ index 31a92c1..eb7aa10 100644
self.store = TCPStore(master, port, world, rank == 0, timeout=timedelta(seconds=600))
uid = _UniqueId()
if rank == 0:
-@@ -72,6 +78,25 @@ class NCCL:
- self._check(self.lib.ncclAllGather(send.data_ptr(), recv.data_ptr(), send.numel(), _DTYPES[send.dtype],
- self.comm, stream))
+@@ -97,6 +103,25 @@ class NCCL:
+ print(f"[tensorfold] rank {self.rank} finished {label}; waiting for rank {missing} ({waited:.0f} s)",
+ flush=True)
+ def exchange(self, sends: list[torch.Tensor], recvs: list[torch.Tensor], peer: int) -> None:
+ """One NCCL group on the current stream: every ``sends[i]`` to ``peer`` and ``recvs[i]`` from it (contiguous
@@ -48,7 +48,7 @@ index 31a92c1..eb7aa10 100644
x = torch.zeros((1,), dtype=torch.float32, device="cuda")
y = torch.zeros((self.world,), dtype=torch.float32, device="cuda")
diff --git tensorfold/families/glm5_next/cuda/decode.py tensorfold/families/glm5_next/cuda/decode.py
-index fdc7c53..0591d9f 100644
+index b16ad04..c75f90c 100644
--- tensorfold/families/glm5_next/cuda/decode.py
+++ tensorfold/families/glm5_next/cuda/decode.py
@@ -84,8 +84,9 @@ class Engine:
@@ -75,10 +75,10 @@ index fdc7c53..0591d9f 100644
self.st = State(w, capacity, max_rows)
self.last_hidden: torch.Tensor | None = None
diff --git tensorfold/families/glm5_next/cuda/engine.py tensorfold/families/glm5_next/cuda/engine.py
-index 63c5dd2..4c06a8a 100644
+index b508ba0..3c2b10e 100644
--- tensorfold/families/glm5_next/cuda/engine.py
+++ tensorfold/families/glm5_next/cuda/engine.py
-@@ -136,9 +136,11 @@ class GlmEngine:
+@@ -160,9 +160,11 @@ class GlmEngine:
def __init__(self, model_dir: Path, *, rank: int, master: str, port: int, policy: str = DEFAULT_POLICY,
drafter: Path | None = None, context: int | None = None, context_explicit: bool | None = None, serial_only: bool = False, comm=None,
@@ -92,7 +92,7 @@ index 63c5dd2..4c06a8a 100644
import torch
-@@ -155,6 +157,11 @@ class GlmEngine:
+@@ -180,6 +182,11 @@ class GlmEngine:
# TF_GLM_COPY_DRAFTS=1: a reply that repeats earlier text drafts its continuation (prompt lookup) ahead of
# the MTP head and DFlash2; both ranks must agree, so the settings join the startup comparison below
self.copy = None if serial_only else CopySettings.from_env(MAX_ROWS - 1)
@@ -104,27 +104,28 @@ index 63c5dd2..4c06a8a 100644
torch.cuda.set_device(0)
self.torch = torch
self.rank = rank
-@@ -216,7 +223,7 @@ class GlmEngine:
+@@ -247,7 +254,7 @@ class GlmEngine:
long_context = self.limit > cfg.dense_limit
# both ranks 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] + (self.copy.code() if self.copy is not None else [0, 0])
-+ prefill_rows, self.grid] + (self.copy.code() if self.copy is not None else [0, 0]) + self.split.code()
+- prefill_rows, self.grid] + (self.copy.code() if self.copy is not None else [0, 0]) + \
++ prefill_rows, self.grid] + (self.copy.code() if self.copy is not None else [0, 0]) + self.split.code() + \
+ [int(self.mtp_on), int(DRAFT_RING)]
# other conversations' kept prompts get what the window leaves, at most TF_GLM_CACHE_GIB, the same on both ranks
plan = self.capacity_plan
- wanted = int(float(os.environ.get("TF_GLM_CACHE_GIB", "3")) * 2 ** 30)
-@@ -224,7 +231,8 @@ class GlmEngine:
+@@ -256,8 +263,8 @@ class GlmEngine:
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, "
-- "TF_GLM_LATENT, TF_GLM_PREFILL_ROWS, TF_GLM_PROMPT_GRID, TF_GLM_COPY_*): "
+- "TF_GLM_LATENT, TF_GLM_PREFILL_ROWS, TF_GLM_PROMPT_GRID, TF_GLM_COPY_*, TF_GLM_MTP, "
+- "TF_GLM_DRAFT_RING): "
+ "TF_GLM_LATENT, TF_GLM_PREFILL_ROWS, TF_GLM_PROMPT_GRID, TF_GLM_COPY_*, "
-+ "TF_GLM_HC_SPLIT*, TF_GLM_PREFILL_OVERLAP, TF_GLM_OVERLAP_PIECES): "
++ "TF_GLM_HC_SPLIT*, TF_GLM_PREFILL_OVERLAP, TF_GLM_OVERLAP_PIECES, TF_GLM_MTP, TF_GLM_DRAFT_RING): "
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
-@@ -249,7 +257,11 @@ class GlmEngine:
- self.drafter = Drafter(drafter, w, capacity=capacity)
+@@ -287,7 +294,11 @@ class GlmEngine:
+ self.drafter = Drafter(drafter, w, capacity=capacity, ring=DRAFT_RING)
self.e = Engine(w, capacity=capacity, max_rows=MAX_ROWS, prefill_rows=prefill_rows, graphs=True, graph_rows=GRAPH_ROWS,
long_context=long_context, taps=self.drafter.tap_layers if self.drafter is not None else (),
- grid=self.grid)
@@ -137,10 +138,10 @@ index 63c5dd2..4c06a8a 100644
print(f"[tensorfold] prompt chunks and kept prompt states on a {self.grid}-token grid "
f"(TF_GLM_PROMPT_GRID)", flush=True)
diff --git tensorfold/families/glm5_next/cuda/forward.py tensorfold/families/glm5_next/cuda/forward.py
-index 6c81ba8..dfd613b 100644
+index a961a94..98ed9e6 100644
--- tensorfold/families/glm5_next/cuda/forward.py
+++ tensorfold/families/glm5_next/cuda/forward.py
-@@ -121,6 +121,8 @@ class Buffers:
+@@ -123,6 +123,8 @@ class Buffers:
self.tap_at: dict[int, list[int]] = {}
self.experts = c.experts
self.top_k = c.top_k
@@ -149,7 +150,7 @@ index 6c81ba8..dfd613b 100644
def set_taps(self, layers: tuple[int, ...], hidden: int) -> None:
self.tap_at = {}
-@@ -242,9 +244,27 @@ def mm(b: Buffers, x: torch.Tensor, q, xs: torch.Tensor | None, out: torch.Tenso
+@@ -244,9 +246,27 @@ def mm(b: Buffers, x: torch.Tensor, q, xs: torch.Tensor | None, out: torch.Tenso
return qmm.matmul(x, q, xs, out=out, f32=f32, part=b.sk)
@@ -180,7 +181,7 @@ index 6c81ba8..dfd613b 100644
def kda_block(layer: LayerW, w: Weights, st: State, b: Buffers, R: int) -> torch.Tensor:
-@@ -388,26 +408,48 @@ def moe_block(layer: LayerW, w: Weights, b: Buffers, R: int) -> torch.Tensor:
+@@ -406,26 +426,48 @@ def moe_block(layer: LayerW, w: Weights, b: Buffers, R: int) -> torch.Tensor:
with prof.timed("moe: routed (exl3)"):
exl3_mm.routed(b.normed[:R], b.pick, b.plan, m.experts, b.exl3, b.ey.view(-1, c.hidden), R, c.limit)
s = m.shared
@@ -245,7 +246,7 @@ index 6c81ba8..dfd613b 100644
def layer_forward(layer: LayerW, w: Weights, st: State, b: Buffers, R: int, nch: int | None = None,
-@@ -417,24 +459,43 @@ def layer_forward(layer: LayerW, w: Weights, st: State, b: Buffers, R: int, nch:
+@@ -435,24 +477,43 @@ def layer_forward(layer: LayerW, w: Weights, st: State, b: Buffers, R: int, nch:
h = layer.attn_hc
glue.hc_pre(x, h.fn, h.base, h.scale, layer.in_norm, b.normed[:R], b.xs[:R], b.post[:R], b.comb[:R],
b.hcpart[:R], c.eps, c.hc_eps, c.hc_iters, prompt=b.prefill)
@@ -299,7 +300,7 @@ index 6c81ba8..dfd613b 100644
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:
-@@ -467,11 +528,14 @@ def compute(w: Weights, st: State, b: Buffers, R: int, *, logits: bool = True, n
+@@ -485,11 +546,14 @@ def compute(w: Weights, st: State, b: Buffers, R: int, *, logits: bool = True, n
if inject is not None:
rows, features = inject
b.x.index_copy_(0, rows, features.repeat(1, c.streams))
diff --git a/patches/0011-glm-draft-sim.patch b/patches/0011-glm-draft-sim.patch
index f262ddf..6b49988 100644
--- a/patches/0011-glm-draft-sim.patch
+++ b/patches/0011-glm-draft-sim.patch
@@ -1,8 +1,8 @@
diff --git tensorfold/families/glm5_next/cuda/dflash2.py tensorfold/families/glm5_next/cuda/dflash2.py
-index ebace1f..a6ee808 100644
+index 309104e..0ca8c5d 100644
--- tensorfold/families/glm5_next/cuda/dflash2.py
+++ tensorfold/families/glm5_next/cuda/dflash2.py
-@@ -136,9 +136,10 @@ def _dconv(x: torch.Tensor, dyn: torch.Tensor, base: torch.Tensor, branch: int,
+@@ -144,9 +144,10 @@ def _dconv(x: torch.Tensor, dyn: torch.Tensor, base: torch.Tensor, branch: int,
def _quantize4(w: torch.Tensor) -> qmm.Q4:
@@ -984,10 +984,10 @@ index 0000000..64d4f54
+if __name__ == "__main__":
+ sys.exit(main())
diff --git tensorfold/families/glm5_next/cuda/engine.py tensorfold/families/glm5_next/cuda/engine.py
-index 4c06a8a..b27eb43 100644
+index 3c2b10e..613a0f7 100644
--- tensorfold/families/glm5_next/cuda/engine.py
+++ tensorfold/families/glm5_next/cuda/engine.py
-@@ -221,9 +221,17 @@ class GlmEngine:
+@@ -252,10 +252,17 @@ class GlmEngine:
self.limit = self.capacity_plan["context_window"]
capacity = self.capacity_plan["cache_slots"]
long_context = self.limit > cfg.dense_limit
@@ -1000,23 +1000,24 @@ index 4c06a8a..b27eb43 100644
+ quant_code = DRAFT_QUANTS.index(draft_quant())
# both ranks 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] + (self.copy.code() if self.copy is not None else [0, 0]) + self.split.code()
+- prefill_rows, self.grid] + (self.copy.code() if self.copy is not None else [0, 0]) + self.split.code() + \
+- [int(self.mtp_on), int(DRAFT_RING)]
+ prefill_rows, self.grid] + (self.copy.code() if self.copy is not None else [0, 0]) + self.split.code() + [
-+ int(self.dump is not None), quant_code]
++ int(self.dump is not None), quant_code, int(self.mtp_on), int(DRAFT_RING)]
# other conversations' kept prompts get what the window leaves, at most TF_GLM_CACHE_GIB, the same on both ranks
plan = self.capacity_plan
wanted = int(float(os.environ.get("TF_GLM_CACHE_GIB", "3")) * 2 ** 30)
-@@ -232,7 +240,8 @@ class GlmEngine:
+@@ -264,7 +271,8 @@ class GlmEngine:
if both[0][:-1] != both[1][:-1]:
raise RuntimeError("the two ranks were started with different settings (draft model, context, drafts, "
"TF_GLM_LATENT, TF_GLM_PREFILL_ROWS, TF_GLM_PROMPT_GRID, TF_GLM_COPY_*, "
-- "TF_GLM_HC_SPLIT*, TF_GLM_PREFILL_OVERLAP, TF_GLM_OVERLAP_PIECES): "
+- "TF_GLM_HC_SPLIT*, TF_GLM_PREFILL_OVERLAP, TF_GLM_OVERLAP_PIECES, TF_GLM_MTP, TF_GLM_DRAFT_RING): "
+ "TF_GLM_HC_SPLIT*, TF_GLM_PREFILL_OVERLAP, TF_GLM_OVERLAP_PIECES, TF_GLM_DRAFT_DUMP, "
-+ "TF_GLM_DRAFT_QUANT): "
++ "TF_GLM_DRAFT_QUANT, TF_GLM_MTP, TF_GLM_DRAFT_RING): "
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
-@@ -262,6 +271,12 @@ class GlmEngine:
+@@ -299,6 +307,12 @@ 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)
@@ -1029,7 +1030,7 @@ index 4c06a8a..b27eb43 100644
if rank == 0 and self.grid:
print(f"[tensorfold] prompt chunks and kept prompt states on a {self.grid}-token grid "
f"(TF_GLM_PROMPT_GRID)", flush=True)
-@@ -536,6 +551,16 @@ class GlmEngine:
+@@ -601,6 +615,16 @@ class GlmEngine:
copies = CopyDrafts(list(prompt) + [first], self.copy.match, self.copy.most)
if policy is None:
res = serial_decode(self.e, first, max_tokens, sampling, stop_eos=stop_eos, on_tokens=on_tokens)
@@ -1047,7 +1048,7 @@ index 4c06a8a..b27eb43 100644
greedy = sampling is None or sampling.temperature <= 0
m_policy = DepthPolicy(3, fixed=True, confidence=0.35) if greedy else DepthPolicy(3, low=0.6, high=0.85)
diff --git tensorfold/families/glm5_next/cuda/qmm.py tensorfold/families/glm5_next/cuda/qmm.py
-index ee83025..6ed26f1 100644
+index 6377c42..3c40295 100644
--- tensorfold/families/glm5_next/cuda/qmm.py
+++ tensorfold/families/glm5_next/cuda/qmm.py
@@ -211,6 +211,29 @@ def quantize4_mse(w: torch.Tensor, chunk: int = 4096, grid: int = 16) -> Q4:
@@ -1081,7 +1082,7 @@ index ee83025..6ed26f1 100644
return quantize4_mse(weight.to(torch.bfloat16)) if weight.shape[1] % 64 == 0 else make_f8(weight)
diff --git tensorfold/families/glm5_next/cuda/weights.py tensorfold/families/glm5_next/cuda/weights.py
-index 2d6ab83..8b8b10d 100644
+index 766a3b0..55bb452 100644
--- tensorfold/families/glm5_next/cuda/weights.py
+++ tensorfold/families/glm5_next/cuda/weights.py
@@ -13,7 +13,8 @@ from tensorfold.cuda import experts as grouped
@@ -1094,7 +1095,7 @@ index 2d6ab83..8b8b10d 100644
PREFIX = "model.language_model."
-@@ -425,7 +426,8 @@ def load(model_dir: str | Path, *, rank: int, device: str = "cuda") -> Weights:
+@@ -430,7 +431,8 @@ def load(model_dir: str | Path, *, rank: int, device: str = "cuda", mtp: bool =
if exl3:
raw = rd.get("lm_head.weight")[rank * vl:(rank + 1) * vl].to(dev)
head = dense(raw)
diff --git a/patches/0012-glm-kda-chunked.patch b/patches/0012-glm-kda-chunked.patch
index 3797206..ce2c981 100644
--- a/patches/0012-glm-kda-chunked.patch
+++ b/patches/0012-glm-kda-chunked.patch
@@ -1,8 +1,8 @@
diff --git tensorfold/families/glm5_next/cuda/forward.py tensorfold/families/glm5_next/cuda/forward.py
-index dfd613b..c4c8ab3 100644
+index 98ed9e6..c1fb8ce 100644
--- tensorfold/families/glm5_next/cuda/forward.py
+++ tensorfold/families/glm5_next/cuda/forward.py
-@@ -283,7 +283,7 @@ def kda_block(layer: LayerW, w: Weights, st: State, b: Buffers, R: int) -> torch
+@@ -285,7 +285,7 @@ def kda_block(layer: LayerW, w: Weights, st: State, b: Buffers, R: int) -> torch
with prof.timed("kda: recurrence"):
out = kda_mod.chain(p, k.b_off, b.ka[:R], b.kg[:R], st.conv[li], k.conv, st.rec[cur, li], k.a_log,
k.dt_bias, k.norm, c.eps, c.lower, R, b.kscratch if pre else st.scratch[li],
diff --git a/patches/0013-glm-decode-rounds.patch b/patches/0013-glm-decode-rounds.patch
index 486eedf..1c0cfa6 100644
--- a/patches/0013-glm-decode-rounds.patch
+++ b/patches/0013-glm-decode-rounds.patch
@@ -1,19 +1,19 @@
diff --git tensorfold/cuda/geometry.py tensorfold/cuda/geometry.py
-index 908f94e..82b565f 100644
+index 9a1b8d5..7abbd21 100644
--- tensorfold/cuda/geometry.py
+++ tensorfold/cuda/geometry.py
-@@ -7,6 +7,7 @@ from .capacity import Geometry, itemsize
-
+@@ -10,6 +10,7 @@ from .capacity import Geometry, Weights, headers, itemsize
PREFILL_ROWS = 2048 # a prompt chunk's rows: Flash Next and GLM keep buffers of this many rows
+ PROMPT_SHARE = 32 # a dense prompt chunk's arrays take at most this fraction of the GPU's memory
PREFILL_ATT_ROWS = 256 # Flash Next's prompt attention block
+MLA_DECODE_ROWS = 64 # GLM's decode windows the MLA estimate sizes buffers for (its verify windows: at most this)
+ MLA_PROMPT_ATT_ROWS = 512 # GLM's prompt-chunk rows one dense latent attention call takes (forward.PROMPT_ATT_ROWS)
+ MLA_SELECT_ROWS = 512 # GLM's prompt-chunk rows whose pool scores are held at once (sparse.SELECT_ROWS)
-
- def size(info: dict, name: str = "tensor") -> int:
-@@ -204,7 +205,7 @@ def mla_geometry(t: dict, world: int, reserve: int, *, minimum_slots: int = 2560
+@@ -238,7 +239,7 @@ def mla_geometry(t: dict, world: int, reserve: int, *, minimum_slots: int = 2560
kd = int(t["qk_nope_head_dim"]) + int(t.get("qk_rope_head_dim", 0))
vd, index = int(t["v_head_dim"]), int(t.get("index_head_dim", 128))
- mtp = int(t.get("num_nextn_predict_layers", 0)) > 0
+ mtp = int(t.get("num_nextn_predict_layers", 0)) > 0 if mtp is None else bool(mtp)
- rows, d, streams = 64, int(t["hidden_size"]), int(t.get("hc_mult", 4))
+ rows, d, streams = MLA_DECODE_ROWS, int(t["hidden_size"]), int(t.get("hc_mult", 4))
fixed = linear * (4 * lh * ld * ld * 4 + 3 * (conv - 1) * 3 * lh * ld * 2)
@@ -33,7 +33,7 @@ index 25e4be7..3aa3b25 100644
@dataclass(frozen=True)
diff --git tensorfold/families/glm5_next/cuda/decode.py tensorfold/families/glm5_next/cuda/decode.py
-index 0591d9f..52a5182 100644
+index c75f90c..cd9a9f1 100644
--- tensorfold/families/glm5_next/cuda/decode.py
+++ tensorfold/families/glm5_next/cuda/decode.py
@@ -84,9 +84,11 @@ class Engine:
@@ -69,7 +69,7 @@ index 0591d9f..52a5182 100644
self.reset()
def reset(self) -> None:
-@@ -390,6 +393,8 @@ class DecodeResult:
+@@ -421,6 +424,8 @@ class DecodeResult:
rounds: int
drafted: int = 0
accepted: int = 0
@@ -78,7 +78,7 @@ index 0591d9f..52a5182 100644
stages: dict[str, float] = field(default_factory=dict)
depths: list[int] = field(default_factory=list)
keeps: list[int] = field(default_factory=list)
-@@ -408,6 +413,55 @@ def _sync(w: Weights) -> None:
+@@ -439,6 +444,55 @@ def _sync(w: Weights) -> None:
torch.cuda.synchronize()
@@ -134,7 +134,7 @@ index 0591d9f..52a5182 100644
@torch.no_grad()
def serial_decode(e: Engine, pending: int, count: int, sampling: Sampling | None, *,
stop_eos: bool = False, on_tokens=None) -> DecodeResult:
-@@ -416,24 +470,26 @@ def serial_decode(e: Engine, pending: int, count: int, sampling: Sampling | None
+@@ -447,24 +501,26 @@ def serial_decode(e: Engine, pending: int, count: int, sampling: Sampling | None
w, st, b = e.w, e.st, e.buf
out = [pending]
stages = dict(forward=0.0, sample=0.0, commit=0.0)
@@ -166,7 +166,7 @@ index 0591d9f..52a5182 100644
_sync(w)
return DecodeResult(out, time.perf_counter() - start, len(out) - 1, stages=stages)
-@@ -474,6 +530,7 @@ def mtp_decode(e: Engine, pending: int, count: int, sampling: Sampling | None, *
+@@ -505,6 +561,7 @@ def mtp_decode(e: Engine, pending: int, count: int, sampling: Sampling | None, *
c_rounds = c_drafted = c_accepted = 0
depths: list[int] = []
keeps: list[int] = []
@@ -174,7 +174,7 @@ index 0591d9f..52a5182 100644
_sync(w)
start = time.perf_counter()
t0 = time.perf_counter()
-@@ -486,12 +543,13 @@ def mtp_decode(e: Engine, pending: int, count: int, sampling: Sampling | None, *
+@@ -517,12 +574,13 @@ def mtp_decode(e: Engine, pending: int, count: int, sampling: Sampling | None, *
drafts = draft(e, e.last_hidden, [pending], st.pos + 1, depth, sampling, policy.confidence) if depth > 0 else []
stages["draft"] += time.perf_counter() - t0
while len(out) < count and not (stop_eos and out[-1] in w.cfg.eos):
@@ -190,7 +190,7 @@ index 0591d9f..52a5182 100644
t1 = time.perf_counter()
sampled = e.sample(logits[:R], [st.pos + 1 + r for r in range(R)], sampling)
keep = 1
-@@ -513,9 +571,8 @@ def mtp_decode(e: Engine, pending: int, count: int, sampling: Sampling | None, *
+@@ -544,9 +602,8 @@ def mtp_decode(e: Engine, pending: int, count: int, sampling: Sampling | None, *
out.extend(sampled[:keep])
if copies is not None:
copies.extend(sampled[:keep])
@@ -202,7 +202,7 @@ index 0591d9f..52a5182 100644
stages["sample"] += t2 - t1
stages["commit"] += t3 - t2
if len(out) >= count or (stop_eos and out[-1] in w.cfg.eos):
-@@ -531,6 +588,7 @@ def mtp_decode(e: Engine, pending: int, count: int, sampling: Sampling | None, *
+@@ -562,6 +619,7 @@ def mtp_decode(e: Engine, pending: int, count: int, sampling: Sampling | None, *
drafts = (draft(e, e.main_hidden(slice(0, keep)), sampled[:keep], st.pos + 1, depth, sampling,
policy.confidence) if depth > 0 else [])
stages["draft"] += time.perf_counter() - t4
@@ -210,7 +210,7 @@ index 0591d9f..52a5182 100644
_sync(w)
return DecodeResult(out[:count], time.perf_counter() - start, rounds, drafted, accepted, stages, depths, keeps,
copy_rounds=c_rounds, copy_drafted=c_drafted, copy_accepted=c_accepted)
-@@ -550,6 +608,7 @@ def dflash_decode(e: Engine, drafter, pending: int, count: int, sampling: Sampli
+@@ -581,6 +639,7 @@ def dflash_decode(e: Engine, drafter, pending: int, count: int, sampling: Sampli
c_rounds = c_drafted = c_accepted = 0
depths: list[int] = []
keeps: list[int] = []
@@ -218,7 +218,7 @@ index 0591d9f..52a5182 100644
_sync(w)
start = time.perf_counter()
depth = min(policy.next(0, 0), count - len(out))
-@@ -564,8 +623,10 @@ def dflash_decode(e: Engine, drafter, pending: int, count: int, sampling: Sampli
+@@ -595,8 +654,10 @@ def dflash_decode(e: Engine, drafter, pending: int, count: int, sampling: Sampli
tokens = e.verify_window([out[-1]] + drafts)
drafts = tokens[1:]
R = len(tokens)
@@ -230,7 +230,7 @@ index 0591d9f..52a5182 100644
t2 = time.perf_counter()
sampled = e.sample(logits[:R], [st.pos + 1 + r for r in range(R)], sampling)
keep = 1
-@@ -589,14 +650,14 @@ def dflash_decode(e: Engine, drafter, pending: int, count: int, sampling: Sampli
+@@ -620,14 +681,14 @@ def dflash_decode(e: Engine, drafter, pending: int, count: int, sampling: Sampli
out.extend(sampled[:keep])
if copies is not None:
copies.extend(sampled[:keep])
@@ -249,23 +249,23 @@ index 0591d9f..52a5182 100644
return DecodeResult(out[:count], time.perf_counter() - start, rounds, drafted, accepted, stages, depths, keeps,
copy_rounds=c_rounds, copy_drafted=c_drafted, copy_accepted=c_accepted)
diff --git tensorfold/families/glm5_next/cuda/dflash2.py tensorfold/families/glm5_next/cuda/dflash2.py
-index a6ee808..427d7f6 100644
+index 0ca8c5d..62c9373 100644
--- tensorfold/families/glm5_next/cuda/dflash2.py
+++ tensorfold/families/glm5_next/cuda/dflash2.py
-@@ -166,7 +166,11 @@ class DraftLayer:
- class Drafter:
+@@ -175,8 +175,10 @@ class Drafter:
"""Draft one sequence from position-indexed context using device lengths and static buffers shared by eager execution and CUDA graphs."""
-- def __init__(self, draft_dir: str | Path, w: Weights, *, block: int | None = None, capacity: int = 2560) -> None:
-+ def __init__(self, draft_dir: str | Path, w: Weights, *, block: int | None = None, capacity: int = 2560,
-+ tap_rows: int = 0) -> None:
+ def __init__(self, draft_dir: str | Path, w: Weights, *, block: int | None = None, capacity: int = 2560,
+- ring: bool = False) -> None:
+- """``ring`` (TF_GLM_DRAFT_RING): the context in a ring of the window and block, the same drafts."""
++ tap_rows: int = 0, ring: bool = False) -> None:
+ """``tap_rows``: context updates up to this many rows (a verify window's kept rows) replay captured graphs too
-+ (the block's own size always does)."""
-+
++ (the block's own size always does). ``ring`` (TF_GLM_DRAFT_RING): the context in a ring of the window and
++ block, the same drafts."""
+
path = Path(draft_dir)
cfg = json.loads((path / "config.json").read_text())
- dc = cfg["dflash_config"]
-@@ -252,11 +256,20 @@ class Drafter:
+@@ -268,11 +270,20 @@ class Drafter:
self.ids_host = torch.zeros((1,), dtype=torch.int32, pin_memory=torch.cuda.is_available())
self.ar = torch.arange(max(64, n), device=dev)
self.tap_in = torch.zeros((64, len(self.tap_layers) * self.D), dtype=torch.bfloat16, device=dev)
@@ -288,7 +288,7 @@ index a6ee808..427d7f6 100644
def nbytes(self) -> int:
total = sum(q.nbytes() for L in self.layers for q in (L.a_kp, L.m_kp, L.qkv, L.kv, L.o, L.gu, L.down))
-@@ -368,23 +381,21 @@ class Drafter:
+@@ -390,23 +401,21 @@ class Drafter:
vals, local = torch.topk(logits.float(), self.top_k, dim=-1)
gids = (local + self.w.vocab_offset).to(torch.int32)
packed = torch.cat([vals, gids.view(torch.float32)], dim=1).contiguous()
@@ -318,7 +318,7 @@ index a6ee808..427d7f6 100644
for _ in range(2):
self._taps_compute(n)
torch.cuda.synchronize()
-@@ -413,7 +424,15 @@ class Drafter:
+@@ -435,7 +444,15 @@ class Drafter:
self.block_graph.replay()
else:
self._block_compute()
@@ -335,7 +335,7 @@ index a6ee808..427d7f6 100644
k = self.top_k
values = torch.cat([g[r, :, :k] for r in range(g.shape[0])], dim=1).numpy().astype(np.float64)
tokens = torch.cat([g[r, :, k:].contiguous().view(torch.int32) for r in range(g.shape[0])],
-@@ -422,7 +441,7 @@ class Drafter:
+@@ -444,7 +461,7 @@ class Drafter:
order = np.lexsort((tokens, -values), axis=-1)[:, :k]
values = np.take_along_axis(values, order, axis=1)
tokens = np.take_along_axis(tokens, order, axis=1)
@@ -394,7 +394,7 @@ index b14a7e9..01ad045 100644
seconds = time.perf_counter() - start
if drafter is not None and n_f:
diff --git tensorfold/families/glm5_next/cuda/engine.py tensorfold/families/glm5_next/cuda/engine.py
-index b27eb43..d770cff 100644
+index 613a0f7..76602c5 100644
--- tensorfold/families/glm5_next/cuda/engine.py
+++ tensorfold/families/glm5_next/cuda/engine.py
@@ -14,8 +14,9 @@ from typing import Any, Callable
@@ -407,9 +407,9 @@ index b27eb43..d770cff 100644
+MAX_ROWS = 16 # the widest verify window (a pending token and up to 15 drafts: copy drafts)
+MTP_ROWS = 8 # rows an MTP step takes at once (a kept backlog is absorbed in steps of this)
DENSE_CAPACITY = 2560 # cache slots while DSA attention stays dense (contexts up to 2,051 tokens)
- # --vision (rank 0): what startup reserves beside the tower's 1.05 GiB of bf16 weights for an encode and its
- # prompt's feature rows (8 KiB a row, which stay through the prefill). The encode's scratch takes turns with a prompt
-@@ -183,7 +184,7 @@ class GlmEngine:
+ # TF_GLM_DRAFT_RING=0: DFlash2's context in a flat buffer of the whole window, not a 2,176-row ring (the same drafts)
+ DRAFT_RING = os.environ.get("TF_GLM_DRAFT_RING", "1").strip() != "0"
+@@ -208,7 +209,7 @@ class GlmEngine:
explicit = context is not None if context_explicit is None else bool(context_explicit)
from . import LATENT
@@ -418,45 +418,45 @@ index b27eb43..d770cff 100644
# TF_GLM_DENSE=fp8 (an EXL3 checkpoint): its BF16 matrices take a byte a value, which the estimate counts
weights_estimate = split_weights(rule)
-@@ -191,6 +192,9 @@ class GlmEngine:
+@@ -216,6 +217,9 @@ class GlmEngine:
weights_estimate = fp8_weights(weights_estimate)
elif cfg.quant == "exl3" and dense_kind() == "q4":
weights_estimate = q4_weights(weights_estimate)
+ # TF_GLM_KVB=fp8/q4 (an EXL3 checkpoint, latent cache): kv_b as the absorb and expand kernels read it
+ kvb = kvb_kind() if cfg.quant == "exl3" and LATENT else "bf16"
+ weights_estimate = kvb_weights(weights_estimate, kvb)
- # rows a prompt chunk runs at once: TF_GLM_PREFILL_ROWS (both ranks alike), more amortizes each chunk's expert
- # weight decode over more tokens and costs buffer memory
- if prefill_rows is None:
-@@ -230,8 +234,8 @@ class GlmEngine:
+ # TF_GLM_MTP off: the MTP layer's tensors, caches and buffers are neither loaded nor estimated
+ self.mtp_on = mtp_head(drafter is not None, serial_only, cfg.mtp_layers)
+ if not self.mtp_on:
+@@ -261,8 +265,8 @@ class GlmEngine:
quant_code = DRAFT_QUANTS.index(draft_quant())
# both ranks 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] + (self.copy.code() if self.copy is not None else [0, 0]) + self.split.code() + [
-- int(self.dump is not None), quant_code]
+- int(self.dump is not None), quant_code, int(self.mtp_on), int(DRAFT_RING)]
+ prefill_rows, self.grid, KVB_KINDS.index(kvb)] + (self.copy.code() if self.copy is not None else [0, 0]) + \
-+ self.split.code() + [int(self.dump is not None), quant_code]
++ self.split.code() + [int(self.dump is not None), quant_code, int(self.mtp_on), int(DRAFT_RING)]
# other conversations' kept prompts get what the window leaves, at most TF_GLM_CACHE_GIB, the same on both ranks
plan = self.capacity_plan
wanted = int(float(os.environ.get("TF_GLM_CACHE_GIB", "3")) * 2 ** 30)
-@@ -239,7 +243,7 @@ class GlmEngine:
+@@ -270,7 +274,7 @@ class GlmEngine:
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, "
- "TF_GLM_LATENT, TF_GLM_PREFILL_ROWS, TF_GLM_PROMPT_GRID, TF_GLM_COPY_*, "
+ "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_DRAFT_QUANT, TF_GLM_MTP, TF_GLM_DRAFT_RING): "
f"rank 0 {both[0][:-1]}, rank 1 {both[1][:-1]}; pull the draft model on both machines "
-@@ -263,10 +267,11 @@ class GlmEngine:
+@@ -299,10 +303,11 @@ class GlmEngine:
if drafter is not None:
from .dflash2 import Drafter
-- self.drafter = Drafter(drafter, w, capacity=capacity)
+- self.drafter = Drafter(drafter, w, capacity=capacity, ring=DRAFT_RING)
- self.e = Engine(w, capacity=capacity, max_rows=MAX_ROWS, prefill_rows=prefill_rows, graphs=True, graph_rows=GRAPH_ROWS,
- long_context=long_context, taps=self.drafter.tap_layers if self.drafter is not None else (),
- grid=self.grid, split=self.split)
-+ self.drafter = Drafter(drafter, w, capacity=capacity, tap_rows=MAX_ROWS)
++ self.drafter = Drafter(drafter, w, capacity=capacity, tap_rows=MAX_ROWS, ring=DRAFT_RING)
+ self.e = Engine(w, capacity=capacity, max_rows=MAX_ROWS, prefill_rows=prefill_rows, graphs=True,
+ graph_rows=GRAPH_ROWS, long_context=long_context,
+ taps=self.drafter.tap_layers if self.drafter is not None else (), grid=self.grid,
@@ -464,7 +464,7 @@ index b27eb43..d770cff 100644
if self.e.pbuf.split is not None:
self.e.pbuf.split.warm() # both ranks: open the send/receive connection now
if rank == 0:
-@@ -327,7 +332,7 @@ class GlmEngine:
+@@ -364,7 +369,7 @@ class GlmEngine:
return [int(t) for t in rng.integers(0, vocab, n)]
prefill(e, tokens(64), None, mtp=True, drafter=self.drafter)
@@ -473,7 +473,7 @@ index b27eb43..d770cff 100644
one, six = tokens(1), tokens(6)
start = st.mtp_len
-@@ -335,7 +340,10 @@ class GlmEngine:
+@@ -372,7 +377,10 @@ class GlmEngine:
st.set_mtp_len(start)
st.mtp_drafted = 0
@@ -485,7 +485,7 @@ index b27eb43..d770cff 100644
if self.w.mtp is not None:
pieces["m1"] = (lambda: draft(e, hidden[:1], one, st.pos + 1, 1, None), rewind)
pieces["m3"] = (lambda: draft(e, hidden[:1], one, st.pos + 1, 3, None), rewind)
-@@ -374,7 +382,7 @@ class GlmEngine:
+@@ -411,7 +419,7 @@ class GlmEngine:
e.reset()
if self.drafter is not None:
self.drafter.reset()
@@ -495,7 +495,7 @@ index b27eb43..d770cff 100644
slope = statistics.median((ys[j] - ys[i]) / (rows[j] - rows[i]) for i in range(len(rows))
for j in range(i + 1, len(rows)))
diff --git tensorfold/families/glm5_next/cuda/latent.py tensorfold/families/glm5_next/cuda/latent.py
-index 62cc861..fff0bf6 100644
+index 55e7e77..e6d7924 100644
--- tensorfold/families/glm5_next/cuda/latent.py
+++ tensorfold/families/glm5_next/cuda/latent.py
@@ -76,6 +76,46 @@ class AbsorbQ4:
@@ -681,7 +681,7 @@ index 62cc861..fff0bf6 100644
BN = 16
_expand_v4[(H, a.v_dim // BN)](o_lat, a.wvw, a.wvs, a.wvb, out, R, H=H, DV=a.v_dim, LW=a.lw, BN=BN,
diff --git tensorfold/families/glm5_next/cuda/qmm.py tensorfold/families/glm5_next/cuda/qmm.py
-index 6ed26f1..f5225c6 100644
+index 3c40295..e0b06a3 100644
--- tensorfold/families/glm5_next/cuda/qmm.py
+++ tensorfold/families/glm5_next/cuda/qmm.py
@@ -180,6 +180,14 @@ def quantize4_mse(w: torch.Tensor, chunk: int = 4096, grid: int = 16) -> Q4:
@@ -752,7 +752,7 @@ index 6ed26f1..f5225c6 100644
_F8_NAMES = __import__("re").compile(
r"(\.(q_proj|k_proj|v_proj|f_a_proj|g_a_proj|b_proj|f_b_proj|g_b_proj|o_proj|q_a_proj|kv_a_proj_with_mqa|q_b_proj"
diff --git tensorfold/families/glm5_next/cuda/weights.py tensorfold/families/glm5_next/cuda/weights.py
-index 8b8b10d..3d7a6b0 100644
+index 55bb452..783bd39 100644
--- tensorfold/families/glm5_next/cuda/weights.py
+++ tensorfold/families/glm5_next/cuda/weights.py
@@ -13,8 +13,8 @@ from tensorfold.cuda import experts as grouped
@@ -766,7 +766,7 @@ index 8b8b10d..3d7a6b0 100644
PREFIX = "model.language_model."
-@@ -148,12 +148,12 @@ class DSAW:
+@@ -153,12 +153,12 @@ class DSAW:
q_norm: torch.Tensor
kv_norm: torch.Tensor
q_b: Q4
@@ -782,7 +782,7 @@ index 8b8b10d..3d7a6b0 100644
@dataclass
-@@ -222,7 +222,8 @@ class Weights:
+@@ -227,7 +227,8 @@ class Weights:
if isinstance(t, torch.Tensor) and t.data_ptr() not in seen:
seen.add(t.data_ptr())
total += t.numel() * t.element_size()
@@ -792,7 +792,7 @@ index 8b8b10d..3d7a6b0 100644
for v in vars(t).values():
add(v)
elif isinstance(t, (list, tuple)):
-@@ -275,6 +276,7 @@ def load(model_dir: str | Path, *, rank: int, device: str = "cuda") -> Weights:
+@@ -280,6 +281,7 @@ def load(model_dir: str | Path, *, rank: int, device: str = "cuda", mtp: bool =
big, big_stack = make_dense_q4, stack_dense_q4
else:
big, big_stack = dense, dense_stack
@@ -800,7 +800,7 @@ index 8b8b10d..3d7a6b0 100644
def q4(name: str) -> Q4 | B16 | F8:
return big(t(name + ".weight")) if exl3 else make_q4(*trip(name))
-@@ -300,18 +302,22 @@ def load(model_dir: str | Path, *, rank: int, device: str = "cuda") -> Weights:
+@@ -305,18 +307,22 @@ def load(model_dir: str | Path, *, rank: int, device: str = "cuda", mtp: bool =
proj = stack([p + "q_a_proj", p + "kv_a_proj_with_mqa"])
rows = torch.arange(HL * 512, device=dev).view(HL, 512)
krows, vrows = rows[:, :cfg.qk_dim].reshape(-1), rows[:, cfg.qk_dim:].reshape(-1)
diff --git a/patches/0015-glm-shared-prefix.patch b/patches/0015-glm-shared-prefix.patch
index fe309f7..e7f21c4 100644
--- a/patches/0015-glm-shared-prefix.patch
+++ b/patches/0015-glm-shared-prefix.patch
@@ -1,8 +1,8 @@
diff --git tensorfold/families/glm5_next/cuda/decode.py tensorfold/families/glm5_next/cuda/decode.py
-index 52a5182..64f5be7 100644
+index cd9a9f1..79a6427 100644
--- tensorfold/families/glm5_next/cuda/decode.py
+++ tensorfold/families/glm5_next/cuda/decode.py
-@@ -282,17 +282,36 @@ def _row_views(st, n: int, m: int) -> list[torch.Tensor]:
+@@ -308,18 +308,37 @@ def _row_views(st, n: int, m: int) -> list[torch.Tensor]:
return views
@@ -33,8 +33,10 @@ index 52a5182..64f5be7 100644
snap.rows = [v.clone() for v in views]
snap.nbytes = sum(r.numel() * r.element_size() for r in snap.rows)
- snap.drafter_end = -1
+- snap.drafter_rows = None
+ if drafter is None or snap.drafter_end != len(snap.ids):
+ snap.drafter_end = -1
++ snap.drafter_rows = None
-def row_bytes(e: Engine, snap: Snapshot) -> int:
@@ -45,7 +47,7 @@ index 52a5182..64f5be7 100644
def snapshot_bytes(snap: Snapshot) -> int:
-@@ -301,9 +320,12 @@ def snapshot_bytes(snap: Snapshot) -> int:
+@@ -328,9 +347,12 @@ def snapshot_bytes(snap: Snapshot) -> int:
return sum(t.numel() * t.element_size() for t in held) + (snap.nbytes if snap.rows is not None else 0)
@@ -62,10 +64,10 @@ index 52a5182..64f5be7 100644
diff --git tensorfold/families/glm5_next/cuda/engine.py tensorfold/families/glm5_next/cuda/engine.py
-index d770cff..ddb968f 100644
+index 76602c5..c4b826e 100644
--- tensorfold/families/glm5_next/cuda/engine.py
+++ tensorfold/families/glm5_next/cuda/engine.py
-@@ -70,6 +70,84 @@ def grid_point(n: int, cut: int, grid: int) -> int | None:
+@@ -72,6 +72,84 @@ def grid_point(n: int, cut: int, grid: int) -> int | None:
return point if point > cut else None
@@ -150,7 +152,7 @@ index d770cff..ddb968f 100644
def encode_policy(spec: str) -> list[int]:
"""Encode policy kind, maximum drafts, and two parameters in millionths as four integers, with 10 added to kind for DFlash2."""
-@@ -135,6 +213,9 @@ def _ints_f64(lo: int, hi: int) -> float:
+@@ -159,6 +237,9 @@ def without_mtp(transform, layers: int):
class GlmEngine:
"""GLM-5.3-Flash on two ranks (this one ``rank``): weights, MTP and DFlash2 drafting, per-request policies."""
@@ -160,7 +162,7 @@ index d770cff..ddb968f 100644
def __init__(self, model_dir: Path, *, rank: int, master: str, port: int, 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,
-@@ -204,6 +285,9 @@ class GlmEngine:
+@@ -233,6 +314,9 @@ class GlmEngine:
raise ValueError(f"prefill rows: a multiple of 64 from 64 to 16,384, not {prefill_rows}")
# TF_GLM_PROMPT_GRID=G: prompt chunks start on multiples of G and kept prompt states sit on them
self.grid = prompt_grid(prefill_rows)
@@ -170,25 +172,25 @@ index d770cff..ddb968f 100644
vision = bool(vision) and rank == 0
workspace = vision_workspace() if vision else 0
if vision: # the tower's bf16 weights, which the split rule drops
-@@ -235,7 +319,7 @@ class GlmEngine:
+@@ -266,7 +350,7 @@ class GlmEngine:
# both ranks 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]) + \
-- self.split.code() + [int(self.dump is not None), quant_code]
-+ self.split.code() + [int(self.dump is not None), quant_code, self.shared]
+- self.split.code() + [int(self.dump is not None), quant_code, int(self.mtp_on), int(DRAFT_RING)]
++ self.split.code() + [int(self.dump is not None), quant_code, self.shared, int(self.mtp_on), int(DRAFT_RING)]
# other conversations' kept prompts get what the window leaves, at most TF_GLM_CACHE_GIB, the same on both ranks
plan = self.capacity_plan
wanted = int(float(os.environ.get("TF_GLM_CACHE_GIB", "3")) * 2 ** 30)
-@@ -245,7 +329,7 @@ class GlmEngine:
+@@ -276,7 +360,7 @@ class GlmEngine:
raise RuntimeError("the two 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_DRAFT_QUANT, TF_GLM_SHARED_PREFIX): "
+- "TF_GLM_DRAFT_QUANT, TF_GLM_MTP, TF_GLM_DRAFT_RING): "
++ "TF_GLM_DRAFT_QUANT, TF_GLM_SHARED_PREFIX, TF_GLM_MTP, TF_GLM_DRAFT_RING): "
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
-@@ -285,6 +369,11 @@ class GlmEngine:
+@@ -321,6 +405,11 @@ class GlmEngine:
if rank == 0 and self.grid:
print(f"[tensorfold] prompt chunks and kept prompt states on a {self.grid}-token grid "
f"(TF_GLM_PROMPT_GRID)", flush=True)
@@ -200,7 +202,7 @@ index d770cff..ddb968f 100644
if self.drafter is not None:
self.drafter.capture()
self.costs = self._calibrate()
-@@ -465,6 +554,7 @@ class GlmEngine:
+@@ -529,6 +618,7 @@ class GlmEngine:
"""Save the rows of every kept snapshot the next prefill overwrites, dropping the oldest entries past the memory budget; both ranks decide alike."""
from .decode import row_bytes, save_rows
@@ -208,7 +210,7 @@ index d770cff..ddb968f 100644
live = self.live
dropped = False
-@@ -478,7 +568,7 @@ class GlmEngine:
+@@ -542,7 +632,7 @@ class GlmEngine:
if live[:n] != snap.ids: # its rows are already gone: nothing to resume from
self._drop(snap)
continue
@@ -217,7 +219,7 @@ index d770cff..ddb968f 100644
while self._held_bytes() + need > self.cache_bytes:
old = next((c for c in self.cache if c is not snap and not resumes(c)), None)
if old is None:
-@@ -489,28 +579,51 @@ class GlmEngine:
+@@ -553,28 +643,51 @@ class GlmEngine:
self._drop(snap)
dropped = True
continue
@@ -273,7 +275,7 @@ index d770cff..ddb968f 100644
from .decode import DepthPolicy, dflash_decode, mtp_decode, prefill, serial_decode, take_snapshot
from .drafter_choice import DrafterChoice, auto_decode
-@@ -523,7 +636,7 @@ class GlmEngine:
+@@ -587,7 +700,7 @@ class GlmEngine:
cut = len(hit.ids) if hit is not None else 0
self._take_over(list(hit.ids) if hit is not None else [])
if hit is not None and hit.rows is not None:
@@ -282,7 +284,7 @@ index d770cff..ddb968f 100644
hit.rows, hit.nbytes = None, 0 # live again
# an image prompt's rows are not its token ids' rows: nothing resumes from them, and they are not kept
self.live = list(prompt) if feed is None else []
-@@ -532,22 +645,32 @@ class GlmEngine:
+@@ -596,22 +709,32 @@ class GlmEngine:
# first token), keeps that state, and resumes from it as a later request would: so any prompt extending
# prompt[:point] passes through the same state there, fresh or resumed. Both ranks decide alike
point = grid_point(len(prompt), cut, self.grid) if draft and feed is None else None
@@ -326,7 +328,7 @@ index d770cff..ddb968f 100644
on_tokens([first])
if max_tokens <= 1 or (stop_eos and first in self.eos):
return stats
-@@ -634,12 +757,14 @@ class GlmEngine:
+@@ -698,12 +821,14 @@ class GlmEngine:
feed = VisionFeed(self, positions, rows)
feed.encode_s = time.perf_counter() - t
hit = self._resume(list(prompt), code) if draft and feed is None else None
@@ -341,8 +343,8 @@ index d770cff..ddb968f 100644
+ *(shared + [0] * SHARED_MOST)[:SHARED_MOST]] + code
from tensorfold.engine.grammar import pack
- self._share(header)
-@@ -648,7 +773,8 @@ class GlmEngine:
+ self._ring() # wakes rank 1, which idles on the store, not in the all-gather
+@@ -713,7 +838,8 @@ class GlmEngine:
self._share(pack(constraint))
if positions:
self._share(positions)
@@ -352,7 +354,7 @@ index d770cff..ddb968f 100644
stats.update(policy=spec, drafts=draft)
if hasattr(self.comm, "check"): # a RoCE wait that timed out inside a graph surfaces here
self.comm.check()
-@@ -659,32 +785,38 @@ class GlmEngine:
+@@ -724,33 +850,39 @@ class GlmEngine:
def follow(self) -> None:
"""Rank 1: mirror every request rank 0 serves, forever."""
@@ -365,6 +367,7 @@ index d770cff..ddb968f 100644
from tensorfold.engine.exact_sampling import Sampling
- while True:
+- self._await_bell()
- (max_tokens, stop_eos, draft, cached, s_lo, s_hi, s_top, t_lo, t_hi, top_k, p_lo, p_hi, m_lo, m_hi, shaped,
- images, *code) = self._share(None)
- prompt = self._share(None)
@@ -388,6 +391,7 @@ index d770cff..ddb968f 100644
- constraint, feed)
- if hasattr(self.comm, "check"):
- self.comm.check()
++ self._await_bell()
+ (max_tokens, stop_eos, draft, cached, s_lo, s_hi, s_top, t_lo, t_hi, top_k, p_lo, p_hi, m_lo, m_hi, shaped,
+ images, *rest) = self._share(None)
+ shared, code = [p for p in rest[:SHARED_MOST] if p], rest[SHARED_MOST:]
diff --git a/patches/0016-glm-decode-kernels.patch b/patches/0016-glm-decode-kernels.patch
index 8e258f0..841d572 100644
--- a/patches/0016-glm-decode-kernels.patch
+++ b/patches/0016-glm-decode-kernels.patch
@@ -1,9 +1,9 @@
diff --git tensorfold/cuda/kernels/qmm.cpp tensorfold/cuda/kernels/qmm.cpp
-index c46571f..c94e59b 100644
+index 81c10c7..bb6a473 100644
--- tensorfold/cuda/kernels/qmm.cpp
+++ tensorfold/cuda/kernels/qmm.cpp
-@@ -3,6 +3,8 @@
-
+@@ -4,6 +4,8 @@
+ bool qmm_clusters(int, bool);
void qmm_cuda(const at::Tensor&, const at::Tensor&, const at::Tensor&, const at::Tensor&, const at::Tensor&,
at::Tensor&, const at::Tensor&, int, int, int, int, bool, bool);
+void qmm_cfg_cuda(const at::Tensor&, const at::Tensor&, const at::Tensor&, const at::Tensor&, const at::Tensor&,
@@ -11,7 +11,7 @@ index c46571f..c94e59b 100644
void qmm_prefill_cuda(const at::Tensor&, const at::Tensor&, const at::Tensor&, const at::Tensor&, at::Tensor&, int,
int, bool, int);
void qmm_prefill8w_cuda(const at::Tensor&, const at::Tensor&, const at::Tensor&, const at::Tensor&, at::Tensor&, int,
-@@ -43,6 +45,36 @@ void qmm(const at::Tensor& x, const at::Tensor& xs, const at::Tensor& w, const a
+@@ -44,6 +46,36 @@ void qmm(const at::Tensor& x, const at::Tensor& xs, const at::Tensor& w, const a
static_cast<int>(bm), f32, reduce);
}
@@ -37,7 +37,7 @@ index c46571f..c94e59b 100644
+ out.scalar_type() == (f32 ? at::kFloat : at::kBFloat16), "out: (M, n)");
+ c10::cuda::CUDAGuard guard(x.device());
+ at::Tensor p;
-+ if (sk > 8) {
++ if (sk > 1 && !qmm_clusters(static_cast<int>(sk), true)) {
+ p = part.has_value() ? *part : at::empty({sk, m, n}, x.options().dtype(at::kFloat));
+ TORCH_CHECK(p.is_contiguous() && p.scalar_type() == at::kFloat && p.numel() >= sk * m * n, "part");
+ }
@@ -48,7 +48,7 @@ index c46571f..c94e59b 100644
// Prefill: x (M, K) bf16 times a packed 4-bit weight with each weight rounded once to bf16, one fp32 chain over K.
void qmm_prefill(const at::Tensor& x, const at::Tensor& w, const at::Tensor& scales, const at::Tensor& biases,
at::Tensor& out, int64_t n, int64_t gs, bool f32, int64_t tile) {
-@@ -114,6 +146,7 @@ void qmm_prefill8w(const at::Tensor& x8, const at::Tensor& a, const at::Tensor&
+@@ -115,6 +147,7 @@ void qmm_prefill8w(const at::Tensor& x8, const at::Tensor& a, const at::Tensor&
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
m.def("qmm", &qmm);
@@ -57,10 +57,10 @@ index c46571f..c94e59b 100644
m.def("qmm_prefill8", &qmm_prefill8);
m.def("qmm_prefill8w", &qmm_prefill8w);
diff --git tensorfold/cuda/kernels/qmm.cu tensorfold/cuda/kernels/qmm.cu
-index a763387..2828909 100644
+index e8afd09..c759255 100644
--- tensorfold/cuda/kernels/qmm.cu
+++ tensorfold/cuda/kernels/qmm.cu
-@@ -288,8 +288,51 @@ void dispatch(int bm, const at::Tensor& x, const at::Tensor& xs, const at::Tenso
+@@ -292,6 +292,28 @@ void dispatch(int bm, const at::Tensor& x, const at::Tensor& xs, const at::Tenso
}
}
@@ -88,12 +88,17 @@ index a763387..2828909 100644
+
} // namespace
+ // Clusters hold up to 8 K slices (the portable size) from sm_90; more, unreduced slices or older GPUs use the buffer.
+@@ -299,6 +321,27 @@ bool qmm_clusters(int SK, bool reduce) {
+ return SK > 1 && SK <= 8 && reduce && at::cuda::getCurrentDeviceProperties()->major >= 9;
+ }
+
+// ``qmm_cuda`` for decode rows (M <= 16, groups of 64, K slices reduced) on tile config ``cfg``.
+void qmm_cfg_cuda(const at::Tensor& x, const at::Tensor& xs, const at::Tensor& w, const at::Tensor& scales,
+ const at::Tensor& biases, at::Tensor& out, const at::Tensor& part, int N, int SK, bool f32, int cfg) {
+ const int M = x.size(0);
+ TORCH_CHECK(M <= 16, "qmm_cfg: decode rows (up to 16)");
-+ const bool cluster = SK > 1 && SK <= 8;
++ const bool cluster = qmm_clusters(SK, true);
+ if (f32) { if (cluster) dispatch_cfg<true, true>(cfg, x, xs, w, scales, biases, out, part, N, SK);
+ else dispatch_cfg<true, false>(cfg, x, xs, w, scales, biases, out, part, N, SK); }
+ else { if (cluster) dispatch_cfg<false, true>(cfg, x, xs, w, scales, biases, out, part, N, SK);
@@ -113,7 +118,7 @@ index a763387..2828909 100644
const at::Tensor& biases, at::Tensor& out, const at::Tensor& part, int N, int SK, int gs, int bm,
bool f32, bool reduce) {
diff --git tensorfold/cuda/kernels/qmm.py tensorfold/cuda/kernels/qmm.py
-index 8792eb5..da21210 100644
+index 2c8fc13..83e6366 100644
--- tensorfold/cuda/kernels/qmm.py
+++ tensorfold/cuda/kernels/qmm.py
@@ -16,7 +16,7 @@ def _ext():
@@ -149,7 +154,7 @@ index 8792eb5..da21210 100644
return out if sk == 1 or reduce else part.reshape(-1)[:sk * m * q.n].view(sk, m, q.n)
diff --git tensorfold/families/glm5_next/cuda/decode.py tensorfold/families/glm5_next/cuda/decode.py
-index 64f5be7..2debdad 100644
+index 79a6427..116000f 100644
--- tensorfold/families/glm5_next/cuda/decode.py
+++ tensorfold/families/glm5_next/cuda/decode.py
@@ -96,6 +96,10 @@ class Engine:
@@ -564,7 +569,7 @@ index 9975ab1..bd3a28e 100644
conv_w: torch.Tensor, state_in: torch.Tensor, a_log: torch.Tensor, dt_bias: torch.Tensor,
norm_w: torch.Tensor, eps: float, lower: float, rows: int, scratch: KDAScratch,
diff --git tensorfold/families/glm5_next/cuda/qmm.py tensorfold/families/glm5_next/cuda/qmm.py
-index f5225c6..7330c93 100644
+index e0b06a3..a3668ae 100644
--- tensorfold/families/glm5_next/cuda/qmm.py
+++ tensorfold/families/glm5_next/cuda/qmm.py
@@ -343,7 +343,29 @@ def matmul(x: torch.Tensor, q: Q4 | B16, xs: torch.Tensor | None = None, *, out:
diff --git a/patches/0018-glm-noise-policies.patch b/patches/0018-glm-noise-policies.patch
index 2e214e0..8fa6cd1 100644
--- a/patches/0018-glm-noise-policies.patch
+++ b/patches/0018-glm-noise-policies.patch
@@ -1,8 +1,8 @@
diff --git tensorfold/families/glm5_next/cuda/decode.py tensorfold/families/glm5_next/cuda/decode.py
-index 2debdad..2c20f11 100644
+index 116000f..946e2d6 100644
--- tensorfold/families/glm5_next/cuda/decode.py
+++ tensorfold/families/glm5_next/cuda/decode.py
-@@ -521,14 +521,24 @@ def serial_decode(e: Engine, pending: int, count: int, sampling: Sampling | None
+@@ -552,14 +552,24 @@ def serial_decode(e: Engine, pending: int, count: int, sampling: Sampling | None
class DepthPolicy:
@@ -29,7 +29,7 @@ index 2debdad..2c20f11 100644
def next(self, drafted: int, accepted: int) -> int:
if self.fixed:
return self.most
-@@ -644,7 +654,8 @@ def dflash_decode(e: Engine, drafter, pending: int, count: int, sampling: Sampli
+@@ -675,7 +685,8 @@ def dflash_decode(e: Engine, drafter, pending: int, count: int, sampling: Sampli
if copied:
drafts = copied
else:
@@ -40,7 +40,7 @@ index 2debdad..2c20f11 100644
tokens = e.verify_window([out[-1]] + drafts)
drafts = tokens[1:]
diff --git tensorfold/families/glm5_next/cuda/dflash2.py tensorfold/families/glm5_next/cuda/dflash2.py
-index 427d7f6..9e5aece 100644
+index 62c9373..25947bb 100644
--- tensorfold/families/glm5_next/cuda/dflash2.py
+++ tensorfold/families/glm5_next/cuda/dflash2.py
@@ -21,6 +21,31 @@ from .weights import Weights
@@ -75,7 +75,7 @@ index 427d7f6..9e5aece 100644
@triton.jit
-@@ -444,8 +469,12 @@ class Drafter:
+@@ -464,8 +489,12 @@ class Drafter:
return tokens, values, proj.numpy().astype(np.float64) # astype copies: nothing keeps cand_host
def chain(self, tokens: np.ndarray, values: np.ndarray, proj: np.ndarray, anchor: int, first: int,
@@ -90,7 +90,7 @@ index 427d7f6..9e5aece 100644
depth = tokens.shape[0]
sampled = sampling is not None and sampling.temperature > 0
-@@ -453,27 +482,44 @@ class Drafter:
+@@ -473,27 +502,44 @@ class Drafter:
noise = None
if sampled:
noise = -np.log(-np.log(uniform_rows(sampling.seed, first + np.arange(depth), tokens)))
@@ -139,10 +139,10 @@ index 427d7f6..9e5aece 100644
+ round_ms=round_ms)
return self.chain(tokens, values, proj, pending, self.context_end + 1, sampling, confidence)
diff --git tensorfold/families/glm5_next/cuda/engine.py tensorfold/families/glm5_next/cuda/engine.py
-index ddb968f..f50b3a1 100644
+index c4b826e..b626ecf 100644
--- tensorfold/families/glm5_next/cuda/engine.py
+++ tensorfold/families/glm5_next/cuda/engine.py
-@@ -149,11 +149,16 @@ def user_opener(model_dir: Path) -> int | None:
+@@ -151,11 +151,16 @@ def user_opener(model_dir: Path) -> int | None:
def encode_policy(spec: str) -> list[int]:
@@ -161,7 +161,7 @@ index ddb968f..f50b3a1 100644
try:
if spec == "auto" or spec.startswith("auto:"):
parts = spec.split(":")
-@@ -163,6 +168,8 @@ def encode_policy(spec: str) -> list[int]:
+@@ -165,6 +170,8 @@ def encode_policy(spec: str) -> list[int]:
if explore < 1 or every < 0 or not 0 <= margin < 1:
raise bad
return [4 if len(parts) == 1 else 5, explore, every, int(round(margin * 1e6))]
@@ -170,7 +170,7 @@ index ddb968f..f50b3a1 100644
if spec.startswith("f"):
code = encode_policy(spec[1:])
return [code[0] + 10] + code[1:] if code[0] else code
-@@ -186,8 +193,30 @@ def encode_policy(spec: str) -> list[int]:
+@@ -188,8 +195,30 @@ def encode_policy(spec: str) -> list[int]:
return [1 if most > 0 else 0, most, 0, 0]
@@ -203,7 +203,7 @@ index ddb968f..f50b3a1 100644
from .decode import DepthPolicy
-@@ -199,9 +228,22 @@ def decode_policy(code: list[int]):
+@@ -201,9 +230,22 @@ def decode_policy(code: list[int]):
return DepthPolicy(min(most, MAX_ROWS - 1), low=a / 1e6, high=b / 1e6)
if kind == 3:
return DepthPolicy(min(most, MAX_ROWS - 1), fixed=True, confidence=a / 1e6)
@@ -226,7 +226,7 @@ index ddb968f..f50b3a1 100644
def _f64_ints(x: float) -> list[int]:
return list(struct.unpack("<2i", struct.pack("<d", float(x))))
-@@ -674,7 +716,7 @@ class GlmEngine:
+@@ -738,7 +780,7 @@ class GlmEngine:
on_tokens([first])
if max_tokens <= 1 or (stop_eos and first in self.eos):
return stats
diff --git a/patches/0019-glm-decode-kernels2.patch b/patches/0019-glm-decode-kernels2.patch
index 1e1a691..05967b9 100644
--- a/patches/0019-glm-decode-kernels2.patch
+++ b/patches/0019-glm-decode-kernels2.patch
@@ -1,5 +1,5 @@
diff --git tensorfold/cuda/kernels/qmm.cu tensorfold/cuda/kernels/qmm.cu
-index 2828909..5853a81 100644
+index c759255..5aa20ae 100644
--- tensorfold/cuda/kernels/qmm.cu
+++ tensorfold/cuda/kernels/qmm.cu
@@ -56,9 +56,15 @@ __global__ void __launch_bounds__(WM * WN * 32) qmm_kernel(
@@ -21,7 +21,7 @@ index 2828909..5853a81 100644
}
unsigned char* ps = pw + T::W;
for (int c = tid; c < 2 * (T::S / 16); c += T::THREADS) {
-@@ -306,7 +312,11 @@ void dispatch_cfg(int cfg, const at::Tensor& x, const at::Tensor& xs, const at::
+@@ -310,7 +316,11 @@ void dispatch_cfg(int cfg, const at::Tensor& x, const at::Tensor& xs, const at::
case 9: launch<64, 16, 128, 1, 4, 6, F32, CLUSTER, true>(x, xs, w, s, b, out, part, N, SK); break;
case 10: launch<64, 16, 64, 1, 2, 8, F32, CLUSTER>(x, xs, w, s, b, out, part, N, SK); break;
case 11: launch<64, 16, 128, 1, 2, 6, F32, CLUSTER>(x, xs, w, s, b, out, part, N, SK); break;
@@ -35,10 +35,10 @@ index 2828909..5853a81 100644
}
diff --git tensorfold/families/glm5_next/cuda/forward.py tensorfold/families/glm5_next/cuda/forward.py
-index c4c8ab3..7f56f87 100644
+index c1fb8ce..adec331 100644
--- tensorfold/families/glm5_next/cuda/forward.py
+++ tensorfold/families/glm5_next/cuda/forward.py
-@@ -415,7 +415,9 @@ def moe_block(layer: LayerW, w: Weights, b: Buffers, R: int) -> torch.Tensor:
+@@ -433,7 +433,9 @@ def moe_block(layer: LayerW, w: Weights, b: Buffers, R: int) -> torch.Tensor:
glue.swiglu(b.sgu[lo:hi], b.sact[lo:hi], b.sxs[lo:hi], c.limit)
mm(b, b.sact[lo:hi], s.down, b.sxs[lo:hi], b.sy[lo:hi], f32=True)
with prof.timed("moe: combine"):
@@ -218,7 +218,7 @@ index 0000000..2236475
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
+}
diff --git tensorfold/families/glm5_next/cuda/latent.py tensorfold/families/glm5_next/cuda/latent.py
-index fff0bf6..50a7372 100644
+index e6d7924..cfe50b3 100644
--- tensorfold/families/glm5_next/cuda/latent.py
+++ tensorfold/families/glm5_next/cuda/latent.py
@@ -587,6 +587,12 @@ def _merge(PO, PM, PL, OUT, CNT, R, H: tl.constexpr, LW: tl.constexpr, NCH: tl.c
@@ -232,9 +232,9 @@ index fff0bf6..50a7372 100644
+
+
class LatentScratch:
- """Chunk partials for up to rows x heads x chunks, the absorbed queries and the attended latents."""
+ """Chunk partials for ``part_rows`` (one ``attention`` call) x heads x chunks; queries and latents for ``rows``."""
-@@ -615,7 +621,8 @@ def attention(qa: torch.Tensor, cache: torch.Tensor, pos: torch.Tensor, s: Laten
+@@ -616,7 +622,8 @@ def attention(qa: torch.Tensor, cache: torch.Tensor, pos: torch.Tensor, s: Laten
if hb not in (HB, HB_WIDE):
raise ValueError(f"latent attention: {hb} heads a tile, not {HB} or {HB_WIDE}")
_dense_chunks[(R, triton.cdiv(H, hb), nch)](qa, cache, pos, s.po[:n * LW], s.pm[:n], s.pl[:n], R, H=H, LW=LW,
@@ -244,7 +244,7 @@ index fff0bf6..50a7372 100644
_merge[(R, H)](s.po, s.pm, s.pl, out, s.dummy, R, H=H, LW=LW, NCH=nch, SPARSE=False, num_warps=4)
return out
-@@ -632,7 +639,8 @@ def sparse_attention(qa: torch.Tensor, cache: torch.Tensor, tokens: torch.Tensor
+@@ -633,7 +640,8 @@ def sparse_attention(qa: torch.Tensor, cache: torch.Tensor, tokens: torch.Tensor
pl = torch.empty((n,), dtype=torch.float32, device=qa.device)
hb = head_block(R)
_sparse_chunks[(R, triton.cdiv(H, hb), nch)](qa, cache, tokens, counts, po, pm, pl, R, W=W, H=H, LW=LW,
@@ -255,7 +255,7 @@ index fff0bf6..50a7372 100644
diff --git tensorfold/families/glm5_next/cuda/qmm.py tensorfold/families/glm5_next/cuda/qmm.py
-index 7330c93..65e7921 100644
+index a3668ae..074a507 100644
--- tensorfold/families/glm5_next/cuda/qmm.py
+++ tensorfold/families/glm5_next/cuda/qmm.py
@@ -350,7 +350,7 @@ def matmul(x: torch.Tensor, q: Q4 | B16, xs: torch.Tensor | None = None, *, out:
diff --git a/patches/0021-glm-dflash-policy-env.patch b/patches/0021-glm-dflash-policy-env.patch
index 0941897..3692a2e 100644
--- a/patches/0021-glm-dflash-policy-env.patch
+++ b/patches/0021-glm-dflash-policy-env.patch
@@ -1,5 +1,5 @@
diff --git tensorfold/families/glm5_next/cuda/engine.py tensorfold/families/glm5_next/cuda/engine.py
-index f50b3a1..edcf082 100644
+index b626ecf..e37584a 100644
--- tensorfold/families/glm5_next/cuda/engine.py
+++ tensorfold/families/glm5_next/cuda/engine.py
@@ -12,7 +12,9 @@ from pathlib import Path
@@ -13,8 +13,8 @@ index f50b3a1..edcf082 100644
EXL3_AUTO = DFLASH_POLICY # what auto runs on an EXL3 checkpoint with the draft model
GRAPH_ROWS = (1, 2, 3, 4, 5, 6, 7, 8) # verify windows (and MTP steps) captured as CUDA graphs; wider ones run eagerly
MAX_ROWS = 16 # the widest verify window (a pending token and up to 15 drafts: copy drafts)
-@@ -276,6 +278,8 @@ class GlmEngine:
- from tensorfold.cuda.geometry import PREFILL_ROWS, draft_geometry, mla_geometry, split_weights
+@@ -301,6 +303,8 @@ class GlmEngine:
+ split_weights)
encode_policy(policy) # a bad default fails here, not in the first request
+ if not encode_policy(DFLASH_POLICY)[0] >= 10:
diff --git a/patches/0023-glm-idle-doorbell.patch b/patches/0023-glm-idle-doorbell.patch
deleted file mode 100644
index 6253555..0000000
--- a/patches/0023-glm-idle-doorbell.patch
+++ /dev/null
@@ -1,58 +0,0 @@
-diff --git tensorfold/families/glm5_next/cuda/engine.py tensorfold/families/glm5_next/cuda/engine.py
-index edcf082..f37de3e 100644
---- tensorfold/families/glm5_next/cuda/engine.py
-+++ tensorfold/families/glm5_next/cuda/engine.py
-@@ -535,6 +535,37 @@ class GlmEngine:
- self.comm.all_gather(mine, got)
- return [got[:len(values)].tolist(), got[len(values):].tolist()]
-
-+ # -- the idle doorbell ---------------------------------------------------------------------------------------------
-+ # Between requests rank 1 used to wait inside the next header's all-gather: an NCCL kernel spinning on its GPU and
-+ # a host thread spinning in the copy that waits for it, for as long as the server stays idle. Rank 0 now rings a
-+ # key in the rendezvous TCP store (NCCL.store) before each request's header, and rank 1 blocks on that socket first,
-+ # so an idle rank 1 holds no GPU and no core. Communicators without a store (tests, single-rank runs) skip it.
-+ def _store(self):
-+ return getattr(self.comm, "store", None)
-+
-+ def _ring(self) -> None:
-+ 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")
-+
-+ def _await_bell(self) -> None:
-+ store = self._store()
-+ if store is None:
-+ return
-+ from datetime import timedelta
-+
-+ key = f"tf_glm_request_{getattr(self, '_bell', 0) + 1}"
-+ while True:
-+ try:
-+ store.wait([key], timedelta(hours=1))
-+ break
-+ except Exception as e: # an idle hour: wait again (a lost rank 0 is a connection error instead)
-+ if "timeout" not in str(e).lower():
-+ raise
-+ store.delete_key(key)
-+ self._bell = getattr(self, "_bell", 0) + 1
-+
- def _share(self, values: list[int] | None) -> list[int]:
- """Rank 0's int list on every rank (a length, then the values, through the all-gather)."""
-
-@@ -813,6 +844,7 @@ class GlmEngine:
- *(shared + [0] * SHARED_MOST)[:SHARED_MOST]] + code
- from tensorfold.engine.grammar import pack
-
-+ self._ring() # wakes rank 1, which idles on the store, not in the all-gather
- self._share(header)
- self._share(list(prompt))
- if constraint is not None: # the request's grammar: rank 1 compiles the same
-@@ -839,6 +871,7 @@ class GlmEngine:
-
- from tensorfold.engine.exact_sampling import Sampling
-
-+ self._await_bell()
- (max_tokens, stop_eos, draft, cached, s_lo, s_hi, s_top, t_lo, t_hi, top_k, p_lo, p_hi, m_lo, m_hi, shaped,
- images, *rest) = self._share(None)
- shared, code = [p for p in rest[:SHARED_MOST] if p], rest[SHARED_MOST:]
diff --git a/patches/0024-server-effort-max.patch b/patches/0023-server-effort-max.patch
similarity index 52%
rename from patches/0024-server-effort-max.patch
rename to patches/0023-server-effort-max.patch
index 0d6dbfe..ad0d14d 100644
--- a/patches/0024-server-effort-max.patch
+++ b/patches/0023-server-effort-max.patch
@@ -1,5 +1,5 @@
diff --git tensorfold/server/request_options.py tensorfold/server/request_options.py
-index 4e2b39e..a83156a 100644
+index 041c873..ad97a21 100644
--- tensorfold/server/request_options.py
+++ tensorfold/server/request_options.py
@@ -38,13 +38,13 @@ def parse_numbers(fields: dict[str, Any]) -> dict[str, Any]:
@@ -18,20 +18,29 @@ index 4e2b39e..a83156a 100644
+ return frozenset(re.findall(r"""['"](minimal|low|medium|high|xhigh|max)['"]""", template or ""))
- def thinking_fields(body: dict[str, Any], levels: frozenset[str] = frozenset()) -> dict[str, Any]:
-@@ -57,10 +57,11 @@ def thinking_fields(body: dict[str, Any], levels: frozenset[str] = frozenset())
+ def coerce_effort(effort: str | None, levels: frozenset[str] = frozenset()) -> str | None:
+@@ -52,11 +52,12 @@ def coerce_effort(effort: str | None, levels: frozenset[str] = frozenset()) -> s
+
+ if effort is None:
+ return None
+- # OpenAI's "high" and "minimal" are "xhigh" and "low" unless the template names them (GLM-5.3 names "high")
+- if effort in levels or effort not in ("high", "minimal"):
++ # OpenAI's "high" and "minimal" are "xhigh" and "low" unless the template names them (GLM-5.3 names "high"),
++ # and "max" is the template's own top level where it names one (GLM-5.3's default), else "xhigh"
++ if effort in levels or effort not in ("high", "minimal", "max"):
+ chosen = effort
+ else:
+- chosen = "xhigh" if effort == "high" else "low"
++ chosen = {"high": "xhigh", "minimal": "low", "max": "xhigh"}[effort]
+ # GLM lists high and leaves medium unnamed. medium is that high. xhigh stays xhigh, and the template renders Max.
+ if chosen == "medium" and "high" in levels and "medium" not in levels:
+ return "high"
+@@ -79,7 +80,7 @@ def thinking_fields(body: dict[str, Any], levels: frozenset[str] = frozenset())
effort = kwargs.get("reasoning_effort") # where vLLM's clients put it
if effort is not None:
if not isinstance(effort, str) or effort not in EFFORTS:
- raise RequestError("reasoning_effort must be none, minimal, low, medium, high or xhigh")
-- # OpenAI's "high" and "minimal" are "xhigh" and "low" unless the template names them (GLM-5.3 names "high")
-- named = effort in levels or effort not in ("high", "minimal")
-- fields["reasoning_effort"] = effort if named else {"high": "xhigh", "minimal": "low"}[effort]
+ raise RequestError("reasoning_effort must be none, minimal, low, medium, high, xhigh or max")
-+ # OpenAI's "high" and "minimal" are "xhigh" and "low" unless the template names them (GLM-5.3 names "high"),
-+ # and "max" is the template's own top level where it names one (GLM-5.3's default), else "xhigh"
-+ named = effort in levels or effort not in ("high", "minimal", "max")
-+ fields["reasoning_effort"] = effort if named else {"high": "xhigh", "minimal": "low", "max": "xhigh"}[effort]
+ fields["reasoning_effort"] = coerce_effort(effort, levels)
fields["enable_thinking"] = effort != "none"
if isinstance(kwargs, dict) and "enable_thinking" in kwargs: # an explicit switch wins
- fields["enable_thinking"] = bool(kwargs["enable_thinking"])
diff --git a/patches/0026-glm-prompt-select-rows.patch b/patches/0024-glm-prompt-select-rows.patch
similarity index 63%
rename from patches/0026-glm-prompt-select-rows.patch
rename to patches/0024-glm-prompt-select-rows.patch
index 70747cc..bb55db1 100644
--- a/patches/0026-glm-prompt-select-rows.patch
+++ b/patches/0024-glm-prompt-select-rows.patch
@@ -1,30 +1,8 @@
-diff --git tensorfold/cuda/geometry.py tensorfold/cuda/geometry.py
-index 82b565f..8f633f8 100644
---- tensorfold/cuda/geometry.py
-+++ tensorfold/cuda/geometry.py
-@@ -240,7 +240,8 @@ def mla_chunk_scratch(t: dict, world: int, capacity: int, *, latent: bool, prefi
- """A prompt chunk's transient bytes: token selection (fp32 pool scores, chosen pools, token lists), then sparse attention's partials."""
-
- heads, topk = int(t["num_attention_heads"]) // world, int(t.get("index_topk", 2048))
-- select = prefill_rows * (4 * ((capacity + 3) // 4) + 16 * (topk + 3))
-+ # the fp32 pool scores of at most 512 rows at once (glm5_next sparse.SELECT_ROWS), the token lists of the chunk's
-+ select = min(prefill_rows, 512) * 4 * ((capacity + 3) // 4) + prefill_rows * 16 * (topk + 3)
- if latent:
- return select + ((topk + 515) // 512) * prefill_rows * heads * (int(t.get("kv_lora_rank", 512)) + 2) * 4
- kd = int(t["qk_nope_head_dim"]) + int(t.get("qk_rope_head_dim", 0))
diff --git tensorfold/families/glm5_next/cuda/sparse.py tensorfold/families/glm5_next/cuda/sparse.py
-index 124c75c..616632a 100644
+index a7a252d..73cc902 100644
--- tensorfold/families/glm5_next/cuda/sparse.py
+++ tensorfold/families/glm5_next/cuda/sparse.py
-@@ -168,6 +168,7 @@ def pool_bucket(pos: int, R: int, np_max: int) -> int:
-
-
- PROMPT_ROWS = 64 # windows from this many rows (prompt chunks, eager) take the prompt selection below
-+SELECT_ROWS = 512 # a prompt chunk's rows scored at once (the fp32 pool scores grow with the capacity)
-
-
- def pool_count(pos: int, R: int, np_max: int) -> int:
-@@ -255,20 +256,28 @@ def _select_prompt(qi: torch.Tensor, wts: torch.Tensor, pk: torch.Tensor, pos: i
+@@ -276,20 +276,28 @@ def _select_prompt(qi: torch.Tensor, wts: torch.Tensor, pk: torch.Tensor, pos: i
dev = qi.device
NP = pool_count(pos, R, np_max)
diff --git a/patches/0025-cuda-memory-reserve.patch b/patches/0025-cuda-memory-reserve.patch
deleted file mode 100644
index ed39182..0000000
--- a/patches/0025-cuda-memory-reserve.patch
+++ /dev/null
@@ -1,40 +0,0 @@
-diff --git tensorfold/cuda/capacity.py tensorfold/cuda/capacity.py
-index 0136925..b39f665 100644
---- tensorfold/cuda/capacity.py
-+++ tensorfold/cuda/capacity.py
-@@ -5,6 +5,7 @@ from __future__ import annotations
- from dataclasses import dataclass
- import json
- import math
-+import os
- from pathlib import Path
- import re
- import struct
-@@ -154,13 +155,25 @@ def unified(torch) -> bool:
- return False
-
-
-+def reserve_bytes(total: int, *, host: bool = False) -> int:
-+ """What the budget leaves free: max(4 GiB, a tenth of ``total``), or TENSORFOLD_MEMORY_RESERVE_GIB (at least 2)."""
-+
-+ value = os.environ.get("TENSORFOLD_MEMORY_RESERVE_GIB", "").strip()
-+ if not value:
-+ return max(4 * GIB, total // 10 if host else math.ceil(total / 10))
-+ gib = float(value)
-+ if not 2 <= gib <= total / GIB:
-+ raise ValueError(f"TENSORFOLD_MEMORY_RESERVE_GIB={value}: from 2 GiB to the memory's size")
-+ return int(gib * GIB)
-+
-+
- def available_bytes(torch) -> int:
- free, total = map(int, torch.cuda.mem_get_info())
-- available = max(0, free - max(4 * GIB, math.ceil(total / 10)))
-+ available = max(0, free - reserve_bytes(total))
- memory = _meminfo()
- if memory is None:
- return available
-- host = max(0, memory["MemAvailable"] - max(4 * GIB, memory["MemTotal"] // 10))
-+ host = max(0, memory["MemAvailable"] - reserve_bytes(memory["MemTotal"], host=True))
- # one pool on a unified GPU: reclaimable page cache is available; a discrete GPU is bounded by both
- return host if unified(torch) else min(available, host)
-
diff --git a/patches/0025-glm-dflash2-ring.patch b/patches/0025-glm-dflash2-ring.patch
new file mode 100644
index 0000000..bbf971c
--- /dev/null
+++ b/patches/0025-glm-dflash2-ring.patch
@@ -0,0 +1,13 @@
+diff --git tensorfold/families/glm5_next/cuda/decode.py tensorfold/families/glm5_next/cuda/decode.py
+index 946e2d6..93ab4dc 100644
+--- tensorfold/families/glm5_next/cuda/decode.py
++++ tensorfold/families/glm5_next/cuda/decode.py
+@@ -324,7 +324,7 @@ def _saved_views(e: Engine, snap: Snapshot, drafter=None) -> list[torch.Tensor]:
+ DFlash2's window rows."""
+ n = len(snap.ids)
+ views = _row_views(e.st, n, max(snap.mtp_len, 0))
+- if drafter is not None and snap.drafter_end == n:
++ if drafter is not None and snap.drafter_end == n and not getattr(drafter, "ring", 0): # a ring's: drafter_rows
+ views += _drafter_views(drafter, n)
+ return views
+
diff --git a/patches/0028-glm-multi-kda.patch b/patches/0026-glm-multi-kda.patch
similarity index 99%
rename from patches/0028-glm-multi-kda.patch
rename to patches/0026-glm-multi-kda.patch
index 890717c..e22a436 100644
--- a/patches/0028-glm-multi-kda.patch
+++ b/patches/0026-glm-multi-kda.patch
@@ -1,8 +1,8 @@
diff --git tensorfold/families/glm5_next/cuda/forward.py tensorfold/families/glm5_next/cuda/forward.py
-index 7f56f87..5980279 100644
+index adec331..a5bf941 100644
--- tensorfold/families/glm5_next/cuda/forward.py
+++ tensorfold/families/glm5_next/cuda/forward.py
-@@ -594,6 +594,46 @@ def _shift_conv(conv: torch.Tensor, proj: torch.Tensor, keep: int) -> None:
+@@ -612,6 +612,46 @@ def _shift_conv(conv: torch.Tensor, proj: torch.Tensor, keep: int) -> None:
TAPS=taps, BLOCK=1024, num_warps=4)
diff --git a/patches/0027-glm-dflash2-ring.patch b/patches/0027-glm-dflash2-ring.patch
deleted file mode 100644
index 7fc9020..0000000
--- a/patches/0027-glm-dflash2-ring.patch
+++ /dev/null
@@ -1,402 +0,0 @@
-diff --git tensorfold/cuda/capacity.py tensorfold/cuda/capacity.py
-index b39f665..545336d 100644
---- tensorfold/cuda/capacity.py
-+++ tensorfold/cuda/capacity.py
-@@ -243,8 +243,10 @@ def admit(model_dir: str | Path, requested: int | None, explicit: bool | None, t
- geometry: Geometry | Callable, transform: Callable, *, rank: int = 0, world: int = 1,
- gather: Callable | None = None, draft_dir: Path | None = None,
- draft_geometry: Geometry | Callable | None = None, startup_copies: int = 0,
-- extra_files: tuple[Path, ...] = (), files: list[Path] | None = None) -> dict:
-- """Reach the same refusal or capacity before either rank allocates model tensors."""
-+ extra_files: tuple[Path, ...] = (), files: list[Path] | None = None,
-+ draft_weights: Callable[[Path], Weights] | None = None) -> dict:
-+ """Reach the same refusal or capacity before either rank allocates model tensors. ``draft_weights``: what the
-+ draft model holds, from its folder (default: its checkpoint at 4 bytes a value, or more)."""
-
- error = None
- plan = None
-@@ -258,8 +260,8 @@ def admit(model_dir: str | Path, requested: int | None, explicit: bool | None, t
- weights.mapped + more.mapped)
- weights = Weights(weights.resident, weights.staging + startup_copies * weights.resident, weights.mapped)
- if draft_dir is not None:
-- draft = estimate_weights(draft_dir, lambda name, info: (math.prod(info["shape"]) *
-- max(4, itemsize(info, name)), 0))
-+ draft = draft_weights(draft_dir) if draft_weights is not None else estimate_weights(
-+ draft_dir, lambda name, info: (math.prod(info["shape"]) * max(4, itemsize(info, name)), 0))
- weights = Weights(weights.resident + draft.resident, weights.staging + draft.staging, weights.mapped)
- if draft_geometry is not None:
- draft_geometry = draft_geometry(config(draft_dir)) if callable(draft_geometry) else draft_geometry
-diff --git tensorfold/cuda/geometry.py tensorfold/cuda/geometry.py
-index 8f633f8..a33333e 100644
---- tensorfold/cuda/geometry.py
-+++ tensorfold/cuda/geometry.py
-@@ -248,6 +248,15 @@ def mla_chunk_scratch(t: dict, world: int, capacity: int, *, latent: bool, prefi
- return select + 128 * heads * (kd + 2) * 4 * ((topk + 515) // 512)
-
-
-+def draft_ring_rows(window: int, block: int, tile: int = 64) -> int:
-+ """Rows of GLM's DFlash2 context ring (``dflash2.Drafter``, TF_GLM_DRAFT_RING): a block pass at context end s
-+ reads keys from the ``tile``-row tile holding s - window (older rows are masked for every query; ``window`` is the
-+ drafter's, sliding_window - 1) through its own rows s .. s + block - 1, at most window + block + tile - 1 rows,
-+ here rounded up to whole tiles; a kept state's window rows (window + 1) fit as well."""
-+
-+ return -(-(window + block + tile - 1) // tile) * tile
-+
-+
- def draft_geometry(t: dict, world: int, reserve: int, *, bounded: bool = False, streams: int = 1,
- kept: int = 0) -> Geometry:
- layers = int(t["num_hidden_layers"])
-@@ -264,6 +273,69 @@ 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 (``dflash2.Drafter``) on each of ``world`` ranks: one context of keys and values, a ring
-+ of ``draft_ring_rows`` rows whatever the window (``ring``, TF_GLM_DRAFT_RING; a flat buffer when the window is
-+ smaller) or ``capacity`` + block rows, and a block pass's activations. Kept prompt states' copies of its window
-+ count in the kept-state budget (``snapshot_bytes``)."""
-+
-+ layers = int(t["num_hidden_layers"])
-+ heads = int(t["num_key_value_heads"]) // world
-+ hd = int(t["head_dim"])
-+ block = int((t.get("dflash_config") or {}).get("block_size", 16))
-+ window = int(t.get("sliding_window", 0))
-+ fixed = 16 * max(64, block) * (int(t["hidden_size"]) + int(t["intermediate_size"])) * 4
-+ rows = draft_ring_rows(window - 1, block) if ring and window > 0 else 0
-+
-+ def bytes_at(capacity: int) -> int:
-+ slots = capacity + block if not rows else min(rows, capacity + block)
-+ return fixed + 2 * layers * heads * hd * slots * 2
-+ return Geometry(bytes_at, reserve)
-+
-+
-+def dflash2_weights(draft_dir, world: int):
-+ """What GLM's DFlash2 drafter (``dflash2.Drafter``) holds on each of ``world`` ranks, not its checkpoint's BF16:
-+ 4-bit copies (``qmm.quantize4``: groups of 64 with BF16 scales and biases, rows padded to 128) of fc, the
-+ convolutions' kernel projections and this rank's attention and MLP rows (k and v twice: in qkv and in kv); BF16
-+ norms, base kernels and selector projection; the selector's float32 codebooks in host memory (the same memory on
-+ GB10). Staging: the largest matrix read and uploaded in BF16 with its quantization temporaries (float32 groups
-+ of up to 8,192 rows, the packer's int64 lanes)."""
-+
-+ import re
-+
-+ from .capacity import Weights, headers
-+
-+ h = headers(draft_dir)
-+ shape = {name: [int(x) for x in info["shape"]] for name, info in h.items()}
-+
-+ def q4(n: int, k: int) -> int:
-+ return -(-n // 128) * 128 * k * 9 // 16
-+
-+ mats = [tuple(shape["fc.weight"])]
-+ quantized = {"fc.weight"}
-+ for i in sorted({int(m.group(1)) for m in map(re.compile(r"layers\.(\d+)\.").match, shape) if m}):
-+ p = f"layers.{i}."
-+ q, k, v = (shape[p + f"self_attn.{x}_proj.weight"] for x in "qkv")
-+ 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)]
-+ 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")}
-+ for conv in ("attention_conv", "mlp_conv"):
-+ name = p + conv + ".kernel_projection.weight"
-+ mats.append(tuple(shape[name]))
-+ quantized.add(name)
-+ resident = sum(q4(n, k) for n, k in mats)
-+ for name, dims in shape.items():
-+ if name not in quantized:
-+ resident += math.prod(dims) * (4 if name.endswith("_codebook") else 2)
-+ staging = max(4 * n * k + 24 * min(n, 8192) * k for n, k in mats)
-+ return Weights(resident, staging, 0)
-+
-+
- def _gdn_dims(t: dict, world: int) -> tuple:
- d, heads = int(t["hidden_size"]), int(t["num_attention_heads"])
- nk, nv = int(t["linear_num_key_heads"]) // world, int(t["linear_num_value_heads"]) // world
-diff --git tensorfold/families/glm5_next/cuda/decode.py tensorfold/families/glm5_next/cuda/decode.py
-index 2c20f11..cbff019 100644
---- tensorfold/families/glm5_next/cuda/decode.py
-+++ tensorfold/families/glm5_next/cuda/decode.py
-@@ -258,15 +258,20 @@ class Snapshot:
- drafter_end: int
- rows: list | None = None # the attention rows of ids, saved when another conversation took the live caches
- nbytes: int = 0
-+ drafter_rows: list | None = None # a ring drafter's window rows before drafter_end, copied when taken
-
-
- def take_snapshot(e: Engine, ids: Sequence[int], pending: torch.Tensor | None, *, mtp: bool,
- drafter=None) -> Snapshot:
-+ """A ring drafter's window rows are copied now (``_ring_window``): its next rows overwrite them in the ring."""
- st = e.st
- rec = st.rec[st.cur[0]].clone() if st.cur else st.rec[0].clone()
-- return Snapshot(list(ids), rec, st.conv.clone(), pending.clone() if pending is not None else None,
-+ snap = Snapshot(list(ids), rec, st.conv.clone(), pending.clone() if pending is not None else None,
- st.mtp_len - st.mtp_drafted if mtp and pending is not None else -1,
- drafter.context_end if drafter is not None else -1)
-+ if drafter is not None and getattr(drafter, "ring", 0) and snap.drafter_end == len(snap.ids):
-+ snap.drafter_rows = _ring_window(drafter, len(snap.ids))
-+ return snap
-
-
- def _row_views(st, n: int, m: int) -> list[torch.Tensor]:
-@@ -293,12 +298,33 @@ def _drafter_views(drafter, n: int) -> list[torch.Tensor]:
- return [c[:, lo:n] for c in drafter.kc] + [c[:, lo:n] for c in drafter.vc]
-
-
-+def _ring_slots(drafter, n: int) -> torch.Tensor:
-+ """Where a ring drafter (``drafter.ring`` rows) holds the rows ``_drafter_views`` names: positions mod the ring."""
-+ lo = max(0, n - drafter.window - 1)
-+ return torch.arange(lo, n, device=drafter.kc[0].device) % drafter.ring
-+
-+
-+def _ring_window(drafter, n: int) -> list[torch.Tensor]:
-+ """A copy of a ring drafter's window rows before n (``_drafter_views``' rows, in position order)."""
-+ idx = _ring_slots(drafter, n)
-+ return [c.index_select(1, idx) for c in drafter.kc] + [c.index_select(1, idx) for c in drafter.vc]
-+
-+
-+def _put_ring_window(drafter, n: int, rows: list[torch.Tensor]) -> None:
-+ idx = _ring_slots(drafter, n)
-+ caches = list(drafter.kc) + list(drafter.vc)
-+ if len(rows) != len(caches) or any(r.shape[1] != idx.numel() for r in rows):
-+ raise ValueError("a kept state's DFlash2 window does not match the drafter's ring")
-+ for c, r in zip(caches, rows):
-+ c.index_copy_(1, idx, r)
-+
-+
- def _saved_views(e: Engine, snap: Snapshot, drafter=None) -> list[torch.Tensor]:
- """The rows ``save_rows`` copies: the attention rows, and with ``drafter`` (whose context the snapshot ends at)
- DFlash2's window rows."""
- n = len(snap.ids)
- views = _row_views(e.st, n, max(snap.mtp_len, 0))
-- if drafter is not None and snap.drafter_end == n:
-+ if drafter is not None and snap.drafter_end == n and not getattr(drafter, "ring", 0): # a ring's: drafter_rows
- views += _drafter_views(drafter, n)
- return views
-
-@@ -311,6 +337,7 @@ def save_rows(e: Engine, snap: Snapshot, drafter=None) -> None:
- snap.nbytes = sum(r.numel() * r.element_size() for r in snap.rows)
- if drafter is None or snap.drafter_end != len(snap.ids):
- snap.drafter_end = -1
-+ snap.drafter_rows = None
-
-
- def row_bytes(e: Engine, snap: Snapshot, drafter=None) -> int:
-@@ -319,8 +346,9 @@ def row_bytes(e: Engine, snap: Snapshot, drafter=None) -> int:
-
-
- def snapshot_bytes(snap: Snapshot) -> int:
-- """Device memory a kept snapshot holds: its KDA states, conv windows, pending MTP rows and any saved rows."""
-- held = [snap.rec, snap.conv] + ([snap.pending] if snap.pending is not None else [])
-+ """Device memory a kept snapshot holds: its KDA states, conv windows, pending MTP rows, a ring drafter's window
-+ and any saved rows."""
-+ held = [snap.rec, snap.conv] + ([snap.pending] if snap.pending is not None else []) + (snap.drafter_rows or [])
- return sum(t.numel() * t.element_size() for t in held) + (snap.nbytes if snap.rows is not None else 0)
-
-
-@@ -342,6 +370,10 @@ def restore(e: Engine, snap: Snapshot, drafter=None) -> None:
- st.set_mtp_len(max(snap.mtp_len, 0))
- st.mtp_drafted = 0
- if drafter is not None:
-+ if getattr(drafter, "ring", 0):
-+ if snap.drafter_rows is None or snap.drafter_end != len(snap.ids):
-+ raise ValueError("this snapshot kept no DFlash2 window for the drafter's ring")
-+ _put_ring_window(drafter, snap.drafter_end, snap.drafter_rows)
- drafter.context_end = snap.drafter_end
- drafter.pos_dev.fill_(snap.drafter_end)
-
-diff --git tensorfold/families/glm5_next/cuda/dflash2.py tensorfold/families/glm5_next/cuda/dflash2.py
-index 9e5aece..20ed740 100644
---- tensorfold/families/glm5_next/cuda/dflash2.py
-+++ tensorfold/families/glm5_next/cuda/dflash2.py
-@@ -112,8 +112,14 @@ def _prep_kernel(QKV, QN, KN, COS, SIN, QO, KO, VO, L, stride, eps,
-
- @triton.jit
- def _dattn_kernel(Q, K, V, OUT, POS, window, scale, N: tl.constexpr, G: tl.constexpr, NH: tl.constexpr,
-- HD: tl.constexpr, CAP: tl.constexpr, BK: tl.constexpr, CAUSAL: tl.constexpr):
-- """Each KV head attends its query groups to sliding-window context and block keys, masking future block keys when causal, with fp32 softmax."""
-+ HD: tl.constexpr, CAP: tl.constexpr, BK: tl.constexpr, CAUSAL: tl.constexpr,
-+ RING: tl.constexpr = False):
-+ """Each KV head attends its query groups to sliding-window context and block keys, masking future block keys when causal, with fp32 softmax.
-+
-+ RING: K and V hold logical row p at p % CAP (``Drafter.ring``), and the loop starts at the tile holding the
-+ window's first row s - window instead of at 0. Every tile before it is masked for every query, and a masked tile
-+ leaves the running max, sum and accumulator bit for bit as they were (max(-1e30, -inf) = -1e30, alpha = exp(0) =
-+ 1, p = 0), so the tiles that are run see the same keys at the same offsets and the output is the flat buffer's."""
-
- kvh = tl.program_id(0)
- M: tl.constexpr = G * N
-@@ -128,11 +134,18 @@ def _dattn_kernel(Q, K, V, OUT, POS, window, scale, N: tl.constexpr, G: tl.const
- m_i = tl.full([M], -1e30, tl.float32)
- l_i = tl.zeros([M], tl.float32)
- acc = tl.zeros([M, HD], tl.float32)
-- for start in range(0, klen, BK):
-+ lo = 0
-+ if RING:
-+ lo = tl.maximum(s - window, 0) // BK * BK
-+ for start in range(lo, klen, BK):
- kk = start + tl.arange(0, BK)
- kin = kk < klen
-- k = tl.load(K + (kvh * CAP + kk[:, None]) * HD + d[None, :], mask=kin[:, None], other=0.0)
-- v = tl.load(V + (kvh * CAP + kk[:, None]) * HD + d[None, :], mask=kin[:, None], other=0.0)
-+ if RING:
-+ row = kk % CAP
-+ else:
-+ row = kk
-+ k = tl.load(K + (kvh * CAP + row[:, None]) * HD + d[None, :], mask=kin[:, None], other=0.0)
-+ v = tl.load(V + (kvh * CAP + row[:, None]) * HD + d[None, :], mask=kin[:, None], other=0.0)
- sc = tl.dot(q, tl.trans(k)) * scale
- ok = kin[None, :] & (((kk[None, :] < s) & (qpos[:, None] - kk[None, :] <= window)) | (kk[None, :] >= s))
- if CAUSAL:
-@@ -192,9 +205,12 @@ class Drafter:
- """Draft one sequence from position-indexed context using device lengths and static buffers shared by eager execution and CUDA graphs."""
-
- def __init__(self, draft_dir: str | Path, w: Weights, *, block: int | None = None, capacity: int = 2560,
-- tap_rows: int = 0) -> None:
-+ tap_rows: int = 0, ring: bool = False) -> None:
- """``tap_rows``: context updates up to this many rows (a verify window's kept rows) replay captured graphs too
-- (the block's own size always does)."""
-+ (the block's own size always does). ``ring`` (TF_GLM_DRAFT_RING): keep the context in a ring of
-+ ``geometry.draft_ring_rows`` rows (all a block pass reads: its sliding window and its own rows) instead of
-+ ``capacity`` rows; the drafts are the same bits. Kept states then copy the window when taken
-+ (``decode.take_snapshot``), since the ring overwrites it."""
-
- path = Path(draft_dir)
- cfg = json.loads((path / "config.json").read_text())
-@@ -271,7 +287,12 @@ class Drafter:
- torch.cuda.empty_cache()
- self.inv_freq = 1.0 / theta ** (torch.arange(hd // 2, device=dev, dtype=torch.float32) * 2 / hd)
- # Block rows sit past committed context and the next context update overwrites them.
-- self.cap = capacity + self.block
-+ from tensorfold.cuda.geometry import draft_ring_rows
-+
-+ self.capacity = capacity
-+ rows = draft_ring_rows(self.window, self.block) if ring and self.window >= 0 else 0
-+ self.ring = rows if 0 < rows < capacity + self.block else 0 # 0: a flat buffer, logical row p at p
-+ self.cap = self.ring or capacity + self.block
- self.kc = [torch.zeros((KV, self.cap, hd), dtype=torch.bfloat16, device=dev) for _ in self.layers]
- self.vc = [torch.zeros((KV, self.cap, hd), dtype=torch.bfloat16, device=dev) for _ in self.layers]
- self.pos_dev = torch.zeros((1,), dtype=torch.int64, device=dev)
-@@ -304,6 +325,12 @@ class Drafter:
- self.context_end = 0
- self.pos_dev.zero_()
-
-+ def _slots(self, n: int) -> torch.Tensor:
-+ """Where the rows at positions context_end .. context_end + n - 1 go: those positions, modulo the ring."""
-+
-+ idx = self.pos_dev + self.ar[:n]
-+ return idx % self.ring if self.ring else idx
-+
- # -- pieces -------------------------------------------------------------------------------------------------
- def _rotary(self, rows: int) -> tuple[torch.Tensor, torch.Tensor]:
- pos = (self.pos_dev + self.ar[:rows]).to(torch.float32)
-@@ -352,7 +379,7 @@ class Drafter:
- out = torch.empty((rows, self.heads * self.hd), dtype=torch.bfloat16, device=self.dev)
- _dattn_kernel[(self.kvh,)](q, self.kc[i], self.vc[i], out, self.pos_dev, self.window, self.hd ** -0.5,
- N=rows, G=self.heads // self.kvh, NH=self.heads, HD=self.hd, CAP=self.cap, BK=64,
-- CAUSAL=self.causal, num_warps=4)
-+ CAUSAL=self.causal, RING=bool(self.ring), num_warps=4)
- x = _dconv(self._row(out, L.o), dyn, L.a_base, 1, self.gs, x)
- normed, xs = self._norm(x, L.post_norm)
- dyn = _mm(normed, L.m_kp, xs)
-@@ -366,7 +393,7 @@ class Drafter:
- def _taps_compute(self, n: int) -> None:
- ctx, _ = self._norm(_mm(self.tap_in[:n], self.fc), self.hidden_norm)
- cos, sin = self._rotary(n)
-- idx = self.pos_dev + self.ar[:n]
-+ idx = self._slots(n)
- for i, L in enumerate(self.layers):
- _, k, v = self._prep(_mm(ctx, L.kv), L, cos, sin, 0)
- self.kc[i].index_copy_(1, idx, k)
-@@ -380,7 +407,7 @@ class Drafter:
- for start in range(0, taps.shape[0], self.tap_in.shape[0]):
- part = taps[start:start + self.tap_in.shape[0]]
- n = part.shape[0]
-- if self.context_end + n > self.cap - self.block:
-+ if self.context_end + n > self.capacity:
- raise ValueError("drafter context past its capacity")
- self.tap_in[:n].copy_(part)
- g = self.tap_graphs.get(n)
-@@ -398,7 +425,7 @@ class Drafter:
- x = torch.empty((n, self.D), dtype=torch.bfloat16, device=self.dev)
- glue.embed(self.ids, self.w.embed, self.D, 1, x)
- cos, sin = self._rotary(n)
-- idx = self.pos_dev + self.ar[:n]
-+ idx = self._slots(n)
- for i in range(len(self.layers)):
- x = self._layer(i, x, cos, sin, idx)
- h, hs = self._norm(x[1:], self.norm)
-diff --git tensorfold/families/glm5_next/cuda/engine.py tensorfold/families/glm5_next/cuda/engine.py
-index f37de3e..9187080 100644
---- tensorfold/families/glm5_next/cuda/engine.py
-+++ tensorfold/families/glm5_next/cuda/engine.py
-@@ -18,6 +18,10 @@ DFLASH_POLICY = os.environ.get("TF_GLM_DFLASH_POLICY", "").strip() or "fc5:0.3"
- EXL3_AUTO = DFLASH_POLICY # what auto runs on an EXL3 checkpoint with the draft model
- GRAPH_ROWS = (1, 2, 3, 4, 5, 6, 7, 8) # verify windows (and MTP steps) captured as CUDA graphs; wider ones run eagerly
- MAX_ROWS = 16 # the widest verify window (a pending token and up to 15 drafts: copy drafts)
-+# TF_GLM_DRAFT_RING=0: DFlash2 keeps its context in a flat buffer of the whole window (10,240 bytes a slot on each
-+# rank) instead of a ring of its 2,048-row sliding window and block (2,176 rows, 21.25 MiB; ``dflash2.Drafter``) and
-+# its blocks attend with today's loop over every context tile (masked); the drafts are the same bits either way
-+DRAFT_RING = os.environ.get("TF_GLM_DRAFT_RING", "1").strip() != "0"
- MTP_ROWS = 8 # rows an MTP step takes at once (a kept backlog is absorbed in steps of this)
- DENSE_CAPACITY = 2560 # cache slots while DSA attention stays dense (contexts up to 2,051 tokens)
- # --vision (rank 0): what startup reserves beside the tower's 1.05 GiB of bf16 weights for an encode and its
-@@ -275,7 +279,8 @@ class GlmEngine:
- from .weights import Config, load
- from .split import rule
- from tensorfold.cuda.capacity import admit
-- from tensorfold.cuda.geometry import PREFILL_ROWS, draft_geometry, mla_geometry, split_weights
-+ from tensorfold.cuda.geometry import (PREFILL_ROWS, dflash2_geometry, dflash2_weights, mla_geometry,
-+ split_weights)
-
- encode_policy(policy) # a bad default fails here, not in the first request
- if not encode_policy(DFLASH_POLICY)[0] >= 10:
-@@ -351,7 +356,8 @@ class GlmEngine:
- 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_geometry=lambda text: draft_geometry(text, 2, MAX_ROWS))
-+ draft_dir=drafter, draft_weights=lambda d: dflash2_weights(d, 2),
-+ draft_geometry=lambda text: dflash2_geometry(text, 2, MAX_ROWS, ring=DRAFT_RING))
- self.limit = self.capacity_plan["context_window"]
- capacity = self.capacity_plan["cache_slots"]
- long_context = self.limit > cfg.dense_limit
-@@ -365,7 +371,7 @@ class GlmEngine:
- # both ranks 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]) + \
-- self.split.code() + [int(self.dump is not None), quant_code, self.shared]
-+ self.split.code() + [int(self.dump is not None), quant_code, self.shared, int(DRAFT_RING)]
- # other conversations' kept prompts get what the window leaves, at most TF_GLM_CACHE_GIB, the same on both ranks
- plan = self.capacity_plan
- wanted = int(float(os.environ.get("TF_GLM_CACHE_GIB", "3")) * 2 ** 30)
-@@ -375,7 +381,7 @@ class GlmEngine:
- raise RuntimeError("the two 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_QUANT, TF_GLM_SHARED_PREFIX, TF_GLM_DRAFT_RING): "
- 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
-@@ -397,7 +403,7 @@ class GlmEngine:
- if drafter is not None:
- from .dflash2 import Drafter
-
-- self.drafter = Drafter(drafter, w, capacity=capacity, tap_rows=MAX_ROWS)
-+ self.drafter = Drafter(drafter, w, capacity=capacity, tap_rows=MAX_ROWS, ring=DRAFT_RING)
- self.e = Engine(w, capacity=capacity, max_rows=MAX_ROWS, prefill_rows=prefill_rows, graphs=True,
- graph_rows=GRAPH_ROWS, long_context=long_context,
- taps=self.drafter.tap_layers if self.drafter is not None else (), grid=self.grid,
-@@ -611,7 +617,7 @@ class GlmEngine:
-
- def _drop(self, snap) -> None:
- """Forget a kept snapshot and free its saved rows now, even while a caller still holds the object."""
-- snap.rows, snap.nbytes = None, 0
-+ snap.rows, snap.nbytes, snap.drafter_rows = None, 0, None
- self.cache.remove(snap)
-
- def _remember(self, snap) -> None:
diff --git a/patches/0029-glm-multi-dflash2.patch b/patches/0027-glm-multi-dflash2.patch
similarity index 99%
rename from patches/0029-glm-multi-dflash2.patch
rename to patches/0027-glm-multi-dflash2.patch
index dca381a..86bde2b 100644
--- a/patches/0029-glm-multi-dflash2.patch
+++ b/patches/0027-glm-multi-dflash2.patch
@@ -1,5 +1,5 @@
diff --git tensorfold/families/glm5_next/cuda/dflash2.py tensorfold/families/glm5_next/cuda/dflash2.py
-index 20ed740..a96d90f 100644
+index 25947bb..127ea01 100644
--- tensorfold/families/glm5_next/cuda/dflash2.py
+++ tensorfold/families/glm5_next/cuda/dflash2.py
@@ -50,14 +50,19 @@ def best_depth(q, round_ms) -> int:
@@ -25,7 +25,7 @@ index 20ed740..a96d90f 100644
grp = c // GS
d0 = tl.load(DYN + ((row * 2 + BRANCH) * 2) * G + grp, mask=ok, other=0.0).to(tl.float32)
d1 = tl.load(DYN + ((row * 2 + BRANCH) * 2 + 1) * G + grp, mask=ok, other=0.0).to(tl.float32)
-@@ -162,14 +167,14 @@ def _dattn_kernel(Q, K, V, OUT, POS, window, scale, N: tl.constexpr, G: tl.const
+@@ -157,14 +162,14 @@ def _dattn_kernel(Q, K, V, OUT, POS, window, scale, N: tl.constexpr, G: tl.const
def _dconv(x: torch.Tensor, dyn: torch.Tensor, base: torch.Tensor, branch: int, group_size: int,
@@ -42,7 +42,7 @@ index 20ed740..a96d90f 100644
return out
-@@ -184,6 +189,20 @@ def _mm(x: torch.Tensor, w: qmm.Q4, xs: torch.Tensor | None = None, *, f32: bool
+@@ -179,6 +184,20 @@ def _mm(x: torch.Tensor, w: qmm.Q4, xs: torch.Tensor | None = None, *, f32: bool
return qmm.matmul(x, w, xs, f32=f32)
@@ -63,7 +63,7 @@ index 20ed740..a96d90f 100644
@dataclass
class DraftLayer:
in_norm: torch.Tensor
-@@ -485,15 +504,7 @@ class Drafter:
+@@ -478,15 +497,7 @@ class Drafter:
self.cand_host.copy_(self.cand)
g = self.cand_host[:self.cand_n].view(self.gathered, self.block - 1, 2 * self.top_k)[:, :depth]
proj = self.cand_host[self.cand_n:].view(self.block - 1, -1)[:depth]
diff --git a/patches/0031-glm-lean-prompt-scratch.patch b/patches/0028-glm-lean-prompt-scratch.patch
similarity index 66%
rename from patches/0031-glm-lean-prompt-scratch.patch
rename to patches/0028-glm-lean-prompt-scratch.patch
index 506abc0..478c980 100644
--- a/patches/0031-glm-lean-prompt-scratch.patch
+++ b/patches/0028-glm-lean-prompt-scratch.patch
@@ -1,37 +1,32 @@
diff --git tensorfold/cuda/geometry.py tensorfold/cuda/geometry.py
-index dcf1610..49f10d0 100644
+index 7abbd21..0306412 100644
--- tensorfold/cuda/geometry.py
+++ tensorfold/cuda/geometry.py
-@@ -8,6 +8,7 @@ from .capacity import Geometry, itemsize
- PREFILL_ROWS = 2048 # a prompt chunk's rows: Flash Next and GLM keep buffers of this many rows
- PREFILL_ATT_ROWS = 256 # Flash Next's prompt attention block
- MLA_DECODE_ROWS = 64 # GLM's decode windows the MLA estimate sizes buffers for (its verify windows: at most this)
-+MLA_PROMPT_ATT_ROWS = 512 # GLM's prompt-chunk rows a dense latent attention call takes (forward.PROMPT_ATT_ROWS)
-
-
- def size(info: dict, name: str = "tensor") -> int:
-@@ -194,10 +195,26 @@ def _indexed_prefill_row(t: dict, world: int, h: int, hk: int, hd: int, nv: int,
+@@ -220,16 +220,26 @@ def _indexed_prefill_row(t: dict, world: int, h: int, hk: int, hd: int, nv: int,
+ 12 * streams + 64)
+-def exl3_expert_scratch(rows: int, slots: int, d: int, width: int) -> int:
+- """GLM's ``exl3_mm.Scratch`` for ``rows`` x ``slots`` pairs: fp16 rotated inputs and the fp32 split-K sums."""
+def exl3_expert_scratch(rows: int, slots: int, d: int, width: int, *, prompt: bool) -> int:
+ """GLM's ``exl3_mm.Scratch`` for a window of ``rows`` rows: fp16 rotated inputs of gate/up (2 x pairs x d) and down
+ (pairs x ``width``, a rank's expert width); a decode window's fp32 split-K sums (2 x 4 splits x pairs x
+ max(width, d)) and block counters (16-pair items); a prompt window's (``prompt``: TF_GLM_EXL3_PROMPT) launch order."""
-+
-+ pairs = rows * slots
+
+ pairs = rows * slots
+- return 2 * pairs * d * 2 + pairs * width * 2 + 2 * 4 * pairs * max(width, d) * 4
+ total = 2 * pairs * d * 2 + pairs * width * 2
+ if prompt:
+ return total + 4 + 4 + (pairs // 16 + 1024) * 4
+ return total + 2 * 4 * pairs * max(width, d) * 4 + (pairs + pairs // 16 + 1) * max(1, width // 128) * 4 + 4
-+
-+
+
+
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) -> Geometry:
+- """GLM's engine; ``mtp``: whether it holds the MTP head's caches and buffers (None: when the checkpoint has one)."""
+ prefill_rows: int = PREFILL_ROWS, mtp: bool | None = None, onepass: bool = False,
+ exl3_prompt: bool = True, prompt_split_k: bool = True) -> 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)."""
++ """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
@@ -39,11 +34,13 @@ index dcf1610..49f10d0 100644
linear, attention = layer_counts(t)
lin = t.get("linear_attn_config") or {}
heads = int(t["num_attention_heads"]) // world
-@@ -220,16 +237,22 @@ def mla_geometry(t: dict, world: int, reserve: int, *, minimum_slots: int = 2560
+@@ -252,15 +262,18 @@ def mla_geometry(t: dict, world: int, reserve: int, *, minimum_slots: int = 2560
# prompt-chunk buffers: at most 5 row extents a row without the head
fixed += prefill_rows * 5 * (extent - int(t["vocab_size"]) // world)
if (t.get("_quantization") or {}).get("quant_method") == "exl3":
-- fixed += 128 * rows * slots * max(width, d) * 4
+- # EXL3 experts' scratch (decode windows, the MTP head's, a prompt chunk) and the prompt's BF16 split-K partials
+- fixed += (2 if mtp else 1) * exl3_expert_scratch(rows, slots, d, width)
+- fixed += exl3_expert_scratch(prefill_rows, slots, d, width) + 8 * prefill_rows * 16384 * 4
+ # 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)
+ fixed += (2 if mtp else 1) * exl3_expert_scratch(rows, slots, d, width, prompt=False)
@@ -55,18 +52,13 @@ index dcf1610..49f10d0 100644
- scratch = mla_chunk_scratch(t, world, capacity, latent=latent, prefill_rows=prefill_rows)
+ scratch = mla_chunk_scratch(t, world, capacity, latent=latent, prefill_rows=prefill_rows, onepass=onepass)
if latent:
-- # latent cache; one prompt chunk's latent partials and absorbed rows (the MTP absorbs through the same buffers)
+- # latent cache; a prompt chunk's partials (MLA_PROMPT_ATT_ROWS rows at a time) and absorbed rows (MTP's too)
+ # 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)
cache = count * capacity * lw * 2
dense = min(capacity, minimum_slots) + prefill_rows
-- scratch += ((dense + 511) // 512) * prefill_rows * heads * (lw + 2) * 4 + 4 * prefill_rows * heads * lw
-+ scratch += (((dense + 511) // 512) * min(prefill_rows, MLA_PROMPT_ATT_ROWS) * heads * (lw + 2) * 4
-+ + 4 * prefill_rows * heads * lw)
- else:
- cache = count * capacity * heads * (kd + vd) * 2
- scratch += (2 if mtp else 1) * ((capacity + rows + 511) // 512) * rows * heads * (kd + 2) * 4
-@@ -238,12 +261,16 @@ def mla_geometry(t: dict, world: int, reserve: int, *, minimum_slots: int = 2560
+ scratch += (((dense + 511) // 512) * min(prefill_rows, MLA_PROMPT_ATT_ROWS) * heads * (lw + 2) * 4
+@@ -273,12 +286,16 @@ def mla_geometry(t: dict, world: int, reserve: int, *, minimum_slots: int = 2560
return Geometry(bytes_at, reserve, minimum_slots)
@@ -78,18 +70,18 @@ index dcf1610..49f10d0 100644
+ 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))
- # the fp32 pool scores of at most 512 rows at once (glm5_next sparse.SELECT_ROWS), the token lists of the chunk's
- select = min(prefill_rows, 512) * 4 * ((capacity + 3) // 4) + prefill_rows * 16 * (topk + 3)
+ # 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:
+ return select
if latent:
return select + ((topk + 515) // 512) * prefill_rows * heads * (int(t.get("kv_lora_rank", 512)) + 2) * 4
kd = int(t["qk_nope_head_dim"]) + int(t.get("qk_rope_head_dim", 0))
diff --git tensorfold/families/glm5_next/cuda/engine.py tensorfold/families/glm5_next/cuda/engine.py
-index 8fb8085..37051b4 100644
+index e37584a..1a65d1c 100644
--- tensorfold/families/glm5_next/cuda/engine.py
+++ tensorfold/families/glm5_next/cuda/engine.py
-@@ -376,11 +376,15 @@ class GlmEngine:
+@@ -372,11 +372,15 @@ class GlmEngine:
weights_estimate = lambda name, info: ((math.prod(info["shape"]) * 2, 0)
if name.startswith("model.visual.") else text_weights(name, info))
@@ -107,10 +99,10 @@ index 8fb8085..37051b4 100644
self.capacity_plan = admit(model_dir, context if explicit else cfg.dense_limit, explicit, torch,
geometry,
diff --git tensorfold/families/glm5_next/cuda/forward.py tensorfold/families/glm5_next/cuda/forward.py
-index 5980279..d2e45c5 100644
+index a5bf941..f09d0dd 100644
--- tensorfold/families/glm5_next/cuda/forward.py
+++ tensorfold/families/glm5_next/cuda/forward.py
-@@ -16,6 +16,21 @@ from .attention import AttnScratch, attention, kv_write
+@@ -17,6 +17,21 @@ from .attention import AttnScratch, attention, kv_write
from .weights import LayerW, Weights
@@ -132,21 +124,21 @@ index 5980279..d2e45c5 100644
class Buffers:
"""Scratch for windows of up to ``rows`` rows, sliced [:R] for smaller ones; ``prefill`` for prompt chunks."""
-@@ -35,8 +50,12 @@ class Buffers:
+@@ -36,9 +51,12 @@ class Buffers:
if latent.ENABLED:
# Dense attention only ever covers contexts up to the dense limit; longer rows go sparse.
self.attn = None
+- # a prompt chunk's dense pass runs PROMPT_ATT_ROWS rows at a time: its fp32 partials hold that many rows
+ # a prompt chunk's dense pass runs PROMPT_ATT_ROWS rows at a time (``dense_attention``): its fp32
+ # partials hold that many rows, not the chunk's
self.lat_s = latent.LatentScratch(rows, HL, latent.chunks_for(min(capacity, 2560) + rows), dev,
-- lw=c.kv_lora)
-+ lw=c.kv_lora, part_rows=PROMPT_ATT_ROWS if prefill else rows)
+ lw=c.kv_lora, part_rows=PROMPT_ATT_ROWS if prefill else rows)
+ self.att_starts = (torch.arange(0, rows, self.lat_s.part_rows, dtype=torch.int32, device=dev)
+ if prefill else None)
else:
self.attn = AttnScratch(1 if prefill else rows, HL, c.qk_dim, capacity, dev)
if prefill:
-@@ -104,7 +123,10 @@ class Buffers:
+@@ -106,7 +124,10 @@ class Buffers:
# rank partials
self.part = torch.empty((rows, D), dtype=f32, device=dev)
self.gath = torch.empty((w.world * rows * D,), dtype=f32, device=dev)
@@ -158,80 +150,58 @@ index 5980279..d2e45c5 100644
# final
self.hidden = torch.empty((rows, D), dtype=bf, device=dev)
self.fnormed = torch.empty((rows, D), dtype=bf, device=dev)
-@@ -342,6 +364,25 @@ def dense_rows(c, R: int, host_pos: int | None) -> int:
+@@ -344,19 +365,22 @@ def dense_rows(c, R: int, host_pos: int | None) -> int:
return min(R, max(0, sparse.SPARSE_FROM - host_pos))
+-def dense_attention(qa: torch.Tensor, lc: torch.Tensor, pos_dev: torch.Tensor, s: latent.LatentScratch, *,
+- scale: float, nch: int, out: torch.Tensor, hb: int | None = None) -> torch.Tensor:
+- """``latent.attention`` in blocks of ``part_rows`` rows, each at its first row's position: one call's bits a row
+- (``hb``: the window's ``head_block``, which a window's first rows computed alone keep)."""
+def dense_attention(qa: torch.Tensor, lc: torch.Tensor, pos_dev: torch.Tensor, s, *, scale: float, nch: int,
+ out: torch.Tensor, hb: int, starts: torch.Tensor | None = None) -> torch.Tensor:
+ """``latent.attention`` of qa's rows in blocks of the scratch's ``part_rows`` (block i's queries at device
+ position pos_dev + starts[i], ``starts`` = arange(0, rows, part_rows)): every row gets the bits of one call over
+ all of them, since a row's programs read only its query, keys up to its position and its own partials, and
+ ``hb`` and ``nch`` stay the window's (``latent.attention``)."""
-+
-+ R, step = qa.shape[0], s.part_rows
-+ if R <= step:
-+ return latent.attention(qa, lc, pos_dev, s, scale=scale, nch=nch, out=out, hb=hb)
+
+ R, step = qa.shape[0], s.part_rows
+- hb = latent.head_block(R) if hb is None else hb
+ if R <= step:
+ return latent.attention(qa, lc, pos_dev, s, scale=scale, nch=nch, out=out, hb=hb)
+- for r0 in range(0, R, step):
+ if starts is None or starts.numel() < -(-R // step):
+ raise ValueError(f"dense attention of {R} rows in blocks of {step} needs the blocks' start offsets")
+ at = pos_dev + starts # each block's first row's position, on the device
+ for i, r0 in enumerate(range(0, R, step)):
-+ r1 = min(R, r0 + step)
+ r1 = min(R, r0 + step)
+- at = pos_dev if r0 == 0 else pos_dev + r0 # the block's first row's position, on the device
+- latent.attention(qa[r0:r1], lc, at, s, scale=scale, nch=nch, out=out[r0:r1], hb=hb)
+ latent.attention(qa[r0:r1], lc, at[i:i + 1], s, scale=scale, nch=nch, out=out[r0:r1], hb=hb)
-+ return out
-+
-+
- def _dsa_latent(a, w: Weights, lc: torch.Tensor, pos_dev: torch.Tensor, b: Buffers, R: int, nch: int | None,
- index, host_pos: int | None, sparse_np: int | None = None) -> torch.Tensor:
- """DSA on the latent cache: the same indexer and selection, attention over latents with kv_b's key blocks absorbed into the query."""
-@@ -370,8 +411,8 @@ def _dsa_latent(a, w: Weights, lc: torch.Tensor, pos_dev: torch.Tensor, b: Buffe
- # and only the rows before it (a row's dense bits do not depend on the rows after it: latent.attention).
+ return out
+
+
+@@ -389,7 +413,7 @@ def _dsa_latent(a, w: Weights, lc: torch.Tensor, pos_dev: torch.Tensor, b: Buffe
dense = dense_rows(c, R, host_pos) if sparse_rows else R
with prof.timed("dsa: dense attention"):
-- latent.attention(qa[:dense], lc, pos_dev, s, scale=scale, nch=min(nch or s.nch, s.nch), out=ol[:dense],
-- hb=latent.head_block(R))
-+ dense_attention(qa[:dense], lc, pos_dev, s, scale=scale, nch=min(nch or s.nch, s.nch), out=ol[:dense],
+ dense_attention(qa[:dense], lc, pos_dev, s, scale=scale, nch=min(nch or s.nch, s.nch), out=ol[:dense],
+- hb=latent.head_block(R))
+ hb=latent.head_block(R), starts=b.att_starts if b.prefill else None)
if sparse_rows:
with prof.timed("dsa: select tokens"):
mm(b, b.qr[:R], ix.qb, b.xs_qr[:R], b.qi[:R])
diff --git tensorfold/families/glm5_next/cuda/latent.py tensorfold/families/glm5_next/cuda/latent.py
-index 50a7372..3026586 100644
+index cfe50b3..3026586 100644
--- tensorfold/families/glm5_next/cuda/latent.py
+++ tensorfold/families/glm5_next/cuda/latent.py
-@@ -594,13 +594,16 @@ def chunk_stages() -> int:
+@@ -594,7 +594,9 @@ def chunk_stages() -> int:
class LatentScratch:
-- """Chunk partials for up to rows x heads x chunks, the absorbed queries and the attended latents."""
--
-- def __init__(self, rows: int, heads: int, chunks: int, device, lw: int = L) -> None:
-- self.rows, self.heads, self.nch, self.lw = rows, heads, chunks, lw
-- self.po = torch.empty((chunks * rows * heads * lw,), dtype=torch.float32, device=device)
-- self.pm = torch.empty((chunks * rows * heads,), dtype=torch.float32, device=device)
-- self.pl = torch.empty((chunks * rows * heads,), dtype=torch.float32, device=device)
+- """Chunk partials for ``part_rows`` (one ``attention`` call) x heads x chunks; queries and latents for ``rows``."""
+ """Chunk partials for up to part_rows x heads x chunks (``part_rows``: the rows one ``attention`` call takes,
+ default ``rows``; a prompt chunk's dense pass runs in blocks of them), the absorbed queries and the attended
+ latents of up to ``rows``."""
-+
-+ def __init__(self, rows: int, heads: int, chunks: int, device, lw: int = L, part_rows: int | None = None) -> None:
-+ part_rows = rows if part_rows is None else min(rows, part_rows)
-+ self.rows, self.part_rows, self.heads, self.nch, self.lw = rows, part_rows, heads, chunks, lw
-+ self.po = torch.empty((chunks * part_rows * heads * lw,), dtype=torch.float32, device=device)
-+ self.pm = torch.empty((chunks * part_rows * heads,), dtype=torch.float32, device=device)
-+ self.pl = torch.empty((chunks * part_rows * heads,), dtype=torch.float32, device=device)
- self.qa = torch.empty((rows, heads, lw), dtype=torch.bfloat16, device=device)
- self.ol = torch.empty((rows, heads, lw), dtype=torch.bfloat16, device=device)
- self.dummy = torch.zeros((1,), dtype=torch.int32, device=device)
-@@ -613,9 +616,9 @@ def attention(qa: torch.Tensor, cache: torch.Tensor, pos: torch.Tensor, s: Laten
- Row r's programs read only its query, keys 0 .. pos + r and its own partials, so the first rows of a window
- computed alone (``qa[:n]``, the same nch and ``hb``: the window's ``head_block``) get the window's bits."""
- R, H, LW = qa.shape
-- if nch > s.nch or R > s.rows or LW != s.lw:
-+ if nch > s.nch or R > s.part_rows or LW != s.lw:
- raise ValueError(f"latent attention: {R} rows, {nch} chunks, width {LW} past the scratch's "
-- f"{s.rows}, {s.nch}, {s.lw}")
-+ f"{s.part_rows}, {s.nch}, {s.lw}")
- n = nch * R * H
- hb = head_block(R) if hb is None else hb
- if hb not in (HB, HB_WIDE):
+
+ def __init__(self, rows: int, heads: int, chunks: int, device, lw: int = L, part_rows: int | None = None) -> None:
+ part_rows = rows if part_rows is None else min(rows, part_rows)
diff --git a/patches/0032-glm-multi-dsa.patch b/patches/0029-glm-multi-dsa.patch
similarity index 97%
rename from patches/0032-glm-multi-dsa.patch
rename to patches/0029-glm-multi-dsa.patch
index a8648c6..b28bc36 100644
--- a/patches/0032-glm-multi-dsa.patch
+++ b/patches/0029-glm-multi-dsa.patch
@@ -1,8 +1,8 @@
diff --git tensorfold/families/glm5_next/cuda/forward.py tensorfold/families/glm5_next/cuda/forward.py
-index d2e45c5..1a8894f 100644
+index f09d0dd..cb39952 100644
--- tensorfold/families/glm5_next/cuda/forward.py
+++ tensorfold/families/glm5_next/cuda/forward.py
-@@ -428,6 +428,48 @@ def _dsa_latent(a, w: Weights, lc: torch.Tensor, pos_dev: torch.Tensor, b: Buffe
+@@ -429,6 +429,48 @@ def _dsa_latent(a, w: Weights, lc: torch.Tensor, pos_dev: torch.Tensor, b: Buffe
return out_proj(w, b, o, a.o, qmm.group_sums(o, b.xs_ao[:R]), R)
@@ -276,10 +276,10 @@ index 0000000..91b3d06
+ self.counts = torch.zeros((rows,), dtype=torch.int32, device=device)
+ self.split = split_scratch(rows, pools, device)
diff --git tensorfold/families/glm5_next/cuda/sparse.py tensorfold/families/glm5_next/cuda/sparse.py
-index 616632a..dcd849f 100644
+index 73cc902..6cfe91d 100644
--- tensorfold/families/glm5_next/cuda/sparse.py
+++ tensorfold/families/glm5_next/cuda/sparse.py
-@@ -11,6 +11,7 @@ TOPK_POOLS = 512
+@@ -13,6 +13,7 @@ TOPK_POOLS = 512
BR = 16
# the first position whose row select_tokens counts (npool > TOPK_POOLS): rows before it keep dense attention
SPARSE_FROM = (TOPK_POOLS + 1) * POOL - 1
@@ -287,13 +287,14 @@ index 616632a..dcd849f 100644
@triton.jit
-@@ -152,12 +153,17 @@ def _select_rows(S, OUT, NP, K: tl.constexpr, BLOCK: tl.constexpr):
+@@ -163,13 +164,19 @@ def _select_rows(S, OUT, NP, POS, K: tl.constexpr, BLOCK: tl.constexpr, VISIBLE:
- def top_pools(scores: torch.Tensor, k: int) -> torch.Tensor:
+ def top_pools(scores: torch.Tensor, k: int, pos_dev: torch.Tensor | None = None) -> torch.Tensor:
- """``_top_pools``'s pools in one kernel, ascending, without int64 keys, top-k or sort."""
+ """``_top_pools``'s pools, ascending, without int64 keys, top-k or sort: one program a row, or for a decode
-+ window's long rows the split selection (select_split); the same pools either way."""
++ window's long rows the split selection (select_split); the same pools either way. ``pos_dev``: the rows sit at
++ pos_dev, pos_dev + 1, .. and the one-program selection reads each row's visible pools only (the same pools)."""
R, NP = scores.shape
if NP < k or not scores.is_contiguous():
return _top_pools(scores, k)
@@ -302,12 +303,13 @@ index 616632a..dcd849f 100644
+ # one program a row (speed only): decode rows past 1,024 scores 4,096 a step, prompt chunks' rows 1,024
+ block, warps = (4096, 8) if R < SPLIT_ROWS and NP > 1024 else (1024, 4)
out = torch.empty((R, k), dtype=torch.int64, device=scores.device)
-- _select_rows[(R,)](scores, out, NP, K=k, BLOCK=1024, num_warps=4)
-+ _select_rows[(R,)](scores, out, NP, K=k, BLOCK=block, num_warps=warps)
+ _select_rows[(R,)](scores, out, NP, pos_dev if pos_dev is not None else scores,
+- K=k, BLOCK=1024, VISIBLE=pos_dev is not None, num_warps=4)
++ K=k, BLOCK=block, VISIBLE=pos_dev is not None, num_warps=warps)
return out
-@@ -370,3 +376,357 @@ def sparse_attention(q: torch.Tensor, kc: torch.Tensor, vc: torch.Tensor, tokens
+@@ -390,3 +397,357 @@ def sparse_attention(q: torch.Tensor, kc: torch.Tensor, vc: torch.Tensor, tokens
_sparse_chunks[(n, H, nch)](q[rows], kc, vc, tokens[rows], counts[rows], po, pm, pl, W=W, H=H, D=D, CH=CH,
SCALE=scale, num_warps=4, num_stages=1)
_sparse_merge[(n, H)](po, pm, pl, out[rows], counts[rows], H=H, D=D, NCH=nch, CH=CH, num_warps=4)
diff --git a/patches/0030-glm-mtp-off.patch b/patches/0030-glm-mtp-off.patch
deleted file mode 100644
index 8307fb9..0000000
--- a/patches/0030-glm-mtp-off.patch
+++ /dev/null
@@ -1,172 +0,0 @@
-diff --git tensorfold/cuda/geometry.py tensorfold/cuda/geometry.py
-index a33333e..dcf1610 100644
---- tensorfold/cuda/geometry.py
-+++ tensorfold/cuda/geometry.py
-@@ -195,7 +195,9 @@ def _indexed_prefill_row(t: dict, world: int, h: int, hk: int, hd: int, nv: int,
-
-
- def mla_geometry(t: dict, world: int, reserve: int, *, minimum_slots: int = 2560, latent: bool = False,
-- prefill_rows: int = PREFILL_ROWS) -> Geometry:
-+ prefill_rows: int = PREFILL_ROWS, mtp: bool | None = 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)."""
- linear, attention = layer_counts(t)
- lin = t.get("linear_attn_config") or {}
- heads = int(t["num_attention_heads"]) // world
-@@ -204,7 +206,7 @@ def mla_geometry(t: dict, world: int, reserve: int, *, minimum_slots: int = 2560
- 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))
- vd, index = int(t["v_head_dim"]), int(t.get("index_head_dim", 128))
-- mtp = int(t.get("num_nextn_predict_layers", 0)) > 0
-+ mtp = int(t.get("num_nextn_predict_layers", 0)) > 0 if mtp is None else bool(mtp)
- rows, d, streams = MLA_DECODE_ROWS, int(t["hidden_size"]), int(t.get("hc_mult", 4))
- fixed = linear * (4 * lh * ld * ld * 4 + 3 * (conv - 1) * 3 * lh * ld * 2)
- fixed += linear * rows * (3 * lh * ld + 2 * ld + lh) * 2
-diff --git tensorfold/families/glm5_next/cuda/engine.py tensorfold/families/glm5_next/cuda/engine.py
-index 9187080..8fb8085 100644
---- tensorfold/families/glm5_next/cuda/engine.py
-+++ tensorfold/families/glm5_next/cuda/engine.py
-@@ -76,6 +76,30 @@ def grid_point(n: int, cut: int, grid: int) -> int | None:
- return point if point > cut else None
-
-
-+def mtp_head(drafter: bool, serial_only: bool, layers: int, value: str | None = None) -> bool:
-+ """TF_GLM_MTP: whether the engine loads and runs the checkpoint's MTP head (``layers``: its
-+ num_nextn_predict_layers). auto (the default): off when a DFlash2 drafter is loaded or no request drafts
-+ (--no-drafts), on otherwise; 1: on whenever the checkpoint has one (MTP drafts and the per-round choice between
-+ both drafters stay available beside DFlash2); 0: off. Off, the head's weights (1.77 GiB a rank), caches and
-+ decode buffers are never allocated, prompts skip its absorb, and MTP policies draft with DFlash2 instead: the
-+ same replies, since drafts only propose."""
-+
-+ value = os.environ.get("TF_GLM_MTP", "") if value is None else value
-+ value = value.strip().lower() or "auto"
-+ if value not in ("0", "1", "auto"):
-+ raise ValueError(f"TF_GLM_MTP: 0, 1 or auto, not {value!r}")
-+ if value == "auto":
-+ return bool(layers) and not drafter and not serial_only
-+ return value == "1" and bool(layers)
-+
-+
-+def without_mtp(transform, layers: int):
-+ """A startup weight transform that leaves out the MTP layer's tensors (``layers.<num_hidden_layers>.``)."""
-+
-+ prefix = f"model.language_model.layers.{layers}."
-+ return lambda name, info: (0, 0) if name.startswith(prefix) else transform(name, info)
-+
-+
- SHARED_DEFAULT = 256 # TF_GLM_SHARED_PREFIX=1: the fewest tokens a shared-prefix state adds
- SHARED_MIN = 16
- SHARED_MOST = 2 # shared-prefix states a request keeps at most (the header's two slots)
-@@ -327,6 +351,10 @@ class GlmEngine:
- # TF_GLM_KVB=fp8/q4 (an EXL3 checkpoint, latent cache): kv_b as the absorb and expand kernels read it
- kvb = kvb_kind() if cfg.quant == "exl3" and LATENT else "bf16"
- weights_estimate = kvb_weights(weights_estimate, kvb)
-+ # TF_GLM_MTP (``mtp_head``): off, the MTP layer's tensors are not loaded, so the estimate drops them too
-+ self.mtp_on = mtp_head(drafter is not None, serial_only, cfg.mtp_layers)
-+ if not self.mtp_on:
-+ weights_estimate = without_mtp(weights_estimate, cfg.layers)
- # rows a prompt chunk runs at once: TF_GLM_PREFILL_ROWS (both ranks alike), more amortizes each chunk's expert
- # weight decode over more tokens and costs buffer memory
- if prefill_rows is None:
-@@ -351,7 +379,8 @@ 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, 2, MAX_ROWS, minimum_slots=DENSE_CAPACITY, latent=LATENT, prefill_rows=prefill_rows,
-+ mtp=self.mtp_on)
- return Geometry(lambda slots: g.bytes_at(slots) + workspace, g.reserve, g.minimum_slots) if workspace else g
- self.capacity_plan = admit(model_dir, context if explicit else cfg.dense_limit, explicit, torch,
- geometry,
-@@ -371,7 +400,7 @@ class GlmEngine:
- # both ranks 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]) + \
-- self.split.code() + [int(self.dump is not None), quant_code, self.shared, int(DRAFT_RING)]
-+ self.split.code() + [int(self.dump is not None), quant_code, self.shared, int(DRAFT_RING), int(self.mtp_on)]
- # other conversations' kept prompts get what the window leaves, at most TF_GLM_CACHE_GIB, the same on both ranks
- plan = self.capacity_plan
- wanted = int(float(os.environ.get("TF_GLM_CACHE_GIB", "3")) * 2 ** 30)
-@@ -381,7 +410,7 @@ class GlmEngine:
- raise RuntimeError("the two 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_DRAFT_QUANT, TF_GLM_SHARED_PREFIX, TF_GLM_DRAFT_RING, TF_GLM_MTP): "
- 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
-@@ -391,14 +420,18 @@ class GlmEngine:
- if rank == 0 and self.cache_bytes < wanted:
- print(f"[tensorfold] other conversations' prompts are kept in {self.cache_bytes / 2 ** 30:.1f} GiB, what "
- f"the {self.limit}-token window leaves (TF_GLM_CACHE_GIB asks {wanted / 2 ** 30:.1f})", flush=True)
-- w = load(model_dir, rank=rank)
-+ if not self.mtp_on and drafter is None and not serial_only:
-+ 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")
-+ w = load(model_dir, rank=rank, mtp=self.mtp_on)
- w.comm = self.comm
- self.comm.barrier()
-- if w.mtp is None and drafter is None and not serial_only:
-- raise ValueError("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")
- self.w = w
-+ if rank == 0 and cfg.mtp_layers and not self.mtp_on:
-+ print("[tensorfold] the checkpoint's MTP head is not loaded (TF_GLM_MTP=" +
-+ (os.environ.get("TF_GLM_MTP", "").strip() or "auto") + "): " +
-+ ("DFlash2 drafts every request" if drafter is not None else "--no-drafts"), flush=True)
- self.drafter = None
- if drafter is not None:
- from .dflash2 import Drafter
-@@ -432,9 +465,10 @@ class GlmEngine:
- if rank == 0:
- c = self.costs
- print(f"[tensorfold] drafter timings (ms, fastest of 7): {c['timed']}", flush=True)
-- print("[tensorfold] drafter costs (ms): verify " + " ".join(f"{v:.1f}" for v in c["verify"]) +
-- f"; MTP draft {c['mtp']:.2f} (+{c['mtp_step']:.2f} a chained draft, +{c['mtp_row']:.2f} a row); "
-- f"DFlash2 block {c['block']:.2f} (+{c['taps_row']:.3f} a tap row)", flush=True)
-+ mtp = (f"; MTP draft {c['mtp']:.2f} (+{c['mtp_step']:.2f} a chained draft, +{c['mtp_row']:.2f} a row)"
-+ if w.mtp is not None else "")
-+ print("[tensorfold] drafter costs (ms): verify " + " ".join(f"{v:.1f}" for v in c["verify"]) + mtp +
-+ f"; DFlash2 block {c['block']:.2f} (+{c['taps_row']:.3f} a tap row)", flush=True)
- self.vision = None # rank 0's image tower (``tensorfold.vision.glm.GlmVision``), --vision
- if vision:
- from tensorfold.vision.glm import GlmVision
-diff --git tensorfold/families/glm5_next/cuda/weights.py tensorfold/families/glm5_next/cuda/weights.py
-index 3d7a6b0..1289e10 100644
---- tensorfold/families/glm5_next/cuda/weights.py
-+++ tensorfold/families/glm5_next/cuda/weights.py
-@@ -242,8 +242,9 @@ class Weights:
- return total
-
-
--def load(model_dir: str | Path, *, rank: int, device: str = "cuda") -> Weights:
-- """Read one of two ranks from a full checkpoint or rank folder, including MTP and its half of the vocabulary head."""
-+def load(model_dir: str | Path, *, rank: int, device: str = "cuda", mtp: bool = True) -> Weights:
-+ """Read one of two ranks from a full checkpoint or rank folder, including MTP (unless ``mtp`` is False: TF_GLM_MTP
-+ off, whose tensors are then never read) and its half of the vocabulary head."""
-
- from .split import RankReader
-
-@@ -337,8 +338,8 @@ def load(model_dir: str | Path, *, rank: int, device: str = "cuda") -> Weights:
- def expert_names(i: int) -> list[str]:
- """Layer ``i``'s expert tensors in the order ``moe`` reads them (none for a dense layer; ``cfg.layers``: MTP)."""
-
-- mtp = i == cfg.layers and cfg.mtp_layers
-- if not mtp and (i >= cfg.layers or cfg.mlp_kinds[i] != "moe"):
-+ mtp_layer = i == cfg.layers and cfg.mtp_layers and mtp
-+ if not mtp_layer and (i >= cfg.layers or cfg.mlp_kinds[i] != "moe"):
- return []
- p, parts = PREFIX + f"layers.{i}.mlp.", ("trellis", "suh", "svh") if exl3 else ("weight", "scales", "biases")
- names = []
-@@ -439,7 +440,7 @@ def load(model_dir: str | Path, *, rank: int, device: str = "cuda") -> Weights:
- 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))
- mtpw = None
-- if cfg.mtp_layers:
-+ 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))
diff --git a/patches/0033-glm-multi-stream-engine.patch b/patches/0030-glm-multi-stream-engine.patch
similarity index 98%
rename from patches/0033-glm-multi-stream-engine.patch
rename to patches/0030-glm-multi-stream-engine.patch
index ff50c42..eac9f6f 100644
--- a/patches/0033-glm-multi-stream-engine.patch
+++ b/patches/0030-glm-multi-stream-engine.patch
@@ -1,8 +1,8 @@
diff --git tensorfold/cuda/health.py tensorfold/cuda/health.py
-index 47b7270..5902ad3 100644
+index d926642..b08e325 100644
--- tensorfold/cuda/health.py
+++ tensorfold/cuda/health.py
-@@ -64,6 +64,14 @@ class Health:
+@@ -83,6 +83,14 @@ class Health:
if decoder is not None: # read, never locked: sizes of the decoder's own tables
body["streams"] = {"decoding": len(getattr(decoder, "streams", ())),
"prefilling": len(getattr(decoder, "filling", ())), "max": scheduler.max_streams}
@@ -18,10 +18,10 @@ index 47b7270..5902ad3 100644
if window:
body["context_length"] = int(window)
diff --git tensorfold/families/glm5_next/__init__.py tensorfold/families/glm5_next/__init__.py
-index 7076545..0635010 100644
+index a2f4a6f..90cb8f3 100644
--- tensorfold/families/glm5_next/__init__.py
+++ tensorfold/families/glm5_next/__init__.py
-@@ -193,7 +193,7 @@ def cuda_engine(model_dir: str | Path, *, drafter: str = "", tp: int = 1, rank:
+@@ -223,7 +223,7 @@ def cuda_engine(model_dir: str | Path, *, drafter: str = "", tp: int = 1, rank:
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)),
@@ -31,7 +31,7 @@ index 7076545..0635010 100644
def __getattr__(name: str) -> Any:
diff --git tensorfold/families/glm5_next/cuda/decode.py tensorfold/families/glm5_next/cuda/decode.py
-index cbff019..febb0eb 100644
+index 93ab4dc..eb427d0 100644
--- tensorfold/families/glm5_next/cuda/decode.py
+++ tensorfold/families/glm5_next/cuda/decode.py
@@ -84,11 +84,15 @@ class Engine:
@@ -108,7 +108,7 @@ index cbff019..febb0eb 100644
g = self.graphs.mtp.get(n)
elif (self.graphs is not None and not self.mbuf.zero_first and self.st.index is not None
and self.st.mtp_len >= self.w.cfg.dense_limit):
-@@ -408,22 +434,8 @@ def prefill(e: Engine, prompt: Sequence[int], sampling: Sampling | None, *, mtp:
+@@ -407,22 +433,8 @@ def prefill(e: Engine, prompt: Sequence[int], sampling: Sampling | None, *, mtp:
last = None
prof.active = True
for start in range(begin, len(prompt), e.prefill_rows):
@@ -133,7 +133,7 @@ index cbff019..febb0eb 100644
prof.active = False
prof.report(len(prompt) - begin)
if not sample:
-@@ -435,6 +447,32 @@ def prefill(e: Engine, prompt: Sequence[int], sampling: Sampling | None, *, mtp:
+@@ -434,6 +446,32 @@ def prefill(e: Engine, prompt: Sequence[int], sampling: Sampling | None, *, mtp:
return first
@@ -167,10 +167,10 @@ index cbff019..febb0eb 100644
"""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 37051b4..9bc5550 100644
+index 1a65d1c..6b796d7 100644
--- tensorfold/families/glm5_next/cuda/engine.py
+++ tensorfold/families/glm5_next/cuda/engine.py
-@@ -274,6 +274,44 @@ def round_costs(costs: dict) -> tuple[float, ...]:
+@@ -248,6 +248,44 @@ def round_costs(costs: dict) -> tuple[float, ...]:
return tuple(v + costs["block"] + 0.0 + costs["taps_row"] * 1 for v in costs["verify"])
@@ -215,7 +215,7 @@ index 37051b4..9bc5550 100644
def _f64_ints(x: float) -> list[int]:
return list(struct.unpack("<2i", struct.pack("<d", float(x))))
-@@ -287,14 +325,19 @@ class GlmEngine:
+@@ -283,14 +321,19 @@ class GlmEngine:
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
@@ -237,7 +237,7 @@ index 37051b4..9bc5550 100644
import torch
-@@ -322,6 +365,10 @@ class GlmEngine:
+@@ -318,6 +361,10 @@ class GlmEngine:
torch.cuda.set_device(0)
self.torch = torch
self.rank = rank
@@ -248,16 +248,16 @@ index 37051b4..9bc5550 100644
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)
-@@ -352,7 +399,7 @@ class GlmEngine:
+@@ -348,7 +395,7 @@ class GlmEngine:
kvb = kvb_kind() if cfg.quant == "exl3" and LATENT else "bf16"
weights_estimate = kvb_weights(weights_estimate, kvb)
- # TF_GLM_MTP (``mtp_head``): off, the MTP layer's tensors are not loaded, so the estimate drops them too
+ # TF_GLM_MTP off: the MTP layer's tensors, caches and buffers are neither loaded nor estimated
- self.mtp_on = mtp_head(drafter is not None, serial_only, cfg.mtp_layers)
+ self.mtp_on = mtp_head(drafter is not None, serial_only, cfg.mtp_layers) and parallel == 1 # multi: DFlash2
if not self.mtp_on:
weights_estimate = without_mtp(weights_estimate, cfg.layers)
# rows a prompt chunk runs at once: TF_GLM_PREFILL_ROWS (both ranks alike), more amortizes each chunk's expert
-@@ -385,12 +432,29 @@ class GlmEngine:
+@@ -381,12 +428,29 @@ class GlmEngine:
g = mla_geometry(text, 2, MAX_ROWS, 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")
@@ -289,7 +289,7 @@ index 37051b4..9bc5550 100644
self.limit = self.capacity_plan["context_window"]
capacity = self.capacity_plan["cache_slots"]
long_context = self.limit > cfg.dense_limit
-@@ -399,12 +463,18 @@ class GlmEngine:
+@@ -395,12 +459,18 @@ class GlmEngine:
from .draft_dump import dump_dir
from .qmm import DRAFT_QUANTS, draft_quant
@@ -304,17 +304,17 @@ index 37051b4..9bc5550 100644
# both ranks 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]) + \
-- self.split.code() + [int(self.dump is not None), quant_code, self.shared, int(DRAFT_RING), int(self.mtp_on)]
+- self.split.code() + [int(self.dump is not None), quant_code, self.shared, int(self.mtp_on), int(DRAFT_RING)]
+ self.split.code() + [int(self.dump is not None), quant_code, self.shared, int(DRAFT_RING), int(self.mtp_on),
+ parallel, verify_code]
# other conversations' kept prompts get what the window leaves, at most TF_GLM_CACHE_GIB, the same on both ranks
plan = self.capacity_plan
wanted = int(float(os.environ.get("TF_GLM_CACHE_GIB", "3")) * 2 ** 30)
-@@ -414,14 +484,35 @@ class GlmEngine:
+@@ -410,14 +480,35 @@ class GlmEngine:
raise RuntimeError("the two 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): "
+- "TF_GLM_DRAFT_QUANT, TF_GLM_SHARED_PREFIX, TF_GLM_MTP, TF_GLM_DRAFT_RING): "
+ "TF_GLM_DRAFT_QUANT, TF_GLM_SHARED_PREFIX, TF_GLM_DRAFT_RING, TF_GLM_MTP, --parallel, "
+ "TF_GLM_MULTI_VERIFY): "
f"rank 0 {both[0][:-1]}, rank 1 {both[1][:-1]}; pull the draft model on both machines "
@@ -348,7 +348,7 @@ index 37051b4..9bc5550 100644
print(f"[tensorfold] other conversations' prompts are kept in {self.cache_bytes / 2 ** 30:.1f} GiB, what "
f"the {self.limit}-token window leaves (TF_GLM_CACHE_GIB asks {wanted / 2 ** 30:.1f})", flush=True)
if not self.mtp_on and drafter is None and not serial_only:
-@@ -440,11 +531,11 @@ class GlmEngine:
+@@ -437,11 +528,11 @@ class GlmEngine:
if drafter is not None:
from .dflash2 import Drafter
@@ -363,7 +363,7 @@ index 37051b4..9bc5550 100644
if self.e.pbuf.split is not None:
self.e.pbuf.split.warm() # both ranks: open the send/receive connection now
if rank == 0:
-@@ -492,6 +583,18 @@ class GlmEngine:
+@@ -489,6 +580,18 @@ class GlmEngine:
self.cache: list = []
self.live: list[int] = []
self.cache_entries = int(os.environ.get("TF_GLM_CACHE_ENTRIES", "8"))
@@ -382,7 +382,7 @@ index 37051b4..9bc5550 100644
def _calibrate(self) -> dict:
"""Per-piece ms for ``drafter_choice.DrafterChoice``: fastest of interleaved passes, equal on both ranks."""
-@@ -847,8 +950,8 @@ class GlmEngine:
+@@ -840,8 +943,8 @@ class GlmEngine:
return stats
def generate(self, prompt: list[int], max_tokens: int, sampling, on_tokens, draft: bool = True,
@@ -393,7 +393,7 @@ index 37051b4..9bc5550 100644
if len(prompt) >= self.limit:
raise ValueError(f"prompt of {len(prompt)} tokens: this engine serves contexts up to {self.limit}")
-@@ -859,6 +962,14 @@ class GlmEngine:
+@@ -852,6 +955,14 @@ class GlmEngine:
spec = getattr(self.request, "policy", None) or self.policy
code = self._effective(encode_policy(spec))
stop_eos = bool(getattr(self.request, "stop_eos", True))
@@ -408,7 +408,7 @@ index 37051b4..9bc5550 100644
positions: list[int] = []
feed = None
if vision is not None: # encoded here, before rank 1 is told anything, so a failure stops both
-@@ -907,6 +1018,9 @@ class GlmEngine:
+@@ -900,6 +1011,9 @@ class GlmEngine:
def follow(self) -> None:
"""Rank 1: mirror every request rank 0 serves, forever."""
@@ -419,10 +419,10 @@ index 37051b4..9bc5550 100644
self.follow_one()
diff --git tensorfold/families/glm5_next/cuda/forward.py tensorfold/families/glm5_next/cuda/forward.py
-index 1a8894f..42f2929 100644
+index cb39952..e156332 100644
--- tensorfold/families/glm5_next/cuda/forward.py
+++ tensorfold/families/glm5_next/cuda/forward.py
-@@ -160,52 +160,137 @@ class Buffers:
+@@ -161,52 +161,137 @@ class Buffers:
return p
@@ -591,7 +591,7 @@ index 1a8894f..42f2929 100644
def reset(self) -> None:
self.conv.zero_()
-@@ -228,9 +313,11 @@ class State:
+@@ -229,9 +314,11 @@ class State:
return self.cur[0] if self.cur else 0
def clone(self) -> "State":
@@ -603,7 +603,7 @@ index 1a8894f..42f2929 100644
other.conv = self.conv.clone()
other.rec = self.rec.clone()
other.cur = list(self.cur)
-@@ -313,6 +400,30 @@ def kda_block(layer: LayerW, w: Weights, st: State, b: Buffers, R: int) -> torch
+@@ -314,6 +401,30 @@ def kda_block(layer: LayerW, w: Weights, st: State, b: Buffers, R: int) -> torch
return out_proj(w, b, out, k.o, None if pre else qmm.group_sums(out, b.kxs[:R]), R)
@@ -634,7 +634,7 @@ index 1a8894f..42f2929 100644
def dsa_block(layer: LayerW, w: Weights, kc: torch.Tensor, vc: torch.Tensor, pos_dev: torch.Tensor, b: Buffers,
R: int, nch: int | None, index=None, host_pos: int | None = None,
sparse_np: int | None = None) -> torch.Tensor:
-@@ -538,13 +649,16 @@ def _ffn(layer: LayerW, w: Weights, b: Buffers, R: int) -> torch.Tensor | None:
+@@ -539,13 +650,16 @@ def _ffn(layer: LayerW, w: Weights, b: Buffers, R: int) -> torch.Tensor | None:
def layer_forward(layer: LayerW, w: Weights, st: State, b: Buffers, R: int, nch: int | None = None,
@@ -653,7 +653,7 @@ index 1a8894f..42f2929 100644
with prof.timed("hc"):
glue.hc_post(x, x, g, b.post[:R], b.comb[:R])
h = layer.ffn_hc
-@@ -605,7 +719,7 @@ def stage(w: Weights, st: State, b: Buffers, tokens: Sequence[int]) -> int:
+@@ -606,7 +720,7 @@ def stage(w: Weights, st: State, b: Buffers, tokens: Sequence[int]) -> int:
def compute(w: Weights, st: State, b: Buffers, R: int, *, logits: bool = True, nch: int | None = None,
@@ -662,7 +662,7 @@ index 1a8894f..42f2929 100644
"""Run capturable GPU work on static buffers and device positions; eager long contexts use host_pos (graphs sparse_np) to select sparse attention; ``inject``: (rows, features) replacing those rows' embeddings (an image prompt's tower output, on every hyper-connection stream)."""
c = w.cfg
-@@ -613,11 +727,11 @@ def compute(w: Weights, st: State, b: Buffers, R: int, *, logits: bool = True, n
+@@ -614,11 +728,11 @@ def compute(w: Weights, st: State, b: Buffers, R: int, *, logits: bool = True, n
if inject is not None:
rows, features = inject
b.x.index_copy_(0, rows, features.repeat(1, c.streams))
diff --git a/patches/0034-glm-decode-index-regs.patch b/patches/0031-glm-decode-index-regs.patch
similarity index 70%
rename from patches/0034-glm-decode-index-regs.patch
rename to patches/0031-glm-decode-index-regs.patch
index e60799c..103d712 100644
--- a/patches/0034-glm-decode-index-regs.patch
+++ b/patches/0031-glm-decode-index-regs.patch
@@ -1,8 +1,8 @@
diff --git tensorfold/families/glm5_next/cuda/sparse.py tensorfold/families/glm5_next/cuda/sparse.py
-index dcd849f..59c274b 100644
+index 6cfe91d..acfc069 100644
--- tensorfold/families/glm5_next/cuda/sparse.py
+++ tensorfold/families/glm5_next/cuda/sparse.py
-@@ -97,6 +97,51 @@ def _scores(QI, W, w_stride, PK, OUT, POS, R, NP, scale, wscale, H: tl.constexpr
+@@ -107,6 +107,51 @@ def _scores(QI, W, w_stride, PK, OUT, POS, R, NP, scale, wscale, H: tl.constexpr
tl.store(OUT + r * NP + p, sc, mask=p < NP)
@@ -54,20 +54,37 @@ index dcd849f..59c274b 100644
def _top_pools(scores: torch.Tensor, k: int) -> torch.Tensor:
"""Reference top-k: each row's k best pools, ties to the lower pool, ascending, as a stable descending sort keeps them (unique int64 keys)."""
bits = (scores + 0.0).view(torch.int32) # + 0.0: -0 becomes +0, as the sort ties them
-@@ -230,8 +275,10 @@ def select_tokens(qi: torch.Tensor, wts: torch.Tensor, pk: torch.Tensor, pos: in
+@@ -237,23 +282,16 @@ def select_tokens(qi: torch.Tensor, wts: torch.Tensor, pk: torch.Tensor, pos: in
+ return _select_prompt(qi, wts, pk, pos, R, np_max, pos_dev)
+ # score only visible pools, rounded up to a power of two so the allocator reuses a few sizes (exact sizes fragmented memory at 128k)
+ np_max = bucket if bucket is not None else pool_bucket(pos, R, np_max)
+- # rows scored SELECT_ROWS at a time over the window's np_max pools (the same columns, so the same bits a row)
+- B = min(R, SELECT_ROWS)
+- scores = torch.empty((B, np_max), dtype=torch.float32, device=qi.device)
++ scores = torch.empty((R, np_max), dtype=torch.float32, device=qi.device)
+ # heads and width from the tensors: fixed ones read past a row's index query into its window neighbours
H = wts.shape[1]
D = qi.shape[1] // H
wscale = 1.0 / 5.656854249492381 if H == 32 else H ** -0.5 # 32 ** -0.5 exactly as before
-- _scores[(R, triton.cdiv(np_max, 64))](qi, wts, wts.stride(0), pk, scores, pos_dev, R, np_max, D ** -0.5, wscale,
-- H=H, HP=max(16, triton.next_power_of_2(H)), D=D, BP=64, RB=1, num_warps=4)
+- blocks = []
+- for a in range(0, R, B):
+- n = min(B, R - a)
+- at = pos_dev if a == 0 else pos_dev + a # the block's first row's position
+- _scores[(n, triton.cdiv(np_max, 64))](qi[a:a + n], wts[a:a + n], wts.stride(0), pk, scores, at, n, np_max,
+- D ** -0.5, wscale, H=H, HP=max(16, triton.next_power_of_2(H)), D=D,
+- BP=64, RB=1, num_warps=4)
+- blocks.append(top_pools(scores[:n], TOPK_POOLS, at)) # ascending pool index
+- del scores
+- pools = blocks[0] if len(blocks) == 1 else torch.cat(blocks)
+ grid = min(ROW_SCORE_G, triton.cdiv(np_max, 64))
+ _scores_rows[(R, grid)](qi, wts, wts.stride(0), pk, scores, np_max, pos_dev, pos_dev, pos_dev, R, np_max, D ** -0.5,
+ wscale, H=H, HP=max(16, triton.next_power_of_2(H)), D=D, BP=64, G=grid, SEG=False,
+ num_warps=4)
- pools = top_pools(scores, TOPK_POOLS) # ascending pool index
++ pools = top_pools(scores, TOPK_POOLS, pos_dev) # ascending pool index
dev = qi.device
width = TOPK_POOLS * POOL + POOL - 1
-@@ -567,7 +614,9 @@ def seg_select_tokens(qi: torch.Tensor, wts: torch.Tensor, pk: torch.Tensor, row
+ # all rows at once: the 512 pools' tokens ascending, then the incomplete last pool's visible tokens; rows within the dense limit count 0
+@@ -588,7 +626,9 @@ def seg_select_tokens(qi: torch.Tensor, wts: torch.Tensor, pk: torch.Tensor, row
torch.Tensor]:
"""select_tokens for a segmented window: each sparse row's attended tokens [R, 2051] (relative to its stream,
ascending, -1 padded) and counts (0 for dense rows). Scores every segment's pools up to its device-side pool
diff --git a/patches/0035-glm-code-copy-drafts.patch b/patches/0032-glm-code-copy-drafts.patch
similarity index 97%
rename from patches/0035-glm-code-copy-drafts.patch
rename to patches/0032-glm-code-copy-drafts.patch
index c384f52..7af451f 100644
--- a/patches/0035-glm-code-copy-drafts.patch
+++ b/patches/0032-glm-code-copy-drafts.patch
@@ -166,7 +166,7 @@ index 3aa3b25..10860da 100644
+ return drafts
+ return drafts + [drafts[-1]] * (width - rows)
diff --git tensorfold/families/glm5_next/cuda/engine.py tensorfold/families/glm5_next/cuda/engine.py
-index 9bc5550..109dbf0 100644
+index 6b796d7..66fa9ca 100644
--- tensorfold/families/glm5_next/cuda/engine.py
+++ tensorfold/families/glm5_next/cuda/engine.py
@@ -17,7 +17,48 @@ DEFAULT_POLICY = "auto"
@@ -216,10 +216,10 @@ index 9bc5550..109dbf0 100644
+
+
+WIDE_GRAPHS = wide_graphs()
- # TF_GLM_DRAFT_RING=0: DFlash2 keeps its context in a flat buffer of the whole window (10,240 bytes a slot on each
- # rank) instead of a ring of its 2,048-row sliding window and block (2,176 rows, 21.25 MiB; ``dflash2.Drafter``) and
- # its blocks attend with today's loop over every context tile (masked); the drafts are the same bits either way
-@@ -356,7 +397,7 @@ class GlmEngine:
+ MTP_ROWS = 8 # rows an MTP step takes at once (a kept backlog is absorbed in steps of this)
+ DENSE_CAPACITY = 2560 # cache slots while DSA attention stays dense (contexts up to 2,051 tokens)
+ # TF_GLM_DRAFT_RING=0: DFlash2's context in a flat buffer of the whole window, not a 2,176-row ring (the same drafts)
+@@ -352,7 +393,7 @@ class GlmEngine:
# TF_GLM_COPY_DRAFTS=1: a reply that repeats earlier text drafts its continuation (prompt lookup) ahead of
# the MTP head and DFlash2; both ranks must agree, so the settings join the startup comparison below
@@ -228,7 +228,7 @@ index 9bc5550..109dbf0 100644
from .hcsplit import SplitSettings
# TF_GLM_HC_SPLIT=1 / TF_GLM_PREFILL_OVERLAP=1: prompt chunks' hyper-connection glue split by rows between the
-@@ -472,9 +513,10 @@ class GlmEngine:
+@@ -468,9 +509,10 @@ class GlmEngine:
verify_code = 1 + ("batched", "serial").index(verify_kind())
# both ranks 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),
@@ -241,7 +241,7 @@ index 9bc5550..109dbf0 100644
# other conversations' kept prompts get what the window leaves, at most TF_GLM_CACHE_GIB, the same on both ranks
plan = self.capacity_plan
wanted = int(float(os.environ.get("TF_GLM_CACHE_GIB", "3")) * 2 ** 30)
-@@ -485,7 +527,7 @@ class GlmEngine:
+@@ -481,7 +523,7 @@ class GlmEngine:
"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, "
@@ -250,7 +250,7 @@ index 9bc5550..109dbf0 100644
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
-@@ -533,13 +575,21 @@ class GlmEngine:
+@@ -530,13 +572,21 @@ class GlmEngine:
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,
@@ -273,7 +273,7 @@ index 9bc5550..109dbf0 100644
if rank == 0 and self.dump is not None:
print(f"[tensorfold] TF_GLM_DRAFT_DUMP: DFlash2 requests decode serially and record the drafter's view "
f"into {self.dump} (one .npz a request; replies equal draft: false)", flush=True)
-@@ -901,9 +951,7 @@ class GlmEngine:
+@@ -894,9 +944,7 @@ class GlmEngine:
policy = decode_policy(code, self.costs)
copies = None
if policy is not None and self.copy is not None: # prompt and pending token, alike on both ranks
diff --git a/patches/0036-glm-prefill-overlap2.patch b/patches/0033-glm-prefill-overlap2.patch
similarity index 97%
rename from patches/0036-glm-prefill-overlap2.patch
rename to patches/0033-glm-prefill-overlap2.patch
index 9f77a4d..3d0cf34 100644
--- a/patches/0036-glm-prefill-overlap2.patch
+++ b/patches/0033-glm-prefill-overlap2.patch
@@ -1,8 +1,8 @@
diff --git tensorfold/families/glm5_next/cuda/forward.py tensorfold/families/glm5_next/cuda/forward.py
-index 42f2929..ef785e7 100644
+index e156332..79a1ec9 100644
--- tensorfold/families/glm5_next/cuda/forward.py
+++ tensorfold/families/glm5_next/cuda/forward.py
-@@ -376,18 +376,46 @@ def out_proj(w: Weights, b: Buffers, x: torch.Tensor, q: qmm.Q4, xs: torch.Tenso
+@@ -377,18 +377,46 @@ def out_proj(w: Weights, b: Buffers, x: torch.Tensor, q: qmm.Q4, xs: torch.Tenso
return partials(w, b, R, fill)
@@ -55,7 +55,7 @@ index 42f2929..ef785e7 100644
cur = st.cur[li]
with prof.timed("kda: recurrence"):
out = kda_mod.chain(p, k.b_off, b.ka[:R], b.kg[:R], st.conv[li], k.conv, st.rec[cur, li], k.a_log,
-@@ -424,18 +452,27 @@ def kda_segments(layer: LayerW, w: Weights, b: Buffers, R: int, seg: torch.Tenso
+@@ -425,18 +453,27 @@ def kda_segments(layer: LayerW, w: Weights, b: Buffers, R: int, seg: torch.Tenso
return out_proj(w, b, out, k.o, qmm.group_sums(out, b.kxs[:R]), R)
@@ -89,7 +89,7 @@ index 42f2929..ef785e7 100644
if a.absorb is not None:
return _dsa_latent(a, w, kc, pos_dev, b, R, nch, index, host_pos, sparse_np)
if sparse_np is not None:
-@@ -581,14 +618,32 @@ def dsa_segments(layer: LayerW, w: Weights, lc: torch.Tensor, b: Buffers, R: int
+@@ -582,14 +619,32 @@ def dsa_segments(layer: LayerW, w: Weights, lc: torch.Tensor, b: Buffers, R: int
return out_proj(w, b, o, a.o, qmm.group_sums(o, b.xs_ao[:R]), R)
@@ -126,7 +126,7 @@ index 42f2929..ef785e7 100644
c = w.cfg
m = layer.moe
with prof.timed("moe: route"):
-@@ -601,13 +656,11 @@ def moe_block(layer: LayerW, w: Weights, b: Buffers, R: int) -> torch.Tensor:
+@@ -602,13 +657,11 @@ def moe_block(layer: LayerW, w: Weights, b: Buffers, R: int) -> torch.Tensor:
with prof.timed("moe: routed (exl3)"):
exl3_mm.routed(b.normed[:R], b.pick, b.plan, m.experts, b.exl3, b.ey.view(-1, c.hidden), R, c.limit)
@@ -143,7 +143,7 @@ index 42f2929..ef785e7 100644
with prof.timed("moe: combine"):
# the shared row read from sy where it is (the copy's bits, one pass less); decode windows too unless
# TF_GLM_COMBINE_SY=0
-@@ -631,21 +684,40 @@ def moe_block(layer: LayerW, w: Weights, b: Buffers, R: int) -> torch.Tensor:
+@@ -632,21 +685,40 @@ def moe_block(layer: LayerW, w: Weights, b: Buffers, R: int) -> torch.Tensor:
def _mixer(layer: LayerW, w: Weights, st: State, b: Buffers, R: int, nch: int | None, host_pos: int | None,
@@ -189,7 +189,7 @@ index 42f2929..ef785e7 100644
def layer_forward(layer: LayerW, w: Weights, st: State, b: Buffers, R: int, nch: int | None = None,
-@@ -677,20 +749,25 @@ def split_layers(w: Weights, st: State, b: Buffers, R: int, nch: int | None, hos
+@@ -678,20 +750,25 @@ def split_layers(w: Weights, st: State, b: Buffers, R: int, nch: int | None, hos
sp = b.split
layers = w.layers
sp.begin(R)
diff --git a/patches/0037-cuda-nucleus-union.patch b/patches/0034-cuda-nucleus-union.patch
similarity index 95%
rename from patches/0037-cuda-nucleus-union.patch
rename to patches/0034-cuda-nucleus-union.patch
index 6af2cf3..5b8507f 100644
--- a/patches/0037-cuda-nucleus-union.patch
+++ b/patches/0034-cuda-nucleus-union.patch
@@ -1,5 +1,5 @@
diff --git tensorfold/cuda/sampling.py tensorfold/cuda/sampling.py
-index fd435f8..5bc101e 100644
+index bf058e8..3def71f 100644
--- tensorfold/cuda/sampling.py
+++ tensorfold/cuda/sampling.py
@@ -5,6 +5,7 @@ from __future__ import annotations
@@ -10,7 +10,7 @@ index fd435f8..5bc101e 100644
import numpy as np
import torch
-@@ -123,6 +124,8 @@ def nucleus_rows(logits: torch.Tensor, positions: Sequence[int], sampling: Sampl
+@@ -119,6 +120,8 @@ def nucleus_rows(logits: torch.Tensor, positions: Sequence[int], sampling: Sampl
mass = torch.floor(torch.exp(scaled - top[:, None]) * MASS).to(torch.int64)
got = _shares(gather, scaled, mass, NUCLEUS, offset, id_map)
drawn = _draw(got, positions, sampling)
@@ -19,7 +19,7 @@ index fd435f8..5bc101e 100644
if drawn is None: # some row's nucleus runs past the candidates: every whole shard
drawn = _draw(_shares(gather, scaled, mass, int(got[4].max()), offset, id_map), positions, sampling)
if probs is not None:
-@@ -150,17 +153,52 @@ def _shares(gather, scaled, mass, count, offset, id_map):
+@@ -145,17 +148,52 @@ def _shares(gather, scaled, mass, count, offset, id_map):
both[:, :, 2 * count:3 * count], both[:, :, 3 * count], both[:, :, 3 * count + 1])
diff --git a/patches/0038-glm-multi-rounds.patch b/patches/0035-glm-multi-rounds.patch
similarity index 99%
rename from patches/0038-glm-multi-rounds.patch
rename to patches/0035-glm-multi-rounds.patch
index 1381dbb..e4a7b7b 100644
--- a/patches/0038-glm-multi-rounds.patch
+++ b/patches/0035-glm-multi-rounds.patch
@@ -1,5 +1,5 @@
diff --git tensorfold/families/glm5_next/cuda/decode.py tensorfold/families/glm5_next/cuda/decode.py
-index febb0eb..6732311 100644
+index eb427d0..ed74101 100644
--- tensorfold/families/glm5_next/cuda/decode.py
+++ tensorfold/families/glm5_next/cuda/decode.py
@@ -160,7 +160,9 @@ class Engine:
@@ -23,10 +23,10 @@ index febb0eb..6732311 100644
if g is not None:
self.replays[kind] += 1
diff --git tensorfold/families/glm5_next/cuda/dflash2.py tensorfold/families/glm5_next/cuda/dflash2.py
-index a96d90f..8b5ff07 100644
+index 127ea01..b5dcd26 100644
--- tensorfold/families/glm5_next/cuda/dflash2.py
+++ tensorfold/families/glm5_next/cuda/dflash2.py
-@@ -508,11 +508,14 @@ class Drafter:
+@@ -501,11 +501,14 @@ class Drafter:
def chain(self, tokens: np.ndarray, values: np.ndarray, proj: np.ndarray, anchor: int, first: int,
sampling: Sampling | None, confidence: float = 0.0, *, beta: float = 0.0,
@@ -43,7 +43,7 @@ index a96d90f..8b5ff07 100644
depth = tokens.shape[0]
sampled = sampling is not None and sampling.temperature > 0
-@@ -529,7 +532,13 @@ class Drafter:
+@@ -522,7 +525,13 @@ class Drafter:
score = (values[d] + EDGE * edge) / temp
pick = score + NOISE * noise[d] if noise is not None else score
j = int(np.argmax(pick))
@@ -58,7 +58,7 @@ index a96d90f..8b5ff07 100644
c = noisy_confidence(score, noise[d] if noise is not None else None, j, beta)
if round_ms is not None:
conf.append(c)
-@@ -544,7 +553,7 @@ class Drafter:
+@@ -537,7 +546,7 @@ class Drafter:
break
prev = int(tokens[d, j])
out.append(prev)
@@ -68,10 +68,10 @@ index a96d90f..8b5ff07 100644
return out
diff --git tensorfold/families/glm5_next/cuda/engine.py tensorfold/families/glm5_next/cuda/engine.py
-index 109dbf0..8154dc6 100644
+index 66fa9ca..32c01f3 100644
--- tensorfold/families/glm5_next/cuda/engine.py
+++ tensorfold/families/glm5_next/cuda/engine.py
-@@ -506,17 +506,24 @@ class GlmEngine:
+@@ -502,17 +502,24 @@ class GlmEngine:
self.dump = dump_dir() if drafter is not None and not serial_only and parallel == 1 else None
quant_code = DRAFT_QUANTS.index(draft_quant())
@@ -98,7 +98,7 @@ index 109dbf0..8154dc6 100644
# other conversations' kept prompts get what the window leaves, at most TF_GLM_CACHE_GIB, the same on both ranks
plan = self.capacity_plan
wanted = int(float(os.environ.get("TF_GLM_CACHE_GIB", "3")) * 2 ** 30)
-@@ -527,7 +534,8 @@ class GlmEngine:
+@@ -523,7 +530,8 @@ class GlmEngine:
"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, "
@@ -108,7 +108,7 @@ index 109dbf0..8154dc6 100644
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
-@@ -644,7 +652,10 @@ class GlmEngine:
+@@ -641,7 +649,10 @@ class GlmEngine:
print(f"[tensorfold] --parallel {parallel}: up to {parallel} requests decode together, their caches "
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 "
diff --git a/patches/0039-glm-tool-calls.patch b/patches/0036-glm-tool-calls.patch
similarity index 89%
rename from patches/0039-glm-tool-calls.patch
rename to patches/0036-glm-tool-calls.patch
index 86af561..3a4e3b4 100644
--- a/patches/0039-glm-tool-calls.patch
+++ b/patches/0036-glm-tool-calls.patch
@@ -1,8 +1,8 @@
diff --git tensorfold/cuda/http.py tensorfold/cuda/http.py
-index f314446..c3d7cca 100644
+index 83f1ecc..b800c81 100644
--- tensorfold/cuda/http.py
+++ tensorfold/cuda/http.py
-@@ -143,8 +143,12 @@ def make_handler(app: App):
+@@ -148,6 +148,8 @@ def make_handler(app: App):
return self._stream_error({"message": _error_message(exc), "type": "server_error"})
if result["final"]:
emit(result["final"])
@@ -10,13 +10,9 @@ index f314446..c3d7cca 100644
+ emit(delta)
if result["calls"]:
for i, call in enumerate(result["calls"]):
-+ if i < result.get("calls_streamed", 0):
-+ continue
- emit({"tool_calls": [{"index": i, "id": call["id"], "type": "function",
- "function": {"name": call["function"]["name"],
- "arguments": call["function"]["arguments"]}}]})
+ if i < result.get("calls_streamed", 0): # sent as deltas already
diff --git tensorfold/cuda/reply_text.py tensorfold/cuda/reply_text.py
-index 6fa1026..c073b19 100644
+index 6fa1026..2f63be4 100644
--- tensorfold/cuda/reply_text.py
+++ tensorfold/cuda/reply_text.py
@@ -1,4 +1,8 @@
@@ -214,7 +210,7 @@ index 6fa1026..c073b19 100644
+ if self.value_schema is not None: # typed: decoded whole, as the end parser does
+ if end < 0:
+ return out
-+ self._args(out, _json(decode_parameter(rest[:end], self.value_schema)))
++ self._args(out, _json(decode_parameter(rest[:end], self.value_schema, python=False)))
+ elif self.maybe_null: # text or null: held while it may still be ``null``
+ written = rest[:end] if end >= 0 else rest[:len(rest) - _partial_tag(rest, _VALUE_END)]
+ if end >= 0 and written == "null":
@@ -254,10 +250,10 @@ index 6fa1026..c073b19 100644
+
# -- chat template -------------------------------------------------------------------------
diff --git tensorfold/cuda/server.py tensorfold/cuda/server.py
-index 31e0268..4ab6484 100644
+index 3707349..8a3ab2b 100644
--- tensorfold/cuda/server.py
+++ tensorfold/cuda/server.py
-@@ -21,7 +21,8 @@ from tensorfold.server.tools import active_tool_specs, tool_choice_requires_call
+@@ -24,7 +24,8 @@ from tensorfold.server.tools import active_tool_specs, tool_choice_requires_call
from tensorfold.cuda import health
from tensorfold.cuda.chat_template import ChatTemplate
@@ -267,20 +263,25 @@ index 31e0268..4ab6484 100644
from tensorfold.cuda.turns import Turns, Yield
from tensorfold.server.text import is_title_request, reasoning_count, split_thinking
-@@ -273,19 +274,35 @@ class App:
+@@ -309,23 +310,40 @@ class App:
stopped = {"client": False, "stop": False}
failed: list[Exception] = []
stream = StreamDecoder(self.tok, ends)
--
-- def visible(finished: bool) -> tuple[str, str]:
+- # calls stream as argument deltas while written (as on the Mac); one-call requests keep the end parser
+- calls_stream = ToolCallStreamer(tools) if tools and not policy.single else None
+ # a streamed reply's GLM calls go out while they are written (a long file write would otherwise send nothing
+ # for minutes, past the idle cut of clients such as LiteLLM and Node's fetch); one call a reply waits
+ glm_calls = bool(tools) and self._glm_calls()
+ calls_stream = GlmCallStreamer(tools) if glm_calls and body.get("stream") and not policy.single else None
++ # other families' calls stream as argument deltas while written (as on the Mac); one-call requests keep the
++ # end parser
++ xml_stream = ToolCallStreamer(tools) if tools and not glm_calls and not policy.single else None
+ answer_raw = [""]
+ # 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)
-+
+
+- def visible(finished: bool) -> tuple[str, str]:
+ def split(raw: str, finished: bool) -> tuple[str, str]:
+ if not (chat and thinking):
+ return "", raw
@@ -302,15 +303,16 @@ index 31e0268..4ab6484 100644
- else:
- reasoning, answer = "", raw
+ reasoning, answer = split(raw, finished)
+ answer_raw[0] = answer
if tools:
answer = (policy.content(answer, finished=finished) if policy.single
else hide_tool_calls(answer, finished=finished))
- return reasoning, answer
+ return reasoning, answer, 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
-@@ -304,7 +321,7 @@ class App:
+ serving: list[Any] = [None]
+
+@@ -346,7 +364,7 @@ class App:
else:
out.extend(new)
stream.add(new)
@@ -319,7 +321,7 @@ index 31e0268..4ab6484 100644
delta: dict[str, Any] = {}
if len(reasoning) > sent["reasoning"]:
delta["reasoning_content"] = reasoning[sent["reasoning"]:]
-@@ -312,7 +329,10 @@ class App:
+@@ -354,10 +372,13 @@ class App:
if len(answer) > sent["content"]:
delta["content"] = answer[sent["content"]:]
sent["content"] = len(answer)
@@ -329,9 +331,14 @@ index 31e0268..4ab6484 100644
+ parts += calls_stream.feed(call_text(raw))
+ if not all(emit(part) for part in parts):
stopped["client"] = True
- elif cancelled is not None and cancelled(): # every round, with or without new text
- stopped["client"] = True
-@@ -383,21 +403,33 @@ class App:
+- if calls_stream is not None and not stopped["client"]:
+- for call_delta in calls_stream.feed(answer_raw[0]): # never the reasoning
++ 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):
+ stopped["client"] = True
+ break
+@@ -442,29 +463,42 @@ 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)}
@@ -363,13 +370,24 @@ index 31e0268..4ab6484 100644
+ else "length")
if body.get("return_token_ids"): # the reply's ids in the "tensorfold" block, for exactness checks
stats = {**(stats or {}), "token_ids": [int(t) for t in out]}
+ logprobs = (self._probability_decoder.format(probabilities.emitted(out), ends)
+ if probabilities is not None else None)
+ # the calls already sent as deltas; the handler sends the rest (a call the streamer could not follow)
+- streamed = calls_stream.index + 1 if calls_stream is not None and calls_stream.streamed else 0
- return {"final": final, "calls": calls, "finish": finish, "content": content, "reasoning": reasoning,
++ if xml_stream is not None and xml_stream.streamed:
++ streamed = xml_stream.index + 1
+ return {"final": final, "calls": calls, "call_deltas": call_deltas, "calls_streamed": streamed,
+ "finish": finish, "content": content, "reasoning": reasoning,
+ **({"logprobs": logprobs} if logprobs is not None else {}),
"prompt_tokens": len(prompt), "completion_tokens": len(out), "cached_tokens": (cached or [0])[0],
"reasoning_tokens": reasoning_count(out, self.tok.token_to_id("</think>") if chat and thinking else None),
- "stats": stats}
-@@ -418,6 +450,14 @@ class App:
+- "stats": stats, "calls_streamed": streamed}
++ "stats": stats}
+
+ def _turns(self) -> Turns:
+ """The engine's turns (one request at a time, background ones last), made on first use."""
+@@ -482,6 +516,14 @@ class App:
close += self.tok.encode("\n\n", add_special_tokens=False).ids
return ThinkBudget(prepared.think_budget, close, think_end)
@@ -437,10 +455,10 @@ index bd64ae6..83497ba 100644
out.append(self._args(json.dumps(decode_parameter(self.value_buffer, self.value_schema), ensure_ascii=False)))
else:
diff --git tensorfold/families/glm5_next/cuda/app.py tensorfold/families/glm5_next/cuda/app.py
-index f46b66c..c776de5 100644
+index 350e5b0..c776de5 100644
--- tensorfold/families/glm5_next/cuda/app.py
+++ tensorfold/families/glm5_next/cuda/app.py
-@@ -6,19 +6,25 @@ from pathlib import Path
+@@ -6,18 +6,25 @@ from pathlib import Path
from typing import Any, Callable
from tensorfold.cuda.server import App, PreparedRequest, RequestError
@@ -450,8 +468,8 @@ index f46b66c..c776de5 100644
class ThinkingOffTemplate:
- """The checkpoint's chat template, rendered as GLM-5.3's thinking-off template renders it when thinking is off
-- (``prompts.thinking_off``, as the Mac's tokenizer renders it)."""
+- """The checkpoint template as GLM-5.3's thinking-off template renders it (``prompts.thinking_off``)."""
++ """The checkpoint's chat template, rendered as GLM-5.3's thinking-off template renders it when thinking is off
+ (``prompts.thinking_off``, as the Mac's tokenizer renders it), an agent's history made renderable first
+ (``prompts.agent_history``), with the reasoning of tool-calling steps the client dropped put back (``kept``,
+ ``kept_reasoning.KeptReasoning``; None: off)."""
@@ -470,7 +488,7 @@ index f46b66c..c776de5 100644
allow_images=allow_images)
return text if enable_thinking else thinking_off(text)
-@@ -49,7 +55,7 @@ class GlmApp(App):
+@@ -48,7 +55,7 @@ class GlmApp(App):
super().__init__(engine, model_dir, served, **kwargs)
if self.vision is not None:
media_template(self.template, Path(model_dir))
@@ -479,7 +497,7 @@ index f46b66c..c776de5 100644
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."""
-@@ -77,4 +83,9 @@ class GlmApp(App):
+@@ -76,4 +83,9 @@ class GlmApp(App):
model = str(body.get("model") or "")
self.engine.request.policy = body.get("tf_policy") or (model.split("@", 1)[1] if "@" in model else None)
self.engine.request.stop_eos = not bool(body.get("ignore_eos", False))
@@ -652,10 +670,10 @@ index 0000000..297326c
+ out[i] = {**m, "reasoning_content": kept}
+ return messages if out is None else out
diff --git tensorfold/families/glm5_next/prompts.py tensorfold/families/glm5_next/prompts.py
-index a8ad5fb..c64b155 100644
+index 0bf8532..8763a93 100644
--- tensorfold/families/glm5_next/prompts.py
+++ tensorfold/families/glm5_next/prompts.py
-@@ -3,12 +3,59 @@ line and opens a think block whatever ``enable_thinking`` says, and its thinking
+@@ -2,12 +2,59 @@
from __future__ import annotations
@@ -713,9 +731,9 @@ index a8ad5fb..c64b155 100644
+
+
def thinking_off(text: str) -> str:
- """The checkpoint template's ``text`` as the thinking-off template renders it: no effort line, an empty think
- block after a generation prompt."""
-@@ -27,6 +74,7 @@ class GlmTokenizer:
+ """The checkpoint text as the thinking-off template renders it: no effort line, an empty think block."""
+
+@@ -25,6 +72,7 @@ class GlmTokenizer:
return getattr(self._inner, name)
def apply_chat_template(self, messages: Any, *args: Any, tokenize: bool = True, **kwargs: Any) -> Any:
@@ -740,7 +758,7 @@ index dde2b67..2679969 100644
if not out:
instructions.append(item)
diff --git tensorfold/tool_parameters.py tensorfold/tool_parameters.py
-index 2ae9146..ea2fae6 100644
+index d722004..6e07f31 100644
--- tensorfold/tool_parameters.py
+++ tensorfold/tool_parameters.py
@@ -1,4 +1,9 @@
@@ -754,7 +772,7 @@ index 2ae9146..ea2fae6 100644
from __future__ import annotations
-@@ -23,9 +28,39 @@ def parameter_schemas(tools: Sequence[dict[str, Any]] | None) -> dict[str, dict[
+@@ -24,9 +29,39 @@ def parameter_schemas(tools: Sequence[dict[str, Any]] | None) -> dict[str, dict[
return result
@@ -796,8 +814,8 @@ index 2ae9146..ea2fae6 100644
def closed_json(text: str) -> str | None:
-@@ -44,12 +79,25 @@ def closed_json(text: str) -> str | None:
- return text.rstrip() + "".join(reversed(closers)) if closers and not in_string else None
+@@ -68,22 +103,39 @@ def _python_literal(text: str) -> Any:
+ raise ValueError(str(exc)) from None
+def nullable_text(schema: dict[str, Any]) -> bool:
@@ -808,27 +826,58 @@ index 2ae9146..ea2fae6 100644
+ return "string" in kinds and "null" in kinds
+
+
- def decode_parameter(value: str, schema: dict[str, Any]) -> Any:
+ def decode_parameter(value: str, schema: dict[str, Any], *, python: bool = True) -> Any:
+- """``value`` as the schema's type when it spells one, else the text; ``python`` also reads Python's spelling."""
+ """A parameter's text read by its schema: a string schema keeps the text (a nullable one reads ``null`` as None,
+ which the template renders back as ``null``); a typed one reads JSON of an admitted type, or the value closed
-+ (#87). Anything else stays as written, so a resent history renders the tokens the model wrote (a quoted ``"5"``,
-+ Python's ``True`` or ``2.0`` for an integer are not coerced: their JSON would render differently)."""
-+
++ (#87), and with ``python`` (Qwen's parsers) Python's spelling of one (``True``, ``None``, ``['a']``). Anything
++ else stays as written, so a resent history renders the tokens the model wrote: GLM's parsers pass python=False
++ (a quoted ``"5"``, Python's ``True`` or ``2.0`` for an integer are not coerced: their JSON would render
++ differently)."""
+
if not typed_parameter(schema):
- return value
- kind = schema["type"]
+- valid = {
+- "array": lambda v: isinstance(v, list),
+- "object": lambda v: isinstance(v, dict),
+- "boolean": lambda v: isinstance(v, bool),
+- "integer": lambda v: type(v) is int,
+- "number": lambda v: type(v) in (int, float),
+- "null": lambda v: v is None,
+- }[kind]
+ return None if nullable_text(schema) and value == "null" else value
+ kinds = schema_types(schema)
++
++ def admitted(parsed: Any) -> bool:
++ valid = {
++ "array": isinstance(parsed, list),
++ "object": isinstance(parsed, dict),
++ "boolean": isinstance(parsed, bool),
++ "integer": type(parsed) is int,
++ "number": type(parsed) in (int, float),
++ "null": parsed is None,
++ }
++ return any(valid[kind] for kind in kinds)
++
# a model can end an object or array value one closer short (#87): the value closed is what it meant
- for text in (value, closed_json(value) if kind in ("array", "object") else None):
+ for text in (value, closed_json(value) if kinds & {"array", "object"} else None):
if text is None:
continue
try:
-@@ -65,5 +113,5 @@ def decode_parameter(value: str, schema: dict[str, Any]) -> Any:
- "number": type(parsed) in (int, float),
- "null": parsed is None,
- }
-- return parsed if valid[kind] else value
-+ return parsed if any(valid[kind] for kind in kinds) else value
- return value
+@@ -91,7 +143,7 @@ def decode_parameter(value: str, schema: dict[str, Any], *, python: bool = True)
+ json.dumps(parsed, allow_nan=False)
+ except (ValueError, TypeError):
+ continue
+- return parsed if valid(parsed) else value
++ return parsed if admitted(parsed) else value
+ # not JSON: Python's spelling (True, None, single-quoted strings), as vLLM's Qwen parsers also accept
+ if not python:
+ return value
+@@ -100,4 +152,4 @@ def decode_parameter(value: str, schema: dict[str, Any], *, python: bool = True)
+ json.dumps(parsed, allow_nan=False)
+ except (ValueError, TypeError):
+ return value
+- return parsed if valid(parsed) else value
++ return parsed if admitted(parsed) else value
diff --git a/patches/0040-cuda-tokenize.patch b/patches/0037-cuda-tokenize.patch
similarity index 96%
rename from patches/0040-cuda-tokenize.patch
rename to patches/0037-cuda-tokenize.patch
index bb994c3..e2f111e 100644
--- a/patches/0040-cuda-tokenize.patch
+++ b/patches/0037-cuda-tokenize.patch
@@ -1,5 +1,5 @@
diff --git tensorfold/cuda/http.py tensorfold/cuda/http.py
-index c3d7cca..da26749 100644
+index b800c81..84ae839 100644
--- tensorfold/cuda/http.py
+++ tensorfold/cuda/http.py
@@ -18,6 +18,9 @@ if TYPE_CHECKING:
@@ -12,7 +12,7 @@ index c3d7cca..da26749 100644
def usage_of(result: dict[str, Any]) -> dict[str, Any]:
"""A reply's usage as the Mac server reports it, the prompt tokens found cached included."""
-@@ -81,7 +84,8 @@ def make_handler(app: App):
+@@ -85,7 +88,8 @@ def make_handler(app: App):
if responses.route(self.path) == "": # a Response: this handler's chat completion, translated
return responses.post(self, app)
chat = self.path.rstrip("/").endswith("/chat/completions")
@@ -22,7 +22,7 @@ index c3d7cca..da26749 100644
return self._json(404, {"error": "not found"})
try:
length = int(self.headers.get("Content-Length", 0))
-@@ -92,6 +96,16 @@ def make_handler(app: App):
+@@ -96,6 +100,16 @@ def make_handler(app: App):
body = json.loads(self.rfile.read(length) or b"{}")
except (json.JSONDecodeError, UnicodeDecodeError):
return self._json(400, {"error": {"message": "the request body is not JSON", "type": "invalid_request_error"}})
@@ -40,10 +40,10 @@ index c3d7cca..da26749 100644
prepared = app.prepare(body, chat)
except RequestError as exc:
diff --git tensorfold/cuda/server.py tensorfold/cuda/server.py
-index 4ab6484..bbcf1a1 100644
+index 8a3ab2b..673fc9f 100644
--- tensorfold/cuda/server.py
+++ tensorfold/cuda/server.py
-@@ -190,17 +190,66 @@ class App:
+@@ -223,17 +223,66 @@ class App:
self.sampling_for(body, rendered.tokens), ignore_eos=ignore_eos, stop=stop,
vision=rendered.vision, grammar=compiled, think_budget=budget)
text = render(body["messages"])
@@ -112,7 +112,7 @@ index 4ab6484..bbcf1a1 100644
def check(self, body: dict[str, Any], *, prepared: PreparedRequest | None = None) -> str | None:
"""Why the request cannot run, or None; rendered before a stream's headers are sent."""
-@@ -489,6 +538,13 @@ class App:
+@@ -555,6 +604,13 @@ class App:
encode=lambda t: list(self.tok.encode(t, add_special_tokens=False).ids))
diff --git a/patches/0041-glm-kv-fp8.patch b/patches/0038-glm-kv-fp8.patch
similarity index 97%
rename from patches/0041-glm-kv-fp8.patch
rename to patches/0038-glm-kv-fp8.patch
index 1df6db5..0f46cfe 100644
--- a/patches/0041-glm-kv-fp8.patch
+++ b/patches/0038-glm-kv-fp8.patch
@@ -1,8 +1,8 @@
diff --git tensorfold/cuda/geometry.py tensorfold/cuda/geometry.py
-index 49f10d0..afce1d7 100644
+index 0306412..d5ee33a 100644
--- tensorfold/cuda/geometry.py
+++ tensorfold/cuda/geometry.py
-@@ -195,6 +195,28 @@ def _indexed_prefill_row(t: dict, world: int, h: int, hk: int, hd: int, nv: int,
+@@ -220,6 +220,28 @@ def _indexed_prefill_row(t: dict, world: int, h: int, hk: int, hd: int, nv: int,
+ 12 * streams + 64)
@@ -31,7 +31,7 @@ index 49f10d0..afce1d7 100644
def exl3_expert_scratch(rows: int, slots: int, d: int, width: int, *, prompt: bool) -> int:
"""GLM's ``exl3_mm.Scratch`` for a window of ``rows`` rows: fp16 rotated inputs of gate/up (2 x pairs x d) and down
(pairs x ``width``, a rank's expert width); a decode window's fp32 split-K sums (2 x 4 splits x pairs x
-@@ -209,12 +231,13 @@ def exl3_expert_scratch(rows: int, slots: int, d: int, width: int, *, prompt: bo
+@@ -234,12 +256,13 @@ def exl3_expert_scratch(rows: int, slots: int, d: int, width: int, *, prompt: bo
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,
@@ -47,7 +47,7 @@ index 49f10d0..afce1d7 100644
linear, attention = layer_counts(t)
lin = t.get("linear_attn_config") or {}
heads = int(t["num_attention_heads"]) // world
-@@ -244,19 +267,23 @@ def mla_geometry(t: dict, world: int, reserve: int, *, minimum_slots: int = 2560
+@@ -269,19 +292,23 @@ def mla_geometry(t: dict, world: int, reserve: int, *, minimum_slots: int = 2560
fixed += 8 * prefill_rows * 16384 * 4 if prompt_split_k else 0
count = attention + int(mtp)
lw = int(t.get("kv_lora_rank", 512))
@@ -74,7 +74,7 @@ index 49f10d0..afce1d7 100644
return Geometry(bytes_at, reserve, minimum_slots)
diff --git tensorfold/families/glm5_next/cuda/decode.py tensorfold/families/glm5_next/cuda/decode.py
-index 6732311..813f4c0 100644
+index ed74101..2382093 100644
--- tensorfold/families/glm5_next/cuda/decode.py
+++ tensorfold/families/glm5_next/cuda/decode.py
@@ -85,13 +85,14 @@ class Engine:
@@ -117,7 +117,7 @@ index 6732311..813f4c0 100644
self.slots = Slots(w, streams, max_rows)
self.home = self.st = State(w, capacity, max_rows, caches=self.caches, slots=self.slots)
self.last_hidden: torch.Tensor | None = None
-@@ -287,35 +294,74 @@ class Snapshot:
+@@ -287,16 +294,55 @@ class Snapshot:
rows: list | None = None # the attention rows of ids, saved when another conversation took the live caches
nbytes: int = 0
drafter_rows: list | None = None # a ring drafter's window rows before drafter_end, copied when taken
@@ -176,6 +176,7 @@ index 6732311..813f4c0 100644
if drafter is not None and getattr(drafter, "ring", 0) and snap.drafter_end == len(snap.ids):
snap.drafter_rows = _ring_window(drafter, len(snap.ids))
return snap
+@@ -324,19 +370,19 @@ def _put_ring_window(drafter, n: int, rows: list[torch.Tensor]) -> None:
def _row_views(st, n: int, m: int) -> list[torch.Tensor]:
@@ -200,12 +201,11 @@ index 6732311..813f4c0 100644
return views
-@@ -374,9 +420,10 @@ def row_bytes(e: Engine, snap: Snapshot, drafter=None) -> int:
+@@ -374,8 +420,10 @@ def row_bytes(e: Engine, snap: Snapshot, drafter=None) -> int:
def snapshot_bytes(snap: Snapshot) -> int:
-- """Device memory a kept snapshot holds: its KDA states, conv windows, pending MTP rows, a ring drafter's window
-- and any saved rows."""
+- """A kept snapshot's device bytes: KDA states, conv windows, pending MTP rows, a ring window, saved rows."""
+ """Device memory a kept snapshot holds: its KDA states, conv windows, pending MTP rows, a ring drafter's window,
+ the indexer rings' tail and any saved rows."""
held = [snap.rec, snap.conv] + ([snap.pending] if snap.pending is not None else []) + (snap.drafter_rows or [])
@@ -213,7 +213,7 @@ index 6732311..813f4c0 100644
return sum(t.numel() * t.element_size() for t in held) + (snap.nbytes if snap.rows is not None else 0)
-@@ -391,6 +438,7 @@ def load_rows(e: Engine, snap: Snapshot, drafter=None) -> None:
+@@ -390,6 +438,7 @@ def load_rows(e: Engine, snap: Snapshot, drafter=None) -> None:
def restore(e: Engine, snap: Snapshot, drafter=None) -> None:
st = e.st
@@ -222,10 +222,10 @@ index 6732311..813f4c0 100644
st.rec[st.cur[0]].copy_(snap.rec)
st.conv.copy_(snap.conv)
diff --git tensorfold/families/glm5_next/cuda/engine.py tensorfold/families/glm5_next/cuda/engine.py
-index 8154dc6..b357ce2 100644
+index 32c01f3..2524b65 100644
--- tensorfold/families/glm5_next/cuda/engine.py
+++ tensorfold/families/glm5_next/cuda/engine.py
-@@ -388,7 +388,7 @@ class GlmEngine:
+@@ -384,7 +384,7 @@ class GlmEngine:
from .split import rule
from tensorfold.cuda.capacity import admit
from tensorfold.cuda.geometry import (PREFILL_ROWS, dflash2_geometry, dflash2_weights, mla_geometry,
@@ -234,7 +234,7 @@ index 8154dc6..b357ce2 100644
encode_policy(policy) # a bad default fails here, not in the first request
if not encode_policy(DFLASH_POLICY)[0] >= 10:
-@@ -439,6 +439,13 @@ class GlmEngine:
+@@ -435,6 +435,13 @@ class GlmEngine:
# TF_GLM_KVB=fp8/q4 (an EXL3 checkpoint, latent cache): kv_b as the absorb and expand kernels read it
kvb = kvb_kind() if cfg.quant == "exl3" and LATENT else "bf16"
weights_estimate = kvb_weights(weights_estimate, kvb)
@@ -245,10 +245,10 @@ index 8154dc6..b357ce2 100644
+ if kv != "bf16" and not LATENT:
+ raise ValueError("TF_GLM_KV=fp8 holds the latent cache: it needs TF_GLM_LATENT=1")
+ self.kv = kv
- # TF_GLM_MTP (``mtp_head``): off, the MTP layer's tensors are not loaded, so the estimate drops them too
+ # TF_GLM_MTP off: the MTP layer's tensors, caches and buffers are neither loaded nor estimated
self.mtp_on = mtp_head(drafter is not None, serial_only, cfg.mtp_layers) and parallel == 1 # multi: DFlash2
if not self.mtp_on:
-@@ -472,11 +479,11 @@ class GlmEngine:
+@@ -468,11 +475,11 @@ class GlmEngine:
g = mla_geometry(text, 2, MAX_ROWS, minimum_slots=DENSE_CAPACITY, latent=LATENT, prefill_rows=prefill_rows,
mtp=self.mtp_on, onepass=SPARSE_ONEPASS, exl3_prompt=prompt_kernels(),
@@ -262,7 +262,7 @@ index 8154dc6..b357ce2 100644
per = 4 * MULTI_WINDOW // 4 if parallel > 1 else 0
if not extra and not per:
return g
-@@ -523,7 +530,8 @@ class GlmEngine:
+@@ -519,7 +526,8 @@ class GlmEngine:
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),
parallel, *verify_code, int(union_cover()), MAX_ROWS, len(WIDE_GRAPHS),
@@ -272,7 +272,7 @@ index 8154dc6..b357ce2 100644
# other conversations' kept prompts get what the window leaves, at most TF_GLM_CACHE_GIB, the same on both ranks
plan = self.capacity_plan
wanted = int(float(os.environ.get("TF_GLM_CACHE_GIB", "3")) * 2 ** 30)
-@@ -535,7 +543,7 @@ class GlmEngine:
+@@ -531,7 +539,7 @@ class GlmEngine:
"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, "
@@ -281,7 +281,7 @@ index 8154dc6..b357ce2 100644
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
-@@ -585,7 +593,7 @@ class GlmEngine:
+@@ -582,7 +590,7 @@ class GlmEngine:
self.e = Engine(w, capacity=pool_rows or capacity, max_rows=MAX_ROWS, prefill_rows=prefill_rows, graphs=True,
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,
@@ -290,7 +290,7 @@ index 8154dc6..b357ce2 100644
if self.e.pbuf.split is not None:
self.e.pbuf.split.warm() # both ranks: open the send/receive connection now
if rank == 0:
-@@ -601,6 +609,9 @@ class GlmEngine:
+@@ -598,6 +606,9 @@ class GlmEngine:
if rank == 0 and self.dump is not None:
print(f"[tensorfold] TF_GLM_DRAFT_DUMP: DFlash2 requests decode serially and record the drafter's view "
f"into {self.dump} (one .npz a request; replies equal draft: false)", flush=True)
@@ -301,11 +301,11 @@ index 8154dc6..b357ce2 100644
print("[tensorfold] TF_GLM_DRAFT_QUANT=mse: DFlash2's 4-bit copies (and an EXL3 draft head) with "
"least-squares clipped ranges", flush=True)
diff --git tensorfold/families/glm5_next/cuda/forward.py tensorfold/families/glm5_next/cuda/forward.py
-index ef785e7..c6967f8 100644
+index 79a1ec9..1aab97c 100644
--- tensorfold/families/glm5_next/cuda/forward.py
+++ tensorfold/families/glm5_next/cuda/forward.py
-@@ -11,7 +11,7 @@ import triton.language as tl
- from tensorfold.cuda import experts as grouped
+@@ -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, latent, prof, qmm, sparse
@@ -313,7 +313,7 @@ index ef785e7..c6967f8 100644
from .attention import AttnScratch, attention, kv_write
from .weights import LayerW, Weights
-@@ -160,13 +160,28 @@ class Buffers:
+@@ -161,13 +161,28 @@ class Buffers:
return p
@@ -344,7 +344,7 @@ index ef785e7..c6967f8 100644
from .pool import Arena, Plane
c = w.cfg
-@@ -174,15 +189,21 @@ class Caches:
+@@ -175,15 +190,21 @@ class Caches:
HL = c.heads // w.world
dsa = len([l for l in w.layers if l.kind == "dsa"])
self.latent = latent.ENABLED
@@ -369,7 +369,7 @@ index ef785e7..c6967f8 100644
return add((HL, c.qk_dim)), add((HL, c.v_dim))
self.kc, self.vc = [], []
-@@ -191,14 +212,42 @@ class Caches:
+@@ -192,14 +213,42 @@ class Caches:
self.kc.append(k)
self.vc.append(v)
self.mtp = attention_planes() if w.mtp is not None else None
@@ -414,7 +414,7 @@ index ef785e7..c6967f8 100644
def bind(self, st: "State", base: int, size: int) -> None:
"""Point ``st``'s caches at tokens [base, base + size) of the pool."""
-@@ -207,7 +256,14 @@ class Caches:
+@@ -208,7 +257,14 @@ class Caches:
st.vc = [view(i) for i in self.vc]
if self.mtp is not None:
st.mtp_kc, st.mtp_vc = view(self.mtp[0]), view(self.mtp[1])
@@ -430,7 +430,7 @@ index ef785e7..c6967f8 100644
class Slots:
-@@ -257,8 +313,8 @@ class State:
+@@ -258,8 +314,8 @@ class State:
own (one sequence of ``capacity`` tokens, one slot), as it always held tensors of its own."""
def __init__(self, w: Weights, capacity: int, rows: int, *, caches: Caches | None = None, base: int = 0,
@@ -441,7 +441,7 @@ index ef785e7..c6967f8 100644
self.slots = slots if slots is not None else Slots(w, 1, rows)
self.slot = slot
kda_layers = [l for l in w.layers if l.kind == "kda"]
-@@ -287,6 +343,11 @@ class State:
+@@ -288,6 +344,11 @@ class State:
self.base, self.capacity = int(base), int(capacity)
self.caches.bind(self, self.base, self.capacity)
@@ -1120,12 +1120,12 @@ index 91b3d06..ae8b0d9 100644
t, R = self.fill(segments, sparse_from=sparse_from)
diff --git tensorfold/families/glm5_next/cuda/sparse.py tensorfold/families/glm5_next/cuda/sparse.py
-index 59c274b..bc5362a 100644
+index acfc069..ea3ade3 100644
--- tensorfold/families/glm5_next/cuda/sparse.py
+++ tensorfold/families/glm5_next/cuda/sparse.py
-@@ -6,6 +6,9 @@ import torch
- import triton
- import triton.language as tl
+@@ -8,6 +8,9 @@ import triton.language as tl
+
+ from tensorfold.cuda.geometry import MLA_SELECT_ROWS as SELECT_ROWS # a prompt chunk's rows scored at once
+from . import kv8
+from .kv8 import row_scales
@@ -1133,7 +1133,7 @@ index 59c274b..bc5362a 100644
POOL = 4
TOPK_POOLS = 512
BR = 16
-@@ -15,8 +18,8 @@ TOKENS = TOPK_POOLS * POOL + POOL - 1 # a sparse row's attended tokens: its
+@@ -17,8 +20,8 @@ TOKENS = TOPK_POOLS * POOL + POOL - 1 # a sparse row's attended tokens: its
@triton.jit
@@ -1144,7 +1144,7 @@ index 59c274b..bc5362a 100644
r = tl.program_id(0)
P = tl.load(POS).to(tl.int64)
-@@ -26,13 +29,16 @@ def _index_write(KR, k_stride, GR, LNW, LNB, IK, IG, POS, eps, D: tl.constexpr):
+@@ -28,13 +31,16 @@ def _index_write(KR, k_stride, GR, LNW, LNB, IK, IG, POS, eps, D: tl.constexpr):
xc = x - mean
var = tl.sum(xc * xc, axis=0) / D
y = xc / tl.sqrt(var + eps) * tl.load(LNW + d).to(tl.float32) + tl.load(LNB + d).to(tl.float32)
@@ -1165,7 +1165,7 @@ index 59c274b..bc5362a 100644
i = tl.program_id(0)
P = tl.load(POS).to(tl.int64)
-@@ -40,40 +46,55 @@ def _pool_keys(IK, IG, APE, PK, POS, R, D: tl.constexpr):
+@@ -42,40 +48,55 @@ def _pool_keys(IK, IG, APE, PK, POS, R, D: tl.constexpr):
if 4 * p + 3 > P + R - 1:
return
d = tl.arange(0, D)
@@ -1236,7 +1236,7 @@ index 59c274b..bc5362a 100644
rb = tl.program_id(0)
pb = tl.program_id(1)
-@@ -82,8 +103,10 @@ def _scores(QI, W, w_stride, PK, OUT, POS, R, NP, scale, wscale, H: tl.constexpr
+@@ -92,8 +113,10 @@ def _scores(QI, W, w_stride, PK, OUT, POS, R, NP, scale, wscale, H: tl.constexpr
d = tl.arange(0, D)
hh = tl.arange(0, HP)
hok = hh < H
@@ -1249,7 +1249,7 @@ index 59c274b..bc5362a 100644
for i in tl.static_range(RB):
r = rb * RB + i
if r < R:
-@@ -91,6 +114,8 @@ def _scores(QI, W, w_stride, PK, OUT, POS, R, NP, scale, wscale, H: tl.constexpr
+@@ -101,6 +124,8 @@ def _scores(QI, W, w_stride, PK, OUT, POS, R, NP, scale, wscale, H: tl.constexpr
q = tl.load(QI + (r * H + hh[:, None]) * D + d[None, :], mask=hok[:, None], other=0.0).to(tl.bfloat16)
kr = tl.where((p < npool)[:, None], k, 0.0)
dots = tl.dot(q, tl.trans(kr)) # [HP, BP] fp32
@@ -1258,7 +1258,7 @@ index 59c274b..bc5362a 100644
w = tl.load(W + r * w_stride + hh, mask=hok, other=0.0).to(tl.float32) * wscale
sc = tl.sum(w[:, None] * tl.maximum(dots * scale, 0.0), axis=0)
sc = tl.where(p < npool, sc, float("-inf"))
-@@ -98,12 +123,14 @@ def _scores(QI, W, w_stride, PK, OUT, POS, R, NP, scale, wscale, H: tl.constexpr
+@@ -108,12 +133,14 @@ def _scores(QI, W, w_stride, PK, OUT, POS, R, NP, scale, wscale, H: tl.constexpr
@triton.jit
@@ -1276,7 +1276,7 @@ index 59c274b..bc5362a 100644
r = tl.program_id(0)
g = tl.program_id(1)
-@@ -111,11 +138,11 @@ def _scores_rows(QI, W, w_stride, PK, OUT, o_stride, POS, SPR, BASE, R, NP, scal
+@@ -121,11 +148,11 @@ def _scores_rows(QI, W, w_stride, PK, OUT, o_stride, POS, SPR, BASE, R, NP, scal
if tl.load(SPR + r) == 0:
return
npool = (tl.load(POS + r) + 1) // 4
@@ -1290,7 +1290,7 @@ index 59c274b..bc5362a 100644
nb = (NP + BP - 1) // BP
if g >= nb:
return
-@@ -126,9 +153,12 @@ def _scores_rows(QI, W, w_stride, PK, OUT, o_stride, POS, SPR, BASE, R, NP, scal
+@@ -136,9 +163,12 @@ def _scores_rows(QI, W, w_stride, PK, OUT, o_stride, POS, SPR, BASE, R, NP, scal
w = tl.load(W + r * w_stride + hh, mask=hok, other=0.0).to(tl.float32) * wscale
for pb in tl.range(g, nb, G, num_stages=1): # Triton's pipelining of this loop: slower (measured)
p = pb * BP + tl.arange(0, BP)
@@ -1304,7 +1304,7 @@ index 59c274b..bc5362a 100644
sc = tl.sum(w[:, None] * tl.maximum(dots * scale, 0.0), axis=0)
if SEG:
tl.store(OUT + r * o_stride + p, sc, mask=p < npool)
-@@ -276,9 +306,10 @@ def select_tokens(qi: torch.Tensor, wts: torch.Tensor, pk: torch.Tensor, pos: in
+@@ -288,9 +318,10 @@ def select_tokens(qi: torch.Tensor, wts: torch.Tensor, pk: torch.Tensor, pos: in
D = qi.shape[1] // H
wscale = 1.0 / 5.656854249492381 if H == 32 else H ** -0.5 # 32 ** -0.5 exactly as before
grid = min(ROW_SCORE_G, triton.cdiv(np_max, 64))
@@ -1315,10 +1315,10 @@ index 59c274b..bc5362a 100644
+ _scores_rows[(R, grid)](qi, wts, wts.stride(0), pkv, pks, scores, np_max, pos_dev, pos_dev, pos_dev, R, np_max,
+ D ** -0.5, wscale, H=H, HP=max(16, triton.next_power_of_2(H)), D=D, BP=64, G=grid,
+ SEG=False, RS=rs, FP8=fp8, num_warps=4)
- pools = top_pools(scores, TOPK_POOLS) # ascending pool index
+ pools = top_pools(scores, TOPK_POOLS, pos_dev) # ascending pool index
dev = qi.device
width = TOPK_POOLS * POOL + POOL - 1
-@@ -320,14 +351,15 @@ def _select_prompt(qi: torch.Tensor, wts: torch.Tensor, pk: torch.Tensor, pos: i
+@@ -332,14 +363,15 @@ def _select_prompt(qi: torch.Tensor, wts: torch.Tensor, pk: torch.Tensor, pos: i
width = TOPK_POOLS * POOL + POOL - 1
tokens = torch.empty((R, width), dtype=torch.int32, device=dev)
counts = torch.empty((R,), dtype=torch.int32, device=dev)
@@ -1337,7 +1337,7 @@ index 59c274b..bc5362a 100644
pools = top_pools(scores, TOPK_POOLS) # ascending pool index
_tokens[(n,)](pools, at, tokens[a:a + n], counts[a:a + n], W=width, K=TOPK_POOLS, PL=POOL, BLOCK=1024,
num_warps=4)
-@@ -426,10 +458,12 @@ def sparse_attention(q: torch.Tensor, kc: torch.Tensor, vc: torch.Tensor, tokens
+@@ -438,10 +470,12 @@ def sparse_attention(q: torch.Tensor, kc: torch.Tensor, vc: torch.Tensor, tokens
# ------------------------------------------------------------------------------------- multi-stream windows ---
@@ -1354,7 +1354,7 @@ index 59c274b..bc5362a 100644
@triton.jit
def _ix_put(IX, row, d, x, D: tl.constexpr):
-@@ -444,23 +478,27 @@ def _ix_get(IX, row, d, D: tl.constexpr):
+@@ -456,23 +490,27 @@ def _ix_get(IX, row, d, D: tl.constexpr):
@triton.jit
@@ -1391,7 +1391,7 @@ index 59c274b..bc5362a 100644
d = tl.arange(0, D)
x = tl.load(KR + r * k_stride + d).to(tl.float32)
mean = tl.sum(x, axis=0) / D
-@@ -472,53 +510,62 @@ def _seg_index_write(KR, k_stride, GR, LNW, LNB, IK, IG, POS, BASE, eps, D: tl.c
+@@ -484,53 +522,62 @@ def _seg_index_write(KR, k_stride, GR, LNW, LNB, IK, IG, POS, BASE, eps, D: tl.c
@triton.jit
@@ -1474,7 +1474,7 @@ index 59c274b..bc5362a 100644
"""Program (segment, g): pool blocks g, g + G, .. below the segment's pool count (on the device: the pools its
last row sees), each block's keys (at the stream's pooled base) loaded once for all the segment's sparse rows;
a row's scores are _scores' (its keys masked to its own pools before the dot, as with RB > 1), written for its
-@@ -535,7 +582,7 @@ def _seg_scores(QI, W, w_stride, PK, OUT, o_stride, POS, SPR, SEG_START, SEG_ROW
+@@ -547,7 +594,7 @@ def _seg_scores(QI, W, w_stride, PK, OUT, o_stride, POS, SPR, SEG_START, SEG_ROW
hok = hh < H
for pb in range(g, (npm + BP - 1) // BP, G):
p = pb * BP + tl.arange(0, BP)
@@ -1483,7 +1483,7 @@ index 59c274b..bc5362a 100644
for i in range(nr):
r = r0 + i
if tl.load(SPR + r) != 0:
-@@ -543,6 +590,8 @@ def _seg_scores(QI, W, w_stride, PK, OUT, o_stride, POS, SPR, SEG_START, SEG_ROW
+@@ -555,6 +602,8 @@ def _seg_scores(QI, W, w_stride, PK, OUT, o_stride, POS, SPR, SEG_START, SEG_ROW
q = tl.load(QI + (r * H + hh[:, None]) * D + d[None, :], mask=hok[:, None], other=0.0).to(tl.bfloat16)
kr = tl.where((p < npool)[:, None], k, 0.0)
dots = tl.dot(q, tl.trans(kr)) # [HP, BP] fp32
@@ -1492,7 +1492,7 @@ index 59c274b..bc5362a 100644
w = tl.load(W + r * w_stride + hh, mask=hok, other=0.0).to(tl.float32) * wscale
sc = tl.sum(w[:, None] * tl.maximum(dots * scale, 0.0), axis=0)
tl.store(OUT + r * o_stride + p, sc, mask=p < npool)
-@@ -628,10 +677,11 @@ def seg_select_tokens(qi: torch.Tensor, wts: torch.Tensor, pk: torch.Tensor, row
+@@ -640,10 +689,11 @@ def seg_select_tokens(qi: torch.Tensor, wts: torch.Tensor, pk: torch.Tensor, row
wscale = 1.0 / 5.656854249492381 if H == 32 else H ** -0.5 # select_tokens' constants
scores = scratch.scores
grid = min(SEG_SCORE_GRID, triton.cdiv(scores.shape[1], 64))
diff --git a/patches/0042-glm-kda-chunked-kernel.patch b/patches/0039-glm-kda-chunked-kernel.patch
similarity index 99%
rename from patches/0042-glm-kda-chunked-kernel.patch
rename to patches/0039-glm-kda-chunked-kernel.patch
index 37f80f4..7942227 100644
--- a/patches/0042-glm-kda-chunked-kernel.patch
+++ b/patches/0039-glm-kda-chunked-kernel.patch
@@ -1,8 +1,8 @@
diff --git tensorfold/families/glm5_next/cuda/engine.py tensorfold/families/glm5_next/cuda/engine.py
-index b357ce2..64d16d9 100644
+index 2524b65..ae6a079 100644
--- tensorfold/families/glm5_next/cuda/engine.py
+++ tensorfold/families/glm5_next/cuda/engine.py
-@@ -86,19 +86,34 @@ def vision_workspace() -> int:
+@@ -84,19 +84,34 @@ def vision_workspace() -> int:
GRIDS = (16, 32, 64, 128) # TF_GLM_PROMPT_GRID's values besides 0 (off)
@@ -40,7 +40,7 @@ index b357ce2..64d16d9 100644
if prefill_rows % grid:
raise ValueError(f"TF_GLM_PROMPT_GRID={grid}: prompt chunks of {prefill_rows} rows (TF_GLM_PREFILL_ROWS) "
f"must be a multiple of it")
-@@ -618,6 +633,9 @@ class GlmEngine:
+@@ -615,6 +630,9 @@ class GlmEngine:
if rank == 0 and self.grid:
print(f"[tensorfold] prompt chunks and kept prompt states on a {self.grid}-token grid "
f"(TF_GLM_PROMPT_GRID)", flush=True)
diff --git a/patches/0043-glm-parallel-deadlocks.patch b/patches/0040-glm-parallel-deadlocks.patch
similarity index 99%
rename from patches/0043-glm-parallel-deadlocks.patch
rename to patches/0040-glm-parallel-deadlocks.patch
index a81cbba..a50cf90 100644
--- a/patches/0043-glm-parallel-deadlocks.patch
+++ b/patches/0040-glm-parallel-deadlocks.patch
@@ -39,10 +39,10 @@ index 52bc376..bba421c 100644
self.large += 1
self.nccl.all_gather(send, recv)
diff --git tensorfold/families/glm5_next/cuda/engine.py tensorfold/families/glm5_next/cuda/engine.py
-index 64d16d9..fbb3418 100644
+index ae6a079..2e0d675 100644
--- tensorfold/families/glm5_next/cuda/engine.py
+++ tensorfold/families/glm5_next/cuda/engine.py
-@@ -557,7 +557,7 @@ class GlmEngine:
+@@ -553,7 +553,7 @@ class GlmEngine:
"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, "
diff --git a/patches/0044-glm-parallel-ring-base.patch b/patches/0041-glm-parallel-ring-base.patch
similarity index 100%
rename from patches/0044-glm-parallel-ring-base.patch
rename to patches/0041-glm-parallel-ring-base.patch
diff --git a/patches/0045-glm-prompt-replay.patch b/patches/0042-glm-prompt-replay.patch
similarity index 98%
rename from patches/0045-glm-prompt-replay.patch
rename to patches/0042-glm-prompt-replay.patch
index e0d1004..81a8b7e 100644
--- a/patches/0045-glm-prompt-replay.patch
+++ b/patches/0042-glm-prompt-replay.patch
@@ -1,5 +1,5 @@
diff --git tensorfold/families/glm5_next/cuda/decode.py tensorfold/families/glm5_next/cuda/decode.py
-index 813f4c0..524eda3 100644
+index 2382093..a117edc 100644
--- tensorfold/families/glm5_next/cuda/decode.py
+++ tensorfold/families/glm5_next/cuda/decode.py
@@ -127,6 +127,7 @@ class Engine:
@@ -104,10 +104,10 @@ index 813f4c0..524eda3 100644
e.window = e.constraint.window([0], [-1])
first = e.sample(last, [len(prompt)], sampling)[0]
diff --git tensorfold/families/glm5_next/cuda/engine.py tensorfold/families/glm5_next/cuda/engine.py
-index fbb3418..0ba9f05 100644
+index 2e0d675..032b546 100644
--- tensorfold/families/glm5_next/cuda/engine.py
+++ tensorfold/families/glm5_next/cuda/engine.py
-@@ -834,14 +834,16 @@ class GlmEngine:
+@@ -827,14 +827,16 @@ class GlmEngine:
return auto, auto or not dflash, dflash
def _resume(self, prompt: list[int], code: list[int]):
@@ -126,7 +126,7 @@ index fbb3418..0ba9f05 100644
best is None or len(snap.ids) > len(best.ids)):
best = snap
return best
-@@ -938,7 +940,7 @@ class GlmEngine:
+@@ -931,7 +933,7 @@ class GlmEngine:
def _run_once(self, prompt: list[int], max_tokens: int, sampling, stop_eos: bool,
on_tokens: Callable[[list[int]], Any], code: list[int], hit, draft: bool,
feed=None, shared=()) -> dict[str, Any]:
@@ -135,7 +135,7 @@ index fbb3418..0ba9f05 100644
from .drafter_choice import DrafterChoice, auto_decode
auto, use_mtp, use_dflash = self._drafters(code)
-@@ -973,11 +975,18 @@ class GlmEngine:
+@@ -966,11 +968,18 @@ class GlmEngine:
resume = take_snapshot(self.e, head, self.e.last_hidden if use_mtp else None, mtp=use_mtp,
drafter=drafter)
kept.append(resume)
diff --git a/patches/0046-glm-visible-pools.patch b/patches/0043-glm-visible-pools.patch
similarity index 83%
rename from patches/0046-glm-visible-pools.patch
rename to patches/0043-glm-visible-pools.patch
index 10700a7..2c599d6 100644
--- a/patches/0046-glm-visible-pools.patch
+++ b/patches/0043-glm-visible-pools.patch
@@ -1,8 +1,8 @@
diff --git tensorfold/families/glm5_next/cuda/sparse.py tensorfold/families/glm5_next/cuda/sparse.py
-index bc5362a..36d697a 100644
+index ea3ade3..bfdbf40 100644
--- tensorfold/families/glm5_next/cuda/sparse.py
+++ tensorfold/families/glm5_next/cuda/sparse.py
-@@ -125,12 +125,14 @@ def _scores(QI, W, w_stride, PK, PKS, OUT, POS, R, NP, scale, wscale, H: tl.cons
+@@ -135,12 +135,14 @@ def _scores(QI, W, w_stride, PK, PKS, OUT, POS, R, NP, scale, wscale, H: tl.cons
@triton.jit
def _scores_rows(QI, W, w_stride, PK, PKS, OUT, o_stride, POS, SPR, BASE, R, NP, scale, wscale, H: tl.constexpr,
HP: tl.constexpr, D: tl.constexpr, BP: tl.constexpr, G: tl.constexpr, SEG: tl.constexpr,
@@ -21,7 +21,7 @@ index bc5362a..36d697a 100644
r = tl.program_id(0)
g = tl.program_id(1)
-@@ -143,7 +145,7 @@ def _scores_rows(QI, W, w_stride, PK, PKS, OUT, o_stride, POS, SPR, BASE, R, NP,
+@@ -153,7 +155,7 @@ def _scores_rows(QI, W, w_stride, PK, PKS, OUT, o_stride, POS, SPR, BASE, R, NP,
else:
npool = (tl.load(POS) + r + 1) // 4
pbase = tl.zeros((), tl.int64)
@@ -30,11 +30,11 @@ index bc5362a..36d697a 100644
if g >= nb:
return
d = tl.arange(0, D)
-@@ -191,11 +193,16 @@ def _order_key(s):
+@@ -201,21 +203,25 @@ def _order_key(s):
@triton.jit
--def _select_rows(S, OUT, NP, K: tl.constexpr, BLOCK: tl.constexpr):
+-def _select_rows(S, OUT, NP, POS, K: tl.constexpr, BLOCK: tl.constexpr, VISIBLE: tl.constexpr):
- """Program r: a radix select (8 bits a pass) finds the K-th best score, then one pass in pool order writes the pools above it and the lowest ties."""
+def _select_rows(S, OUT, NPS, POS, K: tl.constexpr, BLOCK: tl.constexpr, VIS: tl.constexpr):
+ """Program r: a radix select (8 bits a pass) finds the K-th best score, then one pass in pool order writes the pools above it and the lowest ties.
@@ -42,6 +42,7 @@ index bc5362a..36d697a 100644
r = tl.program_id(0).to(tl.int64)
- row = S + r * NP
+- limit = tl.minimum(NP, tl.maximum(K, (tl.load(POS) + r + 1) // 4)) if VISIBLE else NP
+ row = S + r * NPS
+ if VIS:
+ NP = _visible_bound(NPS, tl.load(POS), r, K)
@@ -50,11 +51,34 @@ index bc5362a..36d697a 100644
bins = tl.arange(0, 256)
prefix = tl.zeros((), dtype=tl.uint32)
fixed = tl.zeros((), dtype=tl.uint32)
-@@ -227,18 +234,32 @@ def _select_rows(S, OUT, NP, K: tl.constexpr, BLOCK: tl.constexpr):
+ need = K
+ for p in tl.static_range(4):
+ hist = tl.zeros((256,), dtype=tl.int32)
+- for c in range(0, limit, BLOCK):
++ for c in range(0, NP, BLOCK):
+ i = c + tl.arange(0, BLOCK)
+- ok = i < limit
++ ok = i < NP
+ u = _order_key(tl.load(row + i, mask=ok, other=0.0))
+ match = ok & ((u & fixed) == prefix)
+ hist += tl.histogram(((u >> (24 - 8 * p)) & 0xFF).to(tl.int32), 256, mask=match)
+@@ -226,9 +232,9 @@ def _select_rows(S, OUT, NP, POS, K: tl.constexpr, BLOCK: tl.constexpr, VISIBLE:
+ fixed = fixed | (tl.full((), 0xFF, tl.uint32) << (24 - 8 * p))
+ written = 0
+ equal_seen = 0
+- for c in range(0, limit, BLOCK):
++ for c in range(0, NP, BLOCK):
+ i = c + tl.arange(0, BLOCK)
+- ok = i < limit
++ ok = i < NP
+ u = _order_key(tl.load(row + i, mask=ok, other=0.0))
+ eq = (ok & (u == prefix)).to(tl.int32)
+ take = (ok & (u > prefix)) | ((eq == 1) & (tl.cumsum(eq, 0) - eq + equal_seen < need))
+@@ -238,20 +244,32 @@ def _select_rows(S, OUT, NP, POS, K: tl.constexpr, BLOCK: tl.constexpr, VISIBLE:
equal_seen += tl.sum(eq, 0)
--def top_pools(scores: torch.Tensor, k: int) -> torch.Tensor:
+-def top_pools(scores: torch.Tensor, k: int, pos_dev: torch.Tensor | None = None) -> torch.Tensor:
+def _visible_bound(NPS, P, r, K: tl.constexpr):
+ """Columns a decode row at position P + r needs: its complete pools, at least K, at most the NPS scored.
@@ -66,7 +90,8 @@ index bc5362a..36d697a 100644
+
+def top_pools(scores: torch.Tensor, k: int, pos: torch.Tensor | None = None) -> torch.Tensor:
"""``_top_pools``'s pools, ascending, without int64 keys, top-k or sort: one program a row, or for a decode
-- window's long rows the split selection (select_split); the same pools either way."""
+- window's long rows the split selection (select_split); the same pools either way. ``pos_dev``: the rows sit at
+- pos_dev, pos_dev + 1, .. and the one-program selection reads each row's visible pools only (the same pools)."""
+ window's long rows the split selection (select_split); the same pools either way. ``pos`` (device [1]): the
+ rows are decode rows at pos, pos + 1, ..; each is selected over its visible columns only (_visible_bound),
+ and the columns past them need not be written."""
@@ -81,18 +106,19 @@ index bc5362a..36d697a 100644
# one program a row (speed only): decode rows past 1,024 scores 4,096 a step, prompt chunks' rows 1,024
block, warps = (4096, 8) if R < SPLIT_ROWS and NP > 1024 else (1024, 4)
out = torch.empty((R, k), dtype=torch.int64, device=scores.device)
-- _select_rows[(R,)](scores, out, NP, K=k, BLOCK=block, num_warps=warps)
+- _select_rows[(R,)](scores, out, NP, pos_dev if pos_dev is not None else scores,
+- K=k, BLOCK=block, VISIBLE=pos_dev is not None, num_warps=warps)
+ _select_rows[(R,)](scores, out, NP, scores if pos is None else pos, K=k, BLOCK=block, VIS=pos is not None,
+ num_warps=warps)
return out
-@@ -309,19 +330,19 @@ def select_tokens(qi: torch.Tensor, wts: torch.Tensor, pk: torch.Tensor, pos: in
+@@ -321,19 +339,19 @@ def select_tokens(qi: torch.Tensor, wts: torch.Tensor, pk: torch.Tensor, pos: in
pkv, pks, rs, fp8 = kv8.parts(pk)
_scores_rows[(R, grid)](qi, wts, wts.stride(0), pkv, pks, scores, np_max, pos_dev, pos_dev, pos_dev, R, np_max,
D ** -0.5, wscale, H=H, HP=max(16, triton.next_power_of_2(H)), D=D, BP=64, G=grid,
- SEG=False, RS=rs, FP8=fp8, num_warps=4)
-- pools = top_pools(scores, TOPK_POOLS) # ascending pool index
+- pools = top_pools(scores, TOPK_POOLS, pos_dev) # ascending pool index
- dev = qi.device
+ SEG=False, RS=rs, FP8=fp8, K=TOPK_POOLS, num_warps=4)
+ # the graphs' power-of-two bucket past the rows' visible pools: neither scored nor scanned (_visible_bound); the
@@ -119,7 +145,7 @@ index bc5362a..36d697a 100644
return tokens, counts
-@@ -720,10 +741,13 @@ def _split_digits(TOT, r, STEPS: tl.constexpr, K: tl.constexpr):
+@@ -732,10 +750,13 @@ def _split_digits(TOT, r, STEPS: tl.constexpr, K: tl.constexpr):
@triton.jit
def _select_split(S, s_stride, NPC, POS, SPR, TOT, HIST, GT, OUT, TOK, CNT, W: tl.constexpr, K: tl.constexpr,
@@ -136,7 +162,7 @@ index bc5362a..36d697a 100644
r = tl.program_id(0).to(tl.int64)
c = tl.program_id(1)
-@@ -735,9 +759,15 @@ def _select_split(S, s_stride, NPC, POS, SPR, TOT, HIST, GT, OUT, TOK, CNT, W: t
+@@ -747,9 +768,15 @@ def _select_split(S, s_stride, NPC, POS, SPR, TOT, HIST, GT, OUT, TOK, CNT, W: t
return
qpos = tl.load(POS + r).to(tl.int64)
NP = (qpos + 1) // PL
@@ -154,7 +180,7 @@ index bc5362a..36d697a 100644
nch = (NP + CHS - 1) // CHS
if c >= nch:
return
-@@ -769,18 +799,18 @@ def _select_split(S, s_stride, NPC, POS, SPR, TOT, HIST, GT, OUT, TOK, CNT, W: t
+@@ -781,18 +808,18 @@ def _select_split(S, s_stride, NPC, POS, SPR, TOT, HIST, GT, OUT, TOK, CNT, W: t
take = (ok & (u > prefix)) | ((e == 1) & (tl.cumsum(e, 0) - e + equal_seen < need))
t = take.to(tl.int32)
slot = (written + tl.cumsum(t, 0) - t).to(tl.int64)
@@ -176,7 +202,7 @@ index bc5362a..36d697a 100644
else:
tl.store(OUT + r * K + slot, i.to(tl.int64), mask=take)
-@@ -806,8 +836,10 @@ def split_scratch(rows: int, np_: int, device) -> torch.Tensor:
+@@ -818,8 +845,10 @@ def split_scratch(rows: int, np_: int, device) -> torch.Tensor:
def select_split(scores: torch.Tensor, k: int, *, scratch: torch.Tensor | None = None, rows=None,
@@ -189,7 +215,7 @@ index bc5362a..36d697a 100644
tokens / counts, seg_select_tokens' per-row output over each sparse row's visible pools. ``scratch``: at least
split_scratch(R, NP)'s (allocated when None)."""
-@@ -821,11 +853,15 @@ def select_split(scores: torch.Tensor, k: int, *, scratch: torch.Tensor | None =
+@@ -833,11 +862,15 @@ def select_split(scores: torch.Tensor, k: int, *, scratch: torch.Tensor | None =
gt = scratch[R * (1024 + cp * 256):R * (1024 + cp * 257)]
tot.zero_()
seg = rows is not None
diff --git a/patches/0047-cuda-context-errors.patch b/patches/0044-cuda-context-errors.patch
similarity index 53%
rename from patches/0047-cuda-context-errors.patch
rename to patches/0044-cuda-context-errors.patch
index 74f42bb..5665e94 100644
--- a/patches/0047-cuda-context-errors.patch
+++ b/patches/0044-cuda-context-errors.patch
@@ -1,17 +1,8 @@
diff --git tensorfold/cuda/http.py tensorfold/cuda/http.py
-index da26749..9bf5ddd 100644
+index 84ae839..dabd045 100644
--- tensorfold/cuda/http.py
+++ tensorfold/cuda/http.py
-@@ -10,7 +10,7 @@ from typing import TYPE_CHECKING, Any
- from tensorfold.cuda import health
- from tensorfold.server import responses
- from tensorfold.server.cancellation import RequestCancelled, socket_cancellation
--from tensorfold.server.errors import CapacityError, RequestError
-+from tensorfold.server.errors import CapacityError, RequestError, error_body
- from tensorfold.server.http import Server
- from tensorfold.server.stacks import Rearming
-
-@@ -106,11 +106,12 @@ def make_handler(app: App):
+@@ -110,11 +110,12 @@ def make_handler(app: App):
_log_error(exc)
return self._json(400, {"error": {"message": _error_message(exc)}})
return self._json(200, reply)
@@ -20,78 +11,29 @@ index da26749..9bf5ddd 100644
prepared = app.prepare(body, chat)
except RequestError as exc:
return self._json(503 if isinstance(exc, CapacityError) else 400,
-- {"error": {"message": str(exc), "type": "invalid_request_error"}})
+- {"error": error_body(exc)})
+ {"error": error_body(exc, field)})
except Exception as exc: # any other failure to read the request is refused too, as on MLX
_log_error(exc)
return self._json(400, {"error": {"message": _error_message(exc)}})
-@@ -151,7 +152,7 @@ def make_handler(app: App):
+@@ -156,7 +157,7 @@ def make_handler(app: App):
self.close_connection = True
return
except RequestError as exc:
-- return self._stream_error({"message": str(exc), "type": "invalid_request_error"})
+- return self._stream_error(error_body(exc))
+ return self._stream_error(error_body(exc, field))
except Exception as exc:
_log_error(exc)
return self._stream_error({"message": _error_message(exc), "type": "server_error"})
-@@ -183,7 +184,7 @@ def make_handler(app: App):
+@@ -188,7 +189,7 @@ def make_handler(app: App):
return
except RequestError as exc:
return self._json(503 if isinstance(exc, CapacityError) else 400,
-- {"error": {"message": str(exc), "type": "invalid_request_error"}})
+- {"error": error_body(exc)})
+ {"error": error_body(exc, field)})
except Exception as exc:
_log_error(exc)
try:
-diff --git tensorfold/cuda/server.py tensorfold/cuda/server.py
-index bbcf1a1..2350990 100644
---- tensorfold/cuda/server.py
-+++ tensorfold/cuda/server.py
-@@ -11,7 +11,7 @@ from typing import Any, Callable
-
- from tensorfold.engine import grammar
- from tensorfold.server.cancellation import RequestCancelled
--from tensorfold.server.errors import RequestError
-+from tensorfold.server.errors import CONTEXT_LIMIT, RequestError, refusal
- from tensorfold.server.messages import validate_modalities
- from tensorfold.server.request_options import parse_numbers, thinking_fields
- from tensorfold.server.stopping import stop_options
-@@ -265,25 +265,28 @@ class App:
- if limit is not None and len(prepared.prompt) >= limit:
- kind = "safe cache capacity" if limit == self._engine_capacity() else "context window"
- native = f" (model window: {self.native_context_window} tokens)" if self.native_context_window else ""
-- return (f"the rendered prompt has {len(prepared.prompt)} tokens and leaves no room for a reply in "
-- f"the server's {limit}-token {kind}{native}; shorten the prompt"
-+ # v0.6.0 (68c6e35, Apache-2.0): OpenAI's wording, which clients match to compact
-+ return (f"{CONTEXT_LIMIT} {limit} tokens: the rendered prompt has {len(prepared.prompt)} tokens and leaves "
-+ f"no room for a reply in the server's {limit}-token {kind}{native}, which exceeds the context "
-+ f"window; shorten the prompt"
- f"{self._restart(len(prepared.prompt) + 1)}")
- asked = body.get("max_tokens") or body.get("max_completion_tokens")
- if limit is not None and asked and len(prepared.prompt) + prepared.max_tokens > limit:
- kind = "safe cache capacity" if limit == self._engine_capacity() else "context window"
-- return (f"the rendered prompt has {len(prepared.prompt)} tokens and requests {prepared.max_tokens} "
-- f"reply tokens, exceeding the server's {limit}-token {kind}; reduce the prompt or reply "
-- f"length{self._restart(len(prepared.prompt) + prepared.max_tokens)}")
-+ return (f"{CONTEXT_LIMIT} {limit} tokens: the rendered prompt has {len(prepared.prompt)} tokens and "
-+ f"requests {prepared.max_tokens} reply tokens, which exceeds the context window (the server's "
-+ f"{limit}-token {kind}); reduce the prompt or reply length"
-+ f"{self._restart(len(prepared.prompt) + prepared.max_tokens)}")
- return None
-
- def prepare(self, body: dict[str, Any], chat: bool) -> PreparedRequest:
- problem = self._check_fields(body)
- if problem:
-- raise RequestError(problem)
-+ raise refusal(problem)
- prepared = self._prepare(body, chat)
- problem = self.check(body, prepared=prepared)
- if problem:
-- raise RequestError(problem)
-+ raise refusal(problem)
- limit = self._context_limit()
- if limit is not None:
- prepared.max_tokens = min(prepared.max_tokens, limit - len(prepared.prompt))
diff --git tensorfold/families/glm5_next/cuda/app.py tensorfold/families/glm5_next/cuda/app.py
index c776de5..8a96996 100644
--- tensorfold/families/glm5_next/cuda/app.py
@@ -118,41 +60,25 @@ index c776de5..8a96996 100644
def run(self, body: dict[str, Any], chat: bool, emit: Callable[[dict[str, Any]], bool], *,
prepared: PreparedRequest | None = None, cancelled: Callable[[], bool] | None = None) -> dict[str, Any]:
diff --git tensorfold/server/errors.py tensorfold/server/errors.py
-index fa4863d..a4c5240 100644
+index e523c5a..b4a47dd 100644
--- tensorfold/server/errors.py
+++ tensorfold/server/errors.py
-@@ -12,3 +12,29 @@ class RoundError(RuntimeError):
- def __init__(self, error_type: str, message: str) -> None:
- super().__init__(message)
- self.error_type = error_type
-+
-+
-+# Ported from TensorFold v0.6.0 (68c6e35, Apache-2.0): context-window refusals in OpenAI's wording and code
-+class ContextLengthError(RequestError):
-+ """A prompt and its reply past the context window: OpenAI's context_length_exceeded, which clients compact on."""
-+
-+ code = "context_length_exceeded"
-+
-+
-+CONTEXT_LIMIT = "This server's maximum context length is" # OpenAI's wording, which clients match to compact
-+
-+
-+def refusal(problem: str) -> RequestError:
-+ """A refusal string as its error: a context-window one carries OpenAI's code."""
-+
-+ return (ContextLengthError if problem.startswith(CONTEXT_LIMIT) else RequestError)(problem)
-+
-+
+@@ -29,10 +29,11 @@ def refusal(problem: str) -> RequestError:
+ return (ContextLengthError if problem.startswith(CONTEXT_LIMIT) else RequestError)(problem)
+
+
+-def error_body(exc: Exception) -> dict:
+- """OpenAI's error object: the message, its type, and the code clients key on where there is one."""
+def error_body(exc: Exception, param: str | None = None) -> dict:
+ """OpenAI's error object: the message, its type, and where there is a code clients key on, the field and code."""
-+
-+ body = {"message": str(exc), "type": "invalid_request_error"}
-+ if getattr(exc, "code", None):
+
+ body = {"message": str(exc), "type": "invalid_request_error"}
+ if getattr(exc, "code", None):
+ body["param"] = param
-+ body["code"] = exc.code
-+ return body
+ body["code"] = exc.code
+ return body
diff --git tensorfold/server/prompts.py tensorfold/server/prompts.py
-index 52e8009..3b3a23b 100644
+index ee19680..2b9c05b 100644
--- tensorfold/server/prompts.py
+++ tensorfold/server/prompts.py
@@ -5,7 +5,7 @@ from dataclasses import dataclass
diff --git a/patches/0045-cuda-metrics.patch b/patches/0045-cuda-metrics.patch
new file mode 100644
index 0000000..e309c81
--- /dev/null
+++ b/patches/0045-cuda-metrics.patch
@@ -0,0 +1,165 @@
+diff --git tensorfold/server/metrics.py tensorfold/server/metrics.py
+index 4dda35a..c210a65 100644
+--- tensorfold/server/metrics.py
++++ tensorfold/server/metrics.py
+@@ -7,10 +7,12 @@ import time
+ from typing import Any
+
+ PREFIX = "tensorfold:"
++HEALTH = "tensorfold_health:" # the CUDA server's /health fields, named as /health names them
+ # Request and time-to-first-token histograms share these upper edges. +Inf is added when rendered.
+ BUCKETS = (0.01, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0, 60.0, 120.0, 300.0)
+ _MADE = threading.Lock()
+ _local = threading.local()
++_TRIES = 3 # a decoder's tables read while its thread changes them: read again
+
+
+ class Histogram:
+@@ -135,7 +137,7 @@ def render(app: Any) -> str:
+ prompt, generation = metrics.prompt, metrics.generation
+ drafted, accepted = metrics.drafted, metrics.accepted
+ latency, ttft = metrics.latency.copy(), metrics.ttft.copy()
+- running, waiting = _requests(app)
++ running, waiting = _read(lambda: _requests(app), (0, 0))
+ lines: list[str] = []
+ _family(lines, "requests_running", "gauge", "Requests in prefill or decode.",
+ [f"{PREFIX}requests_running {running}"])
+@@ -147,13 +149,15 @@ def render(app: Any) -> str:
+ [f"{PREFIX}generation_tokens_total {generation}"])
+ _family(lines, "kv_cache_usage_ratio", "gauge",
+ "Tokens in a stream cache divided by that stream's context window.",
+- [f'{PREFIX}kv_cache_usage_ratio{{pool="{pool}"}} {_num(ratio)}' for pool, ratio in _pools(app)])
++ [f'{PREFIX}kv_cache_usage_ratio{{pool="{pool}"}} {_num(ratio)}'
++ for pool, ratio in _read(lambda: _pools(app), [("0", 0.0)])])
+ _family(lines, "mtp_drafted_total", "counter", "Draft tokens verified on finished requests.",
+ [f"{PREFIX}mtp_drafted_total {drafted}"])
+ _family(lines, "mtp_accepted_total", "counter", "Draft tokens kept on finished requests.",
+ [f"{PREFIX}mtp_accepted_total {accepted}"])
+ _histogram(lines, "request_latency_seconds", "Seconds from arrival to the reply leaving.", latency)
+ _histogram(lines, "time_to_first_token_seconds", "Seconds from arrival to the first generated token.", ttft)
++ _health(lines, app)
+ return "\n".join(lines) + "\n"
+
+
+@@ -161,18 +165,75 @@ def send(handler: Any, app: Any) -> None:
+ """Write ``render`` as Prometheus text, version 0.0.4."""
+
+ body = render(app).encode()
+- handler.send_response(200)
+- handler.send_header("Content-Type", "text/plain; version=0.0.4; charset=utf-8")
+- handler.send_header("Content-Length", str(len(body)))
+- handler.end_headers()
+ try:
++ handler.send_response(200)
++ handler.send_header("Content-Type", "text/plain; version=0.0.4; charset=utf-8")
++ handler.send_header("Content-Length", str(len(body)))
++ handler.end_headers()
+ handler.wfile.write(body)
+ except (BrokenPipeError, ConnectionResetError):
+ handler.close_connection = True
+
+
+-def _family(lines: list[str], name: str, kind: str, help_text: str, samples: list[str]) -> None:
+- full = PREFIX + name
++# /health's fields under HEALTH: (field, type, help); the totals are the finished requests' engine stats
++_HEALTH_TOTALS = (
++ ("requests_total", "counter", "Finished requests (as /health's requests_total)."),
++ ("completion_tokens_total", "counter", "Reply tokens, the running replies' tokens so far included."),
++ ("cached_tokens_total", "counter", "Prompt tokens found cached, finished requests."),
++ ("rounds_total", "counter", "Decode rounds of finished requests."),
++ ("prefill_seconds_total", "counter", "Engine prefill seconds of finished requests."),
++ ("decode_seconds_total", "counter", "Engine decode seconds of finished requests."),
++)
++_HEALTH_GAUGES = (
++ ("context_length", "Tokens a request's prompt and reply may hold (the server's effective window)."),
++ ("streams_max", "Streams the concurrent engine decodes at most (--parallel)."),
++ ("pool_tokens", "Token rows in the concurrent engine's shared cache pool."),
++ ("pool_free_tokens", "Pool rows no stream or kept prompt holds."),
++ ("kept_prompts", "Prompt states kept in the pool for reuse."),
++)
++
++
++def _health(lines: list[str], app: Any) -> None:
++ """The CUDA server's /health totals and the concurrent engine's streams and pool (the reads /health makes)."""
++
++ from tensorfold.cuda import health
++
++ snapshot = getattr(health.of(app), "snapshot", None) # an app without the CUDA server's /health has none
++ body = _read(lambda: snapshot(app), None) if callable(snapshot) else None
++ if not isinstance(body, dict):
++ return
++ for name, kind, help_text in _HEALTH_TOTALS:
++ if isinstance(body.get(name), (int, float)):
++ _family(lines, name, kind, help_text, [f"{HEALTH}{name} {_num(body[name])}"], HEALTH)
++ streams = dict(body.get("streams") or {})
++ if "max" in streams:
++ body["streams_max"] = streams.pop("max")
++ prefilling = streams.pop("prefilling", None) # GLM's decoder counts the same streams as "filling"
++ if prefilling is not None:
++ streams.setdefault("filling", prefilling)
++ if streams:
++ _family(lines, "streams", "gauge", "The concurrent engine's streams by state.",
++ [f'{HEALTH}streams{{state="{state}"}} {_num(n)}' for state, n in sorted(streams.items())
++ if isinstance(n, (int, float))], HEALTH)
++ for name, help_text in _HEALTH_GAUGES:
++ if isinstance(body.get(name), (int, float)):
++ _family(lines, name, "gauge", help_text, [f"{HEALTH}{name} {_num(body[name])}"], HEALTH)
++
++
++def _read(read, default):
++ """``read()``, again if a table changed size under it; ``default`` if it keeps failing."""
++
++ for _ in range(_TRIES):
++ try:
++ return read()
++ except RuntimeError: # "dictionary changed size during iteration" and the like
++ continue
++ return default
++
++
++def _family(lines: list[str], name: str, kind: str, help_text: str, samples: list[str],
++ prefix: str = PREFIX) -> None:
++ full = prefix + name
+ lines.append(f"# HELP {full} {help_text}")
+ lines.append(f"# TYPE {full} {kind}")
+ lines.extend(samples)
+@@ -235,7 +296,9 @@ def _pools(app: Any) -> list[tuple[str, float]]:
+ def _window(app: Any) -> int:
+ engine = getattr(app, "engine", None)
+ decoder = getattr(getattr(engine, "scheduler", None), "decoder", None) if engine is not None else None
+- for owner, name in ((engine, "context_window"), (app, "context_window"), (decoder, "context")):
++ # the effective window first: GLM's engine keeps its own as ``limit``, below the checkpoint's native window
++ for owner, name in ((app, "effective_context_window"), (engine, "context_window"), (app, "context_window"),
++ (decoder, "context")):
+ n = _positive(getattr(owner, name, None) if owner is not None else None)
+ if n:
+ return n
+@@ -256,16 +319,14 @@ def _lengths(app: Any) -> list[int]:
+
+
+ def _occupied(stream: Any) -> int:
+- """Mac streams publish ``cache_len``. A CUDA stream's ``context`` gains the prompt when decode starts."""
++ """Mac streams publish ``cache_len``; a CUDA stream holds its prompt and reply so far (a ``Stream``'s ``context``
++ holds its reply, or its prompt and reply)."""
+
+ cache = getattr(stream, "cache_len", None)
+ if isinstance(cache, int):
+ return cache
+- context = getattr(stream, "context", None) or ()
+- if len(context):
+- return len(context)
+- prompt = getattr(stream, "prompt", None) or ()
+- return len(prompt)
++ context = len(getattr(stream, "context", None) or ())
++ return max(context, len(getattr(stream, "prompt", None) or ()) + len(getattr(stream, "out", None) or ()))
+
+
+ def _positive(value: Any) -> int:
+@@ -286,5 +347,5 @@ def _edge(value: float) -> str:
+ return f"{value:.4f}".rstrip("0").rstrip(".")
+
+
+-__all__ = ["BUCKETS", "PREFIX", "Histogram", "Metrics", "begin", "bind", "finish_request", "note", "of", "render",
+- "send", "tokens"]
++__all__ = ["BUCKETS", "HEALTH", "PREFIX", "Histogram", "Metrics", "begin", "bind", "finish_request", "note", "of",
++ "render", "send", "tokens"]
diff --git a/patches/0049-glm-l2-prefetch.patch b/patches/0046-glm-l2-prefetch.patch
similarity index 96%
rename from patches/0049-glm-l2-prefetch.patch
rename to patches/0046-glm-l2-prefetch.patch
index 2012eac..c8a2235 100644
--- a/patches/0049-glm-l2-prefetch.patch
+++ b/patches/0046-glm-l2-prefetch.patch
@@ -1,5 +1,5 @@
diff --git tensorfold/families/glm5_next/cuda/decode.py tensorfold/families/glm5_next/cuda/decode.py
-index 524eda3..4c85db5 100644
+index a117edc..9b80e31 100644
--- tensorfold/families/glm5_next/cuda/decode.py
+++ tensorfold/families/glm5_next/cuda/decode.py
@@ -100,6 +100,13 @@ class Engine:
@@ -17,11 +17,11 @@ index 524eda3..4c85db5 100644
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
diff --git tensorfold/families/glm5_next/cuda/forward.py tensorfold/families/glm5_next/cuda/forward.py
-index c6967f8..50cd873 100644
+index 1aab97c..60250c3 100644
--- tensorfold/families/glm5_next/cuda/forward.py
+++ tensorfold/families/glm5_next/cuda/forward.py
-@@ -11,7 +11,7 @@ import triton.language as tl
- from tensorfold.cuda import experts as grouped
+@@ -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, latent, prof, qmm, sparse
@@ -29,7 +29,7 @@ index c6967f8..50cd873 100644
from .attention import AttnScratch, attention, kv_write
from .weights import LayerW, Weights
-@@ -414,7 +414,8 @@ def mm(b: Buffers, x: torch.Tensor, q, xs: torch.Tensor | None, out: torch.Tenso
+@@ -415,7 +415,8 @@ def mm(b: Buffers, x: torch.Tensor, q, xs: torch.Tensor | None, out: torch.Tenso
return qmm.matmul(x, q, xs, out=out, f32=f32, part=b.sk)
@@ -39,7 +39,7 @@ index c6967f8..50cd873 100644
"""``fill(lo, hi)`` writes rows lo .. hi of this rank's fp32 partial b.part; returns every rank's partials
[world, R, D] (``gather``), or None while a prompt chunk runs row-split (TF_GLM_HC_SPLIT), which exchanges them
and runs hc_post itself (``hcsplit.HcSplit``)."""
-@@ -424,17 +425,20 @@ def partials(w: Weights, b: Buffers, R: int, fill, label: str | None = None) ->
+@@ -425,17 +426,20 @@ def partials(w: Weights, b: Buffers, R: int, fill, label: str | None = None) ->
sp.partial(fill)
return None
fill(0, R)
@@ -62,7 +62,7 @@ index c6967f8..50cd873 100644
def undone(R: int, done: tuple[int, int] | None) -> list[tuple[int, int]]:
-@@ -477,6 +481,7 @@ def kda_block(layer: LayerW, w: Weights, st: State, b: Buffers, R: int, done: tu
+@@ -478,6 +482,7 @@ def kda_block(layer: LayerW, w: Weights, st: State, b: Buffers, R: int, done: tu
ga = p[:, k.ga_off:k.ga_off + 128]
mm(b, fa, k.fb, qmm.group_sums(fa, b.xs_fa[:R]), b.ka[:R])
mm(b, ga, k.gb, qmm.group_sums(ga, b.xs_ga[:R]), b.kg[:R])
@@ -70,7 +70,7 @@ index c6967f8..50cd873 100644
cur = st.cur[li]
with prof.timed("kda: recurrence"):
out = kda_mod.chain(p, k.b_off, b.ka[:R], b.kg[:R], st.conv[li], k.conv, st.rec[cur, li], k.a_log,
-@@ -486,7 +491,7 @@ def kda_block(layer: LayerW, w: Weights, st: State, b: Buffers, R: int, done: tu
+@@ -487,7 +492,7 @@ def kda_block(layer: LayerW, w: Weights, st: State, b: Buffers, R: int, done: tu
st.cur[li] = 1 - cur
_shift_conv(st.conv[li:li + 1], b.kproj[:, :R], R)
with prof.timed("kda: out + all-gather"):
@@ -79,7 +79,7 @@ index c6967f8..50cd873 100644
def kda_segments(layer: LayerW, w: Weights, b: Buffers, R: int, seg: torch.Tensor, slots: "Slots",
-@@ -505,12 +510,13 @@ def kda_segments(layer: LayerW, w: Weights, b: Buffers, R: int, seg: torch.Tenso
+@@ -506,12 +511,13 @@ def kda_segments(layer: LayerW, w: Weights, b: Buffers, R: int, seg: torch.Tenso
ga = p[:, k.ga_off:k.ga_off + 128]
mm(b, fa, k.fb, qmm.group_sums(fa, b.xs_fa[:R]), b.ka[:R])
mm(b, ga, k.gb, qmm.group_sums(ga, b.xs_ga[:R]), b.kg[:R])
@@ -94,7 +94,7 @@ index c6967f8..50cd873 100644
def dsa_front(layer: LayerW, w: Weights, b: Buffers, lo: int, hi: int) -> None:
-@@ -535,7 +541,7 @@ def dsa_block(layer: LayerW, w: Weights, kc: torch.Tensor, vc: torch.Tensor, pos
+@@ -536,7 +542,7 @@ def dsa_block(layer: LayerW, w: Weights, kc: torch.Tensor, vc: torch.Tensor, pos
dsa_front(layer, w, b, lo, hi)
HL = a.heads
if a.absorb is not None:
@@ -103,7 +103,7 @@ index c6967f8..50cd873 100644
if sparse_np is not None:
raise ValueError("sparse CUDA graphs need the latent cache (TF_GLM_LATENT=1)")
mm(b, b.lat[:R], a.kv_k, b.xs_lat[:R], b.kn[:R].view(R, HL * c.qk_dim))
-@@ -593,7 +599,7 @@ def dense_attention(qa: torch.Tensor, lc: torch.Tensor, pos_dev: torch.Tensor, s
+@@ -594,7 +600,7 @@ def dense_attention(qa: torch.Tensor, lc: torch.Tensor, pos_dev: torch.Tensor, s
def _dsa_latent(a, w: Weights, lc: torch.Tensor, pos_dev: torch.Tensor, b: Buffers, R: int, nch: int | None,
@@ -112,7 +112,7 @@ index c6967f8..50cd873 100644
"""DSA on the latent cache: the same indexer and selection, attention over latents with kv_b's key blocks absorbed into the query."""
c = w.cfg
-@@ -613,6 +619,7 @@ def _dsa_latent(a, w: Weights, lc: torch.Tensor, pos_dev: torch.Tensor, b: Buffe
+@@ -614,6 +620,7 @@ def _dsa_latent(a, w: Weights, lc: torch.Tensor, pos_dev: torch.Tensor, b: Buffe
sparse.index_update(b.ikr[:R, :c.index_dim], b.igr[:R], ix.ln_w, ix.ln_b, ix.ape, ik, ig, pk, pos_dev)
with prof.timed("dsa: absorb"):
qa = latent.absorb_q(b.q[:R], a.absorb, s.qa[:R], prompt=b.prefill and latent.PROMPT_MMA)
@@ -120,7 +120,7 @@ index c6967f8..50cd873 100644
ol = s.ol[:R]
scale = c.qk_dim ** -0.5
if not all_sparse:
-@@ -634,7 +641,7 @@ def _dsa_latent(a, w: Weights, lc: torch.Tensor, pos_dev: torch.Tensor, b: Buffe
+@@ -635,7 +642,7 @@ def _dsa_latent(a, w: Weights, lc: torch.Tensor, pos_dev: torch.Tensor, b: Buffe
latent.sparse_attention(qa, lc, tokens, counts, ol, scale)
with prof.timed("dsa: expand"):
o = latent.expand_v(ol, a.absorb, b.vn[:R], prompt=b.prefill and latent.PROMPT_MMA).view(R, HL * c.v_dim)
@@ -129,7 +129,7 @@ index c6967f8..50cd873 100644
def dsa_segments(layer: LayerW, w: Weights, lc: torch.Tensor, b: Buffers, R: int, rows, sel=None, index=None, *,
-@@ -672,11 +679,12 @@ def dsa_segments(layer: LayerW, w: Weights, lc: torch.Tensor, b: Buffers, R: int
+@@ -673,11 +680,12 @@ def dsa_segments(layer: LayerW, w: Weights, lc: torch.Tensor, b: Buffers, R: int
tokens, counts = sparse.seg_select_tokens(b.qi[:R], b.ikr[:R, c.index_dim:], pk, rows, sel)
with prof.timed("dsa: absorb"):
qa = latent.absorb_q(b.q[:R], a.absorb, s.qa[:R])
@@ -143,7 +143,7 @@ index c6967f8..50cd873 100644
def mlp_front(layer: LayerW, w: Weights, b: Buffers, lo: int, hi: int) -> None:
-@@ -689,7 +697,7 @@ def mlp_block(layer: LayerW, w: Weights, b: Buffers, R: int, done: tuple[int, in
+@@ -690,7 +698,7 @@ def mlp_block(layer: LayerW, w: Weights, b: Buffers, R: int, done: tuple[int, in
m = layer.mlp
for lo, hi in undone(R, done):
mlp_front(layer, w, b, lo, hi)
@@ -152,7 +152,7 @@ index c6967f8..50cd873 100644
def shared_front(layer: LayerW, w: Weights, b: Buffers, lo: int, hi: int) -> None:
-@@ -715,6 +723,11 @@ def moe_block(layer: LayerW, w: Weights, b: Buffers, R: int, done: tuple[int, in
+@@ -716,6 +724,11 @@ def moe_block(layer: LayerW, w: Weights, b: Buffers, R: int, done: tuple[int, in
# EXL3: the routed slots through the trellis kernels, the shared expert (last slot) through BF16 matmuls
from . import exl3_mm
@@ -164,7 +164,7 @@ index c6967f8..50cd873 100644
with prof.timed("moe: routed (exl3)"):
exl3_mm.routed(b.normed[:R], b.pick, b.plan, m.experts, b.exl3, b.ey.view(-1, c.hidden), R, c.limit)
-@@ -731,7 +744,7 @@ def moe_block(layer: LayerW, w: Weights, b: Buffers, R: int, done: tuple[int, in
+@@ -732,7 +745,7 @@ def moe_block(layer: LayerW, w: Weights, b: Buffers, R: int, done: tuple[int, in
b.ey[lo:hi, c.top_k].copy_(b.sy[lo:hi])
glue.combine(b.ey[lo:hi], b.wts[lo:hi], b.part[lo:hi])
@@ -173,7 +173,7 @@ index c6967f8..50cd873 100644
with prof.timed("moe: gate/up"):
grouped.gate_up(b.normed[:R], m.experts, b.plan, b.eact, R)
with prof.timed("moe: down"):
-@@ -741,7 +754,7 @@ def moe_block(layer: LayerW, w: Weights, b: Buffers, R: int, done: tuple[int, in
+@@ -742,7 +755,7 @@ def moe_block(layer: LayerW, w: Weights, b: Buffers, R: int, done: tuple[int, in
with prof.timed("moe: combine"):
glue.combine(b.ey[lo:hi], b.wts[lo:hi], b.part[lo:hi])
@@ -182,7 +182,7 @@ index c6967f8..50cd873 100644
def _mixer(layer: LayerW, w: Weights, st: State, b: Buffers, R: int, nch: int | None, host_pos: int | None,
-@@ -860,6 +873,22 @@ def compute(w: Weights, st: State, b: Buffers, R: int, *, logits: bool = True, n
+@@ -861,6 +874,22 @@ def compute(w: Weights, st: State, b: Buffers, R: int, *, logits: bool = True, n
host_pos: int | None = None, sparse_np: int | None = None, inject=None, head: bool = True, mixer=None):
"""Run capturable GPU work on static buffers and device positions; eager long contexts use host_pos (graphs sparse_np) to select sparse attention; ``inject``: (rows, features) replacing those rows' embeddings (an image prompt's tower output, on every hyper-connection stream)."""
diff --git a/patches/0050-glm-exl3-decode-loads.patch b/patches/0047-glm-exl3-decode-loads.patch
similarity index 100%
rename from patches/0050-glm-exl3-decode-loads.patch
rename to patches/0047-glm-exl3-decode-loads.patch
diff --git a/patches/0048-cuda-metrics.patch b/patches/0048-cuda-metrics.patch
deleted file mode 100644
index a93ca55..0000000
--- a/patches/0048-cuda-metrics.patch
+++ /dev/null
@@ -1,487 +0,0 @@
-diff --git tensorfold/cuda/health.py tensorfold/cuda/health.py
-index 5902ad3..cb27278 100644
---- tensorfold/cuda/health.py
-+++ tensorfold/cuda/health.py
-@@ -3,9 +3,12 @@
- from __future__ import annotations
-
- import threading
-+import time
- from contextlib import contextmanager
- from typing import Any
-
-+from tensorfold.server import metrics
-+
- STATS = {"prefill_s": "prefill_seconds_total", "decode_s": "decode_seconds_total", "cached": "cached_tokens_total",
- "rounds": "rounds_total", "drafted": "drafted_total", "accepted": "accepted_total"}
- _MADE = threading.Lock()
-@@ -14,8 +17,17 @@ _MADE = threading.Lock()
- class Request:
- """One running request: its prompt length and the server's own list of its reply tokens (only ever read here)."""
-
-- def __init__(self, prompt: int, out: list[int]) -> None:
-+ def __init__(self, prompt: int, out: list[int], arrived: float | None = None) -> None:
- self.prompt, self.out, self.stats = prompt, out, None
-+ # v0.6.0 (4447ac3, Apache-2.0): arrival and first-token clocks for /metrics' latency and TTFT histograms
-+ self.started = time.perf_counter() if arrived is None else float(arrived)
-+ self.first: float | None = None
-+
-+ def saw(self) -> None:
-+ """The first generated token has landed in ``out``."""
-+
-+ if self.first is None and self.out:
-+ self.first = time.perf_counter()
-
-
- class Health:
-@@ -28,10 +40,10 @@ class Health:
- "completion_tokens_total", *STATS.values()), 0)
-
- @contextmanager
-- def running(self, prompt: int, out: list[int]):
-+ def running(self, prompt: int, out: list[int], arrived: float | None = None):
- """Count a request as running while its ``generate`` runs, then fold its reply and ``stats`` into the totals."""
-
-- request = Request(prompt, out)
-+ request = Request(prompt, out, arrived)
- with self.lock:
- self.live.add(request)
- try:
-@@ -40,6 +52,7 @@ class Health:
- with self.lock:
- self.live.discard(request)
- self._fold(request)
-+ self._metrics(request)
-
- def _fold(self, request: Request) -> None:
- t = self.totals
-@@ -51,6 +64,13 @@ class Health:
- if isinstance(value, (int, float)) and not isinstance(value, bool):
- t[name] += value
-
-+ def _metrics(self, request: Request) -> None:
-+ stats = request.stats or {}
-+ metrics.note(getattr(self, "app", None), prompt=request.prompt, generation=len(request.out),
-+ drafted=_stat(stats, "drafted"), accepted=_stat(stats, "accepted"),
-+ latency=max(0.0, time.perf_counter() - request.started),
-+ ttft=(request.first - request.started) if request.first is not None else None)
-+
- def snapshot(self, app) -> dict[str, Any]:
- """The counters now: finished totals, live replies' tokens so far, and a concurrent engine's streams."""
-
-@@ -85,7 +105,13 @@ def of(app) -> Health:
- found = app.__dict__.get("health")
- if found is None:
- found = app.__dict__["health"] = Health()
-+ found.app = app
- return found
-
-
-+def _stat(stats: dict[str, Any], key: str) -> int:
-+ value = stats.get(key)
-+ return int(value) if isinstance(value, (int, float)) and not isinstance(value, bool) else 0
-+
-+
- __all__ = ["Health", "Request", "of"]
-diff --git tensorfold/cuda/http.py tensorfold/cuda/http.py
-index 9bf5ddd..589b56b 100644
---- tensorfold/cuda/http.py
-+++ tensorfold/cuda/http.py
-@@ -8,7 +8,7 @@ import uuid
- from typing import TYPE_CHECKING, Any
-
- from tensorfold.cuda import health
--from tensorfold.server import responses
-+from tensorfold.server import metrics, responses
- from tensorfold.server.cancellation import RequestCancelled, socket_cancellation
- from tensorfold.server.errors import CapacityError, RequestError, error_body
- from tensorfold.server.http import Server
-@@ -68,6 +68,8 @@ def make_handler(app: App):
- self.close_connection = True
-
- def do_GET(self):
-+ if self.path.split("?", 1)[0].rstrip("/") in ("/metrics", "/v1/metrics"): # v0.6.0 (4447ac3, Apache-2.0)
-+ return metrics.send(self, app)
- if self.path.rstrip("/") in ("/v1/models", "/models"):
- self._json(200, {"object": "list", "data": [{"id": app.served, "object": "model", "owned_by": "tensorfold"}]})
- elif self.path.rstrip("/") in ("/health", "/v1/health"):
-diff --git tensorfold/cuda/server.py tensorfold/cuda/server.py
-index 2350990..8598a23 100644
---- tensorfold/cuda/server.py
-+++ tensorfold/cuda/server.py
-@@ -5,6 +5,7 @@ import hashlib
- import inspect
- import json
- import threading
-+import time
- from dataclasses import dataclass
- from pathlib import Path
- from typing import Any, Callable
-@@ -312,6 +313,7 @@ class App:
- prepared: PreparedRequest | None = None, cancelled: Callable[[], bool] | None = None) -> dict[str, Any]:
- """One reply; once ``cancelled()`` holds, a waiting request raises ``RequestCancelled`` unstarted, a running one stops at its next round and raises it after ``generate``."""
-
-+ arrived = time.perf_counter() # v0.6.0 (4447ac3, Apache-2.0): /metrics' latency and TTFT clock
- prepared = prepared if prepared is not None else self.prepare(body, chat)
- prompt, max_tokens = prepared.prompt, prepared.max_tokens
- tools, thinking = prepared.tools, prepared.thinking
-@@ -356,6 +358,8 @@ class App:
- else hide_tool_calls(answer, finished=finished))
- return reasoning, answer, raw
-
-+ serving: list[Any] = [None] # the running request, whose first token /metrics times
-+
- 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 stopped["client"] or stopped["stop"] or failed:
-@@ -388,6 +392,8 @@ class App:
- stopped["client"] = True
- elif cancelled is not None and cancelled(): # every round, with or without new text
- stopped["client"] = True
-+ if serving[0] is not None:
-+ serving[0].saw()
- except Exception as exc: # noqa: BLE001 raised after generate returns, never into the engine
- failed.append(exc)
- return True
-@@ -445,8 +451,12 @@ class App:
- try:
- if cancelled is not None and cancelled(): # the client left while this request waited
- raise RequestCancelled("the client left before the request started")
-- with health.of(self).running(len(prompt), out) as request: # /health reads ``out``; rounds never call in
-- stats = request.stats = generate_gated(generate, prompt, max_tokens, gates, on_tokens)
-+ with health.of(self).running(len(prompt), out, arrived) as request: # /health reads ``out``; rounds never call in
-+ serving[0] = request
-+ try:
-+ stats = request.stats = generate_gated(generate, prompt, max_tokens, gates, on_tokens)
-+ finally:
-+ serving[0] = None
- finally:
- if turns is not None:
- turns.give()
-diff --git tensorfold/cuda/turns.py tensorfold/cuda/turns.py
-index b29e0dc..d85885e 100644
---- tensorfold/cuda/turns.py
-+++ tensorfold/cuda/turns.py
-@@ -14,11 +14,13 @@ class Turns:
- self.cv = threading.Condition()
- self.busy = False
- self.waiting = 0 # foreground requests waiting for the engine
-+ self.parked = 0 # every request in take(), background included (v0.6.0 /metrics)
-
- def take(self, background: bool, cancelled: Callable[[], bool] | None = None) -> None:
- """Wait for the engine (a background request also for no waiting foreground one); RequestCancelled if gone."""
-
- with self.cv:
-+ self.parked += 1
- self.waiting += not background
- try:
- while self.busy or (background and self.waiting):
-@@ -26,6 +28,7 @@ class Turns:
- if cancelled is not None and cancelled():
- raise RequestCancelled("the client left before the request started")
- finally:
-+ self.parked -= 1
- self.waiting -= not background
- self.busy = True
-
-diff --git tensorfold/server/metrics.py tensorfold/server/metrics.py
-new file mode 100644
-index 0000000..b223098
---- /dev/null
-+++ tensorfold/server/metrics.py
-@@ -0,0 +1,295 @@
-+"""Prometheus text for the CUDA server's GET /metrics: counters of finished requests, gauges read at scrape time."""
-+# Ported from TensorFold v0.6.0, commit 4447ac3 "Prometheus /metrics on both servers (#110)" (Apache-2.0): its CUDA part.
-+
-+from __future__ import annotations
-+
-+import threading
-+from typing import Any
-+
-+PREFIX = "tensorfold:" # upstream's names
-+HEALTH = "tensorfold_health:" # this server's /health fields, named as /health names them
-+# Request and time-to-first-token histograms share these upper edges. +Inf is added when rendered.
-+BUCKETS = (0.01, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0, 60.0, 120.0, 300.0)
-+_MADE = threading.Lock()
-+_TRIES = 3 # a decoder's tables read while its thread changes them: read again
-+
-+
-+class Histogram:
-+ """Counts in one bucket each. Render adds them up into Prometheus's cumulative buckets."""
-+
-+ def __init__(self) -> None:
-+ self.counts = [0] * (len(BUCKETS) + 1)
-+ self.total = 0.0
-+ self.n = 0
-+
-+ def observe(self, value: float) -> None:
-+ value = max(0.0, float(value))
-+ self.n += 1
-+ self.total += value
-+ for i, edge in enumerate(BUCKETS):
-+ if value <= edge:
-+ self.counts[i] += 1
-+ return
-+ self.counts[-1] += 1
-+
-+ def copy(self) -> "Histogram":
-+ other = Histogram()
-+ other.counts = list(self.counts)
-+ other.total, other.n = self.total, self.n
-+ return other
-+
-+
-+class Metrics:
-+ """Counters and histograms of finished requests. Gauges are not stored here."""
-+
-+ def __init__(self) -> None:
-+ self.lock = threading.Lock()
-+ self.prompt = 0
-+ self.generation = 0
-+ self.drafted = 0
-+ self.accepted = 0
-+ self.latency = Histogram()
-+ self.ttft = Histogram()
-+
-+ def add(self, *, prompt: int, generation: int, drafted: int, accepted: int,
-+ latency: float | None, ttft: float | None) -> None:
-+ with self.lock:
-+ self.prompt += int(prompt)
-+ self.generation += int(generation)
-+ self.drafted += int(drafted)
-+ self.accepted += int(accepted)
-+ if latency is not None:
-+ self.latency.observe(latency)
-+ if ttft is not None:
-+ self.ttft.observe(ttft)
-+
-+
-+def of(app: Any) -> Metrics:
-+ """The app's counters, made on first use."""
-+
-+ with _MADE:
-+ found = app.__dict__.get("metrics")
-+ if found is None:
-+ found = app.__dict__["metrics"] = Metrics()
-+ return found
-+
-+
-+def note(app: Any, *, prompt: int = 0, generation: int = 0, drafted: int = 0, accepted: int = 0,
-+ latency: float | None = None, ttft: float | None = None) -> None:
-+ """Fold one finished request. A missing app is a no-op."""
-+
-+ if app is None:
-+ return
-+ of(app).add(prompt=prompt, generation=generation, drafted=drafted, accepted=accepted,
-+ latency=latency, ttft=ttft)
-+
-+
-+def render(app: Any) -> str:
-+ """The scrape body, ending in a newline: host-side reads only, no lock the engine's rounds take."""
-+
-+ metrics = of(app)
-+ with metrics.lock:
-+ prompt, generation = metrics.prompt, metrics.generation
-+ drafted, accepted = metrics.drafted, metrics.accepted
-+ latency, ttft = metrics.latency.copy(), metrics.ttft.copy()
-+ running, waiting = _read(lambda: _requests(app), (0, 0))
-+ lines: list[str] = []
-+ _family(lines, "requests_running", "gauge", "Requests in prefill or decode.",
-+ [f"{PREFIX}requests_running {running}"])
-+ _family(lines, "requests_waiting", "gauge", "Requests queued or held until a lane is free.",
-+ [f"{PREFIX}requests_waiting {waiting}"])
-+ _family(lines, "prompt_tokens_total", "counter", "Prompt tokens of finished requests.",
-+ [f"{PREFIX}prompt_tokens_total {prompt}"])
-+ _family(lines, "generation_tokens_total", "counter", "Generated tokens of finished requests.",
-+ [f"{PREFIX}generation_tokens_total {generation}"])
-+ _family(lines, "kv_cache_usage_ratio", "gauge",
-+ "Tokens in a stream cache divided by that stream's context window.",
-+ [f'{PREFIX}kv_cache_usage_ratio{{pool="{pool}"}} {_num(ratio)}'
-+ for pool, ratio in _read(lambda: _pools(app), [("0", 0.0)])])
-+ _family(lines, "mtp_drafted_total", "counter", "Draft tokens verified on finished requests.",
-+ [f"{PREFIX}mtp_drafted_total {drafted}"])
-+ _family(lines, "mtp_accepted_total", "counter", "Draft tokens kept on finished requests.",
-+ [f"{PREFIX}mtp_accepted_total {accepted}"])
-+ _histogram(lines, "request_latency_seconds", "Seconds from arrival to the reply leaving.", latency)
-+ _histogram(lines, "time_to_first_token_seconds", "Seconds from arrival to the first generated token.", ttft)
-+ _health(lines, app)
-+ return "\n".join(lines) + "\n"
-+
-+
-+def send(handler: Any, app: Any) -> None:
-+ """Write ``render`` as Prometheus text, version 0.0.4."""
-+
-+ body = render(app).encode()
-+ try:
-+ handler.send_response(200)
-+ handler.send_header("Content-Type", "text/plain; version=0.0.4; charset=utf-8")
-+ handler.send_header("Content-Length", str(len(body)))
-+ handler.end_headers()
-+ handler.wfile.write(body)
-+ except (BrokenPipeError, ConnectionResetError):
-+ handler.close_connection = True
-+
-+
-+# /health's fields under HEALTH: (field, type, help); the totals are the finished requests' engine stats
-+_HEALTH_TOTALS = (
-+ ("requests_total", "counter", "Finished requests (as /health's requests_total)."),
-+ ("completion_tokens_total", "counter", "Reply tokens, the running replies' tokens so far included."),
-+ ("cached_tokens_total", "counter", "Prompt tokens found cached, finished requests."),
-+ ("rounds_total", "counter", "Decode rounds of finished requests."),
-+ ("prefill_seconds_total", "counter", "Engine prefill seconds of finished requests."),
-+ ("decode_seconds_total", "counter", "Engine decode seconds of finished requests."),
-+)
-+_HEALTH_GAUGES = (
-+ ("context_length", "Tokens a request's prompt and reply may hold (the server's effective window)."),
-+ ("streams_max", "Streams the concurrent engine decodes at most (--parallel)."),
-+ ("pool_tokens", "Token rows in the concurrent engine's shared cache pool."),
-+ ("pool_free_tokens", "Pool rows no stream or kept prompt holds."),
-+ ("kept_prompts", "Prompt states kept in the pool for reuse."),
-+)
-+
-+
-+def _health(lines: list[str], app: Any) -> None:
-+ """/health's totals and the concurrent engine's streams and pool (the same reads /health makes)."""
-+
-+ from tensorfold.cuda import health
-+
-+ body = _read(lambda: health.of(app).snapshot(app), None)
-+ if body is None:
-+ return
-+ for name, kind, help_text in _HEALTH_TOTALS:
-+ if isinstance(body.get(name), (int, float)):
-+ _family(lines, name, kind, help_text, [f"{HEALTH}{name} {_num(body[name])}"], HEALTH)
-+ streams = dict(body.get("streams") or {})
-+ if "max" in streams:
-+ body["streams_max"] = streams.pop("max")
-+ prefilling = streams.pop("prefilling", None) # GLM's decoder counts the same streams as "filling"
-+ if prefilling is not None:
-+ streams.setdefault("filling", prefilling)
-+ if streams:
-+ _family(lines, "streams", "gauge", "The concurrent engine's streams by state.",
-+ [f'{HEALTH}streams{{state="{state}"}} {_num(n)}' for state, n in sorted(streams.items())
-+ if isinstance(n, (int, float))], HEALTH)
-+ for name, help_text in _HEALTH_GAUGES:
-+ if isinstance(body.get(name), (int, float)):
-+ _family(lines, name, "gauge", help_text, [f"{HEALTH}{name} {_num(body[name])}"], HEALTH)
-+
-+
-+def _read(read, default):
-+ """``read()``, again if a table changed size under it; ``default`` if it keeps failing."""
-+
-+ for _ in range(_TRIES):
-+ try:
-+ return read()
-+ except RuntimeError: # "dictionary changed size during iteration" and the like
-+ continue
-+ return default
-+
-+
-+def _family(lines: list[str], name: str, kind: str, help_text: str, samples: list[str],
-+ prefix: str = PREFIX) -> None:
-+ full = prefix + name
-+ lines.append(f"# HELP {full} {help_text}")
-+ lines.append(f"# TYPE {full} {kind}")
-+ lines.extend(samples)
-+
-+
-+def _histogram(lines: list[str], name: str, help_text: str, hist: Histogram) -> None:
-+ full = PREFIX + name
-+ lines.append(f"# HELP {full} {help_text}")
-+ lines.append(f"# TYPE {full} histogram")
-+ cumulative = 0
-+ for edge, count in zip(BUCKETS, hist.counts):
-+ cumulative += count
-+ lines.append(f'{full}_bucket{{le="{_edge(edge)}"}} {cumulative}')
-+ lines.append(f'{full}_bucket{{le="+Inf"}} {cumulative + hist.counts[-1]}')
-+ lines.append(f"{full}_sum {_num(hist.total)}")
-+ lines.append(f"{full}_count {hist.n}")
-+
-+
-+def _decoder(app: Any) -> tuple[Any, Any]:
-+ sched = getattr(getattr(app, "engine", None), "scheduler", None)
-+ return sched, getattr(sched, "decoder", None)
-+
-+
-+def _requests(app: Any) -> tuple[int, int]:
-+ """(running, waiting): a concurrent engine's lanes and queue, else /health's live requests and the turn queue."""
-+
-+ sched, decoder = _decoder(app)
-+ if decoder is not None and hasattr(decoder, "live"):
-+ live = decoder.live
-+ running = int(live() if callable(live) else live)
-+ waiting = 0
-+ queue = getattr(sched, "waiting", None)
-+ if queue is not None and hasattr(queue, "qsize"):
-+ waiting += int(queue.qsize())
-+ if getattr(sched, "held", None) is not None:
-+ waiting += 1
-+ return running, waiting
-+ health = getattr(app, "health", None)
-+ running = len(getattr(health, "live", ()) or ())
-+ turns = getattr(app, "turns", None)
-+ if turns is None:
-+ return running, 0
-+ parked = getattr(turns, "parked", None)
-+ return running, int(parked if parked is not None else getattr(turns, "waiting", 0) or 0)
-+
-+
-+def _pools(app: Any) -> list[tuple[str, float]]:
-+ """One ratio per live stream. An idle server still publishes pool 0 at 0."""
-+
-+ window = _window(app)
-+ lengths = _lengths(app)
-+ if not lengths:
-+ return [("0", 0.0)]
-+ if window <= 0:
-+ return [(str(i), 0.0) for i in range(len(lengths))]
-+ return [(str(i), min(1.0, n / window)) for i, n in enumerate(lengths)]
-+
-+
-+def _window(app: Any) -> int:
-+ engine = getattr(app, "engine", None)
-+ _, decoder = _decoder(app)
-+ # the effective window first: GLM's engine keeps its own as ``limit``, below the checkpoint's native window
-+ for owner, name in ((app, "effective_context_window"), (engine, "context_window"), (app, "context_window"),
-+ (decoder, "context")):
-+ n = _positive(getattr(owner, name, None) if owner is not None else None)
-+ if n:
-+ return n
-+ return 0
-+
-+
-+def _lengths(app: Any) -> list[int]:
-+ _, decoder = _decoder(app)
-+ if decoder is None:
-+ return []
-+ streams = list(getattr(decoder, "streams", {}).values())
-+ streams += list(getattr(decoder, "filling", ()) or ())
-+ return [_occupied(stream) for stream in streams]
-+
-+
-+def _occupied(stream: Any) -> int:
-+ """A stream's prompt and reply so far (a ``Stream``'s ``context`` holds its reply, or its prompt and reply)."""
-+
-+ context = len(getattr(stream, "context", None) or ())
-+ return max(context, len(getattr(stream, "prompt", None) or ()) + len(getattr(stream, "out", None) or ()))
-+
-+
-+def _positive(value: Any) -> int:
-+ try:
-+ n = int(value)
-+ except (TypeError, ValueError):
-+ return 0
-+ return n if n > 0 else 0
-+
-+
-+def _num(value: float) -> str:
-+ if value == int(value):
-+ return str(int(value))
-+ return f"{value:.6f}".rstrip("0").rstrip(".")
-+
-+
-+def _edge(value: float) -> str:
-+ return f"{value:.4f}".rstrip("0").rstrip(".")
-+
-+
-+__all__ = ["BUCKETS", "HEALTH", "PREFIX", "Histogram", "Metrics", "note", "of", "render", "send"]
diff --git a/patches/0051-glm-timing-tokens.patch b/patches/0048-glm-timing-tokens.patch
similarity index 100%
rename from patches/0051-glm-timing-tokens.patch
rename to patches/0048-glm-timing-tokens.patch
diff --git a/patches/0052-glm-multi-prefill.patch b/patches/0049-glm-multi-prefill.patch
similarity index 98%
rename from patches/0052-glm-multi-prefill.patch
rename to patches/0049-glm-multi-prefill.patch
index aa45eeb..279d03f 100644
--- a/patches/0052-glm-multi-prefill.patch
+++ b/patches/0049-glm-multi-prefill.patch
@@ -1,8 +1,8 @@
diff --git tensorfold/families/glm5_next/cuda/engine.py tensorfold/families/glm5_next/cuda/engine.py
-index 04ca1b1..7957ac7 100644
+index 032b546..f021d02 100644
--- tensorfold/families/glm5_next/cuda/engine.py
+++ tensorfold/families/glm5_next/cuda/engine.py
-@@ -681,7 +681,8 @@ class GlmEngine:
+@@ -678,7 +678,8 @@ class GlmEngine:
print(f"[tensorfold] --parallel {parallel}: up to {parallel} requests decode together, their caches "
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 "
@@ -13,10 +13,10 @@ index 04ca1b1..7957ac7 100644
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 50cd873..c363bc4 100644
+index 60250c3..c32686e 100644
--- tensorfold/families/glm5_next/cuda/forward.py
+++ tensorfold/families/glm5_next/cuda/forward.py
-@@ -482,18 +482,47 @@ def kda_block(layer: LayerW, w: Weights, st: State, b: Buffers, R: int, done: tu
+@@ -483,18 +483,47 @@ def kda_block(layer: LayerW, w: Weights, st: State, b: Buffers, R: int, done: tu
mm(b, fa, k.fb, qmm.group_sums(fa, b.xs_fa[:R]), b.ka[:R])
mm(b, ga, k.gb, qmm.group_sums(ga, b.xs_ga[:R]), b.kg[:R])
l2pf.site(layer.index, "o")
@@ -71,7 +71,7 @@ index 50cd873..c363bc4 100644
def kda_segments(layer: LayerW, w: Weights, b: Buffers, R: int, seg: torch.Tensor, slots: "Slots",
proj: torch.Tensor, scratch, li: int) -> torch.Tensor:
"""kda_block's decode path for a multi-stream window (``seg``: kda.segment_table, set): the projections on every
-@@ -602,11 +631,24 @@ def _dsa_latent(a, w: Weights, lc: torch.Tensor, pos_dev: torch.Tensor, b: Buffe
+@@ -603,11 +632,24 @@ def _dsa_latent(a, w: Weights, lc: torch.Tensor, pos_dev: torch.Tensor, b: Buffe
index, host_pos: int | None, sparse_np: int | None = None, layer: int = -1) -> torch.Tensor:
"""DSA on the latent cache: the same indexer and selection, attention over latents with kv_b's key blocks absorbed into the query."""
@@ -97,7 +97,7 @@ index 50cd873..c363bc4 100644
# sparse_np: every row is past the dense limit (a captured graph); else the host position decides
all_sparse = sparse_np is not None or (host_pos is not None and host_pos >= c.dense_limit)
sparse_rows = index is not None and (all_sparse or (host_pos is not None and host_pos + R - 1 >= c.dense_limit))
-@@ -614,13 +656,13 @@ def _dsa_latent(a, w: Weights, lc: torch.Tensor, pos_dev: torch.Tensor, b: Buffe
+@@ -615,13 +657,13 @@ def _dsa_latent(a, w: Weights, lc: torch.Tensor, pos_dev: torch.Tensor, b: Buffe
ik, ig, pk = index
ix = a.index
with prof.timed("dsa: indexer update"):
@@ -116,7 +116,7 @@ index 50cd873..c363bc4 100644
scale = c.qk_dim ** -0.5
if not all_sparse:
# Rows past the dense limit are recomputed sparsely below, so the dense pass needs only the chunks up to it
-@@ -631,8 +673,8 @@ def _dsa_latent(a, w: Weights, lc: torch.Tensor, pos_dev: torch.Tensor, b: Buffe
+@@ -632,8 +674,8 @@ def _dsa_latent(a, w: Weights, lc: torch.Tensor, pos_dev: torch.Tensor, b: Buffe
hb=latent.head_block(R), starts=b.att_starts if b.prefill else None)
if sparse_rows:
with prof.timed("dsa: select tokens"):
@@ -127,7 +127,7 @@ index 50cd873..c363bc4 100644
pk.shape[0] - 2, pos_dev, bucket=sparse_np)
with prof.timed("dsa: sparse attention"):
if b.prefill and latent.SPARSE_ONEPASS: # prompt rows: one pass a row, no partials (their own bits)
-@@ -640,8 +682,7 @@ def _dsa_latent(a, w: Weights, lc: torch.Tensor, pos_dev: torch.Tensor, b: Buffe
+@@ -641,8 +683,7 @@ def _dsa_latent(a, w: Weights, lc: torch.Tensor, pos_dev: torch.Tensor, b: Buffe
else:
latent.sparse_attention(qa, lc, tokens, counts, ol, scale)
with prof.timed("dsa: expand"):
@@ -137,7 +137,7 @@ index 50cd873..c363bc4 100644
def dsa_segments(layer: LayerW, w: Weights, lc: torch.Tensor, b: Buffers, R: int, rows, sel=None, index=None, *,
-@@ -814,10 +855,13 @@ def layer_forward(layer: LayerW, w: Weights, st: State, b: Buffers, R: int, nch:
+@@ -815,10 +856,13 @@ 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])
@@ -153,7 +153,7 @@ index 50cd873..c363bc4 100644
c = w.cfg
sp = b.split
-@@ -831,7 +875,10 @@ def split_layers(w: Weights, st: State, b: Buffers, R: int, nch: int | None, hos
+@@ -832,7 +876,10 @@ def split_layers(w: Weights, st: State, b: Buffers, R: int, nch: int | None, hos
b.comb[:Rp], b.hcpart[:Rp], c.eps, c.hc_eps, c.hc_iters, prompt=True)
done = None # rows whose front the glue already ran (TF_GLM_PREFILL_OVERLAP=2)
for i, layer in enumerate(layers):
@@ -165,7 +165,7 @@ index 50cd873..c363bc4 100644
front = ffn_front(layer, w, b) if fronts else None
with prof.timed("hc"):
sp.glue(layer.ffn_hc, layer.post_norm, front=front)
-@@ -894,8 +941,8 @@ def _compute(w: Weights, st: State, b: Buffers, R: int, *, logits: bool = True,
+@@ -895,8 +942,8 @@ def _compute(w: Weights, st: State, b: Buffers, R: int, *, logits: bool = True,
if inject is not None:
rows, features = inject
b.x.index_copy_(0, rows, features.repeat(1, c.streams))
diff --git a/patches/0053-glm-many-media.patch b/patches/0050-glm-many-media.patch
similarity index 99%
rename from patches/0053-glm-many-media.patch
rename to patches/0050-glm-many-media.patch
index a4ac28d..a27e7fa 100644
--- a/patches/0053-glm-many-media.patch
+++ b/patches/0050-glm-many-media.patch
@@ -1,8 +1,8 @@
diff --git tensorfold/cuda/http.py tensorfold/cuda/http.py
-index 589b56b..81c9b0f 100644
+index dabd045..bebd06f 100644
--- tensorfold/cuda/http.py
+++ tensorfold/cuda/http.py
-@@ -91,9 +91,9 @@ def make_handler(app: App):
+@@ -93,9 +93,9 @@ def make_handler(app: App):
return self._json(404, {"error": "not found"})
try:
length = int(self.headers.get("Content-Length", 0))
@@ -15,7 +15,7 @@ index 589b56b..81c9b0f 100644
body = json.loads(self.rfile.read(length) or b"{}")
except (json.JSONDecodeError, UnicodeDecodeError):
diff --git tensorfold/server/prompts.py tensorfold/server/prompts.py
-index 3b3a23b..ac3fdc7 100644
+index 2b9c05b..9c636df 100644
--- tensorfold/server/prompts.py
+++ tensorfold/server/prompts.py
@@ -40,21 +40,28 @@ def image_slot():
diff --git a/patches/0051-glm-tool-history-recovery.patch b/patches/0051-glm-tool-history-recovery.patch
new file mode 100644
index 0000000..bd09565
--- /dev/null
+++ b/patches/0051-glm-tool-history-recovery.patch
@@ -0,0 +1,71 @@
+diff --git tensorfold/families/glm5_next/prompts.py tensorfold/families/glm5_next/prompts.py
+index 8763a93..2ec5dfa 100644
+--- tensorfold/families/glm5_next/prompts.py
++++ tensorfold/families/glm5_next/prompts.py
+@@ -3,10 +3,9 @@
+ from __future__ import annotations
+
+ import json
++import sys
+ from typing import Any
+
+-from tensorfold.server.errors import RequestError
+-
+ EFFORT_LINE = "<|system|>Reasoning Effort: Max"
+ OPENED = "<|assistant|><think>"
+
+@@ -20,7 +19,12 @@ def _call_id(message: Any) -> Any:
+ def agent_history(messages: Any) -> Any:
+ """A chat as GLM-5.3's template can render every part of it: a call's arguments sent as "" or null are no
+ arguments (the template reads them as a mapping), and results whose ids match none of their calls' ids are
+- rendered in the order sent (the template sorts results by id and silently drops one it cannot place)."""
++ rendered in the order sent (the template sorts results by id and silently drops one it cannot place).
++
++ A call whose arguments are not a JSON object (a truncated or garbled string from a model, client or proxy) is
++ left out with its result, logged, rather than refused: an agent replays its history on every later turn, so a
++ refusal would end the conversation. Its message keeps its other calls, content and reasoning; its result is the
++ one with the call's id, else (no ids) the one in the call's place."""
+
+ if not isinstance(messages, list):
+ return messages
+@@ -29,7 +33,7 @@ def agent_history(messages: Any) -> Any:
+ calls = message.get("tool_calls") if isinstance(message, dict) and message.get("role") == "assistant" else None
+ if not isinstance(calls, list) or not calls:
+ continue
+- fixed = []
++ fixed, bad = [], []
+ for j, call in enumerate(calls):
+ function = call.get("function") if isinstance(call, dict) else None
+ arguments = function.get("arguments") if isinstance(function, dict) else {}
+@@ -41,13 +45,28 @@ def agent_history(messages: Any) -> Any:
+ except ValueError:
+ parsed = None
+ if not isinstance(parsed, dict):
+- raise RequestError(f"messages[{i}].tool_calls[{j}].function.arguments must be a JSON object "
+- f"(or empty), not {arguments[:80]!r}")
++ print(f"[tensorfold] messages[{i}].tool_calls[{j}] ({_call_id(call)!r}): arguments are not a JSON "
++ f"object ({arguments[:80]!r}); the call and its result are left out of the prompt",
++ file=sys.stderr, flush=True)
++ bad.append(j)
++ continue
+ fixed.append(call)
+- out[i] = {**message, "tool_calls": fixed}
+ end = i + 1
+ while end < len(out) and isinstance(out[end], dict) and out[end].get("role") == "tool":
+ end += 1
++ if bad:
++ ids = {_call_id(calls[j]) for j in bad} - {None}
++ by_place = not ids and end - i - 1 == len(calls) # no ids: results in their calls' order
++ out[i + 1:end] = [r for k, r in enumerate(out[i + 1:end])
++ if not (_call_id(r) in ids or (by_place and k in bad))]
++ end = i + 1
++ while end < len(out) and isinstance(out[end], dict) and out[end].get("role") == "tool":
++ end += 1
++ if fixed:
++ out[i] = {**message, "tool_calls": fixed}
++ else:
++ out[i] = {k: v for k, v in message.items() if k != "tool_calls"}
++ continue
+ known = {_call_id(call) for call in fixed}
+ if any(_call_id(result) and _call_id(result) not in known for result in out[i + 1:end]):
+ out[i + 1:end] = [{k: v for k, v in result.items() if k not in ("tool_call_id", "id")}
diff --git a/patches/0052-cuda-roce-startup.patch b/patches/0052-cuda-roce-startup.patch
new file mode 100644
index 0000000..e9ac0fa
--- /dev/null
+++ b/patches/0052-cuda-roce-startup.patch
@@ -0,0 +1,111 @@
+diff --git tensorfold/cuda/roce.py tensorfold/cuda/roce.py
+index bba421c..93535a4 100644
+--- tensorfold/cuda/roce.py
++++ tensorfold/cuda/roce.py
+@@ -30,6 +30,22 @@ BLOCKS = 8 # the largest grid; smaller shards laun
+ SPIN_LIMIT = 20_000_000 # flag polls (~1 us each) before a wait poisons the runtime: ~20 s
+
+
++def spin_limit() -> int:
++ """TF_ROCE_WAIT_S: how long a GPU wait for the peer's shard may take before it poisons the runtime (default 20 s;
++ graphs keep the value they were captured with)."""
++
++ value = os.environ.get("TF_ROCE_WAIT_S", "").strip()
++ if not value:
++ return SPIN_LIMIT
++ try:
++ seconds = float(value)
++ except ValueError:
++ seconds = -1.0
++ if not 1 <= seconds <= 3600:
++ raise ValueError(f"TF_ROCE_WAIT_S: 1 to 3600 seconds, not {value!r}")
++ return int(seconds * 1_000_000)
++
++
+ def _cache_dir() -> Path:
+ root = os.environ.get("TORCH_EXTENSIONS_DIR") or os.path.join(os.path.expanduser("~"), ".cache", "tensorfold")
+ return Path(root) / "roce"
+@@ -61,7 +77,7 @@ def proxy_library() -> ctypes.CDLL:
+ ("roce_create", p, [i, i, ctypes.POINTER(ctypes.c_char_p), i, i, i, p, u64, u64, ctypes.c_char_p, u64]),
+ ("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_destroy", None, [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:
+@@ -131,6 +147,8 @@ class RoceGather:
+ 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.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
+ verdict = torch.tensor([0 if ok else 1], dtype=torch.int32, device="cuda")
+ both = torch.empty(world, dtype=torch.int32, device="cuda")
+@@ -157,7 +175,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),
+- SPIN_LIMIT, 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, len(self.hcas), grid, THREADS)
+ if not torch.cuda.is_current_stream_capturing():
+ self.check()
+
+@@ -168,7 +186,18 @@ class RoceGather:
+ peer, hca = int(self.ctrl_words[3]), int(self.ctrl_words[6])
+ why = self.lib.roce_error(self.ctx).decode(errors="replace") if self.ctx else ""
+ raise RuntimeError(f"RoCE all-gather failed (sequence {int(self.ctrl_words[2])}, peer {peer}, hca {hca})"
+- f"{': ' + why if why else ''}")
++ f"{': ' + why if why else ''} [{self.stats()}]")
++
++ def stats(self) -> str:
++ """The proxy's counters, for a failure report: the doorbell against what was posted and completed."""
++
++ if not self.ctx:
++ return "no proxy"
++ lib, c = self.lib, self.ctx
++ hcas = " ".join(f"hca{h} completed {lib.roce_hca_stat(c, h, 0)} bytes {lib.roce_hca_stat(c, h, 1)}"
++ for h in range(len(self.hcas)))
++ return (f"doorbell {int(self.ctrl_words[0])}, posted {lib.roce_stat(c, 0)}, completed {lib.roce_stat(c, 1)}, "
++ f"last {lib.roce_stat(c, 2)}; {hcas}; wait limit {self.spin / 1e6:g} s (TF_ROCE_WAIT_S)")
+
+ def close(self) -> None:
+ if getattr(self, "ctx", None):
+@@ -185,6 +214,14 @@ class RoceComm:
+ limit = int(os.environ.get("TF_ROCE_MAX_KB", "256")) << 10 if max_bytes is None else max_bytes
+ self.roce = RoceGather(nccl, rank, world, limit)
+ self.small = self.large = 0
++ self.settled = False
++
++ def settle(self) -> None:
++ """Startup is over on this rank (its engine is built). Until then each eager RoCE gather waits for the peer in
++ an NCCL barrier first: the ranks build their CUDA extensions on their own and can drift tens of seconds apart
++ on a first start, past what a RoCE wait allows; NCCL waits without that limit. Captured gathers never do."""
++
++ self.settled = True
+
+ def all_gather(self, send: torch.Tensor, recv: torch.Tensor) -> None:
+ """RoCE for a gather whose size fits, NCCL otherwise: decided by the byte count alone, which every rank's
+@@ -198,6 +235,8 @@ class RoceComm:
+ s = send if send.is_contiguous() and send.data_ptr() % PACK == 0 else send.contiguous().clone()
+ r = recv if recv.is_contiguous() and recv.data_ptr() % PACK == 0 else torch.empty_like(recv,
+ memory_format=torch.contiguous_format)
++ if not self.settled and not torch.cuda.is_current_stream_capturing():
++ self.nccl.barrier()
+ self.roce.all_gather(s, r)
+ if r is not recv:
+ recv.copy_(r)
+diff --git tensorfold/families/glm5_next/cuda/engine.py tensorfold/families/glm5_next/cuda/engine.py
+index f021d02..267e84c 100644
+--- tensorfold/families/glm5_next/cuda/engine.py
++++ tensorfold/families/glm5_next/cuda/engine.py
+@@ -683,6 +683,8 @@ class GlmEngine:
+ 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)
++ if hasattr(self.comm, "settle"): # startup is over: RoCE gathers go without a barrier first
++ self.comm.settle()
+
+ def _calibrate(self) -> dict:
+ """Per-piece ms for ``drafter_choice.DrafterChoice``: fastest of interleaved passes, equal on both ranks."""
diff --git a/patches/0053-glm-whole-tool-calls.patch b/patches/0053-glm-whole-tool-calls.patch
new file mode 100644
index 0000000..e56883a
--- /dev/null
+++ b/patches/0053-glm-whole-tool-calls.patch
@@ -0,0 +1,100 @@
+diff --git tensorfold/cuda/reply_text.py tensorfold/cuda/reply_text.py
+index 2f63be4..1ad8ca7 100644
+--- tensorfold/cuda/reply_text.py
++++ tensorfold/cuda/reply_text.py
+@@ -237,11 +237,14 @@ def _json(value: Any) -> str:
+
+ class GlmCallStreamer:
+ """GLM's ``<tool_call>NAME<arg_key>K</arg_key><arg_value>V</arg_value>...</tool_call>`` calls as OpenAI tool-call
+- deltas while they are written: a header (index, id, name) once the name is whole, then the arguments' JSON in
+- pieces, a string value as it arrives and a typed one when whole, joining to what ``parse_tool_calls`` gives.
++ deltas: each call is followed while it is written (its arguments' JSON built a string value as it arrives and a
++ typed one when whole, joining to what ``parse_tool_calls`` gives) and sent whole, header and arguments in one delta,
++ once its ``</tool_call>`` arrives. A call the reply ends inside (its token limit) is never sent: a client could
++ store or run its cut arguments.
+
+- ``feed`` takes the reply's answer so far (text that only grows) and returns the new deltas. A block it cannot
+- follow (not GLM's markup, a tool the request did not offer) is skipped and stays with the end parser."""
++ ``feed`` takes the reply's answer so far (text that only grows) and returns the new deltas; ``sent`` counts the
++ calls sent. A block it cannot follow (not GLM's markup, a tool the request did not offer) is skipped and stays
++ with the end parser."""
+
+ def __init__(self, tools: list[dict[str, Any]]) -> None:
+ self.known = {_tool_name(t).lower(): _tool_name(t) for t in tools}
+@@ -253,6 +256,7 @@ class GlmCallStreamer:
+ self.schema: dict[str, Any] = {} # the current call's parameter schemas
+ self.value_schema: dict[str, Any] | None = None # the current typed value's schema, None for text
+ self.maybe_null = False # a nullable text value that may still be ``null``: held
++ self.sent = 0 # calls sent whole (the last one may still be open)
+
+ def _args(self, out: list[dict[str, Any]], piece: str) -> None:
+ index = len(self.calls) - 1
+@@ -264,6 +268,15 @@ class GlmCallStreamer:
+ out.append({"tool_calls": [{"index": index, "function": {"arguments": piece}}]})
+
+ def feed(self, text: str) -> list[dict[str, Any]]:
++ self._follow(text)
++ whole = len(self.calls) - (1 if self.open else 0)
++ out = [{"tool_calls": [{"index": i, "id": c["id"], "type": "function",
++ "function": {"name": c["function"]["name"], "arguments": c["function"]["arguments"]}}]}
++ for i, c in enumerate(self.calls[self.sent:whole], self.sent)]
++ self.sent = whole
++ return out
++
++ def _follow(self, text: str) -> list[dict[str, Any]]:
+ out: list[dict[str, Any]] = []
+ while True:
+ rest = text[self.pos:]
+diff --git tensorfold/cuda/server.py tensorfold/cuda/server.py
+index 673fc9f..762cd3d 100644
+--- tensorfold/cuda/server.py
++++ tensorfold/cuda/server.py
+@@ -29,6 +29,10 @@ from tensorfold.cuda.reply_text import (THINK_CALL_HOLD, GlmCallStreamer, StopSt
+ from tensorfold.cuda.turns import Turns, Yield
+ from tensorfold.server.text import is_title_request, reasoning_count, split_thinking
+
++# While a GLM tool call is written it is held until whole (a call the reply ends inside is never sent); an idle client
++# (upstream #114: one that drops a reply sending nothing) gets an empty delta this often meanwhile
++CALL_KEEPALIVE_S = 2.0
++
+
+ # -- requests --------------------------------------------------------------------------------
+
+@@ -363,6 +367,7 @@ class App:
+ # for minutes, past the idle cut of clients such as LiteLLM and Node's fetch); one call a reply waits
+ glm_calls = bool(tools) and self._glm_calls()
+ calls_stream = GlmCallStreamer(tools) if glm_calls and body.get("stream") and not policy.single else None
++ quiet_since = [time.monotonic()] # the last delta sent while a call is held (CALL_KEEPALIVE_S)
+ # other families' calls stream as argument deltas while written (as on the Mac); one-call requests keep the
+ # end parser
+ xml_stream = ToolCallStreamer(tools) if tools and not glm_calls and not policy.single else None
+@@ -424,6 +429,11 @@ class App:
+ parts = [delta] if delta else []
+ if calls_stream is not None:
+ parts += calls_stream.feed(call_text(raw))
++ if parts:
++ 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):
+ stopped["client"] = True
+ if xml_stream is not None and not stopped["client"]:
+@@ -525,11 +535,13 @@ class App:
+ # (never streamed) are the end parser's, sent whole
+ if calls_stream is not None and (think is None or think.stream_from is not None):
+ call_deltas = calls_stream.feed(call_text(raw))
+- streamed = len(calls_stream.calls)
+- calls = [*calls_stream.calls, *calls_stream.rest(tools)] or None
+- cut = calls_stream is not None and calls_stream.open # a streamed call the reply ended inside
+- if cut: # its text went out as a call already, not again as content
++ 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
+ content = answer.strip()
++ elif tools 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:
+ final["content"] = tail
diff --git a/scripts/config.sh b/scripts/config.sh
index e2e2636..65c1728 100644
--- a/scripts/config.sh
+++ b/scripts/config.sh
@@ -38,7 +38,7 @@ MODEL_ID="${MODEL_ID:-Mia-AiLab/GLM-5.3-Flash-EXL3-TR3-4bpw}" # EXL3 routed ex
# 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
MODEL_REVISION="${MODEL_REVISION-$_rev}"
-TF_VERSION="${TF_VERSION:-v0.5.0}"
+TF_VERSION="${TF_VERSION:-v0.6.0}"
TF_REPO="${TF_REPO:-https://github.com/ashhart/TensorFold.git}"
BASE_IMAGE="${BASE_IMAGE:-nvcr.io/nvidia/pytorch:26.07-py3}"
IMAGE="${IMAGE:-tensorfold-glm53:${TF_VERSION}}"
@@ -50,8 +50,8 @@ 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.5.0-cb7c56f7f921}"
-IMAGE_DIGEST="${IMAGE_DIGEST:-sha256:6ee3c6e0430040b69ddcb0c96c7fbbcb94a5bed47d48a8ba092626369ae533b9}"
+IMAGE_TAG="${IMAGE_TAG:-v0.6.0-ae8d1c789b47}"
+IMAGE_DIGEST="${IMAGE_DIGEST:-sha256:22789f0cb3dc308f0b2ce52a33961b88bd624af1725e91e8aba0a74a671bb969}"
# the registry reference prepare.sh pulls for these patches: the pinned digest, or the hash's tag
prebuilt_image() {
local tag="${TF_VERSION}-$(image_hash)"
@@ -64,19 +64,22 @@ HOST="${HOST:-0.0.0.0}"
PORT="${PORT:-8888}"
DRAFTER="${DRAFTER:-dflash2}" # dflash2: incoai/GLM-5.3-Flash-DFlash2 drafts (CC BY-NC-ND 4.0: non-commercial
# use only), +5-10% decode over mtp; mtp: the checkpoint's own MTP head
+# The checkpoint's MTP head beside DFlash2 (TensorFold's TF_GLM_MTP): auto (default) leaves it out while DFlash2
+# drafts every request; TensorFold v0.6.0's own default, 1, would load it (1.77 GiB a Spark) with PARALLEL=1.
+export TF_GLM_MTP="${TF_GLM_MTP:-auto}"
# Image and video input (rank 0 runs GLM's vision tower: 1.05 GiB of bf16 weights and 0.75 GiB of workspace). A picture
# takes at most TENSORFOLD_GLM_IMAGE_TOKENS tokens (2048), a clip TENSORFOLD_GLM_VIDEO_TOKENS (16384) over at most
# TENSORFOLD_GLM_VIDEO_FRAMES frames (128, 2 a second). VISION_URLS=1 also accepts public https URLs (default: data URLs).
VISION="${VISION:-1}"
VISION_URLS="${VISION_URLS:-0}"
-# Concurrent requests (patches 0028-0033, 0038, 0043, 0044: one shared pool of per-token caches, one batched verify window
+# Concurrent requests (patches 0026-0030, 0035, 0040, 0041: one shared pool of per-token caches, one batched verify window
# a round): 1 to 4, with DRAFTER=dflash2 only (mtp: 1). 4 (default), prose in all (sparkDash): 60.4 / 79.2 / 89.5 /
# 108.8 tok/s at 1 / 2 / 3 / 4 at once; structured 114.7 / 147.6 / 196.3 / 227.9.
if [[ "$DRAFTER" == dflash2 ]]; then _par=4; else _par=1; fi
PARALLEL="${PARALLEL:-$_par}"
-# The DSA latent cache and the indexer's pooled keys (patch 0041): fp8 (default) holds them as e4m3 rows with a
+# The DSA latent cache and the indexer's pooled keys (patch 0038): fp8 (default) holds them as e4m3 rows with a
# power-of-two scale each, half bf16's bytes: the 1M-token window with 4 streams fits (rank 0: 88.09 GiB estimated,
-# pool 2,852,864 tokens at the measured start). Lossy: GSM8K 98.0%, HumanEval 97.6%, 1M needle found; drafted replies still equal serial
+# pool 2,922,496 tokens at the measured start). Lossy: GSM8K 98.0%, HumanEval 97.6%, 1M needle found; drafted replies still equal serial
# ones. bf16: the exact cache (~196k tokens with DFlash2).
KV="${KV:-fp8}"
export TF_GLM_KV="$KV"
@@ -92,6 +95,10 @@ DFLASH2_ID="${DFLASH2_ID:-incoai/GLM-5.3-Flash-DFlash2}"
_rev=""; [[ "$DFLASH2_ID" == incoai/GLM-5.3-Flash-DFlash2 ]] && _rev=bf582e4eacc1810f76656d1811693ff6c6737d2a
DFLASH2_REVISION="${DFLASH2_REVISION-$_rev}" # DFlash2's pinned revision, as MODEL_REVISION above
THINKING="${THINKING:-1}"
+# The reply budget of a request that sets no max_tokens (or max_completion_tokens), reasoning and answer together:
+# 32768. GLM thinks at Max by default, and TensorFold's own 4,096 could end a reply inside a tool call (an agent such
+# as Codex sets none). A request's own value wins; this one is cut to what the window has left, never refused.
+MAX_TOKENS="${MAX_TOKENS:-32768}"
# The checkpoint's BF16 weights (attention, shared experts, dense layers, head: ~9.7 GiB a Spark):
# q4 (default): the projections as affine 4-bit groups of 64 with MSE-searched ranges, the head and kv_b in FP8
# (patches 0002, 0005). Over fp8 (DFlash2, one boot each): prose 38.9 -> 44.4 tok/s, code 44.2 -> 48.7, prefill
@@ -124,35 +131,35 @@ DRAFT_POLICY="${DRAFT_POLICY:-fnc7:0.3}"
export TF_GLM_DFLASH_POLICY="$DRAFT_POLICY"
# Prompt chunks' hyper-connection glue split by rows between the two Sparks, its exchanges overlapped with the next
# rows' work (patch 0010): prefill ~1,270 -> ~1,730 tok/s on a 50k prompt (with patches 0009 and 0020); decode rounds
-# pay ~1.5%. The overlap also runs the next block's front on its own rows during the exchanges (patch 0036; with
+# pay ~1.5%. The overlap also runs the next block's front on its own rows during the exchanges (patch 0033; with
# COPY_CODE below, two boots each: a 149k prompt 92.8 -> 90.7 s). Same bits. SPLIT=0 turns it off.
SPLIT="${SPLIT:-1}"
export TF_GLM_HC_SPLIT="$SPLIT" TF_GLM_PREFILL_OVERLAP="$([[ "$SPLIT" == 1 ]] && echo 2 || echo 0)"
-# KDA prompt chunks in chunked (WY) form, one CUDA kernel of 32-row sub-chunks (patches 0012, 0014, 0042): prefill
+# KDA prompt chunks in chunked (WY) form, one CUDA kernel of 32-row sub-chunks (patches 0012, 0014, 0039): prefill
# 50k 29.3 -> 26.4 s, 149k 91.1 -> 84.5 s (one boot each); prompt states then sit on a 64-token grid.
# Close to the serial kernel, not its bits: prompt arithmetic differs, drafted replies still equal serial ones. 0: off.
KDA_CHUNKED="${KDA_CHUNKED:-1}"
export TF_GLM_KDA_CHUNKED="$KDA_CHUNKED"
-# Code-workload copy drafts (patch 0035): 16-row verify windows as CUDA graphs, and a copy from the reply itself only
+# Code-workload copy drafts (patch 0032): 16-row verify windows as CUDA graphs, and a copy from the reply itself only
# when its last 16 tokens match: code 55.4 -> 56.2 tok/s, edit 120 -> 125 (with the overlap above, two boots each).
# Exact. 0: off.
COPY_CODE="${COPY_CODE:-1}"
_w=0; [[ "$COPY_CODE" == 1 ]] && _w=16
export TF_GLM_WIDE_GRAPHS="$_w" TF_GLM_COPY_REPLY_MATCH="$_w"
-# --parallel: a request alone runs on the one-stream graphs (patch 0038; 1, default) instead of the batched ones (0):
+# --parallel: a request alone runs on the one-stream graphs (patch 0035; 1, default) instead of the batched ones (0):
# +0.6-0.9% at 1 stream (two boots each); replies served together still equal the same requests served alone. Exact.
export TF_GLM_MULTI_LONE="${TF_GLM_MULTI_LONE:-1}"
-# Waiting prompts filled together in one forward (patch 0052): shared work (expert weights, glue, projections) runs once
+# 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"
-# L2 prefetch in decode windows (patch 0049, adapted from jayleaton/glm53-tensorfold-spark's patch 0460): a side stream
+# 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.
export TF_GLM_L2PF="${TF_GLM_L2PF:-1}"
-# The decode expert kernel's trellis loads (patch 0050, adapted from jayleaton/glm53-tensorfold-spark's patch 0580): nc
+# The decode expert kernel's trellis loads (patch 0047, adapted from jayleaton/glm53-tensorfold-spark's patch 0580): nc
# (default) as 16-byte non-coherent loads a k step ahead: prose 48.36 -> 48.78 tok/s, code 59.54 -> 60.42 on their own.
# Together with TF_GLM_L2PF=1 and TF_ROCE_MAX_KB=512: one request's prose 49.68, code 61.49 (+2.7% / +3.3%); 4 at once
# prose 74.8 -> 76.6, code 100.0 -> 102.7 tok/s in all (two boots each). Same bits. 0: TensorFold's 32-bit loads.
@@ -166,8 +173,8 @@ export TF_GLM_SHARED_PREFIX="$SHARED_PREFIX"
# (TENSORFOLD_MEMORY_RESERVE_GIB), capped at KV_POOL_GIB (its TF_GLM_CACHE_GIB). The server uses about 10 GiB more than
# its own estimate at its peak (a 1M-token prompt), so the reserve sets the lowest free memory on the head: 14.5 leaves
# about 4.5 GiB there, and the pool comes out at ~2.1-2.9M tokens depending on what is free at start. TensorFold's own
-# defaults (a tenth of RAM, ~12.2; 3 GiB: pool 1,411,072 tokens) leave ~14 GiB. Raise the reserve if other work
-# shares the Sparks' memory.
+# defaults (a tenth of RAM, ~12.2; 3 GiB: pool 1,411,072 tokens) leave more. Raise the reserve if other work shares
+# 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}"
@@ -184,7 +191,7 @@ WORKER_WEIGHTS="${WORKER_WEIGHTS:-copy}"
NFS_PATH="${NFS_PATH:-$HF_CACHE}"
NFS_SERVER="${NFS_SERVER:-}"
NFS_VOLUME="${NFS_VOLUME:-glm53-hf}"
-KERNEL_CACHE="${KERNEL_CACHE:-$HOME/.cache/tensorfold-glm53}" # compiled CUDA kernels (written by the containers)
+KERNEL_CACHE="${KERNEL_CACHE:-$HOME/.cache/tensorfold-glm53}" # compiled CUDA kernels, a folder per image's patches hash
STATE_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;
diff --git a/scripts/prepare.sh b/scripts/prepare.sh
index 45bf83c..cbd82b7 100755
--- a/scripts/prepare.sh
+++ b/scripts/prepare.sh
@@ -206,4 +206,4 @@ done
prepared_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 here and in ~/.cache/tensorfold-glm53 on the worker."
+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)."
diff --git a/start.sh b/start.sh
index 6d3acd3..250abbc 100755
--- a/start.sh
+++ b/start.sh
@@ -18,7 +18,7 @@
# 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, THINKING, VISION, VISION_URLS, COMM, SERVED_NAME, HOST, PORT
+# 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
# 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,
@@ -47,13 +47,14 @@ for arg in "$@"; do [[ "$arg" == -h || "$arg" == --help ]] && { usage; exit 0; }
# The serve arguments both ranks share: scripts/config.sh's defaults first, then the command line's (argparse keeps
# the last value). --drafter goes in front after the setup step, which knows DFlash2's snapshot.
-SERVE_ARGS=(--context "$CONTEXT" --parallel "$PARALLEL")
+SERVE_ARGS=(--context "$CONTEXT" --parallel "$PARALLEL" --max-tokens "$MAX_TOKENS")
[[ "$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"
[[ "$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
[[ "$WORKER_WEIGHTS" == copy || "$WORKER_WEIGHTS" == nfs ]] || die "WORKER_WEIGHTS is copy or nfs, not $WORKER_WEIGHTS"
@@ -131,6 +132,11 @@ fi
why="scripts/prepare.sh did not"; [[ "${PREPARE:-auto}" == 0 ]] && why="PREPARE=0 skipped scripts/prepare.sh, which 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"
+# 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 loaded
+KCACHE=$(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).
@@ -217,7 +223,7 @@ launch() {
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:/cache'
+ -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
@@ -225,7 +231,7 @@ launch() {
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":/cache \
+ -v "$HF_CACHE":/root/.cache/huggingface -v "$KERNEL_CACHE/$KCACHE":/cache \
"$IMAGE" "${rank0[@]}" >/dev/null
}
# FOREGROUND=1: stay attached to rank 0's log and exit with its code (systemd's Restart=on-failure). Either rank ending