Skip to content

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

Python

GLM-5.3-Flash EXL3 on 2x DGX Spark with TensorFold v0.5.0 + 52 patches

MiaAI-Labed026ef92d16
diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml
new file mode 100644
index 0000000..5848e40
--- /dev/null
+++ b/.github/FUNDING.yml
@@ -0,0 +1,4 @@
+# GitHub Sponsors — surfaces a "Sponsor" button in the repo sidebar.
+# Enable the Sponsors profile at https://github.com/sponsors/MiaAI-Lab
+# (the button only renders once Sponsors is activated on the account).
+github: MiaAI-Lab
diff --git a/.github/ISSUE_TEMPLATE/1_bug.md b/.github/ISSUE_TEMPLATE/1_bug.md
new file mode 100644
index 0000000..b9e5b49
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/1_bug.md
@@ -0,0 +1,111 @@
+---
+name: Bug report
+about: The model kit is not behaving as expected, is producing an error, or the numbers do not match the README.
+title: ""
+labels: "bug"
+assignees: ""
+---
+
+<!-- Thank you for using this model kit!
+
+ If you are looking for support, please check the README and scripts/config.sh first,
+ or reach out on X:
+ * https://x.com/MiaAI_lab
+
+ If you have found a bug, then fill out the template below.
+-->
+
+---
+
+## Environment
+
+<!-- Fill in what applies to your setup. The README's "Performance" and
+ "Configuration" sections list the settings that affect behavior and the defaults
+ shipped in scripts/config.sh. -->
+
+- Hardware: <!-- e.g. 2x DGX Spark (GB10, 128 GB unified memory each), one QSFP cable between the CX7 ports -->
+- Memory available before launch, on both Sparks: <!-- `free -g`; other GPU workloads running? -->
+- Image: <!-- `docker images | grep tensorfold-glm53`, or the ghcr.io tag you pulled -->
+- TensorFold version: <!-- `docker exec glm53-flash-tf tensorfold --version` -->
+- `start.sh` invocation: <!-- e.g. `./start.sh`, or `PARALLEL=2 ./start.sh restart --max-tokens 16384` -->
+- Changed settings: <!-- environment, scripts/local.sh or .env: PARALLEL, CONTEXT, KV, DENSE, DRAFTER, DRAFT_POLICY, COPY, SPLIT, KDA_CHUNKED, VISION, COMM, TENSORFOLD_* / TF_GLM_* -->
+- Startup lines: <!-- `docker logs glm53-flash-tf 2>&1 | grep -E "startup estimate|loading GLM|serving"` -->
+
+---
+
+## Steps to Reproduce
+
+<!-- Please include full steps so that we can reproduce the problem. -->
+
+1. Run `./start.sh` <!-- describe any overrides and what it printed up to the failure -->
+2. ... <!-- describe steps to demonstrate the bug -->
+3. ... <!-- for example "a tool call with an array parameter returns a string" -->
+
+**Expected results:** <!-- what did you expect to happen? -->
+
+**Actual results:** <!-- what did you actually see happen? -->
+
+---
+
+### Additional context
+
+Add any other context here: a minimal request that reproduces bad output, JSON
+responses, `docker inspect` output, and so on.
+
+<details>
+<summary>Minimal reproduction sample</summary>
+
+<!--
+ If the bug is about model output or API behavior, attach a minimal reproducible
+ request below between the lines with the backticks.
+
+ NOTE: the model thinks before it answers, in "reasoning_content" rather than
+ "content". Budget enough max_tokens (~2,000 for anything non-trivial), or send
+ "reasoning_effort": "low": with a small budget the reply is often still in its
+ reasoning and "content" comes back empty on a perfectly healthy server. That is
+ not a bug.
+
+ To tell a patch bug from model behavior, send the same request with
+ "draft": false (TensorFold's serial reference) and a fixed "seed": drafted and
+ serial replies must be identical.
+-->
+
+```bash
+curl -s http://<head-address>:8888/v1/chat/completions \
+ -H "Content-Type: application/json" \
+ -d '{
+ "model": "GLM-5.3-Flash-EXL3",
+ "messages": [{"role": "user", "content": "..."}],
+ "max_tokens": 2000
+ }'
+```
+
+</details>
+
+<details>
+ <summary>Logs</summary>
+
+<!--
+ Paste the log output below between the backticks, and mention whether it came
+ from `start.sh`, `scripts/prepare.sh`, `docker logs glm53-flash-tf` (rank 0, on the
+ head), `ssh <worker> docker logs glm53-flash-tf` (rank 1), or a client.
+
+ Common culprits worth checking before filing:
+ * "this start's memory budget holds a N-token window" -> another GPU workload is
+ using memory on one of the Sparks (start.sh retries once with the window that fits).
+ * start.sh warns "only N GiB memory available here (the default needs ~110)" -> stop other GPU
+ containers on that Spark first (`docker ps`).
+ * "no RoCE device or RoCE v2 GID for the link" -> WORKER is reached over another
+ 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.
+ * First start takes long -> the CUDA kernels compile once on each Spark (cached in
+ ~/.cache/tensorfold-glm53); that is expected, not a hang.
+-->
+
+```
+
+```
+
+</details>
diff --git a/.github/ISSUE_TEMPLATE/2_improvement.md b/.github/ISSUE_TEMPLATE/2_improvement.md
new file mode 100644
index 0000000..297f5c8
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/2_improvement.md
@@ -0,0 +1,70 @@
+---
+name: Improvement
+about: Something in this kit already works, but could be faster, safer, clearer or better defaulted.
+title: ""
+labels: "enhancement"
+assignees: ""
+---
+
+<!-- Thank you for using this model kit!
+
+ If you are looking for support, please check the README and scripts/config.sh first,
+ or reach out on X:
+ * https://x.com/MiaAI_lab
+
+ If you want to propose an improvement to something that already exists, fill
+ out the template below. For something that does not exist at all, please use
+ the Feature request template instead.
+-->
+
+## What could be better
+
+<!--
+ Describe the current behavior and why it is not ideal. Examples that fit this
+ repo:
+ * a default in scripts/config.sh that is wrong for most people
+ * a memory setting that is too conservative or does not fit
+ * a patch that no longer applies to a newer TensorFold release
+ * startup time (weights load in ~6 min on each Spark; the first start also
+ compiles kernels)
+ * a benchmark in tools/ that measures the wrong thing
+-->
+
+## Proposed change
+
+<!--
+ What should it do instead? If this touches TensorFold's code, it belongs in a
+ patch under patches/ (a unified diff against site-packages, applied with
+ patch -p0 by scripts/prepare.sh). Drafted replies must still equal serial ones;
+ say whether the patch keeps the same bits.
+-->
+
+## Measured impact
+
+<!--
+ This kit lives or dies on measured numbers, so please include them where you
+ can. The README records results in this shape:
+
+ * prefill tok/s and time to first token at several prompt sizes, and decode
+ tok/s for prose, code and edit replies at 1 to 4 concurrent requests,
+ measured with tools/bench.py or sparkDash (https://github.com/MiaAI-Lab/sparkDash)
+ * rank 0's startup estimate from
+ `docker logs glm53-flash-tf | grep "startup estimate"`
+ * needle retrieval (tools/needle.py) PASS/FAIL
+
+ Before/after pairs are much more useful than a single number, and please say
+ which configuration each number came from (PARALLEL, CONTEXT, KV, DENSE,
+ DRAFTER) - they move a lot between settings, and so do the GPU clocks.
+
+ If you are comparing two configurations, please use the same sample count for
+ both, and alternate restarts: boot-to-boot noise on a Spark is a few percent.
+-->
+
+## Risk
+
+<!--
+ Does this change memory use or output? A setting that raises memory can make the
+ server refuse the default 4 x 1,048,576-token FP8 pool on rank 0; a patch that
+ changes replies (beyond a labelled, measured lossy option) is not acceptable. Say
+ so here if it does.
+-->
diff --git a/.github/ISSUE_TEMPLATE/3_feature_request.md b/.github/ISSUE_TEMPLATE/3_feature_request.md
new file mode 100644
index 0000000..ce97a2a
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/3_feature_request.md
@@ -0,0 +1,46 @@
+---
+name: Feature request
+about: Suggest a new idea for this kit. Something that doesn't exist currently, and you want to see.
+title: ""
+labels: "enhancement"
+assignees: ""
+---
+
+<!-- Thank you for using this model kit!
+
+ If you are looking for support, please check the README and scripts/config.sh first,
+ or reach out on X:
+ * https://x.com/MiaAI_lab
+
+ If you want the kit to do something it currently doesn't, then fill out the
+ template below.
+-->
+
+## Use case
+
+<!--
+ Please tell us the challenge you are running into that led to you wanting a new
+ feature, or the workload you are trying to serve.
+
+ Examples that could fit this repo: an OpenAI-compatible client example, a
+ systemd unit or compose file, a CI lint/validate step, support for a different
+ checkpoint or quantization, an Anthropic-style /v1/messages route, a
+ quality-regression suite.
+
+ Describe the alternative solutions you've considered.
+-->
+
+## Proposal
+
+<!--
+ Briefly but precisely describe what you would like this kit to be able to do.
+
+ Consider attaching something showing what you are imagining:
+ * code samples
+ * a benchmark result or log you are trying to reproduce
+ * images or videos
+
+ Does this have to be provided by this kit directly, or can it be a small
+ user-land script? If the latter, maybe consider implementing and sharing it
+ with us in a pull request rather than filing an issue.
+-->
diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml
new file mode 100644
index 0000000..573d55c
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/config.yml
@@ -0,0 +1,5 @@
+blank_issues_enabled: true
+contact_links:
+ - name: I want help using this model kit on my own hardware.
+ url: https://x.com/MiaAI_lab
+ about: Ask questions about setting this up on a different box, or about how a particular piece of this kit works.
diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md
new file mode 100644
index 0000000..add112d
--- /dev/null
+++ b/.github/PULL_REQUEST_TEMPLATE.md
@@ -0,0 +1,72 @@
+## Description and Motivation
+
+<!--
+
+ Please write a description of what this PR is changing, removing or adding, and why.
+ Consider including before/after comparisons.
+
+ For this kit, a good description usually covers:
+ * which setting in scripts/config.sh, script behavior or patch changes
+ * whether the change affects measured numbers (prefill/decode throughput, TTFT,
+ concurrent requests, the startup memory estimate on rank 0) and in which direction
+ * for a patch: whether it keeps the same bits, and that drafted replies still
+ equal serial ones
+
+-->
+
+## Related Issues
+
+<!--
+
+ Add the list of issues related to this PR from the [issue tracker](https://github.com/MiaAI-Lab/GLM-5.3-Flash-EXL3-2x-DGX-Sparks-TensorFold/issues).
+ Indicate which of these issues are resolved or fixed by this PR, like #XXXX, where XXXX is the issue number.
+
+-->
+
+---
+
+## Testing
+
+<!--
+
+ Tell us how you verified this change. For this kit that usually means:
+
+ * `bash -n start.sh stop.sh scripts/*.sh` (syntax check)
+ * `python3 -m py_compile tools/*.py`
+ * `shellcheck start.sh stop.sh scripts/*.sh` if available
+ * `scripts/prepare.sh` (a patch change rebuilds the image on the head and copies it
+ to the worker; every patch must apply with `patch -p0` against TensorFold's
+ site-packages)
+ * an actual launch on two Sparks, plus
+ `docker logs glm53-flash-tf 2>&1 | grep -E "startup estimate|serving"`
+ * `tools/bench.py`, `tools/needle.py`, `tools/toolcheck.py` against the running server
+ * if behavior changed, the measured numbers with the new settings, stating
+ which configuration they came from (see README "Performance")
+
+ If you changed a patch, confirm drafted replies still equal TensorFold's serial
+ reference: the same request with "draft": false and a fixed "seed" (or
+ temperature 0) must give the same reply. Say whether the patch keeps the same
+ bits as before or changes prompt arithmetic (and measure quality if it does).
+
+-->
+
+---
+
+## Checklist:
+
+<!--
+
+ Thanks for contributing to Mia's AI Lab!
+
+ Before you file this pull request, please follow the items on this checklist and
+ put an x in each of the boxes, like this: [x].
+
+-->
+
+- [ ] I have read the README and `scripts/config.sh` and kept my changes consistent with them.
+- [ ] My pull request has a sound title and description (not something vague like `Update README.md`).
+- [ ] My change is reproducible and verified (script syntax check, `scripts/prepare.sh`, a launch, or a re-measurement).
+- [ ] A patch change keeps drafted replies equal to serial ones, and I said how I checked it (and whether its bits change).
+- [ ] I updated the README and/or `scripts/config.sh` if a setting, default, or measured number changed.
+- [ ] If my change affects memory, I checked rank 0's startup estimate still fits at the default 4 x 1,048,576 FP8 setting.
+- [ ] Defaults in `scripts/config.sh` still work out of the box; a new setting has a sane fallback like the existing ones.
diff --git a/.github/ascii.png b/.github/ascii.png
new file mode 100644
index 0000000..4cd03dc
Binary files /dev/null and b/.github/ascii.png differ
diff --git a/.github/image.png b/.github/image.png
new file mode 100644
index 0000000..3af3a82
Binary files /dev/null and b/.github/image.png differ
diff --git a/CREDITS.md b/CREDITS.md
new file mode 100644
index 0000000..bfafc8b
--- /dev/null
+++ b/CREDITS.md
@@ -0,0 +1,109 @@
+# Credits
+
+This repository is a thin layer of scripts and patches. Almost everything that makes it work was built by others.
+Its own work is licensed under the Apache License 2.0 ([`LICENSE`](LICENSE)); [`NOTICE`](NOTICE) carries the
+third-party notices that go with it (TensorFold's MIT and Apache-2.0 notices, b12x, glm53-tensorfold-spark, the
+checkpoint's ShapleyMcg attribution and the drafter's license).
+
+## Model
+
+- **[GLM-5.3-Flash](https://huggingface.co/zai-org/GLM-5.3-Flash)** by [Z.ai](https://huggingface.co/zai-org): the
+ model's design, training and evaluations. Its license, on the model card, governs any use of the weights. The
+ weights are not part of this repository; `scripts/prepare.sh` downloads them from Hugging Face.
+- **[brandonmusic](https://huggingface.co/brandonmusic)**: the EXL3 4-bit quantization,
+ [`brandonmusic/GLM-5.3-Flash-tr3-4bpw`](https://huggingface.co/brandonmusic/GLM-5.3-Flash-tr3-4bpw), served here
+ from its mirror [`Mia-AiLab/GLM-5.3-Flash-EXL3-TR3-4bpw`](https://huggingface.co/Mia-AiLab/GLM-5.3-Flash-EXL3-TR3-4bpw)
+ (a byte-identical copy), made with **ShapleyMcg** by Brandon M.
+ Music under the **ShapleyMcg License 1.0** (attribution required; the checkpoint's `LICENSE` file has the terms).
+ Its attribution notice:
+
+ > This work includes or was produced using ShapleyMcg, created by Brandon M. Music
+ > (https://github.com/brandonmmusic-max/shapleymcg). ShapleyMcg is licensed under the ShapleyMcg License v1.0, an
+ > attribution-required license that grants no rights to the person known as "0xSero." Use of ShapleyMcg without
+ > this attribution is unlicensed.
+- **[IncoAI](https://huggingface.co/incoai)**: the DFlash2 drafter,
+ [`incoai/GLM-5.3-Flash-DFlash2`](https://huggingface.co/incoai/GLM-5.3-Flash-DFlash2) (**CC BY-NC-ND 4.0**:
+ non-commercial use, no derivatives). Downloaded from its source, never redistributed here.
+
+## 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 itself builds on, and credits in its
+ [third-party notices](https://github.com/ashhart/TensorFold/blob/v0.5.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
+ [z-lab/dflash](https://github.com/z-lab/dflash) (Z Lab, MIT), whose DFlash2 architecture its drafter ports.
+
+## Patches
+
+- `0003-glm-vision`: GLM's image and video processors (resize with pad, 2 fps frame choice, prompt layout) and vision
+ tower, checked bit for bit against Hugging Face [transformers](https://github.com/huggingface/transformers) 5.17
+ (Apache 2.0), the reference they follow; builds on TensorFold's Qwen image pipeline.
+- `0006-cuda-roce-allgather`: the one-shot RoCE all-gather (`COMM=roce`) is the "RoCEnante" transport of
+ **[b12x](https://github.com/local-inference-lab/b12x)** by local-inference-lab (Apache 2.0): its C proxy
+ (`roce_proxy.c`) used as is, its CuTe all-gather kernel reimplemented in CUDA C++ (`roce.cu`).
+- `0012-glm-kda-chunked`, `0014-glm-kda-chunked-gb10`, `0042-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
+ 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
+ [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
+ [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
+ [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`).
+
+## Runtime stack
+
+- **[NVIDIA PyTorch container](https://catalog.ngc.nvidia.com/orgs/nvidia/containers/pytorch)**
+ (`nvcr.io/nvidia/pytorch:26.07-py3`), the base of the image, with NVIDIA's CUDA, cuDNN, cuBLAS, NCCL and related
+ libraries. Governed by the NVIDIA Software License Agreement and the Product-Specific Terms for NVIDIA AI Products.
+- **[PyTorch](https://pytorch.org/)** (BSD-3-Clause): tensors, CUDA streams and the C++ extension builder that compiles
+ the patches' CUDA kernels.
+- **[Triton](https://github.com/triton-lang/triton)** (MIT): the language many of TensorFold's CUDA kernels are
+ written in.
+- **[NCCL](https://github.com/NVIDIA/nccl)** (BSD-3-Clause) and **[rdma-core](https://github.com/linux-rdma/rdma-core)**
+ (libibverbs, GPL-2.0 / BSD-2-Clause): the two ranks' exchanges over the Sparks' ConnectX-7 RoCE link.
+- **[PyAV](https://github.com/PyAV-Org/PyAV)** (BSD-3-Clause) and **[FFmpeg](https://ffmpeg.org/)** (LGPL): video
+ decoding. **[Pillow](https://python-pillow.org/)** (MIT-CMU): image decoding.
+- **[xgrammar](https://github.com/mlc-ai/xgrammar)** (Apache 2.0): structured outputs (`response_format` and the
+ `guided_*` fields).
+- **[Hugging Face Hub](https://huggingface.co/)**: model hosting, the `hf` CLI and `huggingface_hub` (Apache 2.0), and
+ the [safetensors](https://github.com/huggingface/safetensors) format (Apache 2.0) the checkpoint ships in.
+- **[Docker](https://www.docker.com/)** and the
+ **[NVIDIA Container Toolkit](https://github.com/NVIDIA/nvidia-container-toolkit)** (Apache 2.0): running the server
+ on the GPU in a container.
+
+## Hardware
+
+- **[NVIDIA DGX Spark](https://www.nvidia.com/en-us/products/workstations/dgx-spark/)** (GB10 Grace Blackwell,
+ 128 GB unified memory), two of them linked by their ConnectX-7 ports: every number in the README was measured there.
+
+If you believe something here is missing or credited wrongly, please open an issue.
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..d645695
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,202 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/NOTICE b/NOTICE
new file mode 100644
index 0000000..13d63f1
--- /dev/null
+++ b/NOTICE
@@ -0,0 +1,113 @@
+GLM-5.3-Flash EXL3 on 2x DGX Spark with TensorFold
+Copyright 2026 MiaAI-Lab
+
+This project's own code, scripts and documentation are licensed under the Apache License, Version 2.0 (see
+LICENSE). If you redistribute this project or a modified version of it, keep this NOTICE file and state what you
+changed (Apache-2.0, section 4).
+
+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
+ 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:
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in all
+ copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ 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.
+
+b12x
+ https://github.com/local-inference-lab/b12x
+ Copyright the b12x contributors (local-inference-lab). Apache License, Version 2.0.
+ patches/0006-cuda-roce-allgather.patch: tensorfold/cuda/roce_proxy.c is b12x's RDMA proxy
+ (b12x/comm/roce/_roce_proxy.c at commit 8a99d639410e39d5f39cb4037675331beceea1d4), used as is except its header;
+ tensorfold/cuda/roce.cu reimplements b12x's CuTe DSL all-gather kernel (b12x/comm/roce/_allgather_cute.py at the
+ same commit) in CUDA C++, with the same stages and memory orderings.
+
+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:
+ - 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
+ server's call ids and by a signature of the calls). Changed here: the signature covers the whole conversation
+ before the calls, not only the last user message, so a reply is only ever put back into the conversation it
+ 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.
+ 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
+ (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
+ before the forward returns; a budget a site; a 4-bit matrix's chunk heads for one-wave launches; the shared
+ expert run before the routed experts while it is on. Changed here: hooks in this project's forward
+ (single-stream and batched multi-stream verify windows, captured and eager); one device table of pre-split
+ (address, bytes) pieces for every site, each site's grid sized at load, one kernel for the three mechanisms;
+ 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
+ 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,
+ the first steps' words issued before the member rows reach shared memory. Changed here: built into this
+ project's decode kernel (its expert plan, fused down / gate-up epilogues and per-row input rotation kept), ring
+ depth 1, 2 or 4 as a template parameter, no probe or PDL variants.
+
+Model files (downloaded from Hugging Face by scripts/prepare.sh; not included in this repository or its image)
+ The checkpoint, Mia-AiLab/GLM-5.3-Flash-EXL3-TR3-4bpw (a byte-identical mirror of
+ brandonmusic/GLM-5.3-Flash-tr3-4bpw), is under the ShapleyMcg License 1.0, which requires this attribution:
+
+ This work includes or was produced using ShapleyMcg, created by Brandon M. Music
+ (https://github.com/brandonmmusic-max/shapleymcg). ShapleyMcg is licensed under the ShapleyMcg License v1.0, an
+ attribution-required license that grants no rights to the person known as "0xSero." Use of ShapleyMcg without
+ this attribution is unlicensed.
+
+ The base model, zai-org/GLM-5.3-Flash, is under the license on its model card.
+ The DFlash2 drafter, incoai/GLM-5.3-Flash-DFlash2, is licensed CC BY-NC-ND 4.0: non-commercial use only, no
+ derivatives (commercial licensing: [email protected], per its model card). DRAFTER=mtp serves without it.
+
+Third-party software in the image
+ The prebuilt image (and the one scripts/prepare.sh builds) is based on NVIDIA's PyTorch container
+ nvcr.io/nvidia/pytorch:26.07-py3, redistributed as a value-added runtime image. The NVIDIA software in it is
+ governed by the NVIDIA Software License Agreement
+ (https://www.nvidia.com/en-us/agreements/enterprise-software/nvidia-software-license-agreement/) and the
+ Product-Specific Terms for NVIDIA AI Products
+ (https://www.nvidia.com/en-us/agreements/enterprise-software/product-specific-terms-for-ai-products/), which the
+ container prints at every start; by pulling or running the image you accept them. The image also contains PyAV
+ (BSD) with its FFmpeg libraries (LGPL) and xgrammar (Apache 2.0). This project's Apache License covers its own
+ work only (as described above), not the software in the image.
+
+See CREDITS.md for everyone this project builds on.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..528e4b1
--- /dev/null
+++ b/README.md
@@ -0,0 +1,419 @@
+<h1 align="center">GLM-5.3-Flash EXL3 on 2x DGX Spark with TensorFold</h1>
+
+<p align="center">
+ <sub>by <a href="https://x.com/MiaAI_lab">Mia's AI Lab</a></sub>
+ <br><br>
+ <a href="https://github.com/sponsors/MiaAI-Lab" target="_blank" rel="noopener noreferrer" style="display:inline-block;margin:0 8px;vertical-align:middle;"><img src="https://img.shields.io/badge/Sponsor%20me%20on%20GitHub-181717?style=for-the-badge&logo=githubsponsors&logoColor=white" alt="Sponsor me on GitHub" height="28" style="height:28px;width:auto;vertical-align:middle;border:0;" /></a>
+ <a href="https://x.com/MiaAI_lab" target="_blank" rel="noopener noreferrer" style="display:inline-block;margin:0 8px;vertical-align:middle;"><img src="https://img.shields.io/badge/Follow%20me%20on%20X-000000?style=for-the-badge&logo=x&logoColor=white" alt="Follow Mia on X" height="28" style="height:28px;width:auto;vertical-align:middle;border:0;" /></a>
+</p>
+
+<p align="center">
+ <img src=".github/image.png" alt="GLM-5.3 Flash EXL3 on TensorFold, Dual DGX Sparks" width="100%">
+</p>
+
+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)
+in NVIDIA's PyTorch container, plus 52 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`.
+
+- Checkpoint: [`Mia-AiLab/GLM-5.3-Flash-EXL3-TR3-4bpw`](https://huggingface.co/Mia-AiLab/GLM-5.3-Flash-EXL3-TR3-4bpw)
+ (EXL3 routed experts at 4 bits a weight, BF16 elsewhere, ~176 GB), a byte-identical mirror of
+ [`brandonmusic/GLM-5.3-Flash-tr3-4bpw`](https://huggingface.co/brandonmusic/GLM-5.3-Flash-tr3-4bpw)
+- 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.7M tokens** (2,684,928 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
+
+## Performance
+
+Two DGX Sparks at the default configuration (4 streams, 1,048,576-token window, FP8 KV cache, 4-bit dense weights,
+DFlash2 plus copy drafts, vision on), with the GPU clocks capped at 2,200 MHz. Decode and prefill were measured with
+[sparkDash](https://github.com/MiaAI-Lab/sparkDash) through the OpenAI API, from another machine on the network.
+
+**Decode** (aggregate across the concurrent requests, per request, and time to first token)
+
+| Concurrent requests | Prose | Prose, per request | TTFT | Structured | Structured, per request | TTFT |
+| ---: | ---: | ---: | ---: | ---: | ---: | ---: |
+| 1 | 60.4 tok/s | 60.4 tok/s | 170 ms | 114.7 tok/s | 114.7 tok/s | 149 ms |
+| 2 | 79.2 tok/s | 40.4 tok/s | 269 ms | 147.6 tok/s | 77.1 tok/s | 295 ms |
+| 3 | 89.5 tok/s | 30.6 tok/s | 330 ms | 196.3 tok/s | 67.4 tok/s | 317 ms |
+| 4 | 108.8 tok/s | 27.9 tok/s | 340 ms | 227.9 tok/s | 61.1 tok/s | 415 ms |
+
+Replies served 4 at a time are identical to the same requests served one at a time (11 of 11 cases staggered, and 11
+of 11 sent in a burst).
+
+**Prefill**
+
+| Prompt | Prefill | Time to first token |
+| ---: | ---: | ---: |
+| 8,219 tokens | 1,952.2 tok/s | 4.21 s |
+| 16,407 tokens | 1,973.5 tok/s | 8.31 s |
+| 32,790 tokens | 1,978.9 tok/s | 16.57 s |
+| 65,563 tokens | 1,942.5 tok/s | 33.75 s |
+| 131,099 tokens | 1,837.9 tok/s | 71.33 s |
+| 262,170 tokens | 1,641.7 tok/s | 159.69 s |
+| 981,841 tokens (needle in a haystack) | 1,015 tok/s | 967 s, needle found |
+
+**Prompt reuse** (the server resumes from a kept prompt state instead of prefilling, with the same reply)
+
+| Prompt | First time | Next time |
+| --- | ---: | ---: |
+| An identical 64k-token prompt, sent again | 34 s | under 0.07 s |
+| A new conversation with the same 7.9k-token system prompt | 4.24 s | 0.13 s |
+
+**Quality** (FP8 KV cache and 4-bit dense weights, see [Checks](#checks); measured on a build with identical replies)
+
+| Benchmark | Score |
+| --- | ---: |
+| GSM8K (250 problems) | 98.0% |
+| HumanEval (164 problems) | 97.6% |
+
+## Requirements
+
+- **Two DGX Sparks** (or two GB10 systems with 128 GB unified memory), with nothing else large on their GPUs: each
+ needs ~110 GiB free memory when the server starts (`start.sh` warns below that; stop other GPU work).
+- **A direct ConnectX-7 link:** a QSFP cable between the CX7 ports and an IPv4 address on each end in one private
+ subnet (e.g. `192.0.2.1/24` and `192.0.2.2/24`; `ping` must work), with a RoCE v2 GID (`start.sh` checks). With
+ both ports cabled and addressed, both are used (a prompt chunk's all-gather is ~1.8x faster on two rails).
+- **Key-based ssh** from the first Spark (the head, which runs `./start.sh` and the API) to the second (the worker):
+ `ssh-copy-id user@<worker>` (after `ssh-keygen -t ed25519` if you have no key); check with
+ `ssh -o BatchMode=yes user@<worker> true`.
+- Docker with the NVIDIA container runtime, your user in the `docker` group, and `rsync`, on both Sparks.
+- **Disk, on each Spark:** ~205 GB: ~176 GB (164 GiB) for the checkpoint and ~2.3 GB for DFlash2 under
+ `~/.cache/huggingface`, ~25 GB for the image under Docker's root. `prepare.sh` wants 180 GB free for the download
+ (`MIN_FREE_GB`) and 35 GB under Docker's root (`IMAGE_FREE_GB`; the sum when they share a filesystem), and checks the
+ worker before the copy.
+- Optional: the `hf` CLI on the head (faster download) and a Hugging Face token (`~/.cache/huggingface/token` or
+ `HF_TOKEN`).
+
+## Quick start
+
+<p align="center">
+ <img src=".github/ascii.png" alt="start.sh banner: TensorFold ribbon and MIA AI LAB, GLM-5.3 Flash EXL3 · Dual DGX Sparks" width="100%">
+</p>
+
+On the head:
+
+```bash
+git clone https://github.com/MiaAI-Lab/GLM-5.3-Flash-EXL3-2x-DGX-Sparks-TensorFold.git
+cd GLM-5.3-Flash-EXL3-2x-DGX-Sparks-TensorFold
+cp scripts/local.sh.example scripts/local.sh # set [email protected] in it (and FABRIC_PEER, see below)
+./start.sh
+```
+
+`WORKER` is the worker's ssh target. The ranks talk over the route to it: if it is on another network than the link,
+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`).
+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.
+
+Any OpenAI client works with `base_url = "http://<head-address>:8888/v1"` and the model `GLM-5.3-Flash-EXL3`. The model
+thinks before it answers (`reasoning_content`), so give replies enough `max_tokens`.
+
+```bash
+curl -s http://<head-address>:8888/v1/models
+curl -s http://<head-address>:8888/v1/chat/completions -H 'Content-Type: application/json' -d '{
+ "model": "GLM-5.3-Flash-EXL3",
+ "messages": [{"role": "user", "content": "Write a Python fibonacci function."}],
+ "max_tokens": 2000
+}'
+
+./start.sh restart # restart both ranks, e.g. after changing a setting
+./stop.sh # stop both ranks and free their GPU memory
+docker logs -f glm53-flash-tf # rank 0's log (here)
+ssh <worker> docker logs -f glm53-flash-tf # rank 1's log (why it exited, if it did)
+curl -s http://<head-address>:8888/health # busy flag, streams, free pool tokens
+```
+
+If `start.sh` stops at a check:
+
+| Message | What to do |
+| --- | --- |
+| `only N GiB memory available` | other GPU work runs on that Spark: stop it (`docker ps`) and restart |
+| `no RoCE device or RoCE v2 GID for the link` / `no route from this node to ...` | the route to the worker does not go over the CX7 port: set `FABRIC_PEER` to the worker's CX7 address and check both ends are addressed (`ip -4 addr`) |
+| `the worker's .../hub is not writable` | a container left it root-owned: fix its ownership on the worker |
+
+## Images and video
+
+GLM's own vision tower runs on the head (rank 0: 1.05 GiB of bf16 weights and 0.75 GiB of workspace). Send images and
+videos as OpenAI-style content parts in a user message:
+
+```bash
+IMG=$(base64 -w0 photo.jpg)
+curl -s http://<head-address>:8888/v1/chat/completions -H 'Content-Type: application/json' -d '{
+ "model": "GLM-5.3-Flash-EXL3",
+ "messages": [{"role": "user", "content": [
+ {"type": "image_url", "image_url": {"url": "data:image/jpeg;base64,'"$IMG"'"}},
+ {"type": "text", "text": "What is in this picture?"}]}],
+ "max_tokens": 2000
+}'
+```
+
+A video is a `video_url` part (`{"type": "video_url", "video_url": {"url": "data:video/mp4;base64,..."}}`).
+
+| | Images | Videos |
+| --- | --- | --- |
+| Formats | JPEG, PNG, WebP | MP4, WebM, MOV, MKV (anything FFmpeg decodes) |
+| Per request | up to 4, 10 MB each, 20 MB in all | up to 2, 64 MB each, 96 MB in all, up to an hour of footage |
+| Tokens | at most 2,048 a picture (`TENSORFOLD_GLM_IMAGE_TOKENS`; a 1080p picture takes 2,040) | 2 frames a second, at most 128 frames spread over the whole clip (`TENSORFOLD_GLM_VIDEO_FRAMES`), at most 16,384 tokens a clip (`TENSORFOLD_GLM_VIDEO_TOKENS`) |
+
+By default only data URLs are accepted; `VISION_URLS=1` also lets the server fetch public `https://` URLs.
+`VISION=0` serves text only and leaves the tower's ~1.8 GiB on rank 0 to the cache.
+
+## What `start.sh` and `scripts/prepare.sh` do
+
+**`./start.sh`** works in five steps, each shown as it runs:
+
+1. **Setup:** `scripts/prepare.sh`, when the setup is not ready on both Sparks (first run, new patches, another
+ model, drafter, revision, image or worker).
+2. **Checks:** the arguments (TensorFold's own parser), the link, the previous server (stopped on `restart`, or when
+ only one rank is up; a stopped container left from an earlier run is removed), the port, free memory (a warning
+ below ~110 GiB on either Spark).
+3. **Launch:** rank 1 on the worker over ssh, then rank 0 and the API here, with the settings from `scripts/config.sh`.
+4. **Loading:** rank 0's log as it comes, and every 15 s the elapsed time and how much of the startup estimate is on
+ each Spark's GPU; if a rank stops, both ranks' last log lines and why.
+5. **Smoke test:** one chat completion through both ranks, then the LIVE message and the endpoint.
+
+A running server is left alone; `./start.sh restart` stops it only after the setup and argument check pass, so a
+typo leaves it running (running requests are cut off; `stop.sh` warns). Extra arguments go to `tensorfold serve` on
+both ranks after the defaults, so they win (`./start.sh restart --max-tokens 16384`); `./start.sh --help` lists all.
+`FOREGROUND=1 ./start.sh` stays attached to rank 0's log and exits with its exit code (for a systemd unit), without
+the progress lines, the window retry or the smoke test; when either rank ends, it stops the other one.
+
+**`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
+ (video decoding) and xgrammar (structured outputs), on NVIDIA's `nvcr.io/nvidia/pytorch:26.07-py3`. It first
+ pulls `ghcr.io/miaai-lab/glm-5.3-flash-exl3-2x-dgx-sparks-tensorfold:v0.5.0-<image hash>` (the hash covers the
+ patches and those pip packages); without that tag (e.g. after you change `patches/`), or with `PULL=0`, it builds.
+3. The same image on the worker: pulled, else streamed from the head (`docker save | docker load`), checked identical.
+4. The checkpoint, and DFlash2 with `DRAFTER=dflash2`, downloaded into `~/.cache/huggingface` on the head at their
+ pinned revisions (the checkpoint checked with `tensorfold info`), then copied to the worker with `rsync` over ssh
+ and checked file by file. Both resume.
+
+```bash
+scripts/prepare.sh # set up both Sparks without starting the server
+scripts/prepare.sh --rebuild # rebuild the image from scratch
+PREPARE=1 ./start.sh restart # force prepare.sh, then restart; PREPARE=0 skips the check
+```
+
+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).
+
+## KV pool and memory
+
+GLM-5.3-Flash keeps a compressed latent cache (DSA) and the sparse indexer's pooled keys for every token, plus small
+recurrent states for its linear-attention (KDA) layers. With `PARALLEL` above 1, all requests draw their per-token
+caches from **one shared pool**:
+
+| | Default |
+| --- | ---: |
+| 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` 11 GiB a Spark beyond the window) | **2,684,928 tokens** at the measured start (~2.1-2.7M depending on free memory) |
+| Rank 0's startup estimate | 88.09 GiB |
+| Free memory (`MemAvailable`) at idle | 8.2 GiB on rank 0, 11.8 GiB on rank 1 |
+| Lowest free memory under a 1M-token prompt | 6.3 GiB on rank 0, 10.8 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 ~450k. 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:
+
+| Setting | Window | Note |
+| --- | ---: | --- |
+| `KV=bf16` | 196,608 | the exact cache; 163,840 with `VISION=1` and `DENSE=fp8` or `bf16` (the tower costs rank 0 ~66k tokens of window) |
+| `KV=bf16 DRAFTER=mtp` | 524,288 | one request at a time |
+| `CONTEXT=0` | the largest that fits | no memory is left to keep other conversations' prompts |
+
+## Configuration
+
+Every setting lives in [`scripts/config.sh`](scripts/config.sh). Set one for a single run from the environment
+(`PARALLEL=2 ./start.sh restart`), or keep it in `scripts/local.sh` (sourced as bash) or in a `.env` file next to
+`start.sh` (plain `KEY=value` lines, read, never run); both files are yours, not the repository's. The first that
+sets a value wins: the environment, then `scripts/local.sh`, then `.env`, then the default.
+
+| Variable | Default | Meaning |
+| --- | --- | --- |
+| `WORKER` / `FABRIC_PEER` | empty | the worker's ssh target (`user@<address>`), and its CX7 address when `WORKER` is on another network |
+| `MASTER_PORT` | `29551` | the ranks' rendezvous port (keep it on the private link) |
+| `PARALLEL` | `4` (`1` with `DRAFTER=mtp`) | requests decoded together, 1 to 4 (above 1 needs `DRAFTER=dflash2`) |
+| `CONTEXT` | `1048576` | prompt + reply window per request (with `KV=fp8`; other defaults in [KV pool and memory](#kv-pool-and-memory)); `0`: the largest that fits |
+| `KV` | `fp8` | `fp8` or `bf16` (exact, shorter window) DSA latent cache and indexer keys |
+| `KV_POOL_GIB` / `MEMORY_RESERVE_GIB` | `11` / `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-6.3 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) |
+| `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 |
+| `THINKING` | `1` | think before answering by default; `0` answers directly unless a request asks to think |
+| `VISION` / `VISION_URLS` | `1` / `0` | image and video input; `1` also accepts public `https://` URLs |
+| `COMM` | `roce` | the ranks' small all-gathers as one-shot RDMA writes over the RoCE link; `nccl`: NCCL for all |
+| `SPLIT` | `1` | prompt chunks' hyper-connection work split between the Sparks, its exchanges overlapped with the next rows' work |
+| `KDA_CHUNKED` | `1` | KDA prompt chunks in chunked (WY) form, one CUDA kernel |
+| `TF_GLM_L2PF` | `1` | L2 prefetch in decode: the weights the next kernels read brought into L2 during each layer's all-gathers; `0`: off |
+| `TF_GLM_EXL3_LOADS` | `nc` | the decode expert kernel's trellis as 16-byte non-coherent loads a step ahead (`nc2` / `nc4`: 2 or 4 steps); `0`: TensorFold's 32-bit loads |
+| `TF_ROCE_MAX_KB` | `512` | the largest all-gather (KiB) sent over RoCE with `COMM=roce` (TensorFold's default: 256); 512 covers the 17-32-row verify windows of concurrent requests |
+| `TF_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 |
+| `TENSORFOLD_GLM_IMAGE_TOKENS` / `_VIDEO_TOKENS` / `_VIDEO_FRAMES` | `2048` / `16384` / `128` | a picture's and a clip's token caps, and a clip's frames |
+| `PREPARE` / `PULL` | `auto` / `1` | `start.sh` runs `scripts/prepare.sh` when needed (`1` always, `0` never); `prepare.sh` tries the prebuilt image first (`0`: always build locally) |
+| `WAIT_TIMEOUT` / `STOP_TIMEOUT` | `1800` / `30` | seconds `start.sh` waits for the server, and `stop.sh` gives it to shut down |
+
+Speed settings' measured effects: [What the patches change](#what-the-patches-change). Any `TENSORFOLD_*`,
+`TF_GLM_*` or `TF_ROCE_*` variable is passed to both ranks (export it in `scripts/local.sh`; `.env` lines are).
+
+**Revision pins.** The checkpoint and DFlash2 are pinned to the revisions this recipe was measured with
+(`MODEL_REVISION`, `DFLASH2_REVISION`): both ranks serve exactly those from the local cache, and a new upstream commit
+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
+`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
+server reach Hugging Face; by default it serves from the local cache only).
+
+### Thinking and sampling
+
+The checkpoint's own sampling defaults apply (temperature 1.0, top_p 0.95). Per request:
+
+- `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.
+- 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
+ thought until `max_tokens`: give more, or use `reasoning_effort: "low"`.
+
+### API notes
+
+- Endpoints: `/v1/chat/completions`, `/v1/completions`, `/v1/responses`, `/v1/models`, `/tokenize` and
+ `/detokenize` (also under `/v1/`), `/health`, and Prometheus `/metrics` (TensorFold v0.6.0's request counters,
+ latency and time-to-first-token histograms, plus `/health`'s figures as `tensorfold_health:` metrics). No Anthropic
+ `/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,
+ `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).
+- **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.
+- 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,
+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 |
+| 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`, `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; 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 |
+
+## Checks
+
+**Outputs.** Drafts only propose: every drafted token is checked against the model's own keyed sample, so drafted
+replies equal TensorFold's serial, one-token-at-a-time decoding (send `"draft": false` for that reference). Replies
+served 4 at a time equal the same requests served alone; `COMM=roce`, `SPLIT=1`, `TF_GLM_L2PF` and `TF_GLM_EXL3_LOADS`
+move the same bits. Three defaults are not exact against the checkpoint in bf16, for speed and the 1M window:
+`DENSE=q4` and `KV=fp8` are lossy (quality and the 1M needle: [Performance](#performance)), and `KDA_CHUNKED=1` is
+close to the serial kernel but not its bits.
+`DENSE=bf16 KV=bf16 KDA_CHUNKED=0` serves the checkpoint as it is, with a shorter window ([KV pool and memory](#kv-pool-and-memory)).
+
+The scripts in `tools/` talk to the running server (`API_URL`, default `http://127.0.0.1:8888`; or just `PORT`),
+from the head or another machine (`API_URL=http://<head-address>:8888 tools/bench.py`):
+
+| Script | What it does |
+| --- | --- |
+| `tools/bench.py [label]` | prefill at ~0.8k / 3.3k / 13k / 52k tokens (fresh random prompts) and a short decode check |
+| `tools/needle.py [label] [size]` | hides a passphrase in a ~195k-token prompt (the prompt comes out at ~0.8 x `size` tokens) and checks the model returns it |
+| `tools/toolcheck.py` | makes a tool call with an array parameter and checks it comes back as a JSON array |
+
+## Repository layout
+
+```
+start.sh set up (first run) and start both ranks
+stop.sh stop them
+scripts/ config.sh (all settings), local.sh.example (this setup's WORKER), prepare.sh (image + checkpoint on
+ both Sparks), nodes.sh (ssh and the RoCE link), publish-image.sh (push the image to GHCR),
+ banner.sh (start.sh's banner)
+patches/ patches baked into the image
+tools/ benchmark and checks
+CREDITS.md who and what this builds on
+LICENSE Apache License 2.0
+NOTICE third-party notices (TensorFold's MIT and Apache-2.0 notices, b12x, glm53-tensorfold-spark, ShapleyMcg)
+```
+
+## 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 are downloaded from Hugging Face and are not part of this repository:
+
+- **The checkpoint** is under the ShapleyMcg License 1.0, an attribution-required license; its model card and
+ `LICENSE` file have the terms. Its attribution notice:
+
+ > This work includes or was produced using ShapleyMcg, created by Brandon M. Music
+ > (https://github.com/brandonmmusic-max/shapleymcg). ShapleyMcg is licensed under the ShapleyMcg License v1.0, an
+ > attribution-required license that grants no rights to the person known as "0xSero." Use of ShapleyMcg without
+ > this attribution is unlicensed.
+
+- **The base model** [GLM-5.3-Flash](https://huggingface.co/zai-org/GLM-5.3-Flash) is under the license on its model
+ card.
+- **The DFlash2 drafter** is under [CC BY-NC-ND 4.0](https://creativecommons.org/licenses/by-nc-nd/4.0/),
+ non-commercial use only (commercial licensing: [email protected]); `DRAFTER=mtp` serves without it.
+
+**Third-party software in the image.** The prebuilt image (and the one `scripts/prepare.sh` builds) is based on
+NVIDIA's PyTorch container `nvcr.io/nvidia/pytorch:26.07-py3`, redistributed as a value-added runtime image. The NVIDIA
+software in it is governed by the [NVIDIA Software License Agreement](https://www.nvidia.com/en-us/agreements/enterprise-software/nvidia-software-license-agreement/)
+and the [Product-Specific Terms for NVIDIA AI Products](https://www.nvidia.com/en-us/agreements/enterprise-software/product-specific-terms-for-ai-products/),
+which the container prints at every start; by pulling or running the image you accept them. The image also contains
+PyAV (BSD) with its FFmpeg libraries (LGPL) and xgrammar (Apache 2.0). The Apache License above covers this
+repository's own work only.
+
+## Credits
+
+Built on [TensorFold](https://github.com/ashhart/TensorFold) by Ash Hart ([ashhart](https://github.com/ashhart)),
+[GLM-5.3-Flash](https://huggingface.co/zai-org/GLM-5.3-Flash) by Z.ai, the EXL3 quantization by [Brandon M.
+Music](https://huggingface.co/brandonmusic) (ShapleyMcg), the DFlash2 drafter by
+[IncoAI](https://huggingface.co/incoai), b12x's RoCE transport by local-inference-lab, and code from
+[glm53-tensorfold-spark](https://github.com/jayleaton/glm53-tensorfold-spark) by Jay Leaton (tool calling, L2 prefetch,
+expert loads). The full list, including the runtime stack and licenses, is in [`CREDITS.md`](CREDITS.md).
diff --git a/patches/0001-glm-exl3-prompt-experts.patch b/patches/0001-glm-exl3-prompt-experts.patch
new file mode 100644
index 0000000..9f4bb99
--- /dev/null
+++ b/patches/0001-glm-exl3-prompt-experts.patch
@@ -0,0 +1,214 @@
+diff --git tensorfold/families/glm5_next/cuda/exl3.cpp tensorfold/families/glm5_next/cuda/exl3.cpp
+index a9931e7..789d20e 100644
+--- tensorfold/families/glm5_next/cuda/exl3.cpp
++++ tensorfold/families/glm5_next/cuda/exl3.cpp
+@@ -3,7 +3,7 @@
+
+ void exl3_grouped_cuda(const at::Tensor&, const at::Tensor&, const at::Tensor&, const at::Tensor&, const at::Tensor&,
+ const at::Tensor&, const at::Tensor&, at::Tensor&, int64_t, int64_t, int64_t, int64_t, int64_t,
+- int64_t, int64_t, int64_t, int64_t);
++ int64_t, int64_t, int64_t, int64_t, bool, bool);
+ void exl3_rot_in_cuda(const at::Tensor&, int64_t, const at::Tensor&, const at::Tensor&, const at::Tensor&, at::Tensor&,
+ at::Tensor&, int64_t, int64_t, int64_t);
+ void exl3_gateup_epilogue_cuda(const at::Tensor&, const at::Tensor&, const at::Tensor&, const at::Tensor&,
+@@ -18,7 +18,8 @@ static void check(const at::Tensor& x, at::ScalarType t, const char* name) {
+
+ void grouped(const at::Tensor& X0, const at::Tensor& X1, const at::Tensor& T0, const at::Tensor& T1,
+ const at::Tensor& items, const at::Tensor& counts, const at::Tensor& members, at::Tensor Z, int64_t mats,
+- int64_t K, int64_t N, int64_t P, int64_t SK, int64_t max_items, int64_t nt, int64_t warps) {
++ int64_t K, int64_t N, int64_t P, int64_t SK, int64_t max_items, int64_t nt, int64_t warps, bool nfirst,
++ bool pf) {
+ const int64_t E = T0.size(0);
+ check(X0, at::kHalf, "X0");
+ check(X1, at::kHalf, "X1");
+@@ -30,7 +31,7 @@ void grouped(const at::Tensor& X0, const at::Tensor& X1, const at::Tensor& T0, c
+ check(Z, at::kFloat, "Z");
+ TORCH_CHECK(Z.numel() >= mats * SK * P * N, "Z too small");
+ c10::cuda::CUDAGuard guard(X0.device());
+- exl3_grouped_cuda(X0, X1, T0, T1, items, counts, members, Z, mats, K, N, P, SK, max_items, nt, warps, E);
++ exl3_grouped_cuda(X0, X1, T0, T1, items, counts, members, Z, mats, K, N, P, SK, max_items, nt, warps, E, nfirst, pf);
+ }
+
+ void rot_in(const at::Tensor& x, int64_t x_stride, const at::Tensor& pick, const at::Tensor& suh0,
+diff --git tensorfold/families/glm5_next/cuda/exl3.cu tensorfold/families/glm5_next/cuda/exl3.cu
+index 2514bdc..47cf55c 100644
+--- tensorfold/families/glm5_next/cuda/exl3.cu
++++ tensorfold/families/glm5_next/cuda/exl3.cu
+@@ -53,12 +53,14 @@ __device__ __forceinline__ uint32_t load_pair(const half* x, bool ok) {
+ }
+
+ // Grid (item, n block, mat * SK + split) -> Z[mat][split][pair][n]; warps sum fixed k ranges, added in warp order.
+-template <int NT, int W>
++template <int NT, int W, bool NFIRST, bool PF>
+ __global__ void __launch_bounds__(W * 32) grouped_kernel(
+ const half* __restrict__ X0, const half* __restrict__ X1, const uint32_t* __restrict__ T0,
+ const uint32_t* __restrict__ T1, const int* __restrict__ items, const int* __restrict__ counts,
+ const int* __restrict__ members, float* __restrict__ Z, int K, int N, int P, int SK, int E) {
+- const int item = blockIdx.x;
++ // NFIRST: the n blocks of an item are adjacent in launch order, so they read its rows while L2 holds them
++ const int item = NFIRST ? blockIdx.y : blockIdx.x;
++ const int nblock = NFIRST ? blockIdx.x : blockIdx.y;
+ if (item >= counts[0]) return;
+ const int e = items[3 * item], first = items[3 * item + 1], cnt = items[3 * item + 2];
+ if (e >= E) return; // the shared expert (id E) is not EXL3
+@@ -79,7 +81,7 @@ __global__ void __launch_bounds__(W * 32) grouped_kernel(
+
+ const int per_split = KT / SK, per_warp = per_split / W;
+ const int kt0 = split * per_split + warp * per_warp;
+- const int nt0 = blockIdx.y * NT;
++ const int nt0 = nblock * NT;
+ const uint32_t* tile = T + (((size_t)e * KT + kt0) * NTILES + nt0) * 32 + lane;
+
+ float acc[NT][2][4];
+@@ -90,21 +92,59 @@ __global__ void __launch_bounds__(W * 32) grouped_kernel(
+ #pragma unroll
+ for (int c = 0; c < 4; ++c) acc[i][h][c] = 0.f;
+
+- for (int kt = kt0; kt < kt0 + per_warp; ++kt) {
+- uint32_t words[NT];
++ if (PF) {
++ // the next k step's words and A fragments load while this one decodes and multiplies (the same mma order)
++ uint32_t words[NT], a[4];
+ #pragma unroll
+ for (int i = 0; i < NT; ++i) words[i] = __ldg(tile + i * 32);
+- const int k = kt * 16;
+- uint32_t a[4] = {load_pair(x0 + k, r0 >= 0), load_pair(x1 + k, r1 >= 0), load_pair(x0 + k + 8, r0 >= 0),
+- load_pair(x1 + k + 8, r1 >= 0)};
++ {
++ const int k = kt0 * 16;
++ a[0] = load_pair(x0 + k, r0 >= 0); a[1] = load_pair(x1 + k, r1 >= 0);
++ a[2] = load_pair(x0 + k + 8, r0 >= 0); a[3] = load_pair(x1 + k + 8, r1 >= 0);
++ }
++ for (int kt = kt0; kt < kt0 + per_warp; ++kt) {
++ uint32_t nw[NT], na[4];
++ const bool more = kt + 1 < kt0 + per_warp;
++ if (more) {
++ const uint32_t* next = tile + (size_t)NTILES * 32;
++#pragma unroll
++ for (int i = 0; i < NT; ++i) nw[i] = __ldg(next + i * 32);
++ const int k = (kt + 1) * 16;
++ na[0] = load_pair(x0 + k, r0 >= 0); na[1] = load_pair(x1 + k, r1 >= 0);
++ na[2] = load_pair(x0 + k + 8, r0 >= 0); na[3] = load_pair(x1 + k + 8, r1 >= 0);
++ }
++#pragma unroll
++ for (int i = 0; i < NT; ++i) {
++ uint32_t b0[2], b1[2];
++ decode_tile(words[i], lane, b0, b1);
++ mma16816(acc[i][0], a, b0);
++ mma16816(acc[i][1], a, b1);
++ }
++ if (more) {
++#pragma unroll
++ for (int i = 0; i < NT; ++i) words[i] = nw[i];
++#pragma unroll
++ for (int c = 0; c < 4; ++c) a[c] = na[c];
++ }
++ tile += (size_t)NTILES * 32;
++ }
++ } else {
++ for (int kt = kt0; kt < kt0 + per_warp; ++kt) {
++ uint32_t words[NT];
++#pragma unroll
++ for (int i = 0; i < NT; ++i) words[i] = __ldg(tile + i * 32);
++ const int k = kt * 16;
++ uint32_t a[4] = {load_pair(x0 + k, r0 >= 0), load_pair(x1 + k, r1 >= 0),
++ load_pair(x0 + k + 8, r0 >= 0), load_pair(x1 + k + 8, r1 >= 0)};
+ #pragma unroll
+- for (int i = 0; i < NT; ++i) {
+- uint32_t b0[2], b1[2];
+- decode_tile(words[i], lane, b0, b1);
+- mma16816(acc[i][0], a, b0);
+- mma16816(acc[i][1], a, b1);
++ for (int i = 0; i < NT; ++i) {
++ uint32_t b0[2], b1[2];
++ decode_tile(words[i], lane, b0, b1);
++ mma16816(acc[i][0], a, b0);
++ mma16816(acc[i][1], a, b1);
++ }
++ tile += (size_t)NTILES * 32;
+ }
+- tile += (size_t)NTILES * 32;
+ }
+
+ // warps' partial sums through shared memory, added in warp order
+@@ -240,19 +280,23 @@ __global__ void down_epilogue_kernel(const float* __restrict__ Z, const int* __r
+ void exl3_grouped_cuda(const at::Tensor& X0, const at::Tensor& X1, const at::Tensor& T0, const at::Tensor& T1,
+ const at::Tensor& items, const at::Tensor& counts, const at::Tensor& members, at::Tensor& Z,
+ int64_t mats, int64_t K, int64_t N, int64_t P, int64_t SK, int64_t max_items, int64_t nt,
+- int64_t warps, int64_t E) {
++ int64_t warps, int64_t E, bool nfirst, bool pf) {
+ TORCH_CHECK(K % (16 * SK * warps) == 0 && N % (16 * nt) == 0, "K and N must split evenly");
+- dim3 grid((unsigned)max_items, (unsigned)(N / (16 * nt)), (unsigned)(mats * SK));
++ dim3 grid = nfirst ? dim3((unsigned)(N / (16 * nt)), (unsigned)max_items, (unsigned)(mats * SK))
++ : dim3((unsigned)max_items, (unsigned)(N / (16 * nt)), (unsigned)(mats * SK));
+ auto stream = at::cuda::getCurrentCUDAStream();
+ auto x0 = reinterpret_cast<const half*>(X0.data_ptr());
+ auto x1 = reinterpret_cast<const half*>(X1.data_ptr());
+ auto t0 = reinterpret_cast<const uint32_t*>(T0.data_ptr());
+ auto t1 = reinterpret_cast<const uint32_t*>(T1.data_ptr());
+ #define LAUNCH(NT_, W_) \
+- grouped_kernel<NT_, W_><<<grid, W_ * 32, 0, stream>>>(x0, x1, t0, t1, items.data_ptr<int>(), \
+- counts.data_ptr<int>(), members.data_ptr<int>(), \
+- Z.data_ptr<float>(), (int)K, (int)N, (int)P, (int)SK, \
+- (int)E)
++ do { \
++ auto fn = nfirst ? (pf ? grouped_kernel<NT_, W_, true, true> : grouped_kernel<NT_, W_, true, false>) \
++ : (pf ? grouped_kernel<NT_, W_, false, true> : grouped_kernel<NT_, W_, false, false>); \
++ fn<<<grid, W_ * 32, 0, stream>>>(x0, x1, t0, t1, items.data_ptr<int>(), counts.data_ptr<int>(), \
++ members.data_ptr<int>(), Z.data_ptr<float>(), (int)K, (int)N, (int)P, \
++ (int)SK, (int)E); \
++ } while (0)
+ if (nt == 8 && warps == 4) LAUNCH(8, 4);
+ else if (nt == 4 && warps == 4) LAUNCH(4, 4);
+ else if (nt == 4 && warps == 8) LAUNCH(4, 8);
+diff --git tensorfold/families/glm5_next/cuda/exl3_mm.py tensorfold/families/glm5_next/cuda/exl3_mm.py
+index b816401..58e739d 100644
+--- tensorfold/families/glm5_next/cuda/exl3_mm.py
++++ tensorfold/families/glm5_next/cuda/exl3_mm.py
+@@ -13,6 +13,22 @@ from tensorfold.cuda import experts as grouped
+ # Gate/up and down tile counts, warps, and K splits stay fixed across row counts to preserve each row's bits.
+ GATEUP_CFG = (8, 4, 4)
+ DOWN_CFG = (8, 4, 1)
++# Prompt chunks launch an item's n blocks next to each other (TF_GLM_EXL3_NFIRST=0: the decode order), so they read
++# its rows while L2 still holds them: the same kernel and arithmetic, 2.3-2.5x faster at 4,096 rows.
++PROMPT_ROWS = 64 # rows from which a window takes the prompt order
++
++
++def _pf() -> bool:
++ """TF_GLM_EXL3_PF=0: no register prefetch in the expert kernel (the same bits either way)."""
++ import os
++
++ return os.environ.get("TF_GLM_EXL3_PF", "1") != "0"
++
++
++def _nfirst() -> bool:
++ import os
++
++ return os.environ.get("TF_GLM_EXL3_NFIRST", "1") != "0"
+
+
+ @lru_cache(maxsize=1)
+@@ -20,7 +36,7 @@ def _ext():
+ from tensorfold.cuda.build import load
+
+ here = Path(__file__).parent
+- return load(name="tensorfold_glm_exl3_v1", sources=[str(here / "exl3.cpp"), str(here / "exl3.cu")],
++ return load(name="tensorfold_glm_exl3_v9", sources=[str(here / "exl3.cpp"), str(here / "exl3.cu")],
+ extra_cuda_cflags=["-O3"], verbose=False)
+
+
+@@ -78,9 +94,12 @@ def routed(x: torch.Tensor, pick: torch.Tensor, plan: grouped.Plan, ex: Exl3Expe
+ D, NI = ex.dims, ex.width
+ items = grouped.max_items(R * slots, plan.experts)
+ ext.rot_in(x, x.stride(0), pick, ex.suh_g, ex.suh_u, s.xg, s.xu, R, D, slots)
++ nfirst = R >= PROMPT_ROWS and _nfirst()
+ nt, w, sk = GATEUP_CFG
+- ext.grouped(s.xg, s.xu, ex.gt, ex.ut, plan.items, plan.counts, plan.members, s.z, 2, D, NI, P, sk, items, nt, w)
++ ext.grouped(s.xg, s.xu, ex.gt, ex.ut, plan.items, plan.counts, plan.members, s.z, 2, D, NI, P, sk, items, nt,
++ w, nfirst, _pf())
+ ext.gateup_epilogue(s.z, pick, ex.svh_g, ex.svh_u, ex.suh_d, s.xd, R, P, NI, sk, slots, float(limit))
+ nt, w, sk = DOWN_CFG
+- ext.grouped(s.xd, s.xd, ex.dt, ex.dt, plan.items, plan.counts, plan.members, s.z, 1, NI, D, P, sk, items, nt, w)
++ ext.grouped(s.xd, s.xd, ex.dt, ex.dt, plan.items, plan.counts, plan.members, s.z, 1, NI, D, P, sk, items, nt,
++ w, nfirst, _pf())
+ ext.down_epilogue(s.z, pick, ex.svh_d, y, R, P, D, sk, slots)
diff --git a/patches/0002-glm-dense-fp8.patch b/patches/0002-glm-dense-fp8.patch
new file mode 100644
index 0000000..f600569
--- /dev/null
+++ b/patches/0002-glm-dense-fp8.patch
@@ -0,0 +1,318 @@
+diff --git tensorfold/families/glm5_next/cuda/engine.py tensorfold/families/glm5_next/cuda/engine.py
+index 43c1af4..3393fa0 100644
+--- tensorfold/families/glm5_next/cuda/engine.py
++++ tensorfold/families/glm5_next/cuda/engine.py
+@@ -111,10 +111,16 @@ class GlmEngine:
+ explicit = context is not None if context_explicit is None else bool(context_explicit)
+ from . import LATENT
+
++ from .qmm import dense_kind, fp8_weights
++
++ # TF_GLM_DENSE=fp8 (an EXL3 checkpoint): its BF16 matrices take a byte a value, which the estimate counts
++ weights_estimate = split_weights(rule)
++ if cfg.quant == "exl3" and dense_kind() == "fp8":
++ weights_estimate = fp8_weights(weights_estimate)
+ 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
+--- 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
+ k = layer.kda
+ li = st.kda_index[layer.index]
+ p = b.kproj[0, :R] if b.prefill else st.proj[li, :R]
+- mm(b, b.normed[:R], k.proj, b.xs[:R], p)
+- fa = p[:, k.fa_off:k.fa_off + 128]
+- ga = p[:, k.ga_off:k.ga_off + 128]
+ pre = b.prefill
+- 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])
++ with prof.timed("kda: projections"):
++ mm(b, b.normed[:R], k.proj, b.xs[:R], p)
++ fa = p[:, k.fa_off:k.fa_off + 128]
++ ga = p[:, k.ga_off:k.ga_off + 128]
++ 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])
++ 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 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)
+- return out_proj(w, b, out, k.o, None if pre else qmm.group_sums(out, b.kxs[:R]), R)
++ with prof.timed("kda: out + all-gather"):
++ return out_proj(w, b, out, k.o, None if pre else qmm.group_sums(out, b.kxs[:R]), R)
+
+
+ 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:
+ # EXL3: the routed slots through the trellis kernels, the shared expert (last slot) through BF16 matmuls
+ from . import exl3_mm
+
+- exl3_mm.routed(b.normed[:R], b.pick, b.plan, m.experts, b.exl3, b.ey.view(-1, c.hidden), R, c.limit)
++ 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
+- mm(b, b.normed[:R], s.gu, b.xs[:R], b.sgu[:R])
+- 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)
+- b.ey[:R, c.top_k].copy_(b.sy[:R])
+- glue.combine(b.ey[:R], b.wts[:R], b.part[:R])
+- return gather(w, b, R)
++ with prof.timed("moe: shared expert"):
++ mm(b, b.normed[:R], s.gu, b.xs[:R], b.sgu[:R])
++ 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"):
++ b.ey[:R, c.top_k].copy_(b.sy[:R])
++ glue.combine(b.ey[:R], b.wts[:R], b.part[:R])
++ with prof.timed("moe: all-gather"):
++ return gather(w, b, R)
+ with prof.timed("moe: gate/up"):
+ grouped.gate_up(b.normed[:R], m.experts, b.plan, b.eact, R)
+ with prof.timed("moe: down"):
+diff --git tensorfold/families/glm5_next/cuda/qmm.py tensorfold/families/glm5_next/cuda/qmm.py
+index a366806..827db2b 100644
+--- tensorfold/families/glm5_next/cuda/qmm.py
++++ tensorfold/families/glm5_next/cuda/qmm.py
+@@ -220,10 +220,12 @@ B16_CONFIG = {16: (4, 3), 32: (4, 3), 64: (4, 2), 128: (8, 2)}
+
+ def matmul(x: torch.Tensor, q: Q4 | B16, xs: torch.Tensor | None = None, *, out: torch.Tensor | None = None,
+ f32: bool = False, part: torch.Tensor | None = None) -> torch.Tensor:
+- """Multiply strided bf16 x by Q4 or BF16 q.T, returning bf16 or unrounded fp32 with f32; BF16 weights ignore xs."""
++ """Multiply strided bf16 x by Q4, BF16 or FP8 q.T, returning bf16 or unrounded fp32 with f32; BF16 and FP8 weights ignore xs."""
+
+ if isinstance(q, B16):
+ return _matmul_b16(x, q, out=out, f32=f32, part=part)
++ if isinstance(q, F8):
++ return _matmul_f8(x, q, out=out, f32=f32, part=part)
+ if x.shape[1] != q.k or x.stride(1) != 1 or x.dtype != torch.bfloat16:
+ raise ValueError(f"matmul: x {tuple(x.shape)} {x.dtype} does not match K={q.k}")
+ if out is not None and (out.shape != (x.shape[0], q.n) or not out.is_contiguous()):
+@@ -265,3 +267,141 @@ def _matmul_b16(x: torch.Tensor, q: B16, *, out: torch.Tensor | None, f32: bool,
+ total = m * q.n
+ _reduce[(triton.cdiv(total, 1024),)](part, out, total, SK=sk, BLOCK=1024, F32=f32, num_warps=4)
+ return out
++
++
++# -- FP8 weights (TF_GLM_DENSE=fp8): the checkpoint's BF16 matrices stored as e4m3 with an fp32 scale per row and
++# 128-column block, quantized once at load. Lossy (replies differ from BF16 weights); the activations stay bf16 and
++# the kernel keeps _bmm's structure (a row's bits never depend on the other rows), so drafted replies still equal
++# serial ones under it.
++F8_BLOCK = 128
++F8_MAX = 448.0
++
++
++@dataclass
++class F8:
++ """A BF16 matrix [n, k] held as FP8 e4m3 [n, k] and fp32 scales [n, k / 128]: W ~ q * scale."""
++
++ weight: torch.Tensor # [n, k] torch.float8_e4m3fn
++ scale: torch.Tensor # [n, k // 128] fp32
++ n: int
++ k: int
++
++ def nbytes(self) -> int:
++ return self.weight.numel() + self.scale.numel() * 4
++
++
++def make_f8(weight: torch.Tensor, rows: int = 8192) -> F8 | B16:
++ """Quantize a BF16 matrix a block of 128 columns at a time (absmax / 448 scale, round to nearest); a matrix whose
++ width is not a multiple of 128 stays BF16."""
++
++ n, k = weight.shape
++ if k % F8_BLOCK:
++ return make_b16(weight)
++ q = torch.empty((n, k), dtype=torch.float8_e4m3fn, device=weight.device)
++ scale = torch.empty((n, k // F8_BLOCK), dtype=torch.float32, device=weight.device)
++ for r in range(0, n, rows):
++ g = weight[r:r + rows].float().view(-1, k // F8_BLOCK, F8_BLOCK)
++ s = (g.abs().amax(-1) / F8_MAX).clamp_min(1e-30)
++ q[r:r + rows] = (g / s[..., None]).clamp(-F8_MAX, F8_MAX).view(-1, k).to(torch.float8_e4m3fn)
++ scale[r:r + rows] = s
++ return F8(q, scale, int(n), int(k))
++
++
++def stack_f8(parts: list[torch.Tensor]) -> F8 | B16:
++ return make_f8(torch.cat([p.to(torch.bfloat16) for p in parts]))
++
++
++def _fmm(X, W, S, OUT, PART, M, x_stride, N: tl.constexpr, K: tl.constexpr, SK: tl.constexpr, BM: tl.constexpr,
++ BLOCK_N: tl.constexpr, BK: tl.constexpr, F32: tl.constexpr):
++ """_bmm over FP8 weights: each BK step's product (bf16 inputs, fp32 sums) times its 128-column block's scales."""
++
++ PER: tl.constexpr = K // SK
++ KB: tl.constexpr = K // 128
++ pid_n = tl.program_id(1)
++ pid_s = tl.program_id(2)
++ rm = tl.program_id(0) * BM + tl.arange(0, BM)
++ rn = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
++ rk = tl.arange(0, BK)
++ m_ok = rm < M
++ n_ok = rn < N
++ acc = tl.zeros((BM, BLOCK_N), dtype=tl.float32)
++ for k0 in range(pid_s * PER, pid_s * PER + PER, BK):
++ x = tl.load(X + rm[:, None] * x_stride + (k0 + rk)[None, :], mask=m_ok[:, None], other=0.0)
++ w = tl.load(W + rn[:, None].to(tl.int64) * K + (k0 + rk)[None, :], mask=n_ok[:, None], other=0.0)
++ s = tl.load(S + rn.to(tl.int64) * KB + k0 // 128, mask=n_ok, other=0.0)
++ acc = acc + tl.dot(x, tl.trans(w.to(tl.bfloat16))) * s[None, :]
++ out_mask = m_ok[:, None] & n_ok[None, :]
++ if SK == 1:
++ if F32:
++ tl.store(OUT + rm[:, None] * N + rn[None, :], acc, mask=out_mask)
++ else:
++ tl.store(OUT + rm[:, None] * N + rn[None, :], acc.to(tl.bfloat16), mask=out_mask)
++ else:
++ tl.store(PART + (pid_s * M + rm[:, None]) * N + rn[None, :], acc, mask=out_mask)
++
++
++def _matmul_f8(x: torch.Tensor, q: F8, *, out: torch.Tensor | None, f32: bool,
++ part: torch.Tensor | None) -> torch.Tensor:
++ m, k = x.shape
++ if k != q.k or x.stride(1) != 1 or x.dtype != torch.bfloat16 or k % F8_BLOCK:
++ raise ValueError(f"matmul: x {tuple(x.shape)} {x.dtype} does not match K={q.k}")
++ bm = bucket(min(m, 128))
++ warps, stages = F8_CONFIG[bm]
++ sk = b16_split_k(q.n, q.k)
++ if out is None:
++ out = torch.empty((m, q.n), dtype=torch.float32 if f32 else torch.bfloat16, device=x.device)
++ elif out.shape != (m, q.n) or not out.is_contiguous():
++ raise ValueError(f"matmul: out {tuple(out.shape)} must be a contiguous ({m}, {q.n})")
++ if sk > 1:
++ need = sk * m * q.n
++ if part is None or part.numel() < need:
++ part = torch.empty((need,), dtype=torch.float32, device=x.device)
++ bn = F8_BN_DECODE if bm == 16 else F8_BN
++ grid = (triton.cdiv(m, bm), triton.cdiv(q.n, bn), sk)
++ _fmm[grid](x, q.weight, q.scale, out, part if sk > 1 else out, m, x.stride(0), N=q.n, K=k, SK=sk, BM=bm,
++ BLOCK_N=bn, BK=B16_BK, F32=f32, num_warps=warps, num_stages=stages)
++ if sk > 1:
++ total = m * q.n
++ _reduce[(triton.cdiv(total, 1024),)](part, out, total, SK=sk, BLOCK=1024, F32=f32, num_warps=4)
++ return out
++
++
++F8_BN = 64
++F8_BN_DECODE = 32 # decode windows (up to 16 rows): narrower column tiles, deeper pipeline (measured +8%)
++# (warps, stages) by row bucket; neither they nor the column tile change a row's bits
++F8_CONFIG = {16: (4, 6), 32: (4, 3), 64: (4, 2), 128: (8, 2)}
++
++
++def dense_kind() -> str:
++ """TF_GLM_DENSE: how an EXL3 checkpoint's BF16 (non-expert) weights are held: bf16 (as stored) or fp8."""
++
++ import os
++
++ kind = os.environ.get("TF_GLM_DENSE", "bf16")
++ if kind not in ("bf16", "fp8"):
++ raise ValueError(f"TF_GLM_DENSE is bf16 or fp8, not {kind!r}")
++ return kind
++
++
++# The matrices TF_GLM_DENSE=fp8 converts (weights.py's q4 / stack / head), for the startup memory estimate
++_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"
++ r"|wk|weights_proj|wq_b|gate_proj|up_proj|down_proj|eh_proj)\.weight|^lm_head\.weight)$")
++
++
++def fp8_weights(base):
++ """A split_weights transform that counts the matrices held as FP8 at a byte a value plus their block scales."""
++
++ def transform(name: str, info: dict) -> tuple[int, int]:
++ total, extra = base(name, info)
++ shape = info.get("shape") or []
++ if (total and info.get("dtype") == "BF16" and len(shape) == 2 and shape[-1] % F8_BLOCK == 0
++ and "experts." not in name.replace("shared_experts.", "") and _F8_NAMES.search(name)):
++ if name == "lm_head.weight": # keep the 4-bit draft head split_weights adds
++ n = total * 16 // (2 * 16 + 9) # its values: total = 2n + 9n / 16
++ return n + n // F8_BLOCK * 4 + n * 9 // 16, extra
++ n = total // 2
++ return n + n // F8_BLOCK * 4, extra
++ 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
+--- 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
+
+ from .exl3_mm import Exl3Experts, words as exl3_words
+ from . import latent
+-from .qmm import B16, Q4, as_i32, make_b16, make_q4, quantize4, stack_b16, stack_q4
++from .qmm import B16, F8, Q4, as_i32, dense_kind, make_b16, make_f8, make_q4, quantize4, stack_b16, stack_f8, stack_q4
+
+ PREFIX = "model.language_model."
+
+@@ -199,7 +199,7 @@ class Weights:
+ embed: tuple[torch.Tensor, torch.Tensor, torch.Tensor]
+ layers: list[LayerW]
+ norm: torch.Tensor
+- head: Q4 | B16
++ head: Q4 | B16 | F8
+ mtp: MTPW | None
+ rank: int
+ world: int
+@@ -221,7 +221,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()
+- elif isinstance(t, (Q4, B16, grouped.Experts, Exl3Experts, HCW, KDAW, DSAW, MLPW, MoEW, LayerW, MTPW, IndexW)):
++ elif isinstance(t, (Q4, B16, F8, grouped.Experts, Exl3Experts, HCW, KDAW, DSAW, MLPW, MoEW, LayerW, MTPW, IndexW)):
+ 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:
+ def trip(name: str) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+ return (as_i32(t(name + ".weight")), t(name + ".scales"), t(name + ".biases"))
+
+- def q4(name: str) -> Q4 | B16:
+- return make_b16(t(name + ".weight")) if exl3 else make_q4(*trip(name))
++ # TF_GLM_DENSE=fp8: the BF16 matrices as FP8 with block scales (lossy, half the bytes a decode round reads)
++ fp8 = exl3 and dense_kind() == "fp8"
++ dense, dense_stack = (make_f8, stack_f8) if fp8 else (make_b16, stack_b16)
+
+- def stack(names: list[str]) -> Q4 | B16:
++ def q4(name: str) -> Q4 | B16 | F8:
++ return dense(t(name + ".weight")) if exl3 else make_q4(*trip(name))
++
++ def stack(names: list[str]) -> Q4 | B16 | F8:
+ if exl3:
+- return stack_b16([t(n + ".weight") for n in names])
++ return dense_stack([t(n + ".weight") for n in names])
+ 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:
+ krows, vrows = rows[:, :cfg.qk_dim].reshape(-1), rows[:, cfg.qk_dim:].reshape(-1)
+ if exl3:
+ w = t(p + "kv_b_proj.weight")
+- kv_k, kv_v = make_b16(w[krows]), make_b16(w[vrows])
++ kv_k, kv_v = dense(w[krows]), dense(w[vrows])
+ 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:
+ vl = cfg.vocab // world
+ draft_head = None
+ if exl3:
+- head = make_b16(rd.get("lm_head.weight")[rank * vl:(rank + 1) * vl].to(dev))
+- # Draft steps use the quantized head; verification keeps the original head.
+- draft_head = quantize4(head.weight)
++ raw = rd.get("lm_head.weight")[rank * vl:(rank + 1) * vl].to(dev)
++ head = dense(raw)
++ draft_head = quantize4(raw) # Draft steps use the quantized head; verification keeps the original head.
+ else:
+ hw, hs, hb = (rd.get("lm_head." + x) for x in ("weight", "scales", "biases"))
+ head = make_q4(as_i32(hw[rank * vl:(rank + 1) * vl]).to(dev), hs[rank * vl:(rank + 1) * vl].to(dev),
diff --git a/patches/0003-glm-vision.patch b/patches/0003-glm-vision.patch
new file mode 100644
index 0000000..2b73e2c
--- /dev/null
+++ b/patches/0003-glm-vision.patch
@@ -0,0 +1,1257 @@
+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
+--- tensorfold/cuda/server.py
++++ tensorfold/cuda/server.py
+@@ -353,11 +353,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
+- from tensorfold.vision.qwen_processing import continued
+-
+ same = list(ids) == list(prepared.vision.token_ids)
+- extra["vision"] = prepared.vision if same else continued(prepared.vision, ids,
+- self.vision.frontend.config)
++ if same:
++ extra["vision"] = prepared.vision
++ elif hasattr(prepared.vision, "continued"): # a frontend that extends its own prompts
++ extra["vision"] = prepared.vision.continued(ids)
++ else:
++ from tensorfold.vision.qwen_processing import continued
++
++ extra["vision"] = continued(prepared.vision, ids, self.vision.frontend.config)
+ stats = self.engine.generate(ids, count, sampling, feed, **extra)
+ if not cached:
+ cached.append(int((stats or {}).get("cached") or 0))
+diff --git tensorfold/families/glm5_next/__init__.py tensorfold/families/glm5_next/__init__.py
+index f95a051..7076545 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:
+ 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"),
+- serial_only=bool(no_drafts))
++ serial_only=bool(no_drafts), vision=bool(options.get("vision", False)),
++ vision_urls=bool(options.get("vision_urls", False)))
+
+
+ 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
+--- tensorfold/families/glm5_next/cuda/app.py
++++ tensorfold/families/glm5_next/cuda/app.py
+@@ -2,6 +2,7 @@
+
+ from __future__ import annotations
+
++from pathlib import Path
+ from typing import Any, Callable
+
+ from tensorfold.cuda.server import App, PreparedRequest, RequestError
+@@ -16,16 +17,38 @@ class ThinkingOffTemplate:
+ self.inner = inner
+ self.efforts = getattr(inner, "efforts", frozenset())
+
+- def render(self, messages, *, tools, enable_thinking, extra=None) -> str:
+- text = self.inner.render(messages, tools=tools, enable_thinking=enable_thinking, extra=extra)
++ def render(self, messages, *, tools, enable_thinking, extra=None, allow_images: bool = False) -> str:
++ text = self.inner.render(messages, tools=tools, enable_thinking=enable_thinking, extra=extra,
++ allow_images=allow_images)
+ return text if enable_thinking else thinking_off(text)
+
+
++# the checkpoint's template answers a picture or clip with this reminder; with --vision it writes GLM's markers instead
++# (Glm5NextProcessor's layout), and every text-only prompt renders as before
++_NO_MEDIA = ('{{- "<reminder>You are unable to process this " ~ media_type ~ " because you don\'t have multi-modal '
++ 'input ability. Try different methods.</reminder>" }}')
++_MEDIA = ("{%- if media_type == 'image' -%}<|begin_of_image|><|image|><|end_of_image|>"
++ "{%- elif media_type == 'video' -%}<|begin_of_video|><|video|><|end_of_video|>"
++ "{%- else -%}" + _NO_MEDIA + "{%- endif -%}")
++
++
++def media_template(inner, model_dir) -> None:
++ """Swap the checkpoint template's no-media reminder for GLM's image and video markers."""
++
++ source = (model_dir / "chat_template.jinja").read_text()
++ if source.count(_NO_MEDIA) != 1:
++ raise ValueError("--vision: this checkpoint's chat template has no media branch TensorFold knows how to "
++ "extend (GLM-5.3 Flash's chat_template.jinja)")
++ inner.template = inner.template.environment.from_string(source.replace(_NO_MEDIA, _MEDIA))
++
++
+ class GlmApp(App):
+ reads_ignore_eos = True # ``run`` hands it to the engine's request
+
+ def __init__(self, engine, model_dir, served: str, **kwargs: Any) -> None:
+ super().__init__(engine, model_dir, served, **kwargs)
++ if self.vision is not None:
++ media_template(self.template, Path(model_dir))
+ self.template = ThinkingOffTemplate(self.template)
+
+ 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
+--- 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:
+ # -- prefill ----------------------------------------------------------------------------------------------------
+ @torch.no_grad()
+ def prefill(e: Engine, prompt: Sequence[int], sampling: Sampling | None, *, mtp: bool = True, drafter=None,
+- resume: Snapshot | None = 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:
++ """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])
+ R = len(chunk)
+- last = compute(w, st, b, stage(w, st, b, chunk), nch=chunks_for(st, R), host_pos=st.pos).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()
+ e.last_hidden = b.fnormed[R - 1:R].clone()
+ if drafter is not None:
+ drafter.add_taps(e.tap_rows(R, b))
+diff --git tensorfold/families/glm5_next/cuda/engine.py tensorfold/families/glm5_next/cuda/engine.py
+index 3393fa0..c46aa52 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)
+ 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. 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
++# scales it; TENSORFOLD_VISION_WORKSPACE_MIB sets it outright
++VISION_WORKSPACE = 3 * 2**29
++
++
++def vision_workspace() -> int:
++ value = os.environ.get("TENSORFOLD_VISION_WORKSPACE_MIB", "")
++ if value == "":
++ from tensorfold.vision.glm import GlmVisionLimits
++
++ return VISION_WORKSPACE * max(4096, GlmVisionLimits.from_env().image_tokens) // 4096
++ if not value.isdecimal() or int(value) > 16384:
++ raise ValueError(f"TENSORFOLD_VISION_WORKSPACE_MIB: 0 to 16,384 MiB, not {value!r}")
++ return int(value) * 2**20
+
+
+ def encode_policy(spec: str) -> list[int]:
+@@ -86,8 +102,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,
+- prefill_rows: int | None = None) -> None:
+- """``comm``: a communicator with ``all_gather`` and ``barrier`` instead of NCCL between two machines (tests)."""
++ prefill_rows: int | None = None, vision: bool = False, vision_urls: bool = False) -> None:
++ """``comm``: a communicator with ``all_gather`` and ``barrier`` instead of NCCL between two machines (tests);
++ ``vision``: rank 0 runs the image tower (rank 1 only takes its rows)."""
+
+ 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)
++ 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
++ import math
++
++ text_weights = weights_estimate
++ weights_estimate = lambda name, info: ((math.prod(info["shape"]) * 2, 0)
++ if name.startswith("model.visual.") else text_weights(name, info))
++
++ def geometry(text):
++ from tensorfold.cuda.capacity import Geometry
++
++ g = mla_geometry(text, 2, MAX_ROWS, minimum_slots=DENSE_CAPACITY, latent=LATENT)
++ 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),
++ 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)
++ self.vision = None # rank 0's image tower (``tensorfold.vision.glm.GlmVision``), --vision
++ if vision:
++ from tensorfold.vision.glm import GlmVision
++
++ self.vision = GlmVision(model_dir, torch.device("cuda", 0), allow_urls=vision_urls)
++ self.vision.warm()
++ torch.cuda.empty_cache()
++ lim = self.vision.limits
++ print(f"[tensorfold] vision: image and video input, a {self.vision.weight_bytes / 2**30:.2f} GiB tower "
++ f"with {workspace / 2**30:.2f} GiB of workspace; at most {lim.image_tokens} tokens a picture, "
++ f"{lim.video_tokens} a clip ({lim.video_frames} frames at {lim.fps:g} a second)"
++ f"{'; https URLs allowed' if vision_urls else ''}", flush=True)
+ 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:
+ 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],
+- code: list[int], hit, draft: bool, constraint=None) -> dict[str, Any]:
++ code: list[int], hit, draft: bool, constraint=None, feed=None) -> dict[str, Any]:
+ self.e.constraint, self.e.window = constraint, None # both ranks walk and mask the same rows
+ try:
+- return self._run_once(prompt, max_tokens, sampling, stop_eos, on_tokens, code, hit, draft)
++ return self._run_once(prompt, max_tokens, sampling, stop_eos, on_tokens, code, hit, draft, feed)
+ finally:
+ self.e.constraint = self.e.window = None
+
+ 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) -> 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 .drafter_choice import DrafterChoice, auto_decode
+
+@@ -384,10 +427,11 @@ 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)
++ # 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)
+ 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:
+ 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
+- self.live = list(prompt) + res.tokens[:self.e.st.pos - len(prompt)]
++ if feed is None:
++ self.live = list(prompt) + res.tokens[:self.e.st.pos - len(prompt)]
+ 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:
+ return stats
+
+ def generate(self, prompt: list[int], max_tokens: int, sampling, on_tokens, draft: bool = True,
+- constraint=None) -> dict[str, Any]:
+- """Mirror one rank-0 request on rank 1; draft=False uses serial decoding and fresh prefill as the reference drafted replies must equal."""
++ constraint=None, *, vision=None) -> dict[str, Any]:
++ """Mirror one rank-0 request on rank 1; draft=False uses serial decoding and fresh prefill as the reference drafted replies must equal; ``vision``: an image prompt's prepared pictures (``GlmPrepared``)."""
+
+ 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:
+ spec = getattr(self.request, "policy", None) or self.policy
+ code = self._effective(encode_policy(spec))
+ stop_eos = bool(getattr(self.request, "stop_eos", True))
+- hit = self._resume(list(prompt), code) if draft else None
++ positions: list[int] = []
++ feed = None
++ if vision is not None: # encoded here, before rank 1 is told anything, so a failure stops both
++ if self.vision is None:
++ raise ValueError("image inputs require starting this server with --vision")
++ positions = [int(p) for p in vision.positions]
++ if positions and (positions[-1] >= len(prompt) or positions != sorted(set(positions))):
++ raise ValueError("image rows must sit at increasing positions inside the prompt")
++ t = time.perf_counter()
++ rows = self.vision.features(vision)
++ if rows.shape[0] != len(positions):
++ raise ValueError(f"the tower gave {rows.shape[0]} rows for {len(positions)} image positions")
++ 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
+ seed = (sampling.seed if sampling else 0) & 0xFFFFFFFFFFFFFFFF
+ header = [max_tokens, int(stop_eos), int(draft), len(hit.ids) if hit is not None else 0,
+ seed & 0x7FFFFFFF, (seed >> 31) & 0x7FFFFFFF, seed >> 62,
+ *_f64_ints(sampling.temperature if sampling else 0.0), int(sampling.top_k) if sampling else 0,
+ *_f64_ints(sampling.top_p if sampling else 1.0), *_f64_ints(sampling.min_p if sampling else 0.0),
+- int(constraint is not None)] + code
++ int(constraint is not None), len(positions)] + code
+ from tensorfold.engine.grammar import pack
+
+ self._share(header)
+ self._share(list(prompt))
+ if constraint is not None: # the request's grammar: rank 1 compiles the same
+ self._share(pack(constraint))
+- stats = self._run(list(prompt), max_tokens, sampling, stop_eos, on_tokens, code, hit, draft, constraint)
++ if positions:
++ 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)
++ if feed is not None:
++ stats.update(image_rows=len(positions), encode_s=round(feed.encode_s, 3))
+ return stats
+
+ def follow(self) -> None:
+@@ -462,7 +525,7 @@ class GlmEngine:
+
+ while True:
+ (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:
+ from tensorfold.engine import grammar
+
+ constraint = grammar.compiler(self, self.model_dir, self.eos).follow(packed)
++ feed = VisionFeed(self, self._share(None), None) if images else None
+ 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:
+ 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),
+- constraint)
++ constraint, feed)
++
++
++class VisionFeed:
++ """An image prompt's feature rows for each prefill chunk: rank 0 holds them all, and hands a chunk's rows to
++ rank 1 through the all-gather as the chunk comes (rank 1 sends zeros), so neither rank holds a second copy."""
++
++ def __init__(self, engine: GlmEngine, positions: list[int], rows) -> None:
++ self.engine, self.positions, self.rows = engine, positions, rows
++ self.width = engine.w.cfg.hidden
++ self.encode_s = 0.0
++
++ def chunk(self, start: int, count: int):
++ """(row indices within the chunk, their features) for prompt rows start .. start + count, or None."""
++
++ import bisect
++
++ torch = self.engine.torch
++ lo = bisect.bisect_left(self.positions, start)
++ hi = bisect.bisect_left(self.positions, start + count)
++ if lo == hi:
++ return None
++ n = hi - lo
++ mine = (self.rows[lo:hi].contiguous() if self.rows is not None else
++ torch.zeros((n, self.width), dtype=torch.bfloat16, device="cuda"))
++ both = torch.empty((2 * n, self.width), dtype=torch.bfloat16, device="cuda")
++ self.engine.comm.all_gather(mine, both)
++ index = torch.tensor([p - start for p in self.positions[lo:hi]], dtype=torch.int64, device="cuda")
++ return index, both[:n]
+diff --git tensorfold/families/glm5_next/cuda/forward.py tensorfold/families/glm5_next/cuda/forward.py
+index cd3cfc8..f5f6179 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:
+
+
+ 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):
+- """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):
++ """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
+ 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)
+ for slot in b.tap_at.get(layer.index, ()):
+diff --git tensorfold/server/messages.py tensorfold/server/messages.py
+index 24bbd82..dde2b67 100644
+--- tensorfold/server/messages.py
++++ tensorfold/server/messages.py
+@@ -28,6 +28,9 @@ def late_system_role(render: Callable[[list[dict[str, Any]]], Any]) -> str:
+ return "user"
+
+
++_VISUAL = ("image_url", "image", "video_url", "video") # a video part reaches here only where videos are on
++
++
+ def normalize_messages(messages: list[dict[str, Any]], *, late_system: str = "system",
+ allow_images: bool = False) -> list[dict[str, Any]]:
+ """Merge leading instructions as system text and retain later instructions as ``late_system`` so earlier conversation tokens stay unchanged."""
+@@ -45,12 +48,12 @@ def normalize_messages(messages: list[dict[str, Any]], *, late_system: str = "sy
+ raise RequestError("this server accepts text only; image, audio and video inputs are unsupported")
+ content = message.get("content")
+ if isinstance(content, list) and allow_images and any(
+- isinstance(p, dict) and p.get("type") in ("image_url", "image") for p in content):
++ isinstance(p, dict) and p.get("type") in _VISUAL for p in content):
+ if role != "user":
+- raise RequestError("images are supported only in user messages")
++ raise RequestError("images and videos are supported only in user messages")
+ for part in content:
+- if not isinstance(part, dict) or part.get("type") not in ("text", "image_url", "image"):
+- raise RequestError("image messages may contain text and image_url parts only")
++ if not isinstance(part, dict) or part.get("type") not in ("text", *_VISUAL):
++ raise RequestError("image messages may contain text and image_url (or video_url) parts only")
+ if part["type"] == "text" and not isinstance(part.get("text"), str):
+ 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
+--- tensorfold/server/prompts.py
++++ tensorfold/server/prompts.py
+@@ -18,7 +18,7 @@ class RenderedPrompt:
+
+ def has_images(messages):
+ return any(isinstance(m, dict) and isinstance(m.get('content'), list)
+- and any(isinstance(p, dict) and p.get('type') == 'image_url' for p in m['content'])
++ and any(isinstance(p, dict) and p.get('type') in ('image_url', 'video_url') for p in m['content'])
+ for m in messages or [])
+
+
+@@ -45,14 +45,27 @@ def prepare_images(frontend, messages, render, *, context_limit=None):
+ if frontend is None:
+ raise RequestError('image input requires a supported vision checkpoint served with --vision')
+ allow_urls = bool(getattr(frontend, 'allow_urls', False))
++ videos = bool(getattr(frontend, 'videos', False)) # a frontend that encodes video frames too
+ try:
+- template, sources = split_images(messages, allow_urls=allow_urls)
++ template, sources = split_images(messages, allow_urls=allow_urls, allow_videos=videos)
+ except (ImageInputError, ValueError) as exc:
+ raise RequestError(str(exc)) from exc
+ slot = image_slot()
+ try:
+- images = load_images(sources, allow_urls=allow_urls)
+- prepared = frontend.prepare(render(template), images, max_prompt_tokens=context_limit)
++ from tensorfold.vision.images import ImageSource
++
++ images = load_images([s for s in sources if isinstance(s, ImageSource)], allow_urls=allow_urls)
++ clips = [s for s in sources if not isinstance(s, ImageSource)]
++ if clips:
++ if hasattr(frontend, 'load_videos'): # a frontend with its own frame sampling
++ clips = frontend.load_videos(clips)
++ else:
++ from tensorfold.vision.videos import load_videos
++
++ clips = load_videos(clips, frontend.video_size, allow_urls=allow_urls)
++ prepared = frontend.prepare(render(template), images, videos=clips, max_prompt_tokens=context_limit)
++ else:
++ prepared = frontend.prepare(render(template), images, max_prompt_tokens=context_limit)
+ 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
+--- /dev/null
++++ tensorfold/vision/glm.py
+@@ -0,0 +1,491 @@
++"""GLM-5.3 Flash image and video input on CUDA: the checkpoint's processors (resize with pad, frame choice, prompt
++layout) and its vision tower, run on rank 0.
++
++The arithmetic follows transformers 5.17's ``Glm5NextImageProcessor`` / ``Glm5NextVideoProcessor`` /
++``Glm5NextVisionModel``: images and frame pairs become 14x14x2 patches, 24 blocks of 2-D rotary attention over one
++image (or one frame pair) at a time, a 2x2 downsample and a SwiGLU merger into the language model's 4,096 columns.
++The language model takes the features in place of its ``<|image|>`` rows; its positions are the token positions
++(the MLA layers carry no rotary part), so nothing else about the prompt changes.
++"""
++
++from __future__ import annotations
++
++import hashlib
++import io
++import json
++import math
++import os
++import time
++from dataclasses import dataclass, field
++from pathlib import Path
++from typing import Any
++
++import numpy as np
++
++from .images_http import ImageInputError
++
++IMAGE, VIDEO = "<|image|>", "<|video|>"
++IMAGE_SPAN = "<|begin_of_image|><|image|><|end_of_image|>" # what the chat template writes for a picture
++VIDEO_SPAN = "<|begin_of_video|><|video|><|end_of_video|>" # and for a clip, expanded frame pair by frame pair
++MEAN = (0.48145466, 0.4578275, 0.40821073) # CLIP's, from processor_config.json
++STD = (0.26862954, 0.26130258, 0.27577711)
++PASS_PATCHES = 16384 # patches the tower encodes at once (its workspace scales with this)
++
++
++def _env_int(name: str, default: int, low: int, high: int) -> int:
++ value = os.environ.get(name, "")
++ if value == "":
++ return default
++ if not value.isdecimal() or not low <= int(value) <= high:
++ raise ValueError(f"{name}: {low:,} to {high:,}, not {value!r}")
++ return int(value)
++
++
++@dataclass(frozen=True, slots=True)
++class GlmVisionLimits:
++ """Token caps: the checkpoint allows 8,000 tokens a picture and 240,000 a clip; these keep a request's
++ encode within the tower's reserved workspace and the prompt within a sensible share of the window."""
++
++ image_tokens: int = 2048 # a picture's tokens at most (a 1080p frame is 2,040 at 2,048)
++ video_tokens: int = 16384 # a clip's tokens at most, over all its frame pairs
++ video_frames: int = 128 # frames sampled from a clip at most (2 a second, spread wider past this)
++ fps: float = 2.0 # the processor's rate
++ min_tokens: int = 16
++
++ @classmethod
++ def from_env(cls) -> "GlmVisionLimits":
++ d = cls() # a slots class keeps its defaults on instances, not the class
++ return cls(image_tokens=_env_int("TENSORFOLD_GLM_IMAGE_TOKENS", d.image_tokens, 16, 8000),
++ video_tokens=_env_int("TENSORFOLD_GLM_VIDEO_TOKENS", d.video_tokens, 64, 240000),
++ video_frames=_env_int("TENSORFOLD_GLM_VIDEO_FRAMES", d.video_frames, 2, 2048))
++
++
++# -- the processors' geometry ---------------------------------------------------------------------------------
++def smart_resize(frames: int, height: int, width: int, max_tokens: int, min_tokens: int = 16, temporal: int = 2,
++ factor: int = 28) -> tuple[int, int]:
++ """The canvas (height, width), multiples of ``factor``, within ``max_tokens`` over ``frames`` frames."""
++
++ per_token = temporal * factor ** 2
++ low_pixels, high_pixels = min_tokens * per_token, max_tokens * per_token
++
++ def align(v: float) -> int:
++ return math.ceil(v / factor) * factor
++
++ aligned = max(temporal, round(frames / temporal) * temporal)
++ h, w = align(height), align(width)
++ if aligned * h * w < low_pixels:
++ scale = math.sqrt(low_pixels / (frames * height * width))
++ h, w = align(max(1, math.ceil(height * scale))), align(max(1, math.ceil(width * scale)))
++ if aligned * h * w > high_pixels:
++ if high_pixels < aligned * factor ** 2:
++ raise ImageInputError("the token cap is too small for one patch per frame pair")
++ lo, hi, h, w = 1, height, factor, factor
++ while lo <= hi: # the largest content height whose aligned canvas fits
++ mid = (lo + hi) // 2
++ ch, cw = align(mid), align(max(1, math.floor(width * mid / height)))
++ if aligned * ch * cw <= high_pixels:
++ h, w, lo = ch, cw, mid + 1
++ else:
++ hi = mid - 1
++ return h, w
++
++
++def content_size(frames: int, height: int, width: int, canvas: tuple[int, int], min_tokens: int = 16,
++ temporal: int = 2, factor: int = 28) -> tuple[int, int]:
++ """The resized picture inside the canvas (the rest is zero padding, right and bottom)."""
++
++ th, tw = canvas
++ scale = min(th / height, tw / width)
++ if frames * height * width >= temporal * factor ** 2 * min_tokens:
++ scale = min(1.0, scale)
++ return max(1, min(th, math.floor(height * scale))), max(1, min(tw, math.floor(width * scale)))
++
++
++def fit(frame, canvas: tuple[int, int], content: tuple[int, int]):
++ """One uint8 [3, H, W] frame resized (bicubic, antialiased, as torchvision does for the processor) and padded."""
++
++ import torch
++ from torchvision.transforms.v2 import functional as tvF
++
++ if tuple(frame.shape[-2:]) != content:
++ frame = tvF.resize(frame, list(content), interpolation=tvF.InterpolationMode.BICUBIC, antialias=True)
++ out = torch.zeros((3, *canvas), dtype=torch.uint8)
++ out[:, :content[0], :content[1]] = frame
++ return out
++
++
++def sample_frames(total: int, fps: float, duration: float, limits: GlmVisionLimits) -> list[int]:
++ """``Glm5NextVideoProcessor.sample_frames``: one frame each 1/fps seconds from the start, at most
++ ``video_frames`` (then spread evenly), duplicates dropped, an even count (the last frame repeated)."""
++
++ duration = duration or round((total - 1) / fps) + 1
++ max_seconds = int(duration)
++ want = min(int(duration * limits.fps), limits.video_frames)
++ if total < want:
++ picks = np.linspace(0, total - 1, want, dtype=int).tolist()
++ else:
++ picks, second, step = [], 0.0, 1 / limits.fps
++ for i in range(total):
++ if i / fps >= second:
++ second += step
++ picks.append(i)
++ if second >= max_seconds:
++ break
++ if len(picks) < want:
++ start, end = (picks[0], picks[-1]) if picks else (0, max(total - 1, 0))
++ picks = np.linspace(start, end, want, dtype=int).tolist()
++ elif len(picks) > want:
++ picks = np.linspace(0, total - 1, want, dtype=int).tolist()
++ seen: set[int] = set()
++ unique = [i for i in picks if not (i in seen or seen.add(i))]
++ if not unique:
++ unique = [0]
++ if len(unique) % 2:
++ unique.append(unique[-1])
++ return unique
++
++
++# -- inputs -----------------------------------------------------------------------------------------------------
++@dataclass(frozen=True, slots=True)
++class GlmClip:
++ """A clip's sampled frames at the tower's canvas: uint8 [frames, 3, H, W], and each frame pair's time."""
++
++ frames: Any
++ seconds: tuple[float, ...] # one per frame pair: its first frame's time
++ content_hash: str = field(init=False)
++
++ def __post_init__(self) -> None:
++ digest = hashlib.sha256(b"tensorfold-glm-clip-v1\0" + json.dumps(list(self.frames.shape)).encode())
++ digest.update(self.frames.numpy().tobytes())
++ object.__setattr__(self, "content_hash", digest.hexdigest())
++
++
++def decode_clip(data: bytes, limits: GlmVisionLimits, deadline: float, *, max_dimension: int = 8192,
++ max_seconds: float = 3600.0) -> GlmClip:
++ """Decode one clip's sampled frames, each resized onto the clip's canvas as it is decoded."""
++
++ import torch
++
++ from .videos import _av
++
++ av = _av()
++ try:
++ with av.open(io.BytesIO(data), mode="r") as container:
++ if not container.streams.video:
++ raise ImageInputError("the video has no video stream")
++ stream = container.streams.video[0]
++ stream.thread_type = "AUTO"
++ width, height = int(stream.codec_context.width or 0), int(stream.codec_context.height or 0)
++ if min(width, height) <= 0 or max(width, height) > max_dimension:
++ raise ImageInputError("video dimensions are missing or exceed the pixel limit")
++ fps = float(stream.average_rate or stream.guessed_rate or 0)
++ total = int(stream.frames or 0)
++ if not total and fps > 0: # WebM and some MKV files carry no frame count
++ seconds = (float(stream.duration * stream.time_base) if stream.duration else
++ container.duration / 1e6 if container.duration else 0.0)
++ total = int(round(seconds * fps))
++ if not 0 < fps <= 1000 or total <= 0:
++ raise ImageInputError("the video's frame count or rate is missing")
++ if total / fps > max_seconds:
++ raise ImageInputError(f"videos are limited to {max_seconds / 60:.0f} minutes")
++ picks = sample_frames(total, fps, total / fps, limits)
++ canvas = smart_resize(len(picks), height, width, limits.video_tokens, limits.min_tokens)
++ content = content_size(len(picks), height, width, canvas, limits.min_tokens)
++ wanted = set(picks)
++ got: dict[int, Any] = {}
++ for n, frame in enumerate(container.decode(stream)):
++ if n > picks[-1] or time.monotonic() >= deadline:
++ break
++ if n in wanted:
++ rgb = torch.from_numpy(frame.to_ndarray(format="rgb24")).permute(2, 0, 1)
++ got[n] = fit(rgb, canvas, content)
++ if time.monotonic() >= deadline:
++ raise ImageInputError("video decoding exceeds the time limit")
++ except ImageInputError:
++ raise
++ except (OSError, ValueError, MemoryError) as exc:
++ raise ImageInputError(f"video bytes are invalid or unsupported ({type(exc).__name__}); use MP4 or "
++ "WebM") from None
++ if not got:
++ raise ImageInputError("the video has no decodable frames")
++ last = max(got) # a stream shorter than its header: repeat the last frame decoded
++ frames = torch.stack([got.get(i, got[last]) if i <= last else got[last] for i in picks])
++ return GlmClip(frames, tuple(i / fps for i in picks[::2]))
++
++
++@dataclass
++class GlmPrepared:
++ """A prompt with pictures or clips: its tokens, where the tower's rows go, and what to encode.
++
++ ``items``: in prompt order, ("image", uint8 [3, H, W]) or ("video", uint8 [frames, 3, H, W]); ``positions``:
++ the prompt positions of their feature rows, in order (a picture's rows, then the next item's)."""
++
++ token_ids: list[int]
++ items: list[tuple[str, Any]]
++ positions: list[int]
++ content_hash: str = ""
++
++ def continued(self, ids: list[int]) -> "GlmPrepared":
++ """The same pictures under a longer prompt (a tool gate's continuation): positions are token positions."""
++
++ if list(ids[:len(self.token_ids)]) != list(self.token_ids):
++ raise ValueError("a continued image prompt must extend the original prompt")
++ return GlmPrepared(list(ids), self.items, self.positions, self.content_hash)
++
++
++# -- the tower --------------------------------------------------------------------------------------------------
++class GlmVisionTower:
++ """``Glm5NextVisionModel`` in plain torch on bf16 weights; one image or frame pair attends within itself."""
++
++ def __init__(self, model_dir: Path, device) -> None:
++ import torch
++ from safetensors import safe_open
++
++ cfg = json.loads((model_dir / "config.json").read_text())
++ v = cfg["vision_config"]
++ self.hidden, self.heads = int(v["hidden_size"]), int(v["num_heads"])
++ self.head_dim = self.hidden // self.heads
++ self.depth, self.eps = int(v["depth"]), float(v["rms_norm_eps"])
++ self.patch, self.temporal = int(v["patch_size"]), int(v["temporal_patch_size"])
++ self.merge, self.out = int(v["spatial_merge_size"]), int(v["out_hidden_size"])
++ self.limit = float(v.get("swiglu_limit", 10.0))
++ theta = float((v.get("rope_parameters") or {}).get("rope_theta", 10000.0))
++ if self.merge != 2 or self.patch != 14 or self.temporal != 2 or self.head_dim % 4:
++ raise ValueError("this GLM vision tower's geometry is not the one TensorFold implements")
++ spatial = self.head_dim // 2
++ self.inv_freq = 1.0 / (theta ** (torch.arange(0, spatial, 2, dtype=torch.float32, device=device) / spatial))
++ index = json.loads((model_dir / "model.safetensors.index.json").read_text())["weight_map"]
++ names = sorted(n for n in index if n.startswith("model.visual."))
++ if not names:
++ raise ValueError("this checkpoint has no vision tower (model.visual.*)")
++ t: dict[str, Any] = {}
++ for file in sorted({index[n] for n in names}):
++ with safe_open(str(model_dir / file), framework="pt", device="cpu") as f:
++ for n in names:
++ if index[n] == file:
++ t[n[len("model.visual."):]] = f.get_tensor(n).to(device=device, dtype=torch.bfloat16)
++ self.weight_bytes = sum(x.numel() * x.element_size() for x in t.values())
++ self.t = t
++ self.device = device
++ self.mean = torch.tensor(MEAN, device=device).view(3, 1, 1) * 255
++ self.std = torch.tensor(STD, device=device).view(3, 1, 1) * 255
++
++ # the processors' patch layout: rows are merge blocks (2x2 patches), a patch's values (channel, time, y, x)
++ def patches(self, frames):
++ """uint8 [T, 3, H, W] (T even) on the device -> normalized [T/2 * H/14 * W/14, 3 * 2 * 14 * 14] float32."""
++
++ T, C, H, W = frames.shape
++ p, m = self.patch, self.merge
++ x = (frames.float() - self.mean) / self.std
++ x = x.view(T // 2, 2, C, H // p // m, m, p, W // p // m, m, p)
++ x = x.permute(0, 3, 6, 4, 7, 2, 1, 5, 8)
++ return x.reshape(T // 2 * (H // p) * (W // p), C * 2 * p * p)
++
++ def _rms(self, x, w):
++ import torch
++
++ xf = x.float()
++ return w * (xf * torch.rsqrt(xf.pow(2).mean(-1, keepdim=True) + self.eps)).to(x.dtype)
++
++ def _rope(self, gh: int, gw: int):
++ import torch
++
++ m = self.merge
++ hpos, wpos = torch.meshgrid(torch.arange(gh, device=self.device), torch.arange(gw, device=self.device),
++ indexing="ij")
++ shape = (gh // m, m, gw // m, m)
++ pos = torch.stack([hpos.reshape(shape).transpose(1, 2).flatten(),
++ wpos.reshape(shape).transpose(1, 2).flatten()], dim=-1).float()
++ freqs = (pos[..., None] * self.inv_freq).flatten(1) # [S, h freqs then w freqs]
++ freqs = torch.cat([freqs, freqs], dim=-1)
++ return freqs.cos()[None, :, None, :], freqs.sin()[None, :, None, :]
++
++ @staticmethod
++ def _rotate(x, cos, sin):
++ import torch
++
++ xf = x.float()
++ half = xf.shape[-1] // 2
++ return (xf * cos + torch.cat((-xf[..., half:], xf[..., :half]), dim=-1) * sin).to(x.dtype)
++
++ def _block(self, i: int, x, cos, sin):
++ import torch
++ import torch.nn.functional as F
++
++ t, L = self.t, self.limit
++ g = f"blocks.{i}."
++ B, S, D = x.shape
++ h = self._rms(x, t[g + "norm1.weight"])
++ q, k, v = F.linear(h, t[g + "attn.qkv.weight"], t[g + "attn.qkv.bias"]).view(B, S, 3, self.heads,
++ self.head_dim).unbind(2)
++ q = self._rotate(self._rms(q, t[g + "attn.q_norm.weight"]), cos, sin)
++ k = self._rotate(self._rms(k, t[g + "attn.k_norm.weight"]), cos, sin)
++ o = F.scaled_dot_product_attention(q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2),
++ scale=self.head_dim ** -0.5)
++ x = x + F.linear(o.transpose(1, 2).reshape(B, S, D), t[g + "attn.proj.weight"], t[g + "attn.proj.bias"])
++ h = self._rms(x, t[g + "norm2.weight"])
++ gate = F.linear(h, t[g + "mlp.gate_proj.weight"], t[g + "mlp.gate_proj.bias"]).clamp(max=L)
++ up = F.linear(h, t[g + "mlp.up_proj.weight"], t[g + "mlp.up_proj.bias"]).clamp(-L, L)
++ del h
++ return x + F.linear(F.silu(gate) * up, t[g + "mlp.down_proj.weight"], t[g + "mlp.down_proj.bias"])
++
++ def encode(self, patches, groups: int, gh: int, gw: int):
++ """``groups`` images (or frame pairs) of gh x gw patches each, [groups * gh * gw, 1176] -> their
++ [groups * gh * gw / 4, out] features in the language model's dtype."""
++
++ import torch
++ import torch.nn.functional as F
++
++ t = self.t
++ S = gh * gw
++ # the reference's convolutions, not the equal matmuls: 24 blocks turn their last-bit differences into ~3%
++ x = F.conv3d(patches.to(torch.bfloat16).view(-1, 3, self.temporal, self.patch, self.patch),
++ t["patch_embed.proj.weight"], t["patch_embed.proj.bias"], stride=(self.temporal, self.patch,
++ self.patch))
++ x = x.view(groups, S, self.hidden)
++ cos, sin = self._rope(gh, gw)
++ for i in range(self.depth):
++ x = self._block(i, x, cos, sin)
++ x = self._rms(x, t["post_layernorm.weight"]).reshape(-1, self.merge, self.merge, self.hidden)
++ x = F.conv2d(x.permute(0, 3, 1, 2), t["downsample.weight"], t["downsample.bias"],
++ stride=self.merge).view(-1, self.out)
++ x = F.linear(x, t["merger.proj.weight"])
++ x = F.gelu(F.layer_norm(x, (self.out,), t["merger.post_projection_norm.weight"],
++ t["merger.post_projection_norm.bias"]))
++ gate = F.linear(x, t["merger.gate_proj.weight"]).clamp(max=self.limit)
++ up = F.linear(x, t["merger.up_proj.weight"]).clamp(-self.limit, self.limit)
++ return F.linear(F.silu(gate) * up, t["merger.down_proj.weight"])
++
++ def features(self, items: list[tuple[str, Any]]):
++ """Every item's feature rows, in order: [rows, out] bf16 on the device."""
++
++ import torch
++
++ out = []
++ for _, frames in items:
++ frames = frames if frames.dim() == 4 else frames.unsqueeze(0).expand(2, -1, -1, -1)
++ T, _, H, W = frames.shape
++ gh, gw = H // self.patch, W // self.patch
++ per = max(1, PASS_PATCHES // (gh * gw)) # frame pairs a pass
++ for start in range(0, T // 2, per):
++ pairs = frames[2 * start:2 * min(T // 2, start + per)].to(self.device, non_blocking=True)
++ out.append(self.encode(self.patches(pairs), pairs.shape[0] // 2, gh, gw))
++ return torch.cat(out) if out else torch.empty((0, self.out), dtype=torch.bfloat16, device=self.device)
++
++
++# -- the frontend ------------------------------------------------------------------------------------------------
++class GlmVision:
++ """What the server needs for GLM pictures and clips: ``prepare`` (rendered text -> tokens and items),
++ ``load_videos``, and the tower's ``features`` (rank 0)."""
++
++ videos = True
++
++ def __init__(self, model_dir: Path, device, *, allow_urls: bool = False,
++ limits: GlmVisionLimits | None = None) -> None:
++ from tokenizers import Tokenizer
++
++ cfg = json.loads((model_dir / "config.json").read_text())
++ self.image_token = int(cfg.get("image_token_id", 154854))
++ self.allow_urls = allow_urls
++ self.limits = limits or GlmVisionLimits.from_env()
++ self.tok = Tokenizer.from_file(str(model_dir / "tokenizer.json"))
++ if self.tok.token_to_id(IMAGE) != self.image_token:
++ raise ValueError("the tokenizer's <|image|> id does not match config.json's image_token_id")
++ self.tower = GlmVisionTower(model_dir, device)
++ self.weight_bytes = self.tower.weight_bytes
++
++ def load_videos(self, sources) -> list[GlmClip]:
++ from .videos import DEFAULT_VIDEO_LIMITS as L, VIDEO_MEDIA_TYPES
++ from .images import _data_bytes
++ from .images_http import fetch_image
++
++ if len(sources) > L.max_videos:
++ raise ImageInputError(f"a request supports at most {L.max_videos} videos")
++ total, out = 0, []
++ deadline = time.monotonic() + L.total_timeout_seconds
++ for source in sources:
++ remaining = min(L.max_encoded_bytes, L.max_total_encoded_bytes - total)
++ if remaining <= 0 or time.monotonic() >= deadline:
++ raise ImageInputError("video request exceeds the total byte or time limit")
++ if source.url.startswith("data:"):
++ data = _data_bytes(source.url, remaining)
++ elif self.allow_urls:
++ data, _ = fetch_image(source.url, max_bytes=remaining,
++ deadline=min(deadline, time.monotonic() + L.timeout_seconds),
++ max_redirects=L.max_redirects, max_url_chars=L.max_url_chars,
++ media_types=VIDEO_MEDIA_TYPES)
++ else:
++ raise ImageInputError("video URLs are off on this server")
++ total += len(data)
++ out.append(decode_clip(data, self.limits, deadline, max_dimension=L.max_dimension,
++ max_seconds=L.max_seconds))
++ return out
++
++ def _picture(self, image):
++ import torch
++
++ rgb = torch.frombuffer(bytearray(image.pixels), dtype=torch.uint8).view(image.height, image.width, 3)
++ rgb = rgb.permute(2, 0, 1)
++ canvas = smart_resize(2, image.height, image.width, self.limits.image_tokens, self.limits.min_tokens)
++ return fit(rgb, canvas, content_size(2, image.height, image.width, canvas, self.limits.min_tokens))
++
++ def prepare(self, text: str, images, *, videos=(), max_prompt_tokens: int | None = None) -> GlmPrepared:
++ """The rendered prompt with each picture's and clip's placeholder expanded as Glm5NextProcessor does."""
++
++ videos = list(videos or ())
++ if text.count(IMAGE) != text.count(IMAGE_SPAN) or text.count(IMAGE_SPAN) != len(images) or \
++ text.count(VIDEO) != len(videos) or text.count(VIDEO_SPAN) != len(videos):
++ raise ImageInputError("the prompt's image and video markers do not match its images and videos "
++ "(is <|image|> or <|video|> in the text?)")
++ items: list[tuple[str, Any]] = []
++ pieces: list[str] = []
++ image_iter, video_iter = iter(images), iter(videos)
++ rest = text
++ while True:
++ i, v = rest.find(IMAGE_SPAN), rest.find(VIDEO_SPAN)
++ if i < 0 and v < 0:
++ pieces.append(rest)
++ break
++ if v < 0 or 0 <= i < v:
++ picture = self._picture(next(image_iter))
++ n = picture.shape[1] // 28 * (picture.shape[2] // 28)
++ pieces.append(rest[:i] + "<|begin_of_image|>" + IMAGE * n + "<|end_of_image|>")
++ items.append(("image", picture))
++ rest = rest[i + len(IMAGE_SPAN):]
++ else:
++ clip = next(video_iter)
++ n = clip.frames.shape[2] // 28 * (clip.frames.shape[3] // 28)
++ frames = "".join(f"<|begin_of_image|>{IMAGE * n}<|end_of_image|>{s:.1f} seconds"
++ for s in clip.seconds)
++ pieces.append(rest[:v] + "<|begin_of_video|>" + frames + "<|end_of_video|>")
++ items.append(("video", clip.frames))
++ rest = rest[v + len(VIDEO_SPAN):]
++ ids = self.tok.encode("".join(pieces), add_special_tokens=False).ids
++ if max_prompt_tokens and len(ids) >= max_prompt_tokens:
++ raise ValueError(f"the prompt with its images is {len(ids):,} tokens; this server's window is "
++ f"{max_prompt_tokens:,}: send fewer or smaller images, or a shorter video")
++ positions = [p for p, t in enumerate(ids) if t == self.image_token]
++ rows = sum(self._rows(kind, x) for kind, x in items)
++ if len(positions) != rows:
++ raise ImageInputError(f"the prompt has {len(positions)} image positions for {rows} feature rows")
++ digest = hashlib.sha256(b"tensorfold-glm-vision-v1\0")
++ for kind, x in items:
++ digest.update(kind.encode() + json.dumps(list(x.shape)).encode())
++ digest.update(x.numpy().tobytes())
++ return GlmPrepared(ids, items, positions, digest.hexdigest())
++
++ @staticmethod
++ def _rows(kind: str, x) -> int:
++ pairs = x.shape[0] // 2 if kind == "video" else 1
++ return pairs * (x.shape[-2] // 28) * (x.shape[-1] // 28)
++
++ def features(self, prepared: GlmPrepared):
++ return self.tower.features(prepared.items)
++
++ def warm(self) -> None:
++ """Run a small picture through the tower once, so its kernels are loaded before the first request."""
++
++ import torch
++
++ self.tower.features([("image", torch.zeros((3, 56, 56), dtype=torch.uint8))])
++ torch.cuda.synchronize()
+diff --git tensorfold/vision/images.py tensorfold/vision/images.py
+index cd4b1d2..e68c516 100644
+--- tensorfold/vision/images.py
++++ tensorfold/vision/images.py
+@@ -113,9 +113,10 @@ def _check_source(source: ImageSource, limits: ImageLimits, allow_urls: bool = F
+ raise ImageInputError("image URL is too long")
+
+
+-def split_images(messages: list[dict[str, Any]], *, limits: ImageLimits = DEFAULT_LIMITS, allow_urls: bool = False
+- ) -> tuple[list[dict[str, Any]], list[ImageSource]]:
+- """Preserve ordered parts, replacing user image URLs with processor image markers."""
++def split_images(messages: list[dict[str, Any]], *, limits: ImageLimits = DEFAULT_LIMITS, allow_urls: bool = False,
++ allow_videos: bool = False) -> tuple[list[dict[str, Any]], list[ImageSource]]:
++ """Preserve ordered parts, replacing user image URLs with processor image markers; ``allow_videos``: also
++ ``video_url`` parts (``VideoSource`` among the sources, a video marker in the template)."""
+ if not isinstance(messages, list) or not messages:
+ raise ImageInputError("messages must be a non-empty list")
+ output, sources = [], []
+@@ -142,18 +143,32 @@ def split_images(messages: list[dict[str, Any]], *, limits: ImageLimits = DEFAUL
+ if not isinstance(part.get("text"), str) or any(part.get(key) for key in _MEDIA):
+ raise ImageInputError("text parts must contain a text string without media")
+ parts.append(dict(part))
++ elif kind == "video_url" and allow_videos:
++ from .videos import DEFAULT_VIDEO_LIMITS, video_source
++
++ if role != "user":
++ raise ImageInputError("video_url parts are supported only in user messages")
++ if any(part.get(key) for key in _MEDIA - {"video_url"}):
++ raise ImageInputError("video_url parts cannot contain other media")
++ videos = sum(type(s).__name__ == "VideoSource" for s in sources)
++ if videos >= DEFAULT_VIDEO_LIMITS.max_videos:
++ raise ImageInputError(f"a request supports at most {DEFAULT_VIDEO_LIMITS.max_videos} videos")
++ sources.append(video_source(part.get("video_url"), DEFAULT_VIDEO_LIMITS, allow_urls))
++ parts.append({"type": "video"})
+ elif kind == "image_url":
+ if role != "user":
+ raise ImageInputError("image_url parts are supported only in user messages")
+ if any(part.get(key) for key in _MEDIA - {"image_url"}):
+ raise ImageInputError("image_url parts cannot contain other media")
+- if len(sources) >= limits.max_images:
++ if sum(isinstance(s, ImageSource) for s in sources) >= limits.max_images:
+ raise ImageInputError(f"a request supports at most {limits.max_images} images")
+ source = _source(part.get("image_url"), limits, allow_urls)
+ sources.append(source)
+ parts.append({"type": "image", "detail": source.detail})
+ else:
+- raise ImageInputError("content parts must be text or image_url; audio and video are unsupported")
++ raise ImageInputError("content parts must be text, image_url or video_url; audio is unsupported"
++ if allow_videos else
++ "content parts must be text or image_url; audio and video are unsupported")
+ output.append({**message, "content": parts})
+ return output, sources
+
+diff --git tensorfold/vision/images_http.py tensorfold/vision/images_http.py
+index 16d6627..f354aea 100644
+--- tensorfold/vision/images_http.py
++++ tensorfold/vision/images_http.py
+@@ -109,7 +109,7 @@ def _close_socket(sock: socket.socket) -> None:
+
+
+ def _request(host: str, port: int, target: str, addresses: list[tuple],
+- max_bytes: int, deadline: float) -> tuple[bytes | None, str | None, str | None]:
++ max_bytes: int, deadline: float, media_types=MEDIA_TYPES) -> tuple[bytes | None, str | None, str | None]:
+ """A watchdog bounds slow headers and TLS handshakes, not just individual reads."""
+ timeout = _remaining(deadline)
+ family, kind, protocol, _, address = addresses[0]
+@@ -128,7 +128,7 @@ def _request(host: str, port: int, target: str, addresses: list[tuple],
+ sock.settimeout(_remaining(deadline))
+ sock.do_handshake()
+ connection.sock = sock
+- connection.request("GET", target, headers={"Accept": ", ".join(MEDIA_TYPES), "Accept-Encoding": "identity",
++ connection.request("GET", target, headers={"Accept": ", ".join(media_types), "Accept-Encoding": "identity",
+ "User-Agent": f"TensorFold/{__version__}"})
+ response = connection.getresponse()
+ _remaining(deadline)
+@@ -142,8 +142,9 @@ def _request(host: str, port: int, target: str, addresses: list[tuple],
+ if response.getheader("Content-Encoding", "identity").lower() != "identity":
+ raise ImageInputError("compressed HTTP image responses are unsupported")
+ media = response.getheader("Content-Type", "").split(";", 1)[0].strip().lower()
+- if media not in MEDIA_TYPES:
+- raise ImageInputError("image URL content type must be JPEG, PNG or WebP")
++ if media not in media_types:
++ raise ImageInputError("image URL content type must be JPEG, PNG or WebP" if media_types is MEDIA_TYPES
++ else f"media URL content type must be one of {', '.join(media_types)}")
+ length = response.getheader("Content-Length")
+ if length is not None:
+ if not length.isascii() or not length.isdecimal() or int(length) > max_bytes:
+@@ -166,13 +167,13 @@ def _request(host: str, port: int, target: str, addresses: list[tuple],
+
+
+ def fetch_image(url: str, *, max_bytes: int, deadline: float, max_redirects: int,
+- max_url_chars: int) -> tuple[bytes, str]:
++ max_url_chars: int, media_types=MEDIA_TYPES) -> tuple[bytes, str]:
+ """Resolve and validate each redirect, then connect directly to its checked address."""
+ try:
+ for redirect in range(max_redirects + 1):
+ host, port, target = _url(url, max_url_chars)
+ addresses = _resolve(host, port, deadline)
+- data, location, media = _request(host, port, target, addresses, max_bytes, deadline)
++ data, location, media = _request(host, port, target, addresses, max_bytes, deadline, media_types)
+ if location is None:
+ return data, media
+ if redirect == max_redirects:
+diff --git tensorfold/vision/videos.py tensorfold/vision/videos.py
+new file mode 100644
+index 0000000..271f7ce
+--- /dev/null
++++ tensorfold/vision/videos.py
+@@ -0,0 +1,172 @@
++"""CPU video inputs: bounded bytes, frames sampled at a fixed rate, decoded straight to the tower's resolution."""
++
++from __future__ import annotations
++
++import hashlib
++import io
++import math
++import time
++from dataclasses import dataclass, field
++from typing import Any, Callable
++
++import numpy as np
++
++from .images import _data_bytes
++from .images_http import ImageInputError, fetch_image
++
++VIDEO_MEDIA_TYPES = {"video/mp4": "mp4", "video/webm": "webm", "video/quicktime": "mov", "video/x-matroska": "mkv"}
++
++
++@dataclass(frozen=True, slots=True)
++class VideoLimits:
++ max_videos: int = 2
++ max_encoded_bytes: int = 64 * 1024 * 1024
++ max_total_encoded_bytes: int = 96 * 1024 * 1024
++ max_dimension: int = 8192
++ max_seconds: float = 3600.0 # of footage; frames past the sampled ones are decoded and dropped
++ fps: float = 2.0 # frames sampled a second (Qwen3-VL's rate)
++ min_frames: int = 4
++ max_frames: int = 256 # a longer video is sampled more sparsely, over its whole length
++ timeout_seconds: float = 20.0
++ total_timeout_seconds: float = 120.0
++ max_redirects: int = 3
++ max_url_chars: int = 4096
++
++
++DEFAULT_VIDEO_LIMITS = VideoLimits()
++
++
++@dataclass(frozen=True, slots=True)
++class VideoSource:
++ url: str
++
++
++@dataclass(frozen=True, slots=True)
++class VideoInput:
++ frames: np.ndarray # [frames, height, width, 3] uint8, already at the tower's resolution
++ indices: tuple[int, ...] # each frame's index in the source
++ fps: float # the source's frame rate
++ content_hash: str = field(init=False)
++
++ def __post_init__(self) -> None:
++ if (not isinstance(self.frames, np.ndarray) or self.frames.dtype != np.uint8 or self.frames.ndim != 4
++ or self.frames.shape[-1] != 3 or len(self.indices) != self.frames.shape[0] or not self.indices
++ or not math.isfinite(self.fps) or self.fps <= 0):
++ raise ImageInputError("video input requires RGB frames, one index each and a positive frame rate")
++ self.frames.setflags(write=False)
++ digest = hashlib.sha256(b"tensorfold-video-v1\0" + np.asarray(self.frames.shape, dtype=">u4").tobytes())
++ digest.update(np.asarray(self.indices, dtype=">u8").tobytes())
++ digest.update(self.frames.tobytes())
++ object.__setattr__(self, "content_hash", digest.hexdigest())
++
++ def timestamps(self, temporal: int) -> list[float]:
++ """Each group of ``temporal`` frames' time: the mean of its first and last frame (Qwen3-VL's processor)."""
++ indices = list(self.indices)
++ if len(indices) % temporal:
++ indices.extend(indices[-1] for _ in range(temporal - len(indices) % temporal))
++ seconds = [i / self.fps for i in indices]
++ return [(seconds[i] + seconds[i + temporal - 1]) / 2 for i in range(0, len(seconds), temporal)]
++
++
++def video_source(value: Any, limits: VideoLimits, allow_urls: bool) -> VideoSource:
++ if not isinstance(value, dict) or not isinstance(value.get("url"), str) or not value["url"]:
++ raise ImageInputError("video_url must contain a non-empty url string")
++ url = value["url"]
++ if url.startswith("data:"):
++ if len(url) > limits.max_encoded_bytes * 3 // 2 + 256:
++ raise ImageInputError("video data URL exceeds the encoded byte limit")
++ elif not url.startswith("https://"):
++ raise ImageInputError("videos require data URLs or public HTTPS URLs")
++ elif not allow_urls:
++ raise ImageInputError("video URLs are off on this server; send the video as a data URL, or start the server "
++ "with --vision-urls")
++ elif len(url) > limits.max_url_chars:
++ raise ImageInputError("video URL is too long")
++ return VideoSource(url)
++
++
++def _av():
++ try:
++ import av
++ except ImportError:
++ raise ImageInputError("video inputs require PyAV (pip install av)") from None
++ return av
++
++
++def sample_indices(total: int, fps: float, limits: VideoLimits) -> np.ndarray:
++ """Qwen3-VL's frame choice: ``limits.fps`` frames a second (at least min_frames, at most max_frames) spread
++ evenly over the whole video."""
++ count = int(total / fps * limits.fps)
++ count = min(max(count, limits.min_frames), limits.max_frames, total)
++ return np.linspace(0, total - 1, count).round().astype(int)
++
++
++def decode_video(data: bytes, size: Callable[[int, int, int], tuple[int, int]], limits: VideoLimits,
++ deadline: float) -> VideoInput:
++ """Decode the sampled frames of one video, each scaled to ``size(frames, height, width)`` (bicubic)."""
++ av = _av()
++ try:
++ with av.open(io.BytesIO(data), mode="r") as container:
++ if not container.streams.video:
++ raise ImageInputError("the video has no video stream")
++ stream = container.streams.video[0]
++ stream.thread_type = "AUTO"
++ width, height = int(stream.codec_context.width or 0), int(stream.codec_context.height or 0)
++ if min(width, height) <= 0 or max(width, height) > limits.max_dimension:
++ raise ImageInputError("video dimensions are missing or exceed the pixel limit")
++ rate = stream.average_rate or stream.guessed_rate or 24
++ fps = float(rate)
++ seconds = float(stream.duration * stream.time_base) if stream.duration else (
++ container.duration / 1e6 if container.duration else 0.0)
++ total = int(stream.frames or round(seconds * fps))
++ if not 0 < fps <= 1000 or total <= 0:
++ raise ImageInputError("the video's frame count or rate is missing")
++ if total / fps > limits.max_seconds:
++ raise ImageInputError(f"videos are limited to {limits.max_seconds / 60:.0f} minutes")
++ wanted = sample_indices(total, fps, limits)
++ out_h, out_w = size(len(wanted), height, width)
++ keep = set(int(i) for i in wanted)
++ frames, indices = [], []
++ for n, frame in enumerate(container.decode(stream)):
++ if n > wanted[-1] or time.monotonic() >= deadline:
++ break
++ if n in keep:
++ frames.append(frame.to_ndarray(format="rgb24", width=out_w, height=out_h,
++ interpolation="BICUBIC"))
++ indices.append(n)
++ if time.monotonic() >= deadline:
++ raise ImageInputError("video decoding exceeds the time limit")
++ except ImageInputError:
++ raise
++ except (OSError, ValueError, MemoryError) as exc:
++ raise ImageInputError(f"video bytes are invalid or unsupported ({type(exc).__name__}); use MP4 or "
++ "WebM") from None
++ if len(frames) < 2:
++ raise ImageInputError("the video has fewer than two decodable frames")
++ return VideoInput(np.stack(frames), tuple(indices), fps)
++
++
++def load_videos(sources: list[VideoSource], size: Callable[[int, int, int], tuple[int, int]], *,
++ limits: VideoLimits = DEFAULT_VIDEO_LIMITS, allow_urls: bool = False) -> list[VideoInput]:
++ """Bound encoded bytes and decoding time across the videos of one request."""
++ if len(sources) > limits.max_videos:
++ raise ImageInputError(f"a request supports at most {limits.max_videos} videos")
++ total = 0
++ deadline = time.monotonic() + limits.total_timeout_seconds
++ output = []
++ for source in sources:
++ remaining = min(limits.max_encoded_bytes, limits.max_total_encoded_bytes - total)
++ if remaining <= 0 or time.monotonic() >= deadline:
++ raise ImageInputError("video request exceeds the total byte or time limit")
++ if source.url.startswith("data:"):
++ data = _data_bytes(source.url, remaining)
++ elif allow_urls:
++ data, _ = fetch_image(source.url, max_bytes=remaining,
++ deadline=min(deadline, time.monotonic() + limits.timeout_seconds),
++ max_redirects=limits.max_redirects, max_url_chars=limits.max_url_chars,
++ media_types=VIDEO_MEDIA_TYPES)
++ else:
++ raise ImageInputError("video URLs are off on this server")
++ total += len(data)
++ output.append(decode_video(data, size, limits, deadline))
++ return output
diff --git a/patches/0004-glm-prompt-kernels.patch b/patches/0004-glm-prompt-kernels.patch
new file mode 100644
index 0000000..b7c902b
--- /dev/null
+++ b/patches/0004-glm-prompt-kernels.patch
@@ -0,0 +1,1140 @@
+diff --git tensorfold/cuda/experts.cpp tensorfold/cuda/experts.cpp
+index 85c2887..c036c64 100644
+--- tensorfold/cuda/experts.cpp
++++ tensorfold/cuda/experts.cpp
+@@ -36,7 +36,7 @@ void plan(const at::Tensor& picks, int64_t pairs, int64_t experts, int64_t tile,
+ TORCH_CHECK(picks.is_contiguous() && picks.numel() >= pairs, "picks: contiguous, one id a pair");
+ for (const auto* t : {&members, &items, &counts, &rank, &hist}) check(*t, "plan buffer", at::kInt);
+ TORCH_CHECK(members.numel() >= pairs && counts.numel() >= 2, "plan buffers too small");
+- TORCH_CHECK(tile == 16 || tile == 64, "items hold 16 pairs (decode) or 64 (prefill)");
++ TORCH_CHECK(tile == 16 || tile == 64 || tile == 128, "items hold 16 pairs (decode), 64 or 128 (prefill)");
+ experts_plan_cuda(picks, pairs, experts, tile, members, items, counts, rank, hist);
+ }
+
+diff --git tensorfold/cuda/experts.py tensorfold/cuda/experts.py
+index 1a39067..450503c 100644
+--- tensorfold/cuda/experts.py
++++ tensorfold/cuda/experts.py
+@@ -20,7 +20,7 @@ def _ext():
+ from tensorfold.cuda.build import load
+
+ here = Path(__file__).parent
+- return load(name="tensorfold_experts_v7", sources=[str(here / "experts.cpp"), str(here / "experts.cu"),
++ return load(name="tensorfold_experts_v8", sources=[str(here / "experts.cpp"), str(here / "experts.cu"),
+ str(here / "experts_prefill.cu"), str(here / "experts_pack.cu")],
+ extra_cuda_cflags=["-O3"], verbose=False)
+
+@@ -102,10 +102,10 @@ class Plan:
+ """Scratch grouping pairs by expert: members, items (expert, first, count), counts [items, distinct experts]."""
+
+ def __init__(self, rows: int, slots: int, experts: int, device: torch.device | str, *,
+- prefill: bool = False) -> None:
++ 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.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.counts = torch.zeros((2,), dtype=torch.int32, device=device)
+diff --git tensorfold/cuda/geometry.py tensorfold/cuda/geometry.py
+index ee444c2..908f94e 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)
+
+
+-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:
+ 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
+ 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
+ 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)
+ 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
++ dense = min(capacity, minimum_slots) + prefill_rows
++ scratch += ((dense + 511) // 512) * prefill_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
+ return Geometry(bytes_at, reserve, minimum_slots)
+
+
+-def mla_chunk_scratch(t: dict, world: int, capacity: int, *, latent: bool) -> int:
++def mla_chunk_scratch(t: dict, world: int, capacity: int, *, latent: bool, prefill_rows: int = PREFILL_ROWS) -> int:
+ """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))
+ 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
+ kd = int(t["qk_nope_head_dim"]) + int(t.get("qk_rope_head_dim", 0))
+ 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
+--- 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)
+ # --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
+-# scales it; TENSORFOLD_VISION_WORKSPACE_MIB sets it outright
+-VISION_WORKSPACE = 3 * 2**29
++# prompt's feature rows (8 KiB a row, which stay through the prefill). The encode's scratch takes turns with a prompt
++# chunk's transient scratch (~1 GiB at 164k), so this covers the rows and the scratch past it. A picture cap past
++# 4,096 tokens scales it; TENSORFOLD_VISION_WORKSPACE_MIB sets it outright
++VISION_WORKSPACE = 3 * 2**28
+
+
+ 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)
++ # 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:
++ prefill_rows = int(os.environ.get("TF_GLM_PREFILL_ROWS", "") or PREFILL_ROWS)
++ 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}")
+ 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:
+ 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)
+ 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:
+ 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]
+ # 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:
+ 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()
++ # the tower's scratch and a prompt chunk's (token selection, sparse partials) take turns in the same
++ # memory: torch's cache goes back to the driver before and after the encode
++ self.torch.cuda.empty_cache()
+ rows = self.vision.features(vision)
++ self.torch.cuda.empty_cache()
+ if rows.shape[0] != len(positions):
+ raise ValueError(f"the tower gave {rows.shape[0]} rows for {len(positions)} image positions")
+ feed = VisionFeed(self, positions, rows)
+diff --git tensorfold/families/glm5_next/cuda/exl3.cpp tensorfold/families/glm5_next/cuda/exl3.cpp
+index 789d20e..79210dd 100644
+--- tensorfold/families/glm5_next/cuda/exl3.cpp
++++ tensorfold/families/glm5_next/cuda/exl3.cpp
+@@ -3,7 +3,7 @@
+
+ void exl3_grouped_cuda(const at::Tensor&, const at::Tensor&, const at::Tensor&, const at::Tensor&, const at::Tensor&,
+ const at::Tensor&, const at::Tensor&, at::Tensor&, int64_t, int64_t, int64_t, int64_t, int64_t,
+- int64_t, int64_t, int64_t, int64_t, bool, bool);
++ int64_t, int64_t, int64_t, int64_t, bool, bool, bool);
+ void exl3_rot_in_cuda(const at::Tensor&, int64_t, const at::Tensor&, const at::Tensor&, const at::Tensor&, at::Tensor&,
+ at::Tensor&, int64_t, int64_t, int64_t);
+ void exl3_gateup_epilogue_cuda(const at::Tensor&, const at::Tensor&, const at::Tensor&, const at::Tensor&,
+@@ -11,6 +11,11 @@ void exl3_gateup_epilogue_cuda(const at::Tensor&, const at::Tensor&, const at::T
+ void exl3_down_epilogue_cuda(const at::Tensor&, const at::Tensor&, const at::Tensor&, at::Tensor&, int64_t, int64_t,
+ int64_t, int64_t, int64_t);
+
++void exl3_prompt_cuda(const at::Tensor&, const at::Tensor&, const at::Tensor&, const at::Tensor&, const at::Tensor&,
++ const at::Tensor&, const at::Tensor&, const at::Tensor&, const at::Tensor&, const at::Tensor&,
++ const at::Tensor&, const at::Tensor&, at::Tensor&, at::Tensor&, int64_t, int64_t, int64_t, int64_t,
++ double, int64_t);
++
+ static void check(const at::Tensor& x, at::ScalarType t, const char* name) {
+ TORCH_CHECK(x.is_cuda() && x.scalar_type() == t && x.is_contiguous(), name,
+ ": expected a contiguous CUDA tensor of the right dtype");
+@@ -19,7 +24,7 @@ static void check(const at::Tensor& x, at::ScalarType t, const char* name) {
+ void grouped(const at::Tensor& X0, const at::Tensor& X1, const at::Tensor& T0, const at::Tensor& T1,
+ const at::Tensor& items, const at::Tensor& counts, const at::Tensor& members, at::Tensor Z, int64_t mats,
+ int64_t K, int64_t N, int64_t P, int64_t SK, int64_t max_items, int64_t nt, int64_t warps, bool nfirst,
+- bool pf) {
++ bool pf, bool seq) {
+ const int64_t E = T0.size(0);
+ check(X0, at::kHalf, "X0");
+ check(X1, at::kHalf, "X1");
+@@ -31,7 +36,7 @@ void grouped(const at::Tensor& X0, const at::Tensor& X1, const at::Tensor& T0, c
+ check(Z, at::kFloat, "Z");
+ TORCH_CHECK(Z.numel() >= mats * SK * P * N, "Z too small");
+ c10::cuda::CUDAGuard guard(X0.device());
+- exl3_grouped_cuda(X0, X1, T0, T1, items, counts, members, Z, mats, K, N, P, SK, max_items, nt, warps, E, nfirst, pf);
++ exl3_grouped_cuda(X0, X1, T0, T1, items, counts, members, Z, mats, K, N, P, SK, max_items, nt, warps, E, nfirst, pf, seq);
+ }
+
+ void rot_in(const at::Tensor& x, int64_t x_stride, const at::Tensor& pick, const at::Tensor& suh0,
+@@ -72,8 +77,23 @@ void down_epilogue(const at::Tensor& Z, const at::Tensor& pick, const at::Tensor
+ exl3_down_epilogue_cuda(Z, pick, svh_d, y, rows, P, D, SK, slots);
+ }
+
++void prompt(const at::Tensor& Xg, const at::Tensor& Xu, const at::Tensor& Tg, const at::Tensor& Tu,
++ const at::Tensor& Td, const at::Tensor& items, const at::Tensor& counts, const at::Tensor& members,
++ const at::Tensor& svh_g, const at::Tensor& svh_u, const at::Tensor& suh_d, const at::Tensor& svh_d,
++ at::Tensor xd, at::Tensor y, int64_t D, int64_t N, int64_t E, int64_t max_items, double limit,
++ int64_t pass) {
++ const at::cuda::CUDAGuard guard(Xg.device());
++ for (auto* t : {&Xg, &Xu, &svh_g, &svh_u, &suh_d, &svh_d}) check(*t, at::kHalf, "prompt: fp16 input");
++ for (auto* t : {&Tg, &Tu, &Td, &items, &counts, &members}) check(*t, at::kInt, "prompt: int32 input");
++ check(xd, at::kHalf, "prompt: xd");
++ check(y, at::kFloat, "prompt: y");
++ exl3_prompt_cuda(Xg, Xu, Tg, Tu, Td, items, counts, members, svh_g, svh_u, suh_d, svh_d, xd, y, D, N, E,
++ max_items, limit, pass);
++}
++
+ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
+ m.def("grouped", &grouped);
++ m.def("prompt", &prompt);
+ m.def("rot_in", &rot_in);
+ m.def("gateup_epilogue", &gateup_epilogue);
+ m.def("down_epilogue", &down_epilogue);
+diff --git tensorfold/families/glm5_next/cuda/exl3.cu tensorfold/families/glm5_next/cuda/exl3.cu
+index 47cf55c..7a27c46 100644
+--- tensorfold/families/glm5_next/cuda/exl3.cu
++++ tensorfold/families/glm5_next/cuda/exl3.cu
+@@ -53,7 +53,10 @@ __device__ __forceinline__ uint32_t load_pair(const half* x, bool ok) {
+ }
+
+ // Grid (item, n block, mat * SK + split) -> Z[mat][split][pair][n]; warps sum fixed k ranges, added in warp order.
+-template <int NT, int W, bool NFIRST, bool PF>
++// SEQ (prompt chunks): grid (.., .., mat); one program runs the SK splits in turn and writes Z[mat][0][pair][n] =
++// ((0 + split 0) + split 1) + ..., the epilogue's own sum, so an SK = 1 epilogue gives the same bits without the
++// SK fp32 partials' round trip through memory.
++template <int NT, int W, bool NFIRST, bool PF, bool SEQ>
+ __global__ void __launch_bounds__(W * 32) grouped_kernel(
+ const half* __restrict__ X0, const half* __restrict__ X1, const uint32_t* __restrict__ T0,
+ const uint32_t* __restrict__ T1, const int* __restrict__ items, const int* __restrict__ counts,
+@@ -64,8 +67,7 @@ __global__ void __launch_bounds__(W * 32) grouped_kernel(
+ if (item >= counts[0]) return;
+ const int e = items[3 * item], first = items[3 * item + 1], cnt = items[3 * item + 2];
+ if (e >= E) return; // the shared expert (id E) is not EXL3
+- const int split = blockIdx.z % SK;
+- const int mat = blockIdx.z / SK;
++ const int mat = SEQ ? blockIdx.z : blockIdx.z / SK;
+ const half* X = mat ? X1 : X0;
+ const uint32_t* T = mat ? T1 : T0;
+ const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31;
+@@ -80,8 +82,13 @@ __global__ void __launch_bounds__(W * 32) grouped_kernel(
+ const half* x1 = X + (size_t)(r1 < 0 ? 0 : r1) * K + 2 * t;
+
+ const int per_split = KT / SK, per_warp = per_split / W;
+- const int kt0 = split * per_split + warp * per_warp;
+ const int nt0 = nblock * NT;
++ constexpr int OUT = 16 * NT * 16 / (W * 32); // the sums a thread writes (SEQ keeps them in registers)
++ float tot[OUT];
++ __shared__ float red[W][16][NT * 16];
++ for (int si = 0; si < (SEQ ? SK : 1); ++si) {
++ const int split = SEQ ? si : blockIdx.z % SK;
++ const int kt0 = split * per_split + warp * per_warp;
+ const uint32_t* tile = T + (((size_t)e * KT + kt0) * NTILES + nt0) * 32 + lane;
+
+ float acc[NT][2][4];
+@@ -148,7 +155,7 @@ __global__ void __launch_bounds__(W * 32) grouped_kernel(
+ }
+
+ // warps' partial sums through shared memory, added in warp order
+- __shared__ float red[W][16][NT * 16];
++ if (SEQ && si > 0) __syncthreads(); // the previous split's sums are read
+ #pragma unroll
+ for (int i = 0; i < NT; ++i)
+ #pragma unroll
+@@ -160,14 +167,29 @@ __global__ void __launch_bounds__(W * 32) grouped_kernel(
+ red[warp][g + 8][col + 1] = acc[i][h][3];
+ }
+ __syncthreads();
+- for (int idx = threadIdx.x; idx < 16 * NT * 16; idx += W * 32) {
++#pragma unroll
++ for (int j = 0; j < OUT; ++j) {
++ const int idx = threadIdx.x + j * W * 32;
+ const int row = idx / (NT * 16), col = idx % (NT * 16);
+ const int r = rows_sh[row];
+- if (r < 0) continue;
+ float s = red[0][row][col];
+ #pragma unroll
+ for (int w = 1; w < W; ++w) s += red[w][row][col];
+- Z[(((size_t)mat * SK + split) * P + r) * N + nt0 * 16 + col] = s;
++ if (SEQ) {
++ tot[j] = si == 0 ? 0.f + s : tot[j] + s;
++ } else if (r >= 0) {
++ Z[(((size_t)mat * SK + split) * P + r) * N + nt0 * 16 + col] = s;
++ }
++ }
++ } // splits
++ if (SEQ) {
++#pragma unroll
++ for (int j = 0; j < OUT; ++j) {
++ const int idx = threadIdx.x + j * W * 32;
++ const int row = idx / (NT * 16), col = idx % (NT * 16);
++ const int r = rows_sh[row];
++ if (r >= 0) Z[((size_t)mat * P + r) * N + nt0 * 16 + col] = tot[j];
++ }
+ }
+ }
+
+@@ -274,16 +296,268 @@ __global__ void down_epilogue_kernel(const float* __restrict__ Z, const int* __r
+ for (int j = 0; j < 4; ++j) o[j] = v[j] * HAD_SCALE * __half2float(svh_d[(size_t)e * D + n + j]);
+ }
+
++
++// ---- prompt chunks: Y^T = W^T X^T --------------------------------------------------------------------------------
++// A decoded trellis tile is, reordered, an m16n8k16 A fragment of W^T (lane (g, t): a0 = b0[0], a1 = b1[0],
++// a2 = b0[1], a3 = b1[1]), so each warp decodes its own tiles straight into registers and every decoded fragment
++// feeds the whole pass's member rows (up to 64 tokens, the prefill plan's item) as B fragments from shared memory.
++// Each output is one fp32 chain of mma over ascending k tiles (no split K, no partials in memory), so a row's bits
++// depend on its own values only (any chunking gives the same prompt state), though they are not the decode
++// kernel's (which sums split and warp partials). The epilogues are gateup/down_epilogue_kernel's formulas.
++constexpr int PBK = 32; // k values a shared-memory stage (2 k tiles)
++constexpr int PKT = PBK / 16;
++constexpr int PSTAGES = 3;
++constexpr int PXS = PBK + 8; // stage row stride in halves (+16 B: ldmatrix rows on distinct banks)
++
++__device__ __forceinline__ void cp_async16(void* smem, const void* gmem, bool ok) {
++ const unsigned s = (unsigned)__cvta_generic_to_shared(smem);
++ asm volatile("cp.async.cg.shared.global [%0], [%1], 16, %2;\n" ::"r"(s), "l"(gmem), "r"(ok ? 16 : 0));
++}
++__device__ __forceinline__ void cp_async_commit() { asm volatile("cp.async.commit_group;\n" ::); }
++template <int N>
++__device__ __forceinline__ void cp_async_wait() { asm volatile("cp.async.wait_group %0;\n" ::"n"(N)); }
++__device__ __forceinline__ void ldsm_x4(uint32_t (&r)[4], const void* p) {
++ const unsigned s = (unsigned)__cvta_generic_to_shared(p);
++ asm volatile("ldmatrix.sync.aligned.m8n8.x4.shared.b16 {%0,%1,%2,%3}, [%4];\n"
++ : "=r"(r[0]), "=r"(r[1]), "=r"(r[2]), "=r"(r[3])
++ : "r"(s));
++}
++
++// A block covers 16 m tiles (gate/up: 8 of each matrix = one 128-column Hadamard block; down: 256 columns) for a
++// pass of PM members with NW warps: each warp holds MT = 16 / NW m tiles for all PM members (PM / 8 n blocks), so a
++// decoded tile feeds PM / 8 mma. PM 64 / 8 warps (two blocks an SM) or PM 128 / 16 warps (one): the same per-element
++// chains, so the same bits. Every stage brings the members' next PBK k values and the 16 tiles' trellis words into
++// shared memory (cp.async, PSTAGES deep).
++constexpr int PWORDS = 16 * PKT * 32; // a stage's trellis words (16 m tiles x PKT k tiles x 32)
++
++template <int MATS, int PM, int NW>
++struct PromptCfg {
++ static constexpr int MT = 16 / NW, NB = PM / 8, T = NW * 32;
++ static constexpr size_t STAGE_HALVES = (size_t)MATS * PM * PXS + 2 * PWORDS;
++};
++
++// Which (matrix, m tile) warp-tile q (0..15) of block cb is.
++template <int MATS>
++__device__ __forceinline__ void prompt_tile(int q, int cb, int& mat, int& nt) {
++ mat = MATS == 2 ? q >> 3 : 0;
++ nt = MATS == 2 ? cb * 8 + (q & 7) : cb * 16 + q;
++}
++
++template <int MATS, int PM, int NW>
++__device__ __forceinline__ void prompt_mainloop(const half* __restrict__ X0, const half* __restrict__ X1,
++ const uint32_t* __restrict__ T0, const uint32_t* __restrict__ T1,
++ const int* rows_sh, int cnt, int e, int K, int NTILES, int cb,
++ half* stage, float (&acc)[16 / NW][PM / 8][4]) {
++ using C = PromptCfg<MATS, PM, NW>;
++ const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31;
++ int mat, nt_unused;
++ prompt_tile<MATS>(warp * C::MT, cb, mat, nt_unused);
++ const int KT = K >> 4, chunks = K / PBK;
++ const int nblocks = (cnt + 15) >> 4; // 16-member blocks in use
++
++#pragma unroll
++ for (int i = 0; i < C::MT; ++i)
++#pragma unroll
++ for (int j = 0; j < C::NB; ++j)
++#pragma unroll
++ for (int c = 0; c < 4; ++c) acc[i][j][c] = 0.f;
++
++ auto load = [&](int chunk) {
++ half* dst = stage + (size_t)(chunk % PSTAGES) * C::STAGE_HALVES;
++ const int k0 = chunk * PBK;
++ for (int idx = threadIdx.x; idx < MATS * PM * (PBK / 8); idx += C::T) {
++ const int m = idx / (PM * (PBK / 8)), rem = idx % (PM * (PBK / 8)), i = rem / (PBK / 8),
++ j = rem % (PBK / 8);
++ const int r = rows_sh[i];
++ const half* src = (m ? X1 : X0) + (size_t)(r < 0 ? 0 : r) * K + k0 + j * 8;
++ cp_async16(dst + ((size_t)m * PM + i) * PXS + j * 8, src, r >= 0);
++ }
++ uint32_t* wdst = reinterpret_cast<uint32_t*>(dst + (size_t)MATS * PM * PXS);
++ for (int idx = threadIdx.x; idx < 16 * PKT * 8; idx += C::T) { // 16 B pieces of 128-B tile words
++ const int q = idx / (PKT * 8), kk = (idx / 8) % PKT, part = idx % 8;
++ int wm, nt;
++ prompt_tile<MATS>(q, cb, wm, nt);
++ const uint32_t* src = (wm ? T1 : T0) + (((size_t)e * KT + chunk * PKT + kk) * NTILES + nt) * 32 + part * 4;
++ cp_async16(wdst + ((size_t)q * PKT + kk) * 32 + part * 4, src, true);
++ }
++ };
++#pragma unroll
++ for (int c = 0; c < PSTAGES - 1; ++c) {
++ if (c < chunks) load(c);
++ cp_async_commit();
++ }
++ for (int c = 0; c < chunks; ++c) {
++ cp_async_wait<PSTAGES - 2>();
++ __syncthreads();
++ if (c + PSTAGES - 1 < chunks) load(c + PSTAGES - 1);
++ cp_async_commit();
++ const half* base = stage + (size_t)(c % PSTAGES) * C::STAGE_HALVES;
++ const half* xs = base + (size_t)mat * PM * PXS;
++ const uint32_t* ws = reinterpret_cast<const uint32_t*>(base + (size_t)MATS * PM * PXS);
++#pragma unroll
++ for (int kk = 0; kk < PKT; ++kk) {
++ uint32_t a[C::MT][4];
++#pragma unroll
++ for (int i = 0; i < C::MT; ++i) {
++ uint32_t b0[2], b1[2];
++ decode_tile(ws[((size_t)(warp * C::MT + i) * PKT + kk) * 32 + lane], lane, b0, b1);
++ a[i][0] = b0[0]; a[i][1] = b1[0]; a[i][2] = b0[1]; a[i][3] = b1[1];
++ }
++#pragma unroll
++ for (int jb = 0; jb < PM / 16; ++jb) {
++ if (jb < nblocks) {
++ uint32_t r[4];
++ const int row = jb * 16 + (lane & 7) + ((lane >> 4) & 1) * 8;
++ ldsm_x4(r, xs + (size_t)row * PXS + kk * 16 + ((lane >> 3) & 1) * 8);
++ const uint32_t bl[2] = {r[0], r[1]}, bh[2] = {r[2], r[3]};
++#pragma unroll
++ for (int i = 0; i < C::MT; ++i) {
++ mma16816(acc[i][2 * jb], a[i], bl);
++ mma16816(acc[i][2 * jb + 1], a[i], bh);
++ }
++ }
++ }
++ }
++ }
++ cp_async_wait<0>();
++ __syncthreads(); // the stages become the epilogue's rows
++}
++
++// acc (this warp's m tiles, members PM / 2 * hf .. + PM / 2 - 1) -> E[member - PM / 2 * hf][col] fp32, row stride
++// ES; col0: the first m tile's first column within the block's E columns.
++template <int MT, int PM>
++__device__ __forceinline__ void prompt_spill(float* E, int ES, int col0, const float (&acc)[MT][PM / 8][4], int hf) {
++ const int lane = threadIdx.x & 31, g = lane >> 2, t = lane & 3;
++#pragma unroll
++ for (int i = 0; i < MT; ++i)
++#pragma unroll
++ for (int q = 0; q < PM / 16; ++q) {
++ const int nb = hf * (PM / 16) + q;
++ const int tok = q * 8 + 2 * t, col = col0 + i * 16 + g;
++ E[(size_t)tok * ES + col] = acc[i][nb][0];
++ E[(size_t)(tok + 1) * ES + col] = acc[i][nb][1];
++ E[(size_t)tok * ES + col + 8] = acc[i][nb][2];
++ E[(size_t)(tok + 1) * ES + col + 8] = acc[i][nb][3];
++ }
++}
++
++constexpr int GU_ES = 128 + 4, DN_ES = 256 + 4;
++template <int PM>
++constexpr size_t prompt_smem() {
++ // max of: gate/up stages, down stages, gate/up epilogue half (2 x PM/2 x GU_ES), down half (PM/2 x DN_ES)
++ const size_t gu = (size_t)PSTAGES * (2 * PM * PXS + 2 * PWORDS) * 2;
++ const size_t ep = (size_t)2 * (PM / 2) * GU_ES * 4;
++ const size_t dn = (size_t)(PM / 2) * DN_ES * 4;
++ return gu > ep ? (gu > dn ? gu : dn) : (ep > dn ? ep : dn);
++}
++
++template <int PM, int NW>
++__global__ void __launch_bounds__(NW * 32, 16 / NW) prompt_gateup_kernel(
++ const half* __restrict__ Xg, const half* __restrict__ Xu, const uint32_t* __restrict__ Tg,
++ const uint32_t* __restrict__ Tu, const int* __restrict__ items, const int* __restrict__ counts,
++ const int* __restrict__ members, const half* __restrict__ svh_g, const half* __restrict__ svh_u,
++ const half* __restrict__ suh_d, half* __restrict__ xd, int K, int N, int E, float limit) {
++ constexpr int MT = 16 / NW, PH = PM / 2;
++ extern __shared__ __align__(16) unsigned char smem_raw[];
++ __shared__ int rows_sh[PM];
++ const int cb = blockIdx.x, item = blockIdx.y;
++ if (item >= counts[0]) return;
++ const int e = items[3 * item], first = items[3 * item + 1], cnt = items[3 * item + 2];
++ if (e >= E) return; // the shared expert
++ if (threadIdx.x < PM) rows_sh[threadIdx.x] = (int)threadIdx.x < cnt ? members[first + threadIdx.x] : -1;
++ __syncthreads();
++ const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31;
++ float acc[MT][PM / 8][4];
++ prompt_mainloop<2, PM, NW>(Xg, Xu, Tg, Tu, rows_sh, cnt, e, K, N >> 4, cb, reinterpret_cast<half*>(smem_raw),
++ acc);
++ float* Eg = reinterpret_cast<float*>(smem_raw);
++ int mat, nt;
++ prompt_tile<2>(warp * MT, cb, mat, nt);
++ const int col0 = (nt - cb * 8) * 16;
++ const int n = cb * 128 + 4 * lane;
++ for (int hf = 0; hf < 2 && hf * PH < cnt; ++hf) {
++ if (hf) __syncthreads(); // the first half's rows are read
++ prompt_spill<MT, PM>(Eg + (size_t)mat * PH * GU_ES, GU_ES, col0, acc, hf);
++ __syncthreads();
++ for (int i = warp; i < PH && hf * PH + i < cnt; i += NW) {
++ const int p = rows_sh[hf * PH + i];
++ float gv[4], uv[4];
++#pragma unroll
++ for (int j = 0; j < 4; ++j) {
++ gv[j] = Eg[(size_t)i * GU_ES + 4 * lane + j];
++ uv[j] = Eg[(size_t)(PH + i) * GU_ES + 4 * lane + j];
++ }
++ fwht128(gv, lane);
++ fwht128(uv, lane);
++ float v[4];
++#pragma unroll
++ for (int j = 0; j < 4; ++j) {
++ float gg = fminf(bf16r(gv[j] * HAD_SCALE * __half2float(svh_g[(size_t)e * N + n + j])), limit);
++ float uu = fminf(fmaxf(bf16r(uv[j] * HAD_SCALE * __half2float(svh_u[(size_t)e * N + n + j])), -limit),
++ limit);
++ float act = bf16r(bf16r(gg / (1.f + expf(-gg))) * uu);
++ v[j] = act * __half2float(suh_d[(size_t)e * N + n + j]);
++ }
++ fwht128(v, lane);
++ half* o = xd + (size_t)p * N + n;
++#pragma unroll
++ for (int j = 0; j < 4; ++j) o[j] = __float2half_rn(v[j] * HAD_SCALE);
++ }
++ } // halves
++}
++
++template <int PM, int NW>
++__global__ void __launch_bounds__(NW * 32, 16 / NW) prompt_down_kernel(
++ const half* __restrict__ Xd, const uint32_t* __restrict__ Td, const int* __restrict__ items,
++ const int* __restrict__ counts, const int* __restrict__ members, const half* __restrict__ svh_d,
++ float* __restrict__ y, int K, int D, int E) {
++ constexpr int MT = 16 / NW, PH = PM / 2;
++ extern __shared__ __align__(16) unsigned char smem_raw[];
++ __shared__ int rows_sh[PM];
++ const int cb = blockIdx.x, item = blockIdx.y;
++ if (item >= counts[0]) return;
++ const int e = items[3 * item], first = items[3 * item + 1], cnt = items[3 * item + 2];
++ if (e >= E) return;
++ if (threadIdx.x < PM) rows_sh[threadIdx.x] = (int)threadIdx.x < cnt ? members[first + threadIdx.x] : -1;
++ __syncthreads();
++ const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31;
++ float acc[MT][PM / 8][4];
++ prompt_mainloop<1, PM, NW>(Xd, Xd, Td, Td, rows_sh, cnt, e, K, D >> 4, cb, reinterpret_cast<half*>(smem_raw),
++ acc);
++ float* Ed = reinterpret_cast<float*>(smem_raw);
++ for (int hf = 0; hf < 2 && hf * PH < cnt; ++hf) {
++ if (hf) __syncthreads();
++ prompt_spill<MT, PM>(Ed, DN_ES, warp * MT * 16, acc, hf);
++ __syncthreads();
++ for (int i = warp; i < PH && hf * PH + i < cnt; i += NW) {
++ const int p = rows_sh[hf * PH + i];
++#pragma unroll
++ for (int blk = 0; blk < 2; ++blk) {
++ const int n = cb * 256 + blk * 128 + 4 * lane;
++ float v[4];
++#pragma unroll
++ for (int j = 0; j < 4; ++j) v[j] = Ed[(size_t)i * DN_ES + blk * 128 + 4 * lane + j];
++ fwht128(v, lane);
++ float* o = y + (size_t)p * D + n;
++#pragma unroll
++ for (int j = 0; j < 4; ++j) o[j] = v[j] * HAD_SCALE * __half2float(svh_d[(size_t)e * D + n + j]);
++ }
++ }
++ } // halves
++}
++
+ } // namespace
+
+ // Z [mats, SK, P, N] fp32 = X_mat[each item's pairs] @ W_q(T_mat[the item's expert]) over each split.
+ void exl3_grouped_cuda(const at::Tensor& X0, const at::Tensor& X1, const at::Tensor& T0, const at::Tensor& T1,
+ const at::Tensor& items, const at::Tensor& counts, const at::Tensor& members, at::Tensor& Z,
+ int64_t mats, int64_t K, int64_t N, int64_t P, int64_t SK, int64_t max_items, int64_t nt,
+- int64_t warps, int64_t E, bool nfirst, bool pf) {
++ int64_t warps, int64_t E, bool nfirst, bool pf, bool seq) {
+ TORCH_CHECK(K % (16 * SK * warps) == 0 && N % (16 * nt) == 0, "K and N must split evenly");
+- dim3 grid = nfirst ? dim3((unsigned)(N / (16 * nt)), (unsigned)max_items, (unsigned)(mats * SK))
+- : dim3((unsigned)max_items, (unsigned)(N / (16 * nt)), (unsigned)(mats * SK));
++ TORCH_CHECK(!seq || nfirst, "SEQ runs with the prompt launch order");
++ const unsigned zdim = (unsigned)(seq ? mats : mats * SK);
++ dim3 grid = nfirst ? dim3((unsigned)(N / (16 * nt)), (unsigned)max_items, zdim)
++ : dim3((unsigned)max_items, (unsigned)(N / (16 * nt)), zdim);
+ auto stream = at::cuda::getCurrentCUDAStream();
+ auto x0 = reinterpret_cast<const half*>(X0.data_ptr());
+ auto x1 = reinterpret_cast<const half*>(X1.data_ptr());
+@@ -291,8 +565,9 @@ void exl3_grouped_cuda(const at::Tensor& X0, const at::Tensor& X1, const at::Ten
+ auto t1 = reinterpret_cast<const uint32_t*>(T1.data_ptr());
+ #define LAUNCH(NT_, W_) \
+ do { \
+- auto fn = nfirst ? (pf ? grouped_kernel<NT_, W_, true, true> : grouped_kernel<NT_, W_, true, false>) \
+- : (pf ? grouped_kernel<NT_, W_, false, true> : grouped_kernel<NT_, W_, false, false>); \
++ auto fn = seq ? (pf ? grouped_kernel<NT_, W_, true, true, true> : grouped_kernel<NT_, W_, true, false, true>) \
++ : nfirst ? (pf ? grouped_kernel<NT_, W_, true, true, false> : grouped_kernel<NT_, W_, true, false, false>) \
++ : (pf ? grouped_kernel<NT_, W_, false, true, false> : grouped_kernel<NT_, W_, false, false, false>); \
+ fn<<<grid, W_ * 32, 0, stream>>>(x0, x1, t0, t1, items.data_ptr<int>(), counts.data_ptr<int>(), \
+ members.data_ptr<int>(), Z.data_ptr<float>(), (int)K, (int)N, (int)P, \
+ (int)SK, (int)E); \
+@@ -337,3 +612,47 @@ void exl3_down_epilogue_cuda(const at::Tensor& Z, const at::Tensor& pick, const
+ y.data_ptr<float>(), (int)P, (int)D, (int)SK, (int)slots);
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
+ }
++
++// Prompt chunks (a plan of PM-pair items, PM 64 or 128): Xd [P, N] = the gate/up epilogue of Xg/Xu's pairs;
++// Y [P, D] = the down epilogue.
++template <int PM, int NW>
++static void prompt_launch(const at::Tensor& Xg, const at::Tensor& Xu, const at::Tensor& Tg, const at::Tensor& Tu,
++ const at::Tensor& Td, const at::Tensor& items, const at::Tensor& counts,
++ const at::Tensor& members, const at::Tensor& svh_g, const at::Tensor& svh_u,
++ const at::Tensor& suh_d, const at::Tensor& svh_d, at::Tensor& xd, at::Tensor& y, int64_t D,
++ int64_t N, int64_t E, int64_t max_items, double limit) {
++ constexpr size_t SMEM = prompt_smem<PM>();
++ static bool once = [] {
++ cudaFuncSetAttribute(prompt_gateup_kernel<PM, NW>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int)SMEM);
++ cudaFuncSetAttribute(prompt_down_kernel<PM, NW>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int)SMEM);
++ return true;
++ }();
++ (void)once;
++ auto stream = at::cuda::getCurrentCUDAStream();
++ auto h = [](const at::Tensor& t) { return reinterpret_cast<const half*>(t.data_ptr()); };
++ auto w = [](const at::Tensor& t) { return reinterpret_cast<const uint32_t*>(t.data_ptr()); };
++ prompt_gateup_kernel<PM, NW><<<dim3((unsigned)(N / 128), (unsigned)max_items), NW * 32, SMEM, stream>>>(
++ h(Xg), h(Xu), w(Tg), w(Tu), items.data_ptr<int>(), counts.data_ptr<int>(), members.data_ptr<int>(),
++ h(svh_g), h(svh_u), h(suh_d), reinterpret_cast<half*>(xd.data_ptr()), (int)D, (int)N, (int)E, (float)limit);
++ C10_CUDA_KERNEL_LAUNCH_CHECK();
++ prompt_down_kernel<PM, NW><<<dim3((unsigned)(D / 256), (unsigned)max_items), NW * 32, SMEM, stream>>>(
++ reinterpret_cast<const half*>(xd.data_ptr()), w(Td), items.data_ptr<int>(), counts.data_ptr<int>(),
++ members.data_ptr<int>(), h(svh_d), y.data_ptr<float>(), (int)N, (int)D, (int)E);
++ C10_CUDA_KERNEL_LAUNCH_CHECK();
++}
++
++void exl3_prompt_cuda(const at::Tensor& Xg, const at::Tensor& Xu, const at::Tensor& Tg, const at::Tensor& Tu,
++ const at::Tensor& Td, const at::Tensor& items, const at::Tensor& counts,
++ const at::Tensor& members, const at::Tensor& svh_g, const at::Tensor& svh_u,
++ const at::Tensor& suh_d, const at::Tensor& svh_d, at::Tensor& xd, at::Tensor& y, int64_t D,
++ int64_t N, int64_t E, int64_t max_items, double limit, int64_t pass) {
++ TORCH_CHECK(D % 256 == 0 && N % 128 == 0 && D % PBK == 0 && N % PBK == 0, "prompt experts: shapes");
++ if (pass == 128)
++ prompt_launch<128, 16>(Xg, Xu, Tg, Tu, Td, items, counts, members, svh_g, svh_u, suh_d, svh_d, xd, y, D, N,
++ E, max_items, limit);
++ else if (pass == 64)
++ prompt_launch<64, 8>(Xg, Xu, Tg, Tu, Td, items, counts, members, svh_g, svh_u, suh_d, svh_d, xd, y, D, N, E,
++ max_items, limit);
++ else
++ TORCH_CHECK(false, "prompt experts: passes of 64 or 128 members");
++}
+diff --git tensorfold/families/glm5_next/cuda/exl3_mm.py tensorfold/families/glm5_next/cuda/exl3_mm.py
+index 58e739d..71cd600 100644
+--- tensorfold/families/glm5_next/cuda/exl3_mm.py
++++ tensorfold/families/glm5_next/cuda/exl3_mm.py
+@@ -31,12 +31,19 @@ def _nfirst() -> bool:
+ return os.environ.get("TF_GLM_EXL3_NFIRST", "1") != "0"
+
+
++def _seq() -> bool:
++ """TF_GLM_EXL3_SEQ (default on): prompt chunks sum a matmul's K splits in one program (same bits)."""
++ import os
++
++ return os.environ.get("TF_GLM_EXL3_SEQ", "1") != "0"
++
++
+ @lru_cache(maxsize=1)
+ def _ext():
+ from tensorfold.cuda.build import load
+
+ here = Path(__file__).parent
+- return load(name="tensorfold_glm_exl3_v9", sources=[str(here / "exl3.cpp"), str(here / "exl3.cu")],
++ return load(name="tensorfold_glm_exl3_v14", sources=[str(here / "exl3.cpp"), str(here / "exl3.cu")],
+ extra_cuda_cflags=["-O3"], verbose=False)
+
+
+@@ -70,16 +77,36 @@ def words(trellis: torch.Tensor) -> torch.Tensor:
+ return trellis.contiguous().view(torch.int32)
+
+
++def prompt_pass() -> int:
++ """TF_GLM_EXL3_PASS: members a prompt kernel pass takes (64 or 128, the same bits; 128 measured slower on real
++ routing: most passes are small, and its one 16-warp block an SM keeps fewer experts in flight)."""
++ import os
++
++ value = int(os.environ.get("TF_GLM_EXL3_PASS", "64"))
++ if value not in (64, 128):
++ raise ValueError(f"TF_GLM_EXL3_PASS is 64 or 128, not {value}")
++ return value
++
++
++def prompt_kernels() -> bool:
++ """TF_GLM_EXL3_PROMPT (default on): prompt chunks run the Y^T = W^T X^T kernels on a 64-pair plan (one fp32
++ chain a row: other bits than the decode kernels', independent of the chunking); 0: the decode kernels."""
++ import os
++
++ return os.environ.get("TF_GLM_EXL3_PROMPT", "1") != "0"
++
++
+ class Scratch:
+- """Per-window buffers for up to ``rows`` rows of ``slots`` slots (the last slot is the shared expert's)."""
++ """Per-window buffers for up to ``rows`` rows of ``slots`` slots (the last slot is the shared expert's); a
++ prompt window's (``prompt``) kernels keep no split partials."""
+
+- def __init__(self, rows: int, slots: int, dims: int, width: int, device) -> None:
++ def __init__(self, rows: int, slots: int, dims: int, width: int, device, *, prompt: bool = False) -> None:
+ P = rows * slots
+ sk = max(GATEUP_CFG[2], DOWN_CFG[2])
+ self.xg = torch.zeros((P, dims), dtype=torch.float16, device=device)
+ self.xu = torch.zeros((P, dims), dtype=torch.float16, device=device)
+ self.xd = torch.zeros((P, width), dtype=torch.float16, device=device)
+- self.z = torch.zeros((2 * sk * P * max(width, dims),), dtype=torch.float32, device=device)
++ self.z = torch.zeros((1 if prompt else 2 * sk * P * max(width, dims),), dtype=torch.float32, device=device)
+ self.rows, self.slots = rows, slots
+
+
+@@ -87,19 +114,28 @@ def routed(x: torch.Tensor, pick: torch.Tensor, plan: grouped.Plan, ex: Exl3Expe
+ R: int, limit: float) -> None:
+ """Y[row * slots + slot] (fp32) for rows 0..R-1's routed slots, from normed bf16 x and ``experts.route``'s plan."""
+
+- if plan.tile != grouped.TILE:
+- raise ValueError("the EXL3 kernel takes items of 16 pairs")
+ ext = _ext()
+ slots, P = s.slots, s.rows * s.slots
+ D, NI = ex.dims, ex.width
++ if plan.tile in (64, 128): # a prompt window: the Y^T kernels, an item a pass
++ ext.rot_in(x, x.stride(0), pick, ex.suh_g, ex.suh_u, s.xg, s.xu, R, D, slots)
++ ext.prompt(s.xg, s.xu, ex.gt, ex.ut, ex.dt, plan.items, plan.counts, plan.members, ex.svh_g, ex.svh_u,
++ ex.suh_d, ex.svh_d, s.xd, y, D, NI, ex.count, grouped.max_items(R * slots, plan.experts,
++ plan.tile), float(limit),
++ plan.tile)
++ return
++ if plan.tile != grouped.TILE:
++ raise ValueError("the EXL3 kernel takes items of 16 pairs")
+ items = grouped.max_items(R * slots, plan.experts)
+ ext.rot_in(x, x.stride(0), pick, ex.suh_g, ex.suh_u, s.xg, s.xu, R, D, slots)
+ nfirst = R >= PROMPT_ROWS and _nfirst()
+ nt, w, sk = GATEUP_CFG
++ seq = nfirst and sk > 1 and _seq() # the splits summed in one program: an SK = 1 epilogue, the same bits
+ ext.grouped(s.xg, s.xu, ex.gt, ex.ut, plan.items, plan.counts, plan.members, s.z, 2, D, NI, P, sk, items, nt,
+- w, nfirst, _pf())
+- ext.gateup_epilogue(s.z, pick, ex.svh_g, ex.svh_u, ex.suh_d, s.xd, R, P, NI, sk, slots, float(limit))
++ w, nfirst, _pf(), seq)
++ ext.gateup_epilogue(s.z, pick, ex.svh_g, ex.svh_u, ex.suh_d, s.xd, R, P, NI, 1 if seq else sk, slots,
++ float(limit))
+ nt, w, sk = DOWN_CFG
+ ext.grouped(s.xd, s.xd, ex.dt, ex.dt, plan.items, plan.counts, plan.members, s.z, 1, NI, D, P, sk, items, nt,
+- w, nfirst, _pf())
++ 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
+--- tensorfold/families/glm5_next/cuda/forward.py
++++ tensorfold/families/glm5_next/cuda/forward.py
+@@ -86,17 +86,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)
+- self.plan = grouped.Plan(rows, slots, c.experts + 1, dev, prefill=prefill and not exl3)
+ self.exl3 = None
++ prompt = False
+ if c.quant == "exl3": # EXL3 routed experts, and the shared expert as a BF16 MLP
+- from .exl3_mm import Scratch
++ from .exl3_mm import Scratch, prompt_kernels, prompt_pass
+
++ prompt = prefill and prompt_kernels()
+ sl = c.shared_width // w.world
+- self.exl3 = Scratch(rows, slots, D, ml, dev)
++ self.exl3 = Scratch(rows, slots, D, ml, dev, prompt=prompt)
+ self.sgu = torch.empty((rows, 2 * sl), dtype=bf, device=dev)
+ self.sact = torch.empty((rows, sl), dtype=bf, device=dev)
+ self.sxs = torch.empty((rows, sl // 64), dtype=f32, device=dev)
+ self.sy = torch.empty((rows, D), dtype=f32, device=dev)
++ # a prompt window's EXL3 experts take items of 64 pairs (the prompt kernels' pass), decode windows 16
++ self.plan = grouped.Plan(rows, slots, c.experts + 1, dev, prefill=prefill and (not exl3 or prompt),
++ tile=prompt_pass() if prompt else None)
+ # 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
+ 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"):
+- qa = latent.absorb_q(b.q[:R], a.absorb, s.qa[:R])
++ qa = latent.absorb_q(b.q[:R], a.absorb, s.qa[:R], prompt=b.prefill and latent.PROMPT_MMA)
+ 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
+ with prof.timed("dsa: sparse attention"):
+ latent.sparse_attention(qa, lc, tokens, counts, ol, scale)
+ with prof.timed("dsa: expand"):
+- o = latent.expand_v(ol, a.absorb, b.vn[:R]).view(R, HL * c.v_dim)
++ 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)
+
+
+@@ -393,7 +397,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],
+- b.hcpart[:R], c.eps, c.hc_eps, c.hc_iters)
++ 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:
+ 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],
+- b.hcpart[:R], c.eps, c.hc_eps, c.hc_iters)
++ b.hcpart[:R], c.eps, c.hc_eps, c.hc_iters, prompt=b.prefill)
+ with prof.timed("moe (total)" if layer.mlp is None else "mlp"):
+ g = mlp_block(layer, w, b, R) if layer.mlp is not None else moe_block(layer, w, b, R)
+ glue.hc_post(x, x, g, b.post[:R], b.comb[:R])
+diff --git tensorfold/families/glm5_next/cuda/glue.py tensorfold/families/glm5_next/cuda/glue.py
+index 0a6a4f1..84f0dbe 100644
+--- tensorfold/families/glm5_next/cuda/glue.py
++++ tensorfold/families/glm5_next/cuda/glue.py
+@@ -159,15 +159,47 @@ def _hc_finish(X, PART, BASE, SCALE, NW, OUT, XS, POST, COMB, eps_norm, hc_eps,
+ tl.store(XS + r * (D // 64) + tl.arange(0, BLOCK // 64), g)
+
+
++def _hc_partial_mma(X, FN, PART, R, WIDE: tl.constexpr, NB: tl.constexpr, BM: tl.constexpr, BK: tl.constexpr):
++ """Prompt rows, program (row block, K block): _hc_partial's 24 dots on the tensor cores (one fp32 chain over
++ ascending k tiles, a row's bits independent of the other rows) and its sum of squares, in PART's layout."""
++
++ rm = tl.program_id(0) * BM + tl.arange(0, BM)
++ b = tl.program_id(1)
++ KB: tl.constexpr = WIDE // NB
++ m = tl.arange(0, 32)
++ k = tl.arange(0, BK)
++ ok = rm < R
++ acc = tl.zeros((BM, 32), dtype=tl.float32)
++ ss = tl.zeros((BM,), dtype=tl.float32)
++ for t in range(KB // BK):
++ base = b * KB + t * BK
++ x = tl.load(X + rm[:, None] * WIDE + base + k[None, :], mask=ok[:, None], other=0.0)
++ w = tl.load(FN + m[None, :] * WIDE + base + k[:, None], mask=m[None, :] < 24, other=0.0)
++ acc = tl.dot(x, w, acc)
++ xf = x.to(tl.float32)
++ ss += tl.sum(xf * xf, axis=1)
++ tl.store(PART + (rm[:, None] * NB + b) * 32 + m[None, :], acc, mask=ok[:, None] & (m[None, :] < 24))
++ tl.store(PART + (rm * NB + b) * 32 + 24, ss, mask=ok)
++
++
++HC_MMA = __import__("os").environ.get("TF_GLM_HC_MMA", "1") != "0" # prompt rows' mixing dots on the tensor cores
++
++
+ def hc_pre(x: torch.Tensor, fn: torch.Tensor, base: torch.Tensor, scale: torch.Tensor, norm_w: torch.Tensor,
+ out: torch.Tensor, xs: torch.Tensor, post: torch.Tensor, comb: torch.Tensor, part: torch.Tensor,
+- eps: float, hc_eps: float, iters: int) -> None:
+- """x [R, S*D] bf16 streams -> out [R, D] (normed collapsed row) + xs, and post [R, S], comb [R, S, S]."""
++ eps: float, hc_eps: float, iters: int, *, prompt: bool = False) -> None:
++ """x [R, S*D] bf16 streams -> out [R, D] (normed collapsed row) + xs, and post [R, S], comb [R, S, S];
++ ``prompt``: a prompt chunk's rows, their mixing dots on the tensor cores (other bits than decode rows')."""
+
+ rows, wide = x.shape
+ d = norm_w.shape[0]
+ s = wide // d
+- _hc_partial[(rows, HC_BLOCKS)](x, fn, part, WIDE=wide, NB=HC_BLOCKS, SUB=128, num_warps=4)
++ if prompt and HC_MMA and x.is_contiguous():
++ _hc_partial_mma[(triton.cdiv(rows, 64), HC_BLOCKS)](x, fn, part, rows, WIDE=wide, NB=HC_BLOCKS, BM=64, BK=64,
++ num_warps=4, num_stages=3)
++ else:
++ _hc_partial[(rows, HC_BLOCKS)](x, fn, part, WIDE=wide, NB=HC_BLOCKS, SUB=128, num_warps=4)
+ _hc_finish[(rows,)](x, part, base, scale, norm_w, out, xs, post, comb, eps, hc_eps, D=d, S=s, NB=HC_BLOCKS,
+ 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
+--- 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
+ tl.store(OUT + (r * H + h) * DV + n, acc.to(tl.bfloat16))
+
+
++def _absorb_mma(Q, WK, QA, R, H: tl.constexpr, D: tl.constexpr, LW: tl.constexpr, BM: tl.constexpr,
++ BN: tl.constexpr, BK: tl.constexpr):
++ """Prompt rows, program (head, row block, column block): QA = Q @ WK on the tensor cores, each row one fp32 chain
++ over ascending k blocks (its bits do not depend on the other rows)."""
++
++ h = tl.program_id(0)
++ rm = tl.program_id(1) * BM + tl.arange(0, BM)
++ n = tl.program_id(2) * BN + tl.arange(0, BN)
++ kk = tl.arange(0, BK)
++ ok = rm < R
++ acc = tl.zeros((BM, BN), dtype=tl.float32)
++ for k0 in range(0, D, BK):
++ q = tl.load(Q + (rm[:, None] * H + h) * D + k0 + kk[None, :], mask=ok[:, None], other=0.0)
++ w = tl.load(WK + (h * D + k0 + kk[:, None]) * LW + n[None, :])
++ acc = tl.dot(q, w, acc)
++ tl.store(QA + (rm[:, None] * H + h) * LW + n[None, :], acc.to(tl.bfloat16), mask=ok[:, None])
++
++
++def _expand_mma(OL, WV, OUT, R, H: tl.constexpr, DV: tl.constexpr, LW: tl.constexpr, BM: tl.constexpr,
++ BN: tl.constexpr, BK: tl.constexpr):
++ """Prompt rows, program (head, row block, output block): OUT = OL @ WV^T on the tensor cores, as _absorb_mma."""
++
++ h = tl.program_id(0)
++ rm = tl.program_id(1) * BM + tl.arange(0, BM)
++ n = tl.program_id(2) * BN + tl.arange(0, BN)
++ kk = tl.arange(0, BK)
++ ok = rm < R
++ acc = tl.zeros((BM, BN), dtype=tl.float32)
++ for k0 in range(0, LW, BK):
++ o = tl.load(OL + (rm[:, None] * H + h) * LW + k0 + kk[None, :], mask=ok[:, None], other=0.0)
++ w = tl.load(WV + (h * DV + n[:, None]) * LW + k0 + kk[None, :])
++ acc = tl.dot(o, tl.trans(w), acc)
++ tl.store(OUT + (rm[:, None] * H + h) * DV + n[None, :], acc.to(tl.bfloat16), mask=ok[:, None])
++
++
++# prompt chunks' tiles (rows, columns, k) and (warps, stages); fixed, so a row's bits never depend on the chunk
++PROMPT_MMA = __import__("os").environ.get("TF_GLM_LATENT_MMA", "1") != "0" # 0: prompts on the decode kernels
++MMA_TILE = (64, 128, 64)
++MMA_LAUNCH = (4, 3)
++
++
+ def row_block(R: int) -> int:
+ """Rows per program: 1 for decode windows (most parallel), 16 for prefill chunks (weights reused)."""
+ return 1 if R <= 16 else 16
+
+
+-def absorb_q(q: torch.Tensor, a, out: torch.Tensor) -> torch.Tensor:
+- """q [R, H, qk_dim] bf16 -> out [R, H, latent] bf16."""
++def absorb_q(q: torch.Tensor, a, out: torch.Tensor, *, prompt: bool = False) -> torch.Tensor:
++ """q [R, H, qk_dim] bf16 -> out [R, H, latent] bf16; ``prompt``: a prompt chunk's rows, on the tensor cores
++ (other bits than decode rows', the same for any chunking)."""
+ R, H, D = q.shape
++ if prompt and isinstance(a, AbsorbW) and q.is_contiguous():
++ BM, BN, BK = MMA_TILE
++ warps, stages = MMA_LAUNCH
++ _absorb_mma[(H, triton.cdiv(R, BM), a.lw // BN)](q, a.wk, out, R, H=H, D=D, LW=a.lw, BM=BM, BN=BN, BK=BK,
++ num_warps=warps, num_stages=stages)
++ return out
+ if isinstance(a, AbsorbQ4):
+ rb = row_block(R)
+ _absorb_q4[(H, a.lw // 64, triton.cdiv(R, rb))](q, a.wkw, a.wks, a.wkb, out, R, H=H, D=D, LW=a.lw, RB=rb,
+@@ -172,9 +222,15 @@ def absorb_q(q: torch.Tensor, a, out: torch.Tensor) -> torch.Tensor:
+ return out
+
+
+-def expand_v(o_lat: torch.Tensor, a, out: torch.Tensor) -> torch.Tensor:
+- """o_lat [R, H, latent] bf16 -> out [R, H, v_dim] bf16."""
++def expand_v(o_lat: torch.Tensor, a, out: torch.Tensor, *, prompt: bool = False) -> torch.Tensor:
++ """o_lat [R, H, latent] bf16 -> out [R, H, v_dim] bf16; ``prompt`` as in absorb_q."""
+ R, H, _ = o_lat.shape
++ if prompt and isinstance(a, AbsorbW) and o_lat.is_contiguous():
++ BM, BN, BK = MMA_TILE
++ warps, stages = MMA_LAUNCH
++ _expand_mma[(H, triton.cdiv(R, BM), a.v_dim // BN)](o_lat, a.wv, out, R, H=H, DV=a.v_dim, LW=a.lw, BM=BM,
++ BN=BN, BK=BK, num_warps=warps, num_stages=stages)
++ return out
+ if isinstance(a, AbsorbQ4):
+ 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
+--- 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:
+
+ # BF16 matmuls: columns and K per step; the K slices come from ``split_k`` as for Q4 (fixed by the shape)
+ B16_BN, B16_BK = 64, 64
++# from this many rows (a prompt chunk) one program runs all of a matmul's K slices and sums them in _reduce's order:
++# the same bits as the split grid, without writing and reading back fp32 partials for every row. Measured at 2,048
++# rows (GB10): 1.3-3.2x on N >= 512, K <= 4,096; slower on narrow outputs (N 32-288) and long K (6,144, 8,192)
++SEQ_ROWS = int(__import__("os").environ.get("TF_GLM_SEQ_ROWS", "256"))
++
++
++def _seq(sk: int, m: int, n: int, k: int) -> bool:
++ return sk > 1 and m >= SEQ_ROWS and n >= 512 and k <= 4096
++
++
++# prompt chunks (SEQ_ROWS rows or more): (BM, BN, warps, stages) and SEQ by per-rank shape (N, K), swept on GB10 at
++# 2,048 rows; no choice changes a row's bits. Other shapes take PROMPT_DEFAULT.
++F8_PROMPT = {(6432, 4096): (128, 128, 8, 3), (2048, 4096): (64, 64, 8, 3), (4096, 1024): (64, 128, 8, 3),
++ (4096, 4096): (64, 128, 8, 3), (8192, 1536): (64, 128, 4, 3), (12288, 4096): (128, 64, 4, 3),
++ (4096, 6144): (128, 64, 8, 4), (4096, 8192): (64, 64, 4, 4), (1536, 4096): (64, 64, 8, 3)}
++PROMPT_DEFAULT = (64, 128, 8, 3)
++
++
++def _prompt_cfg(sk: int, m: int, n: int, k: int):
++ """(BM, BN, warps, stages, seq) for a prompt chunk's matmul, or None below SEQ_ROWS rows."""
++ if m < SEQ_ROWS:
++ return None
++ if (n, k) in F8_PROMPT:
++ return (*F8_PROMPT[(n, k)], sk > 1)
++ return (*PROMPT_DEFAULT, _seq(sk, m, n, k))
+
+
+ @triton.jit
+ def _bmm(X, W, OUT, PART, M, x_stride, N: tl.constexpr, K: tl.constexpr, SK: tl.constexpr, BM: tl.constexpr,
+- BLOCK_N: tl.constexpr, BK: tl.constexpr, F32: tl.constexpr):
+- """Multiply bf16 rows over a fixed K slice in order with fp32 sums, independently of other rows."""
++ BLOCK_N: tl.constexpr, BK: tl.constexpr, F32: tl.constexpr, SEQ: tl.constexpr = False):
++ """Multiply bf16 rows over a fixed K slice in order with fp32 sums, independently of other rows; SEQ: one program
++ runs every slice and sums them as _reduce does (the same bits, without the fp32 partials' round trip)."""
+
+ PER: tl.constexpr = K // SK
+ pid_n = tl.program_id(1)
+@@ -199,13 +225,26 @@ def _bmm(X, W, OUT, PART, M, x_stride, N: tl.constexpr, K: tl.constexpr, SK: tl.
+ rk = tl.arange(0, BK)
+ m_ok = rm < M
+ n_ok = rn < N
+- acc = tl.zeros((BM, BLOCK_N), dtype=tl.float32)
+- for k0 in range(pid_s * PER, pid_s * PER + PER, BK):
+- x = tl.load(X + rm[:, None] * x_stride + (k0 + rk)[None, :], mask=m_ok[:, None], other=0.0)
+- w = tl.load(W + rn[:, None].to(tl.int64) * K + (k0 + rk)[None, :], mask=n_ok[:, None], other=0.0)
+- acc = acc + tl.dot(x, tl.trans(w))
++ if SEQ:
++ acc = tl.zeros((BM, BLOCK_N), dtype=tl.float32)
++ for s in tl.static_range(SK):
++ part = tl.zeros((BM, BLOCK_N), dtype=tl.float32)
++ for k0 in range(s * PER, s * PER + PER, BK):
++ x = tl.load(X + rm[:, None] * x_stride + (k0 + rk)[None, :], mask=m_ok[:, None], other=0.0)
++ w = tl.load(W + rn[:, None].to(tl.int64) * K + (k0 + rk)[None, :], mask=n_ok[:, None], other=0.0)
++ part = part + tl.dot(x, tl.trans(w))
++ if s == 0:
++ acc = part
++ else:
++ acc = acc + part
++ else:
++ acc = tl.zeros((BM, BLOCK_N), dtype=tl.float32)
++ for k0 in range(pid_s * PER, pid_s * PER + PER, BK):
++ x = tl.load(X + rm[:, None] * x_stride + (k0 + rk)[None, :], mask=m_ok[:, None], other=0.0)
++ w = tl.load(W + rn[:, None].to(tl.int64) * K + (k0 + rk)[None, :], mask=n_ok[:, None], other=0.0)
++ acc = acc + tl.dot(x, tl.trans(w))
+ out_mask = m_ok[:, None] & n_ok[None, :]
+- if SK == 1:
++ if SK == 1 or SEQ:
+ if F32:
+ tl.store(OUT + rm[:, None] * N + rn[None, :], acc, mask=out_mask)
+ else:
+@@ -252,18 +291,19 @@ def _matmul_b16(x: torch.Tensor, q: B16, *, out: torch.Tensor | None, f32: bool,
+ bm = bucket(min(m, 128)) # a prompt chunk runs as 128-row blocks: no bucket changes a row's bits
+ warps, stages = B16_CONFIG[bm]
+ sk = b16_split_k(q.n, q.k)
++ seq = _seq(sk, m, q.n, q.k)
+ if out is None:
+ out = torch.empty((m, q.n), dtype=torch.float32 if f32 else torch.bfloat16, device=x.device)
+ elif out.shape != (m, q.n) or not out.is_contiguous():
+ raise ValueError(f"matmul: out {tuple(out.shape)} must be a contiguous ({m}, {q.n})")
+- if sk > 1:
++ if sk > 1 and not seq:
+ need = sk * m * q.n
+ if part is None or part.numel() < need:
+ part = torch.empty((need,), dtype=torch.float32, device=x.device)
+- grid = (triton.cdiv(m, bm), triton.cdiv(q.n, B16_BN), sk)
+- _bmm[grid](x, q.weight, out, part if sk > 1 else out, m, x.stride(0), N=q.n, K=k, SK=sk, BM=bm,
+- BLOCK_N=B16_BN, BK=B16_BK, F32=f32, num_warps=warps, num_stages=stages)
+- if sk > 1:
++ grid = (triton.cdiv(m, bm), triton.cdiv(q.n, B16_BN), 1 if seq else sk)
++ _bmm[grid](x, q.weight, out, part if sk > 1 and not seq else out, m, x.stride(0), N=q.n, K=k, SK=sk, BM=bm,
++ BLOCK_N=B16_BN, BK=B16_BK, F32=f32, SEQ=seq, num_warps=warps, num_stages=stages)
++ if sk > 1 and not seq:
+ total = m * q.n
+ _reduce[(triton.cdiv(total, 1024),)](part, out, total, SK=sk, BLOCK=1024, F32=f32, num_warps=4)
+ return out
+@@ -313,8 +353,9 @@ def stack_f8(parts: list[torch.Tensor]) -> F8 | B16:
+
+ @triton.jit
+ def _fmm(X, W, S, OUT, PART, M, x_stride, N: tl.constexpr, K: tl.constexpr, SK: tl.constexpr, BM: tl.constexpr,
+- BLOCK_N: tl.constexpr, BK: tl.constexpr, F32: tl.constexpr):
+- """_bmm over FP8 weights: each BK step's product (bf16 inputs, fp32 sums) times its 128-column block's scales."""
++ BLOCK_N: tl.constexpr, BK: tl.constexpr, F32: tl.constexpr, SEQ: tl.constexpr = False):
++ """_bmm over FP8 weights: each BK step's product (bf16 inputs, fp32 sums) times its 128-column block's scales;
++ SEQ as in _bmm."""
+
+ PER: tl.constexpr = K // SK
+ KB: tl.constexpr = K // 128
+@@ -325,14 +366,28 @@ def _fmm(X, W, S, OUT, PART, M, x_stride, N: tl.constexpr, K: tl.constexpr, SK:
+ rk = tl.arange(0, BK)
+ m_ok = rm < M
+ n_ok = rn < N
+- acc = tl.zeros((BM, BLOCK_N), dtype=tl.float32)
+- for k0 in range(pid_s * PER, pid_s * PER + PER, BK):
+- x = tl.load(X + rm[:, None] * x_stride + (k0 + rk)[None, :], mask=m_ok[:, None], other=0.0)
+- w = tl.load(W + rn[:, None].to(tl.int64) * K + (k0 + rk)[None, :], mask=n_ok[:, None], other=0.0)
+- s = tl.load(S + rn.to(tl.int64) * KB + k0 // 128, mask=n_ok, other=0.0)
+- acc = acc + tl.dot(x, tl.trans(w.to(tl.bfloat16))) * s[None, :]
++ if SEQ:
++ acc = tl.zeros((BM, BLOCK_N), dtype=tl.float32)
++ for p in tl.static_range(SK):
++ part = tl.zeros((BM, BLOCK_N), dtype=tl.float32)
++ for k0 in range(p * PER, p * PER + PER, BK):
++ x = tl.load(X + rm[:, None] * x_stride + (k0 + rk)[None, :], mask=m_ok[:, None], other=0.0)
++ w = tl.load(W + rn[:, None].to(tl.int64) * K + (k0 + rk)[None, :], mask=n_ok[:, None], other=0.0)
++ s = tl.load(S + rn.to(tl.int64) * KB + k0 // 128, mask=n_ok, other=0.0)
++ part = part + tl.dot(x, tl.trans(w.to(tl.bfloat16))) * s[None, :]
++ if p == 0:
++ acc = part
++ else:
++ acc = acc + part
++ else:
++ acc = tl.zeros((BM, BLOCK_N), dtype=tl.float32)
++ for k0 in range(pid_s * PER, pid_s * PER + PER, BK):
++ x = tl.load(X + rm[:, None] * x_stride + (k0 + rk)[None, :], mask=m_ok[:, None], other=0.0)
++ w = tl.load(W + rn[:, None].to(tl.int64) * K + (k0 + rk)[None, :], mask=n_ok[:, None], other=0.0)
++ s = tl.load(S + rn.to(tl.int64) * KB + k0 // 128, mask=n_ok, other=0.0)
++ acc = acc + tl.dot(x, tl.trans(w.to(tl.bfloat16))) * s[None, :]
+ out_mask = m_ok[:, None] & n_ok[None, :]
+- if SK == 1:
++ if SK == 1 or SEQ:
+ if F32:
+ tl.store(OUT + rm[:, None] * N + rn[None, :], acc, mask=out_mask)
+ else:
+@@ -349,19 +404,23 @@ def _matmul_f8(x: torch.Tensor, q: F8, *, out: torch.Tensor | None, f32: bool,
+ bm = bucket(min(m, 128))
+ warps, stages = F8_CONFIG[bm]
+ sk = b16_split_k(q.n, q.k)
++ seq = _seq(sk, m, q.n, q.k)
++ bn = F8_BN_DECODE if bm == 16 else F8_BN
++ cfg = _prompt_cfg(sk, m, q.n, q.k)
++ if cfg is not None:
++ bm, bn, warps, stages, seq = cfg
+ if out is None:
+ out = torch.empty((m, q.n), dtype=torch.float32 if f32 else torch.bfloat16, device=x.device)
+ elif out.shape != (m, q.n) or not out.is_contiguous():
+ raise ValueError(f"matmul: out {tuple(out.shape)} must be a contiguous ({m}, {q.n})")
+- if sk > 1:
++ if sk > 1 and not seq:
+ need = sk * m * q.n
+ if part is None or part.numel() < need:
+ part = torch.empty((need,), dtype=torch.float32, device=x.device)
+- bn = F8_BN_DECODE if bm == 16 else F8_BN
+- grid = (triton.cdiv(m, bm), triton.cdiv(q.n, bn), sk)
+- _fmm[grid](x, q.weight, q.scale, out, part if sk > 1 else out, m, x.stride(0), N=q.n, K=k, SK=sk, BM=bm,
+- BLOCK_N=bn, BK=B16_BK, F32=f32, num_warps=warps, num_stages=stages)
+- if sk > 1:
++ grid = (triton.cdiv(m, bm), triton.cdiv(q.n, bn), 1 if seq else sk)
++ _fmm[grid](x, q.weight, q.scale, out, part if sk > 1 and not seq else out, m, x.stride(0), N=q.n, K=k, SK=sk,
++ BM=bm, BLOCK_N=bn, BK=B16_BK, F32=f32, SEQ=seq, num_warps=warps, num_stages=stages)
++ if sk > 1 and not seq:
+ total = m * q.n
+ _reduce[(triton.cdiv(total, 1024),)](part, out, total, SK=sk, BLOCK=1024, F32=f32, num_warps=4)
+ return out
+diff --git tensorfold/vision/glm.py tensorfold/vision/glm.py
+index 77a96f9..b6f7dde 100644
+--- tensorfold/vision/glm.py
++++ tensorfold/vision/glm.py
+@@ -29,7 +29,8 @@ IMAGE_SPAN = "<|begin_of_image|><|image|><|end_of_image|>" # what the chat t
+ VIDEO_SPAN = "<|begin_of_video|><|video|><|end_of_video|>" # and for a clip, expanded frame pair by frame pair
+ MEAN = (0.48145466, 0.4578275, 0.40821073) # CLIP's, from processor_config.json
+ STD = (0.26862954, 0.26130258, 0.27577711)
+-PASS_PATCHES = 16384 # patches the tower encodes at once (its workspace scales with this)
++PASS_PATCHES = 8192 # patches the tower encodes at once (its workspace scales with this): a
++ # 2,048-token picture is one pass
+
+
+ def _env_int(name: str, default: int, low: int, high: int) -> int:
diff --git a/patches/0005-glm-dense-q4.patch b/patches/0005-glm-dense-q4.patch
new file mode 100644
index 0000000..47e64a6
--- /dev/null
+++ b/patches/0005-glm-dense-q4.patch
@@ -0,0 +1,140 @@
+diff --git tensorfold/families/glm5_next/cuda/engine.py tensorfold/families/glm5_next/cuda/engine.py
+index ff49a2a..0ed6ec3 100644
+--- tensorfold/families/glm5_next/cuda/engine.py
++++ tensorfold/families/glm5_next/cuda/engine.py
+@@ -128,12 +128,14 @@ class GlmEngine:
+ explicit = context is not None if context_explicit is None else bool(context_explicit)
+ from . import LATENT
+
+- from .qmm import dense_kind, fp8_weights
++ from .qmm import dense_kind, fp8_weights, q4_weights
+
+ # TF_GLM_DENSE=fp8 (an EXL3 checkpoint): its BF16 matrices take a byte a value, which the estimate counts
+ weights_estimate = split_weights(rule)
+ if cfg.quant == "exl3" and dense_kind() == "fp8":
+ 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:
+diff --git tensorfold/families/glm5_next/cuda/qmm.py tensorfold/families/glm5_next/cuda/qmm.py
+index b845afa..ee83025 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:
+ return make_q4(words, scales.contiguous(), biases.contiguous())
+
+
++def quantize4_mse(w: torch.Tensor, chunk: int = 4096, grid: int = 16) -> Q4:
++ """TF_GLM_DENSE=q4: bf16 weights as affine 4-bit groups of 64, each group's range the one of ``grid`` clippings
++ (1.0 down to 0.55 of its min / max) with the least squared error, scale and bias as stored (bf16). Lossy."""
++
++ n, k = w.shape
++ words = torch.empty((n, k // 8), dtype=torch.int32, device=w.device)
++ scales = torch.empty((n, k // 64), dtype=torch.bfloat16, device=w.device)
++ biases = torch.empty_like(scales)
++ for r in range(0, n, chunk):
++ g = w[r:r + chunk].float().view(-1, k // 64, 64)
++ lo0, hi0 = g.amin(-1), g.amax(-1)
++ best_err = best_s = best_b = None
++ for i in range(grid):
++ a = 1.0 - 0.45 * i / (grid - 1)
++ lo, hi = lo0 * a, hi0 * a
++ s = ((hi - lo) / 15).clamp_min(1e-8).to(torch.bfloat16)
++ b = lo.to(torch.bfloat16)
++ q = torch.round((g - b.float()[..., None]) / s.float()[..., None]).clamp(0, 15)
++ err = ((q * s.float()[..., None] + b.float()[..., None] - g) ** 2).sum(-1)
++ if best_err is None:
++ best_err, best_s, best_b = err, s, b
++ else:
++ take = err < best_err
++ best_err = torch.where(take, err, best_err)
++ best_s = torch.where(take, s, best_s)
++ best_b = torch.where(take, b, best_b)
++ q = torch.round((g - best_b.float()[..., None]) / best_s.float()[..., None]).clamp(0, 15).to(torch.int32)
++ q = q.view(-1, k // 8, 8)
++ part = torch.zeros(q.shape[:2], dtype=torch.int32, device=w.device)
++ for j in range(8):
++ part |= q[..., j] << (4 * j)
++ words[r:r + chunk], scales[r:r + chunk], biases[r:r + chunk] = part, best_s, best_b
++ return make_q4(words, scales.contiguous(), biases.contiguous())
++
++
++def make_dense_q4(weight: torch.Tensor) -> "Q4 | F8":
++ return quantize4_mse(weight.to(torch.bfloat16)) if weight.shape[1] % 64 == 0 else make_f8(weight)
++
++
++def stack_dense_q4(parts: list[torch.Tensor]) -> "Q4 | F8":
++ return make_dense_q4(torch.cat([p.to(torch.bfloat16) for p in parts]))
++
++
+ def stack_b16(parts: list[torch.Tensor]) -> B16:
+ """Rows of several BF16 matrices with the same K, stacked in order."""
+
+@@ -438,8 +481,8 @@ def dense_kind() -> str:
+ import os
+
+ kind = os.environ.get("TF_GLM_DENSE", "bf16")
+- if kind not in ("bf16", "fp8"):
+- raise ValueError(f"TF_GLM_DENSE is bf16 or fp8, not {kind!r}")
++ if kind not in ("bf16", "fp8", "q4"):
++ raise ValueError(f"TF_GLM_DENSE is bf16, fp8 or q4, not {kind!r}")
+ return kind
+
+
+@@ -449,6 +492,24 @@ _F8_NAMES = __import__("re").compile(
+ r"|wk|weights_proj|wq_b|gate_proj|up_proj|down_proj|eh_proj)\.weight|^lm_head\.weight)$")
+
+
++def q4_weights(base):
++ """fp8_weights, with the 4-bit matrices of TF_GLM_DENSE=q4 (all but the head and kv_b, which stay FP8) at half a
++ byte a value plus a bf16 scale and bias a group of 64."""
++
++ f8 = fp8_weights(base)
++
++ def transform(name: str, info: dict) -> tuple[int, int]:
++ total, extra = f8(name, info)
++ shape = info.get("shape") or []
++ if (total and info.get("dtype") == "BF16" and len(shape) == 2 and shape[-1] % 64 == 0
++ and name != "lm_head.weight" and "kv_b_proj" not in name
++ and "experts." not in name.replace("shared_experts.", "") and _F8_NAMES.search(name)):
++ n = base(name, info)[0] // 2
++ return n // 2 + n // 64 * 4, extra
++ return total, extra
++ return transform
++
++
+ def fp8_weights(base):
+ """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
+--- 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:
+ 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)
+- fp8 = exl3 and dense_kind() == "fp8"
++ fp8 = exl3 and dense_kind() in ("fp8", "q4")
+ dense, dense_stack = (make_f8, stack_f8) if fp8 else (make_b16, stack_b16)
++ # TF_GLM_DENSE=q4: the projections in 4 bits (MSE-searched groups of 64), the head and kv_b in FP8
++ if exl3 and dense_kind() == "q4":
++ from .qmm import make_dense_q4, stack_dense_q4
++
++ big, big_stack = make_dense_q4, stack_dense_q4
++ else:
++ big, big_stack = dense, dense_stack
+
+ def q4(name: str) -> Q4 | B16 | F8:
+- return dense(t(name + ".weight")) if exl3 else make_q4(*trip(name))
++ return big(t(name + ".weight")) if exl3 else make_q4(*trip(name))
+
+ def stack(names: list[str]) -> Q4 | B16 | F8:
+ if exl3:
+- return dense_stack([t(n + ".weight") for n in names])
++ return big_stack([t(n + ".weight") for n in names])
+ return stack_q4([trip(n) for n in names])
+
+ def hc(i: int, site: str) -> HCW:
diff --git a/patches/0006-cuda-roce-allgather.patch b/patches/0006-cuda-roce-allgather.patch
new file mode 100644
index 0000000..eea9ecf
--- /dev/null
+++ b/patches/0006-cuda-roce-allgather.patch
@@ -0,0 +1,1049 @@
+diff --git tensorfold/cuda/roce.cpp tensorfold/cuda/roce.cpp
+new file mode 100644
+index 0000000..285de55
+--- /dev/null
++++ tensorfold/cuda/roce.cpp
+@@ -0,0 +1,23 @@
++#include <torch/extension.h>
++#include <c10/cuda/CUDAGuard.h>
++
++void roce_gather_cuda(const at::Tensor&, at::Tensor&, int64_t, int64_t, int64_t, int64_t, int64_t, int64_t, int64_t,
++ int64_t, int64_t, int64_t, int64_t, int64_t, int64_t, int64_t, int64_t, int64_t, int64_t, int64_t,
++ int64_t, int64_t);
++
++void gather(const at::Tensor& in, at::Tensor out, int64_t shard_packs, int64_t nbytes, int64_t row_packs,
++ int64_t recv_base, int64_t flag_base, int64_t send_base, int64_t ctrl, int64_t slot_bytes, int64_t epoch,
++ int64_t stage_ctr, int64_t tail_ctr, int64_t poison, int64_t spin_limit, int64_t world, int64_t rank,
++ int64_t slots, int64_t flag_stride, int64_t n_hca, int64_t grid, int64_t threads) {
++ TORCH_CHECK(in.is_cuda() && out.is_cuda() && in.is_contiguous() && out.is_contiguous(),
++ "roce gather: contiguous CUDA tensors");
++ TORCH_CHECK(reinterpret_cast<uintptr_t>(in.data_ptr()) % 16 == 0 &&
++ reinterpret_cast<uintptr_t>(out.data_ptr()) % 16 == 0, "roce gather: 16-byte aligned tensors");
++ const at::cuda::CUDAGuard guard(in.device());
++ roce_gather_cuda(in, out, shard_packs, nbytes, row_packs, recv_base, flag_base, send_base, ctrl, slot_bytes, epoch,
++ stage_ctr, tail_ctr, poison, spin_limit, world, rank, slots, flag_stride, n_hca, grid, threads);
++}
++
++PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
++ m.def("gather", &gather, "one-shot RoCE all-gather (b12x's RoCEnante protocol)");
++}
+diff --git tensorfold/cuda/roce.cu tensorfold/cuda/roce.cu
+new file mode 100644
+index 0000000..541c9d6
+--- /dev/null
++++ tensorfold/cuda/roce.cu
+@@ -0,0 +1,143 @@
++// One-shot RoCE all-gather between DGX Sparks: the GPU side of b12x's "RoCEnante" protocol
++// (https://github.com/local-inference-lab/b12x, b12x/comm/roce/_allgather_cute.py at commit
++// 8a99d639410e39d5f39cb4037675331beceea1d4, Copyright the b12x contributors, Apache License 2.0),
++// reimplemented in CUDA C++ from its CuTe DSL kernel with the same stages and memory orderings.
++//
++// The pinned host region (roce_proxy.c) holds, per rank: recv[src][slot], flag[src][slot][hca], send[slot] and a
++// control record {seq, nbytes, error seq, missing peer, nbytes of slot 0, nbytes of slot 1, missing hca}. One launch:
++// 1. every block stages its share of the local shard into send[seq & 1];
++// 2. the last block to finish staging (a free-running arrival counter) publishes nbytes and rings ctrl.seq after
++// a system fence; the proxy thread RDMA-writes the payload to every peer, then a flag per HCA stripe;
++// 3. one thread per (peer, HCA) spins on that stripe's flag with system-scope acquire loads (a limit poisons);
++// 4. every block copies the shards in rank order: its own from the input, the peers' from the NIC-written slots;
++// 5. the last block to finish advances the device epoch, so CUDA graphs replay the exchange.
++
++#include <ATen/ATen.h>
++#include <ATen/cuda/CUDAContext.h>
++#include <c10/cuda/CUDAGuard.h>
++#include <cuda_runtime.h>
++#include <stdint.h>
++
++namespace {
++
++__device__ __forceinline__ uint32_t ld_relaxed_gpu(const uint32_t* p) {
++ uint32_t v;
++ asm volatile("ld.relaxed.gpu.global.u32 %0, [%1];" : "=r"(v) : "l"(p) : "memory");
++ return v;
++}
++__device__ __forceinline__ uint32_t ld_relaxed_sys(const uint32_t* p) {
++ uint32_t v;
++ asm volatile("ld.relaxed.sys.global.u32 %0, [%1];" : "=r"(v) : "l"(p) : "memory");
++ return v;
++}
++__device__ __forceinline__ uint32_t ld_acquire_sys(const uint32_t* p) {
++ uint32_t v;
++ asm volatile("ld.acquire.sys.global.u32 %0, [%1];" : "=r"(v) : "l"(p) : "memory");
++ return v;
++}
++__device__ __forceinline__ uint4 ld_relaxed_sys_v4(const uint4* p) {
++ uint4 v;
++ asm volatile("ld.relaxed.sys.global.v4.u32 {%0, %1, %2, %3}, [%4];"
++ : "=r"(v.x), "=r"(v.y), "=r"(v.z), "=r"(v.w) : "l"(p) : "memory");
++ return v;
++}
++__device__ __forceinline__ void st_relaxed_sys(uint32_t* p, uint32_t v) {
++ asm volatile("st.relaxed.sys.global.u32 [%0], %1;" ::"l"(p), "r"(v) : "memory");
++}
++__device__ __forceinline__ void st_release_gpu(uint32_t* p, uint32_t v) {
++ asm volatile("st.release.gpu.global.u32 [%0], %1;" ::"l"(p), "r"(v) : "memory");
++}
++__device__ __forceinline__ uint32_t atom_add_relaxed_gpu(uint32_t* p, uint32_t v) {
++ uint32_t old;
++ asm volatile("atom.relaxed.gpu.global.add.u32 %0, [%1], %2;" : "=r"(old) : "l"(p), "r"(v) : "memory");
++ return old;
++}
++__device__ __forceinline__ void fence_sc_sys() { asm volatile("fence.sc.sys;" ::: "memory"); }
++__device__ __forceinline__ void fence_sc_gpu() { asm volatile("fence.sc.gpu;" ::: "memory"); }
++
++// ctrl record, in 32-bit words
++constexpr int C_SEQ = 0, C_NBYTES = 1, C_ERROR = 2, C_PEER = 3, C_SLOT_NBYTES = 4, C_HCA = 6;
++
++__global__ void gather_kernel(const uint4* __restrict__ in, uint4* __restrict__ out, int shard_packs, uint32_t nbytes,
++ int row_packs, char* recv_base, char* flag_base, char* send_base, uint32_t* ctrl,
++ long long slot_bytes, uint32_t* epoch, uint32_t* stage_ctr, uint32_t* tail_ctr,
++ uint32_t* poison, uint32_t spin_limit, int world, int rank, int slots, int flag_stride,
++ int n_hca) {
++ const int tid = threadIdx.x;
++ const uint32_t seq = ld_relaxed_gpu(epoch) + 1u;
++ const uint32_t slot = seq & 1u;
++ uint4* send_slot = reinterpret_cast<uint4*>(send_base + (long long)slot * slot_bytes);
++ const int index = blockIdx.x * blockDim.x + tid, stride = gridDim.x * blockDim.x;
++ // a recorded timeout poisons the runtime: later launches do nothing until the host raises
++ if (ld_relaxed_gpu(poison) != 0u) return;
++
++ for (int i = index; i < shard_packs; i += stride) send_slot[i] = in[i]; // 1. stage
++ __syncthreads();
++ if (tid == 0) { // 2. doorbell
++ fence_sc_sys();
++ const uint32_t prior = atom_add_relaxed_gpu(stage_ctr, 1u);
++ if ((prior + 1u) % gridDim.x == 0u) {
++ st_relaxed_sys(ctrl + C_NBYTES, nbytes);
++ st_relaxed_sys(ctrl + C_SLOT_NBYTES + slot, nbytes);
++ fence_sc_sys();
++ st_relaxed_sys(ctrl + C_SEQ, seq);
++ }
++ }
++ if (tid < world * n_hca) { // 3. wait
++ const int peer = tid / n_hca, hca = tid - peer * n_hca;
++ if (peer != rank) {
++ const uint32_t* flag = reinterpret_cast<const uint32_t*>(
++ flag_base + (((long long)peer * slots + slot) * n_hca + hca) * flag_stride);
++ uint32_t polls = 0;
++ while (ld_acquire_sys(flag) != seq) {
++ if (++polls >= spin_limit) {
++ st_relaxed_sys(ctrl + C_PEER, (uint32_t)peer);
++ st_relaxed_sys(ctrl + C_HCA, (uint32_t)hca);
++ st_relaxed_sys(ctrl + C_ERROR, seq);
++ st_release_gpu(poison, seq);
++ break;
++ }
++ }
++ }
++ }
++ __syncthreads();
++ if (ld_relaxed_gpu(poison) == 0u) { // 4. copy out
++ const int out_row_packs = world * row_packs;
++ for (int source = 0; source < world; ++source) {
++ const uint4* peer_slot = reinterpret_cast<const uint4*>(
++ recv_base + ((long long)source * slots + slot) * slot_bytes);
++ for (int i = index; i < shard_packs; i += stride) {
++ const int row = i / row_packs, col = i - row * row_packs;
++ const uint4 w = source == rank ? in[i] : ld_relaxed_sys_v4(peer_slot + i);
++ out[(long long)row * out_row_packs + (long long)source * row_packs + col] = w;
++ }
++ }
++ }
++ fence_sc_gpu(); // 5. epoch
++ __syncthreads();
++ if (tid == 0) {
++ const uint32_t prior = atom_add_relaxed_gpu(tail_ctr, 1u);
++ if ((prior + 1u) % gridDim.x == 0u) {
++ fence_sc_gpu();
++ if (ld_relaxed_sys(ctrl + C_ERROR) == 0u) st_release_gpu(epoch, seq);
++ }
++ }
++}
++
++} // namespace
++
++void roce_gather_cuda(const at::Tensor& in, at::Tensor& out, int64_t shard_packs, int64_t nbytes, int64_t row_packs,
++ int64_t recv_base, int64_t flag_base, int64_t send_base, int64_t ctrl, int64_t slot_bytes,
++ int64_t epoch, int64_t stage_ctr, int64_t tail_ctr, int64_t poison, int64_t spin_limit,
++ int64_t world, int64_t rank, int64_t slots, int64_t flag_stride, int64_t n_hca, int64_t grid,
++ int64_t threads) {
++ auto stream = at::cuda::getCurrentCUDAStream();
++ gather_kernel<<<(unsigned)grid, (unsigned)threads, 0, stream>>>(
++ reinterpret_cast<const uint4*>(in.data_ptr()), reinterpret_cast<uint4*>(out.data_ptr()), (int)shard_packs,
++ (uint32_t)nbytes, (int)row_packs, reinterpret_cast<char*>(recv_base), reinterpret_cast<char*>(flag_base),
++ reinterpret_cast<char*>(send_base), reinterpret_cast<uint32_t*>(ctrl), (long long)slot_bytes,
++ reinterpret_cast<uint32_t*>(epoch), reinterpret_cast<uint32_t*>(stage_ctr),
++ reinterpret_cast<uint32_t*>(tail_ctr), reinterpret_cast<uint32_t*>(poison), (uint32_t)spin_limit, (int)world,
++ (int)rank, (int)slots, (int)flag_stride, (int)n_hca);
++ C10_CUDA_KERNEL_LAUNCH_CHECK();
++}
+diff --git tensorfold/cuda/roce.py tensorfold/cuda/roce.py
+new file mode 100644
+index 0000000..52bc376
+--- /dev/null
++++ tensorfold/cuda/roce.py
+@@ -0,0 +1,200 @@
++"""One-shot RoCE all-gather for two DGX Sparks: b12x's "RoCEnante" transport (https://github.com/local-inference-lab/b12x,
++Apache License 2.0; the C proxy is theirs, roce_proxy.c; the GPU side is roce.cu, rewritten from their CuTe kernel).
++
++A decode round's all-gathers are small (a verify window's partials: rows x 4,096 fp32) and NCCL spends most of each
++in fixed latency (~30-50 us). Here the GB10 GPU writes its shard into pinned host memory the ConnectX-7 RDMA-writes
++to the peer, and reads the peer's shard from its own pinned memory in place: one kernel, no NCCL proxy handoff.
++``RoceComm`` sends gathers of up to ``max_bytes`` a rank this way and the rest through NCCL, with the same output
++layout (rank order), the same bits, and a device-side epoch so CUDA graphs replay it.
++"""
++
++from __future__ import annotations
++
++import ctypes
++import hashlib
++import os
++import shutil
++import subprocess
++import threading
++from functools import lru_cache
++from pathlib import Path
++
++import torch
++
++_SOURCE = Path(__file__).with_name("roce_proxy.c")
++_LOCK = threading.Lock()
++SLOT_ALIGN = 4096
++PACK = 16
++THREADS = 512
++BLOCKS = 8 # the largest grid; smaller shards launch fewer (power-of-two) blocks
++SPIN_LIMIT = 20_000_000 # flag polls (~1 us each) before a wait poisons the runtime: ~20 s
++
++
++def _cache_dir() -> Path:
++ root = os.environ.get("TORCH_EXTENSIONS_DIR") or os.path.join(os.path.expanduser("~"), ".cache", "tensorfold")
++ return Path(root) / "roce"
++
++
++@lru_cache(maxsize=1)
++def proxy_library() -> ctypes.CDLL:
++ """Build roce_proxy.c with the host C compiler and libibverbs once per source hash, and bind it."""
++
++ with _LOCK:
++ source = _SOURCE.read_bytes()
++ target = _cache_dir() / f"roce_proxy-{hashlib.sha256(source).hexdigest()[:16]}.so"
++ if not target.exists():
++ cc = next((c for c in (os.environ.get("CC"), "gcc", "cc", "clang") if c and shutil.which(c)), None)
++ if cc is None:
++ raise RuntimeError("the RoCE all-gather needs a C compiler and libibverbs headers")
++ target.parent.mkdir(parents=True, exist_ok=True)
++ tmp = target.with_name(f".{target.name}.{os.getpid()}")
++ cmd = [cc, "-O2", "-std=gnu11", "-shared", "-fPIC", "-o", str(tmp), str(_SOURCE), "-libverbs", "-lpthread"]
++ done = subprocess.run(cmd, capture_output=True, text=True)
++ if done.returncode != 0:
++ raise RuntimeError("building the RoCE proxy failed: " + " ".join(cmd) + "\n" + done.stderr)
++ os.replace(tmp, target)
++ lib = ctypes.CDLL(str(target), use_errno=True)
++ u64, p, i = ctypes.c_uint64, ctypes.c_void_p, ctypes.c_int
++ for name, res, args in (
++ ("roce_abi_version", i, []), ("roce_layout", i, [i, u64, ctypes.POINTER(u64)]),
++ ("roce_blob_bytes", u64, []),
++ ("roce_create", p, [i, i, ctypes.POINTER(ctypes.c_char_p), i, i, i, p, u64, u64, ctypes.c_char_p, u64]),
++ ("roce_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])):
++ fn = getattr(lib, name)
++ fn.restype, fn.argtypes = res, args
++ if lib.roce_abi_version() != 4:
++ raise RuntimeError("unexpected RoCE proxy ABI version")
++ return lib
++
++
++@lru_cache(maxsize=1)
++def _ext():
++ from tensorfold.cuda.build import load
++
++ here = Path(__file__).parent
++ return load(name="tensorfold_roce_v1", sources=[str(here / "roce.cpp"), str(here / "roce.cu")],
++ extra_cuda_cflags=["-O3"], verbose=False)
++
++
++def _hcas() -> list[str]:
++ raw = os.environ.get("TF_ROCE_HCA") or os.environ.get("NCCL_IB_HCA") or ""
++ names = [x.strip().lstrip("=^").split(":")[0] for x in raw.split(",") if x.strip()]
++ if not names:
++ root = Path("/sys/class/infiniband")
++ names = [d.name for d in sorted(root.glob("*")) if "ACTIVE" in (d / "ports/1/state").read_text()]
++ return names[:2]
++
++
++class RoceGather:
++ """One rank's side of the exchange: the pinned region, the proxy thread and the gather launches."""
++
++ def __init__(self, comm, rank: int, world: int, max_bytes: int = 256 << 10) -> None:
++ lib = proxy_library()
++ self.lib, self.rank, self.world, self.max_bytes = lib, rank, world, int(max_bytes)
++ self.slot_bytes = -(-self.max_bytes // SLOT_ALIGN) * SLOT_ALIGN
++ out = (ctypes.c_uint64 * 7)()
++ if lib.roce_layout(world, self.slot_bytes, out) != 0:
++ raise ValueError(f"RoCE layout refused world {world}, slot {self.slot_bytes}")
++ recv_off, flag_off, send_off, ctrl_off, total, self.flag_stride, self.slots = (int(v) for v in out)
++ self.region = torch.zeros(total, dtype=torch.uint8, pin_memory=True) # flags and ctrl start at 0
++ base = self.region.data_ptr()
++ self.recv, self.flag, self.send, self.ctrl = base + recv_off, base + flag_off, base + send_off, base + ctrl_off
++ self.ctrl_words = self.region[ctrl_off:ctrl_off + 28].view(torch.int32).numpy()
++ self.classes = BLOCKS.bit_length()
++ # epoch, stage arrivals and tail arrivals by power-of-two grid, poison
++ self.counters = torch.zeros(2 + 2 * self.classes, dtype=torch.int32, device="cuda")
++ self.hcas = _hcas()
++ gid = int(os.environ.get("TF_ROCE_GID_INDEX") or os.environ.get("NCCL_IB_GID_INDEX") or 3)
++ tc = int(os.environ.get("NCCL_IB_TC", "0"), 0)
++ names = (ctypes.c_char_p * len(self.hcas))(*[n.encode() for n in self.hcas])
++ err = ctypes.create_string_buffer(512)
++ self.ctx = lib.roce_create(world, rank, names, len(self.hcas), gid, tc, ctypes.c_void_p(base), total,
++ self.slot_bytes, err, len(err))
++ failed = 0 if self.ctx else 1
++ blob_len = int(lib.roce_blob_bytes())
++ blob = ctypes.create_string_buffer(blob_len)
++ if not failed and lib.roce_local_blob(self.ctx, blob, blob_len) != 0:
++ failed = 1
++ # both ranks' verdict, geometry and connection blob through the existing communicator
++ words = -(-blob_len // 4)
++ mine = torch.zeros(4 + words, dtype=torch.int32)
++ mine[:4] = torch.tensor([failed, len(self.hcas), self.slot_bytes >> 12, self.flag_stride])
++ raw = torch.frombuffer(bytearray(blob.raw.ljust(words * 4, b"\0")), dtype=torch.int32)
++ mine[4:] = raw
++ got = torch.empty(world * mine.numel(), dtype=torch.int32, device="cuda")
++ comm.all_gather(mine.cuda(), got)
++ rows = got.view(world, -1).cpu()
++ if int(rows[:, 0].sum()) or len(set(tuple(r[1:4].tolist()) for r in rows)) != 1:
++ why = err.value.decode(errors="replace") if not self.ctx else "the ranks' RoCE geometry differs"
++ self.close()
++ raise RuntimeError(f"RoCE all-gather setup failed on some rank: {why}")
++ blobs = b"".join(bytes(r[4:].numpy().tobytes())[:blob_len] for r in rows)
++ 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")
++ comm.all_gather(verdict, both)
++ if int(both.sum()):
++ why = lib.roce_error(self.ctx).decode(errors="replace") if self.ctx else ""
++ self.close()
++ raise RuntimeError(f"RoCE all-gather could not connect: {why}")
++
++ def fits(self, send: torch.Tensor) -> bool:
++ n = send.numel() * send.element_size()
++ return 0 < n <= self.max_bytes and n % PACK == 0 and send.data_ptr() % PACK == 0 and send.is_contiguous()
++
++ def all_gather(self, send: torch.Tensor, recv: torch.Tensor) -> None:
++ nbytes = send.numel() * send.element_size()
++ packs = nbytes // PACK
++ need = max(1, -(-packs // (2 * THREADS)))
++ grid = min(1 << (need - 1).bit_length(), BLOCKS)
++ klass = grid.bit_length() - 1
++ 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)
++ if not torch.cuda.is_current_stream_capturing():
++ self.check()
++
++ def check(self) -> None:
++ """Raise if a wait timed out on the GPU or the proxy thread failed."""
++
++ if self.ctrl_words[2] != 0 or (self.ctx and self.lib.roce_failed(self.ctx)):
++ 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 ''}")
++
++ def close(self) -> None:
++ if getattr(self, "ctx", None):
++ self.lib.roce_stop(self.ctx)
++ self.lib.roce_destroy(self.ctx)
++ self.ctx = None
++
++
++class RoceComm:
++ """NCCL with small all-gathers over RoCE: the same call, output layout and bits."""
++
++ def __init__(self, nccl, rank: int, world: int, max_bytes: int | None = None) -> None:
++ self.nccl, self.rank, self.world = nccl, rank, world
++ 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
++
++ def all_gather(self, send: torch.Tensor, recv: torch.Tensor) -> None:
++ if self.roce.fits(send) and recv.is_contiguous() and recv.data_ptr() % PACK == 0:
++ self.small += 1
++ self.roce.all_gather(send, recv)
++ else:
++ self.large += 1
++ self.nccl.all_gather(send, recv)
++
++ def barrier(self) -> None:
++ self.nccl.barrier()
++
++ def check(self) -> None:
++ self.roce.check()
++
++ def __getattr__(self, name):
++ return getattr(self.nccl, name)
+diff --git tensorfold/cuda/roce_proxy.c tensorfold/cuda/roce_proxy.c
+new file mode 100644
+index 0000000..5e605ae
+--- /dev/null
++++ tensorfold/cuda/roce_proxy.c
+@@ -0,0 +1,621 @@
++// Adapted from b12x (https://github.com/local-inference-lab/b12x), b12x/comm/roce/_roce_proxy.c at commit
++// 8a99d639410e39d5f39cb4037675331beceea1d4: "RoCEnante", Copyright the b12x contributors, Apache License 2.0
++// (http://www.apache.org/licenses/LICENSE-2.0). Unchanged except this header. Used by tensorfold/cuda/roce.py.
++
++// RDMA proxy for the b12x RoCE one-shot all-reduce.
++//
++// One rank owns one pinned host region laid out as:
++//
++// recv[src][slot] (world * SLOTS * slot_bytes) filled by peers' RDMA writes
++// flag[src][slot][hca] sequence number written on each HCA after that HCA's
++// payload stripe
++// send[slot] (SLOTS * slot_bytes) staged by the local GPU kernel
++// ctrl (FLAG_STRIDE) {u32 seq, u32 nbytes, u32 error,
++// u32 missing_peer} doorbell; the
++// last two are set by the kernel
++// when a wait times out
++//
++// The GPU kernel stages its input into send[seq & 1], publishes nbytes and seq
++// in ctrl, then spins on flag[peer][seq & 1][hca] for every peer and HCA. The
++// proxy thread
++// below spins on ctrl.seq and, for every peer, stripes the payload across every
++// HCA. Each stripe is followed by its own 4-byte seq write on the same reliable
++// QP, so its flag cannot become visible before its payload. The GPU waits for
++// every stripe flag before consuming the receive slot. Nothing on the receive
++// path involves the host.
++//
++// This file is compiled by b12x.comm.roce._proxy at first use with the host
++// gcc and libibverbs; it must stay plain C with no CUDA dependency.
++
++#define _GNU_SOURCE
++#include <errno.h>
++#include <infiniband/verbs.h>
++#include <pthread.h>
++#include <sched.h>
++#include <stdatomic.h>
++#include <stdint.h>
++#include <stdio.h>
++#include <stdlib.h>
++#include <string.h>
++#include <time.h>
++
++#define ROCE_MAX_PEERS 16
++#define ROCE_MAX_HCAS 2
++#define ROCE_SLOTS 2
++#define ROCE_FLAG_STRIDE 128
++#define ROCE_PORT 1
++#define ROCE_SEND_DEPTH 256
++#define ROCE_ABI_VERSION 4
++// Model graphs leave sub-millisecond gaps between collectives. Keep the
++// proxy hot across those gaps; sleeping there adds one scheduler wakeup to
++// every collective on the graph's critical path.
++#define ROCE_IDLE_SPINS 20000000
++
++typedef struct {
++ uint64_t region_addr;
++ uint32_t rkey[ROCE_MAX_HCAS];
++ uint16_t lid[ROCE_MAX_HCAS];
++ uint8_t gid[ROCE_MAX_HCAS][16];
++ uint32_t mtu[ROCE_MAX_HCAS];
++ uint32_t qp_num[ROCE_MAX_HCAS][ROCE_MAX_PEERS];
++} roce_blob_t;
++
++typedef struct {
++ struct ibv_context *ctx;
++ struct ibv_pd *pd;
++ struct ibv_mr *mr;
++ struct ibv_cq *cq;
++ struct ibv_qp *qp[ROCE_MAX_PEERS];
++ uint32_t outstanding[ROCE_MAX_PEERS];
++ uint64_t writes_completed;
++ uint64_t bytes_posted;
++ union ibv_gid gid;
++ uint16_t lid;
++ enum ibv_mtu mtu;
++} roce_hca_t;
++
++typedef struct {
++ int world;
++ int rank;
++ int n_hca;
++ int gid_index;
++ int traffic_class;
++ roce_hca_t hca[ROCE_MAX_HCAS];
++ uint8_t *region;
++ size_t region_bytes;
++ size_t slot_bytes;
++ size_t recv_off;
++ size_t flag_off;
++ size_t send_off;
++ size_t ctrl_off;
++ int started;
++ uint64_t peer_addr[ROCE_MAX_PEERS];
++ uint32_t peer_rkey[ROCE_MAX_HCAS][ROCE_MAX_PEERS];
++ pthread_t thread;
++ atomic_int running;
++ atomic_int failed;
++ uint32_t last_seq;
++ uint64_t ops_posted;
++ uint64_t writes_completed;
++ char err[512];
++} roce_ctx_t;
++
++void roce_destroy(roce_ctx_t *c);
++
++static void set_err(roce_ctx_t *c, const char *what, int e) {
++ snprintf(c->err, sizeof(c->err), "%s: %s", what, e ? strerror(e) : "failed");
++}
++
++int roce_abi_version(void) { return ROCE_ABI_VERSION; }
++
++int roce_layout(int world, uint64_t slot_bytes, uint64_t *out) {
++ // out = {recv_off, flag_off, send_off, ctrl_off, total_bytes, flag_stride, slots}
++ if (world < 2 || world > ROCE_MAX_PEERS || slot_bytes == 0 || (slot_bytes % 4096) != 0) {
++ return -1;
++ }
++ // Reject a layout whose arithmetic would wrap; the caller sizes slots from
++ // configuration, so a wrapped region must fail here rather than at the NIC.
++ uint64_t recv_bytes, flag_bytes, send_bytes, send_off, ctrl_off, total;
++ if (slot_bytes > ((uint64_t)1 << 40) ||
++ __builtin_mul_overflow((uint64_t)world * ROCE_SLOTS, slot_bytes, &recv_bytes) ||
++ __builtin_mul_overflow(
++ (uint64_t)world * ROCE_SLOTS * ROCE_MAX_HCAS,
++ (uint64_t)ROCE_FLAG_STRIDE,
++ &flag_bytes) ||
++ __builtin_mul_overflow((uint64_t)ROCE_SLOTS, slot_bytes, &send_bytes) ||
++ __builtin_add_overflow(recv_bytes, flag_bytes, &send_off) ||
++ __builtin_add_overflow(send_off, send_bytes, &ctrl_off) ||
++ __builtin_add_overflow(ctrl_off, (uint64_t)ROCE_FLAG_STRIDE, &total)) {
++ return -1;
++ }
++ uint64_t recv_off = 0;
++ uint64_t flag_off = recv_off + recv_bytes;
++ out[0] = recv_off;
++ out[1] = flag_off;
++ out[2] = send_off;
++ out[3] = ctrl_off;
++ out[4] = total;
++ out[5] = ROCE_FLAG_STRIDE;
++ out[6] = ROCE_SLOTS;
++ return 0;
++}
++
++uint64_t roce_blob_bytes(void) { return sizeof(roce_blob_t); }
++
++static int open_hca(roce_ctx_t *c, int h, const char *name) {
++ int num = 0;
++ struct ibv_device **list = ibv_get_device_list(&num);
++ if (list == NULL) {
++ set_err(c, "ibv_get_device_list", errno);
++ return -1;
++ }
++ struct ibv_device *dev = NULL;
++ for (int i = 0; i < num; i++) {
++ if (strcmp(ibv_get_device_name(list[i]), name) == 0) {
++ dev = list[i];
++ break;
++ }
++ }
++ if (dev == NULL) {
++ ibv_free_device_list(list);
++ snprintf(c->err, sizeof(c->err), "RDMA device %s not found", name);
++ return -1;
++ }
++ roce_hca_t *hca = &c->hca[h];
++ hca->ctx = ibv_open_device(dev);
++ ibv_free_device_list(list);
++ if (hca->ctx == NULL) {
++ set_err(c, "ibv_open_device", errno);
++ return -1;
++ }
++ struct ibv_port_attr port;
++ if (ibv_query_port(hca->ctx, ROCE_PORT, &port) != 0) {
++ set_err(c, "ibv_query_port", errno);
++ return -1;
++ }
++ if (port.state != IBV_PORT_ACTIVE) {
++ snprintf(c->err, sizeof(c->err), "RDMA device %s port %d is not active", name, ROCE_PORT);
++ return -1;
++ }
++ hca->lid = port.lid;
++ hca->mtu = port.active_mtu;
++ if (ibv_query_gid(hca->ctx, ROCE_PORT, c->gid_index, &hca->gid) != 0) {
++ set_err(c, "ibv_query_gid", errno);
++ return -1;
++ }
++ hca->pd = ibv_alloc_pd(hca->ctx);
++ if (hca->pd == NULL) {
++ set_err(c, "ibv_alloc_pd", errno);
++ return -1;
++ }
++ hca->mr = ibv_reg_mr(hca->pd, c->region, c->region_bytes,
++ IBV_ACCESS_LOCAL_WRITE | IBV_ACCESS_REMOTE_WRITE);
++ if (hca->mr == NULL) {
++ set_err(c, "ibv_reg_mr(pinned region)", errno);
++ return -1;
++ }
++ hca->cq = ibv_create_cq(hca->ctx, ROCE_SEND_DEPTH * ROCE_MAX_PEERS, NULL, NULL, 0);
++ if (hca->cq == NULL) {
++ set_err(c, "ibv_create_cq", errno);
++ return -1;
++ }
++ for (int p = 0; p < c->world; p++) {
++ if (p == c->rank) {
++ continue;
++ }
++ struct ibv_qp_init_attr attr;
++ memset(&attr, 0, sizeof(attr));
++ attr.send_cq = hca->cq;
++ attr.recv_cq = hca->cq;
++ attr.qp_type = IBV_QPT_RC;
++ attr.cap.max_send_wr = ROCE_SEND_DEPTH;
++ attr.cap.max_recv_wr = 1;
++ attr.cap.max_send_sge = 1;
++ attr.cap.max_recv_sge = 1;
++ attr.cap.max_inline_data = 16;
++ hca->qp[p] = ibv_create_qp(hca->pd, &attr);
++ if (hca->qp[p] == NULL) {
++ set_err(c, "ibv_create_qp", errno);
++ return -1;
++ }
++ struct ibv_qp_attr init;
++ memset(&init, 0, sizeof(init));
++ init.qp_state = IBV_QPS_INIT;
++ init.pkey_index = 0;
++ init.port_num = ROCE_PORT;
++ init.qp_access_flags = IBV_ACCESS_REMOTE_WRITE;
++ int rc = ibv_modify_qp(hca->qp[p], &init,
++ IBV_QP_STATE | IBV_QP_PKEY_INDEX | IBV_QP_PORT | IBV_QP_ACCESS_FLAGS);
++ if (rc != 0) {
++ set_err(c, "ibv_modify_qp(INIT)", rc);
++ return -1;
++ }
++ }
++ return 0;
++}
++
++roce_ctx_t *roce_create(int world, int rank, const char *const *hca_names, int n_hca,
++ int gid_index, int traffic_class, void *region, uint64_t region_bytes,
++ uint64_t slot_bytes, char *err, uint64_t err_len) {
++ uint64_t layout[7];
++ if (roce_layout(world, slot_bytes, layout) != 0 || layout[4] > region_bytes ||
++ rank < 0 || rank >= world || n_hca < 1 || n_hca > ROCE_MAX_HCAS ||
++ traffic_class < 0 || traffic_class > 255) {
++ snprintf(err, err_len, "invalid roce runtime geometry");
++ return NULL;
++ }
++ roce_ctx_t *c = calloc(1, sizeof(*c));
++ if (c == NULL) {
++ snprintf(err, err_len, "out of memory");
++ return NULL;
++ }
++ c->world = world;
++ c->rank = rank;
++ c->n_hca = n_hca;
++ c->gid_index = gid_index;
++ c->traffic_class = traffic_class;
++ c->region = region;
++ c->region_bytes = region_bytes;
++ c->slot_bytes = slot_bytes;
++ c->recv_off = layout[0];
++ c->flag_off = layout[1];
++ c->send_off = layout[2];
++ c->ctrl_off = layout[3];
++ for (int h = 0; h < n_hca; h++) {
++ if (open_hca(c, h, hca_names[h]) != 0) {
++ snprintf(err, err_len, "%s", c->err);
++ roce_destroy(c);
++ return NULL;
++ }
++ }
++ return c;
++}
++
++int roce_local_blob(roce_ctx_t *c, void *out, uint64_t out_len) {
++ if (out_len < sizeof(roce_blob_t)) {
++ return -1;
++ }
++ roce_blob_t blob;
++ memset(&blob, 0, sizeof(blob));
++ blob.region_addr = (uint64_t)(uintptr_t)c->region;
++ for (int h = 0; h < c->n_hca; h++) {
++ blob.rkey[h] = c->hca[h].mr->rkey;
++ blob.lid[h] = c->hca[h].lid;
++ blob.mtu[h] = (uint32_t)c->hca[h].mtu;
++ memcpy(blob.gid[h], c->hca[h].gid.raw, 16);
++ for (int p = 0; p < c->world; p++) {
++ blob.qp_num[h][p] = (p == c->rank) ? 0 : c->hca[h].qp[p]->qp_num;
++ }
++ }
++ memcpy(out, &blob, sizeof(blob));
++ return 0;
++}
++
++static int connect_qp(roce_ctx_t *c, int h, int p, const roce_blob_t *peer) {
++ roce_hca_t *hca = &c->hca[h];
++ struct ibv_qp_attr rtr;
++ memset(&rtr, 0, sizeof(rtr));
++ rtr.qp_state = IBV_QPS_RTR;
++ rtr.path_mtu = (enum ibv_mtu)(peer->mtu[h] < (uint32_t)hca->mtu ? peer->mtu[h] : (uint32_t)hca->mtu);
++ rtr.dest_qp_num = peer->qp_num[h][c->rank];
++ rtr.rq_psn = 0;
++ rtr.max_dest_rd_atomic = 1;
++ rtr.min_rnr_timer = 12;
++ rtr.ah_attr.is_global = 1;
++ rtr.ah_attr.dlid = peer->lid[h];
++ rtr.ah_attr.sl = 0;
++ rtr.ah_attr.src_path_bits = 0;
++ rtr.ah_attr.port_num = ROCE_PORT;
++ memcpy(rtr.ah_attr.grh.dgid.raw, peer->gid[h], 16);
++ rtr.ah_attr.grh.sgid_index = (uint8_t)c->gid_index;
++ rtr.ah_attr.grh.hop_limit = 64;
++ rtr.ah_attr.grh.traffic_class = (uint8_t)c->traffic_class;
++ rtr.ah_attr.grh.flow_label = 0;
++ int rc = ibv_modify_qp(hca->qp[p], &rtr,
++ IBV_QP_STATE | IBV_QP_AV | IBV_QP_PATH_MTU | IBV_QP_DEST_QPN |
++ IBV_QP_RQ_PSN | IBV_QP_MAX_DEST_RD_ATOMIC | IBV_QP_MIN_RNR_TIMER);
++ if (rc != 0) {
++ set_err(c, "ibv_modify_qp(RTR)", rc);
++ return -1;
++ }
++ struct ibv_qp_attr rts;
++ memset(&rts, 0, sizeof(rts));
++ rts.qp_state = IBV_QPS_RTS;
++ rts.timeout = 14;
++ rts.retry_cnt = 7;
++ rts.rnr_retry = 7;
++ rts.sq_psn = 0;
++ rts.max_rd_atomic = 1;
++ rc = ibv_modify_qp(hca->qp[p], &rts,
++ IBV_QP_STATE | IBV_QP_TIMEOUT | IBV_QP_RETRY_CNT | IBV_QP_RNR_RETRY |
++ IBV_QP_SQ_PSN | IBV_QP_MAX_QP_RD_ATOMIC);
++ if (rc != 0) {
++ set_err(c, "ibv_modify_qp(RTS)", rc);
++ return -1;
++ }
++ return 0;
++}
++
++int roce_connect(roce_ctx_t *c, const void *blobs, uint64_t blobs_len) {
++ if (blobs_len < sizeof(roce_blob_t) * (uint64_t)c->world) {
++ snprintf(c->err, sizeof(c->err), "peer blob buffer too small");
++ return -1;
++ }
++ const roce_blob_t *all = (const roce_blob_t *)blobs;
++ for (int p = 0; p < c->world; p++) {
++ if (p == c->rank) {
++ continue;
++ }
++ c->peer_addr[p] = all[p].region_addr;
++ for (int h = 0; h < c->n_hca; h++) {
++ c->peer_rkey[h][p] = all[p].rkey[h];
++ if (connect_qp(c, h, p, &all[p]) != 0) {
++ return -1;
++ }
++ }
++ }
++ return 0;
++}
++
++static int drain_cq(roce_ctx_t *c, int h) {
++ struct ibv_wc wc[32];
++ int n = ibv_poll_cq(c->hca[h].cq, 32, wc);
++ if (n < 0) {
++ set_err(c, "ibv_poll_cq", errno);
++ return -1;
++ }
++ for (int i = 0; i < n; i++) {
++ if (wc[i].status != IBV_WC_SUCCESS) {
++ snprintf(c->err, sizeof(c->err),
++ "RDMA write to rank %u failed: %s (vendor_err 0x%x, seq %u)",
++ (unsigned)wc[i].wr_id, ibv_wc_status_str(wc[i].status),
++ wc[i].vendor_err, c->last_seq);
++ return -1;
++ }
++ c->hca[h].outstanding[wc[i].wr_id] -= 1;
++ c->hca[h].writes_completed += 1;
++ c->writes_completed += 1;
++ }
++ return 0;
++}
++
++static int post_op(roce_ctx_t *c, uint32_t seq, uint32_t nbytes) {
++ if (nbytes == 0 || nbytes % 16 != 0) {
++ snprintf(c->err, sizeof(c->err),
++ "RoCE payload size must be a positive multiple of 16 bytes, got %u",
++ nbytes);
++ return -1;
++ }
++ uint32_t slot = seq & 1u;
++ uint8_t *send = c->region + c->send_off + (size_t)slot * c->slot_bytes;
++ uint32_t seq_copy = seq;
++ uint32_t total_packs = nbytes / 16;
++ for (int p = 0; p < c->world; p++) {
++ if (p == c->rank) {
++ continue;
++ }
++ uint32_t pack_offset = 0;
++ for (int h = 0; h < c->n_hca; h++) {
++ roce_hca_t *hca = &c->hca[h];
++ // Two work requests per stripe; keep the queue at most a quarter
++ // full so a provider that needs extra entries can never fail a post.
++ while (hca->outstanding[p] >= ROCE_SEND_DEPTH / 4) {
++ if (drain_cq(c, h) != 0) {
++ return -1;
++ }
++ // A peer that stopped acknowledging keeps the QP retrying for
++ // a long time; honour a stop request instead of blocking
++ // roce_stop (and so teardown) behind it.
++ if (!atomic_load_explicit(&c->running, memory_order_relaxed)) {
++ snprintf(c->err, sizeof(c->err),
++ "RoCE proxy stopped with %u writes outstanding to rank %d",
++ hca->outstanding[p], p);
++ return -1;
++ }
++ }
++ uint32_t stripe_packs = total_packs / (uint32_t)c->n_hca;
++ if ((uint32_t)h < total_packs % (uint32_t)c->n_hca) {
++ stripe_packs += 1;
++ }
++ uint32_t stripe_bytes = stripe_packs * 16;
++ uint64_t byte_offset = (uint64_t)pack_offset * 16;
++ uint64_t remote = c->peer_addr[p];
++ struct ibv_sge flag_sge = {
++ .addr = (uint64_t)(uintptr_t)&seq_copy,
++ .length = 4,
++ .lkey = 0,
++ };
++ struct ibv_send_wr flag_wr;
++ memset(&flag_wr, 0, sizeof(flag_wr));
++ flag_wr.wr_id = (uint64_t)p;
++ flag_wr.sg_list = &flag_sge;
++ flag_wr.num_sge = 1;
++ flag_wr.opcode = IBV_WR_RDMA_WRITE;
++ flag_wr.send_flags = IBV_SEND_SIGNALED | IBV_SEND_INLINE;
++ flag_wr.wr.rdma.remote_addr =
++ remote + c->flag_off +
++ (((uint64_t)c->rank * ROCE_SLOTS + slot) * (uint64_t)c->n_hca +
++ (uint64_t)h) * ROCE_FLAG_STRIDE;
++ flag_wr.wr.rdma.rkey = c->peer_rkey[h][p];
++
++ struct ibv_send_wr data_wr;
++ struct ibv_sge data_sge;
++ struct ibv_send_wr *first_wr = &flag_wr;
++ if (stripe_bytes != 0) {
++ data_sge = (struct ibv_sge){
++ .addr = (uint64_t)(uintptr_t)(send + byte_offset),
++ .length = stripe_bytes,
++ .lkey = hca->mr->lkey,
++ };
++ memset(&data_wr, 0, sizeof(data_wr));
++ data_wr.wr_id = (uint64_t)p;
++ data_wr.next = &flag_wr;
++ data_wr.sg_list = &data_sge;
++ data_wr.num_sge = 1;
++ data_wr.opcode = IBV_WR_RDMA_WRITE;
++ data_wr.wr.rdma.remote_addr =
++ remote + c->recv_off +
++ ((uint64_t)c->rank * ROCE_SLOTS + slot) * c->slot_bytes +
++ byte_offset;
++ data_wr.wr.rdma.rkey = c->peer_rkey[h][p];
++ first_wr = &data_wr;
++ }
++ struct ibv_send_wr *bad = NULL;
++ int rc = ibv_post_send(hca->qp[p], first_wr, &bad);
++ if (rc != 0) {
++ set_err(c, "ibv_post_send", rc);
++ return -1;
++ }
++ hca->outstanding[p] += 1;
++ hca->bytes_posted += stripe_bytes;
++ pack_offset += stripe_packs;
++ }
++ }
++ c->ops_posted += 1;
++ for (int h = 0; h < c->n_hca; h++) {
++ if (drain_cq(c, h) != 0) {
++ return -1;
++ }
++ }
++ return 0;
++}
++
++static void *proxy_main(void *arg) {
++ roce_ctx_t *c = (roce_ctx_t *)arg;
++ volatile uint32_t *ctrl = (volatile uint32_t *)(c->region + c->ctrl_off);
++ // Spin while ops are flowing. After ROCE_IDLE_SPINS polls without a
++ // doorbell, request a short nanosleep between polls (the OS decides the
++ // actual delay) so an idle runtime does not hold a core next to the
++ // serving process. The missed-doorbell catch-up below keeps the protocol
++ // correct however long the thread is away.
++ uint64_t idle = 0;
++ const struct timespec nap = {0, 20000};
++ while (atomic_load_explicit(&c->running, memory_order_relaxed)) {
++ uint32_t seq = __atomic_load_n(&ctrl[0], __ATOMIC_ACQUIRE);
++ if (seq == c->last_seq) {
++ idle++;
++ if (idle % 64 == 0) {
++ for (int h = 0; h < c->n_hca; h++) {
++ if (drain_cq(c, h) != 0) {
++ atomic_store(&c->failed, 1);
++ return NULL;
++ }
++ }
++ }
++ if (idle >= ROCE_IDLE_SPINS) {
++ nanosleep(&nap, NULL);
++ }
++ continue;
++ }
++ idle = 0;
++ // The doorbell holds only the newest sequence. Our kernel for op N
++ // completes on the peers' payloads alone, so op N+1 can ring before
++ // this thread has seen op N (it slept, or the scheduler moved it).
++ // Peers cannot get further than one op ahead of us, so at most
++ // ROCE_SLOTS doorbells are pending and every send slot is intact:
++ // post each missed sequence in order using its per-slot byte count.
++ uint32_t pending = seq - c->last_seq;
++ if (pending > ROCE_SLOTS) {
++ snprintf(c->err, sizeof(c->err),
++ "doorbell skipped %u ops (last %u, now %u)", pending, c->last_seq, seq);
++ atomic_store(&c->failed, 1);
++ return NULL;
++ }
++ for (uint32_t s = c->last_seq + 1; pending > 0; s++, pending--) {
++ uint32_t nbytes = ctrl[4 + (s & 1u)];
++ if (post_op(c, s, nbytes) != 0) {
++ atomic_store(&c->failed, 1);
++ return NULL;
++ }
++ c->last_seq = s;
++ }
++ }
++ return NULL;
++}
++
++int roce_start(roce_ctx_t *c) {
++ if (atomic_load(&c->running)) {
++ return 0;
++ }
++ if (!c->started) {
++ // A restart continues from the last posted sequence so ops that rang
++ // the doorbell while the thread was stopped are still posted.
++ volatile uint32_t *ctrl = (volatile uint32_t *)(c->region + c->ctrl_off);
++ c->last_seq = ctrl[0];
++ c->started = 1;
++ }
++ atomic_store(&c->failed, 0);
++ atomic_store(&c->running, 1);
++ int rc = pthread_create(&c->thread, NULL, proxy_main, c);
++ if (rc != 0) {
++ atomic_store(&c->running, 0);
++ set_err(c, "pthread_create", rc);
++ return -1;
++ }
++ return 0;
++}
++
++void roce_stop(roce_ctx_t *c) {
++ if (atomic_exchange(&c->running, 0)) {
++ pthread_join(c->thread, NULL);
++ }
++}
++
++int roce_failed(roce_ctx_t *c) { return atomic_load(&c->failed); }
++
++const char *roce_error(roce_ctx_t *c) { return c->err; }
++
++uint64_t roce_stat(roce_ctx_t *c, int which) {
++ switch (which) {
++ case 0:
++ return c->ops_posted;
++ case 1:
++ return c->writes_completed;
++ case 2:
++ return c->last_seq;
++ default:
++ return 0;
++ }
++}
++
++uint64_t roce_hca_stat(roce_ctx_t *c, int hca, int which) {
++ if (hca < 0 || hca >= c->n_hca) {
++ return -1;
++ }
++ switch (which) {
++ case 0:
++ return c->hca[hca].writes_completed;
++ case 1:
++ return c->hca[hca].bytes_posted;
++ default:
++ return 0;
++ }
++}
++
++void roce_destroy(roce_ctx_t *c) {
++ if (c == NULL) {
++ return;
++ }
++ roce_stop(c);
++ for (int h = 0; h < ROCE_MAX_HCAS; h++) {
++ roce_hca_t *hca = &c->hca[h];
++ for (int p = 0; p < ROCE_MAX_PEERS; p++) {
++ if (hca->qp[p] != NULL) {
++ ibv_destroy_qp(hca->qp[p]);
++ }
++ }
++ if (hca->cq != NULL) {
++ ibv_destroy_cq(hca->cq);
++ }
++ if (hca->mr != NULL) {
++ ibv_dereg_mr(hca->mr);
++ }
++ if (hca->pd != NULL) {
++ ibv_dealloc_pd(hca->pd);
++ }
++ if (hca->ctx != NULL) {
++ ibv_close_device(hca->ctx);
++ }
++ }
++ free(c);
++}
+diff --git tensorfold/families/glm5_next/cuda/engine.py tensorfold/families/glm5_next/cuda/engine.py
+index 0ed6ec3..cb8d750 100644
+--- tensorfold/families/glm5_next/cuda/engine.py
++++ tensorfold/families/glm5_next/cuda/engine.py
+@@ -123,6 +123,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()
++ if comm is None and os.environ.get("TF_GLM_COMM", "nccl") == "roce":
++ # small all-gathers (a decode round's partials, the samplers) over b12x's one-shot RoCE transport
++ from tensorfold.cuda.roce import RoceComm
++
++ self.comm = RoceComm(self.comm, rank, 2)
++ if rank == 0:
++ print(f"[tensorfold] all-gathers up to {self.comm.roce.max_bytes >> 10} KiB over RoCE "
++ f"({', '.join(self.comm.roce.hcas)}; b12x's RoCEnante transport), larger ones over NCCL",
++ flush=True)
+ 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:
+ 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)
++ if hasattr(self.comm, "check"): # a RoCE wait that timed out inside a graph surfaces here
++ self.comm.check()
+ 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:
+ 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)
++ if hasattr(self.comm, "check"):
++ self.comm.check()
+
+
+ class VisionFeed:
diff --git a/patches/0007-glm-copy-drafts.patch b/patches/0007-glm-copy-drafts.patch
new file mode 100644
index 0000000..e015ffa
--- /dev/null
+++ b/patches/0007-glm-copy-drafts.patch
@@ -0,0 +1,424 @@
+diff --git tensorfold/families/glm5_next/cuda/copy_drafts.py tensorfold/families/glm5_next/cuda/copy_drafts.py
+new file mode 100644
+index 0000000..25e4be7
+--- /dev/null
++++ tensorfold/families/glm5_next/cuda/copy_drafts.py
+@@ -0,0 +1,115 @@
++"""Prompt-lookup ("copy") drafts: when the context's last tokens occurred before, propose what followed them.
++
++A reply that quotes or edits its prompt (or repeats itself) is cheap to draft: its last ``match`` tokens (the
++pending token included) are searched in the prompt and the reply so far, and the tokens after the latest earlier
++occurrence become the drafts. They only propose; verification keeps the serial sample, so replies stay exact.
++
++Both ranks hold the same prompt and sample the same tokens, so each computes the same proposals with no exchange.
++Pure numpy (no torch), so it is testable anywhere."""
++
++from __future__ import annotations
++
++import os
++from dataclasses import dataclass
++from typing import Sequence
++
++import numpy as np
++
++MATCH = 8 # the context's last this many tokens must have occurred before (TF_GLM_COPY_MATCH)
++MOST = 5 # drafts a round: 5 keeps the verify window (6 rows) within the captured graphs (TF_GLM_COPY_MAX)
++
++
++@dataclass(frozen=True)
++class CopySettings:
++ match: int = MATCH
++ most: int = MOST
++
++ @classmethod
++ def from_env(cls, max_drafts: int, env=None) -> CopySettings | None:
++ """TF_GLM_COPY_DRAFTS=1 turns copy drafts on (off by default); TF_GLM_COPY_MATCH and TF_GLM_COPY_MAX tune."""
++
++ env = os.environ if env is None else env
++ on = env.get("TF_GLM_COPY_DRAFTS", "0").strip()
++ if on in ("", "0"):
++ return None
++ if on != "1":
++ raise ValueError(f"TF_GLM_COPY_DRAFTS: 0 or 1, not {on!r}")
++
++ def number(name: str, default: int, low: int, high: int) -> int:
++ text = env.get(name, "").strip()
++ if text == "":
++ return default
++ if not text.isdecimal() or not low <= int(text) <= high:
++ raise ValueError(f"{name}: {low} to {high}, not {text!r}")
++ return int(text)
++
++ return cls(number("TF_GLM_COPY_MATCH", MATCH, 2, 64),
++ number("TF_GLM_COPY_MAX", min(MOST, max_drafts), 1, max_drafts))
++
++ def code(self) -> list[int]:
++ """The settings as ints both ranks compare at startup (zeros: off)."""
++
++ return [self.match, self.most]
++
++
++class CopyDrafts:
++ """One sequence's context (prompt, then committed reply tokens and the pending one) and its copy proposals."""
++
++ def __init__(self, context: Sequence[int], match: int = MATCH, most: int = MOST) -> None:
++ if match < 1 or most < 1:
++ raise ValueError("match and most must be positive")
++ self.match, self.most = int(match), int(most)
++ n = len(context)
++ self.buf = np.empty((max(1024, 2 * n),), dtype=np.int32)
++ self.buf[:n] = np.asarray(context, dtype=np.int32) if n else 0
++ self.length = n
++
++ def __len__(self) -> int:
++ return self.length
++
++ def tokens(self) -> list[int]:
++ return self.buf[:self.length].tolist()
++
++ def extend(self, tokens: Sequence[int]) -> None:
++ """Committed tokens (the last one is the next round's pending token) join the context."""
++
++ k = len(tokens)
++ if not k:
++ return
++ if self.length + k > self.buf.shape[0]:
++ grown = np.empty((2 * (self.length + k),), dtype=np.int32)
++ grown[:self.length] = self.buf[:self.length]
++ self.buf = grown
++ self.buf[self.length:self.length + k] = np.asarray(tokens, dtype=np.int32)
++ self.length += k
++
++ def starts(self) -> np.ndarray:
++ """Ascending starts of the earlier occurrences of the context's last ``match`` tokens (not the suffix)."""
++
++ L, n = self.length, self.match
++ if L <= n:
++ return np.empty((0,), dtype=np.int64)
++ ctx = self.buf
++ q = ctx[L - n:L]
++ # starts 0 .. L - n - 1 (each leaves a token after its match): by the last token, then the others
++ hits = np.flatnonzero(ctx[n - 1:L - 1] == q[n - 1])
++ for k in range(n - 1):
++ if not hits.size:
++ break
++ hits = hits[ctx[hits + k] == q[k]]
++ return hits
++
++ def propose(self, room: int | None = None) -> list[int]:
++ """Up to ``min(most, room)`` drafts: what followed the latest earlier occurrence that has that many tokens
++ after it, else the most after any occurrence (the earliest); [] when the suffix never occurred before."""
++
++ k = self.most if room is None else min(self.most, int(room))
++ if k < 1:
++ return []
++ hits = self.starts()
++ if not hits.size:
++ return []
++ L, n = self.length, self.match
++ full = hits[hits <= L - n - k]
++ 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
+--- tensorfold/families/glm5_next/cuda/decode.py
++++ tensorfold/families/glm5_next/cuda/decode.py
+@@ -377,8 +377,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)
+- arms: str = "" # auto_decode: the drafter of each round, "m" (MTP) or "f" (DFlash2)
++ arms: str = "" # auto_decode: each round's drafter, "m" (MTP), "f" (DFlash2) or "c" (copy)
+ pending: torch.Tensor | None = None # auto_decode: MTP input rows of committed positions not absorbed yet
++ copy_rounds: int = 0 # rounds whose drafts were copied from the context (``copy_drafts``)
++ copy_drafted: int = 0
++ copy_accepted: int = 0
+
+ @property
+ def tokens_per_second(self) -> float:
+@@ -436,23 +439,35 @@ class DepthPolicy:
+ return max(1, min(self.most, 1 if self.rate < self.low else 2 if self.rate < self.high else 3))
+
+
++def copy_room(copies, count: int, out: list[int]) -> int:
++ """Copy drafts a round may propose: the rows still wanted past the pending token (0 without copy drafts)."""
++
++ return 0 if copies is None else count - len(out) - 1
++
++
+ @torch.no_grad()
+ def mtp_decode(e: Engine, pending: int, count: int, sampling: Sampling | None, *, policy: DepthPolicy | None = None,
+- stop_eos: bool = False, on_tokens=None) -> DecodeResult:
+- """Verify pending and MTP draft rows through the first mismatch, starting with every prompt position except the last in the MTP cache."""
++ stop_eos: bool = False, on_tokens=None, copies=None) -> DecodeResult:
++ """Verify pending and MTP draft rows through the first mismatch, starting with every prompt position except the last in the MTP cache; ``copies``: a ``copy_drafts.CopyDrafts`` of prompt and pending token, whose proposals replace the MTP chain (the kept rows are still absorbed)."""
+
+ w, st, b = e.w, e.st, e.buf
+ policy = policy or DepthPolicy()
+ out = [pending]
+ stages = dict(draft=0.0, forward=0.0, sample=0.0, commit=0.0)
+ rounds = drafted = accepted = 0
++ c_rounds = c_drafted = c_accepted = 0
+ depths: list[int] = []
+ keeps: list[int] = []
+ _sync(w)
+ start = time.perf_counter()
+ t0 = time.perf_counter()
+- depth = min(policy.next(0, 0), count - len(out))
+- drafts = draft(e, e.last_hidden, [pending], st.pos + 1, depth, sampling, policy.confidence) if depth > 0 else []
++ copied = copies.propose(copy_room(copies, count, out)) if copies is not None else []
++ if copied:
++ absorb(e, e.last_hidden, [pending])
++ drafts = copied
++ else:
++ depth = min(policy.next(0, 0), count - len(out))
++ 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):
+ t0 = time.perf_counter()
+@@ -474,10 +489,14 @@ def mtp_decode(e: Engine, pending: int, count: int, sampling: Sampling | None, *
+ rounds += 1
+ drafted += len(drafts)
+ accepted += keep - 1
++ if copied:
++ c_rounds, c_drafted, c_accepted = c_rounds + 1, c_drafted + len(drafts), c_accepted + keep - 1
+ depths.append(len(drafts))
+ keeps.append(keep)
+ e.follow(sampled[:keep])
+ out.extend(sampled[:keep])
++ if copies is not None:
++ copies.extend(sampled[:keep])
+ 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, *
+ if len(out) >= count or (stop_eos and out[-1] in w.cfg.eos):
+ break
+ t4 = time.perf_counter()
+- depth = min(policy.next(len(drafts), keep - 1), count - len(out))
+- drafts = (draft(e, e.main_hidden(slice(0, keep)), sampled[:keep], st.pos + 1, depth, sampling,
+- policy.confidence) if depth > 0 else [])
++ was_copy = bool(copied)
++ copied = copies.propose(copy_room(copies, count, out)) if copies is not None else []
++ if copied: # the MTP head still takes the kept rows; it drafts nothing this round
++ absorb(e, e.main_hidden(slice(0, keep)), sampled[:keep])
++ drafts = copied
++ else: # a copied round's acceptance does not move the MTP depth
++ depth = min(policy.next(*((0, 0) if was_copy else (len(drafts), keep - 1))), count - len(out))
++ 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
+ _sync(w)
+- return DecodeResult(out[:count], time.perf_counter() - start, rounds, drafted, accepted, stages, depths, keeps)
++ 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)
+
+
+ @torch.no_grad()
+ def dflash_decode(e: Engine, drafter, pending: int, count: int, sampling: Sampling | None, *,
+- policy: DepthPolicy | None = None, stop_eos: bool = False, on_tokens=None) -> DecodeResult:
+- """Verify pending and DFlash2 draft rows through the first mismatch and absorb kept taps, starting from prefill's drafter state."""
++ policy: DepthPolicy | None = None, stop_eos: bool = False, on_tokens=None,
++ copies=None) -> DecodeResult:
++ """Verify pending and DFlash2 draft rows through the first mismatch and absorb kept taps, starting from prefill's drafter state; ``copies``: a ``copy_drafts.CopyDrafts`` of prompt and pending token, whose proposals replace the round's DFlash2 block (the kept taps are still absorbed)."""
+
+ w, st, b = e.w, e.st, e.buf
+ policy = policy or DepthPolicy(3, fixed=True)
+ out = [pending]
+ stages = dict(draft=0.0, forward=0.0, sample=0.0, commit=0.0)
+ rounds = drafted = accepted = 0
++ c_rounds = c_drafted = c_accepted = 0
+ depths: list[int] = []
+ keeps: list[int] = []
+ _sync(w)
+@@ -511,7 +539,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()
+- drafts = drafter.propose(out[-1], depth, sampling, policy.confidence) if depth > 0 else []
++ copied = copies.propose(copy_room(copies, count, out)) if copies is not None else []
++ if copied:
++ drafts = copied
++ else:
++ drafts = drafter.propose(out[-1], depth, sampling, policy.confidence) if depth > 0 else []
+ 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
+ rounds += 1
+ drafted += len(drafts)
+ accepted += keep - 1
++ if copied:
++ c_rounds, c_drafted, c_accepted = c_rounds + 1, c_drafted + len(drafts), c_accepted + keep - 1
+ depths.append(len(drafts))
+ keeps.append(keep)
+ e.follow(sampled[:keep])
+ out.extend(sampled[:keep])
++ if copies is not None:
++ copies.extend(sampled[:keep])
+ if on_tokens is not None:
+ on_tokens(sampled[:keep][:max(0, count - (len(out) - keep))])
+ stages["draft"] += (t1 - t0) + (t5 - t4)
+ stages["forward"] += t2 - t1
+ stages["sample"] += t3 - t2
+ stages["commit"] += t4 - t3
+- depth = min(policy.next(len(drafts), keep - 1), count - len(out))
++ # a copied round's acceptance does not move DFlash2's depth
++ depth = min(policy.next(*((0, 0) if copied else (len(drafts), keep - 1))), count - len(out))
+ _sync(w)
+- return DecodeResult(out[:count], time.perf_counter() - start, rounds, drafted, accepted, stages, depths, keeps)
++ 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/drafter_choice.py tensorfold/families/glm5_next/cuda/drafter_choice.py
+index e018386..b14a7e9 100644
+--- tensorfold/families/glm5_next/cuda/drafter_choice.py
++++ tensorfold/families/glm5_next/cuda/drafter_choice.py
+@@ -8,7 +8,7 @@ import torch
+
+ from tensorfold.engine.exact_sampling import Sampling
+
+-from .decode import DecodeResult, DepthPolicy, Engine, _sync, absorb, draft
++from .decode import DecodeResult, DepthPolicy, Engine, _sync, absorb, copy_room, draft
+ from .forward import commit
+
+
+@@ -68,8 +68,11 @@ class DrafterChoice:
+ @torch.no_grad()
+ def auto_decode(e: Engine, drafter, pending: int, count: int, sampling: Sampling | None, *,
+ choice: DrafterChoice | None,
+- m_policy: DepthPolicy, f_policy: DepthPolicy, stop_eos: bool = False, on_tokens=None) -> DecodeResult:
+- """Drafted decoding with ``choice`` picking each round's drafter; drafts only propose, so it equals serial."""
++ m_policy: DepthPolicy, f_policy: DepthPolicy, stop_eos: bool = False, on_tokens=None,
++ copies=None) -> DecodeResult:
++ """Drafted decoding with ``choice`` picking each round's drafter; drafts only propose, so it equals serial.
++ ``copies`` (``copy_drafts.CopyDrafts``): a round whose context repeats earlier text drafts the continuation ("c")
++ and runs neither drafter, whose backlogs grow; the choice neither picks nor records it."""
+
+ w, st, b = e.w, e.st, e.buf
+ cap = 256 # backlog rows a drafter may owe before it absorbs them anyway
+@@ -86,14 +89,19 @@ def auto_decode(e: Engine, drafter, pending: int, count: int, sampling: Sampling
+ depths: list[int] = []
+ keeps: list[int] = []
+ arms: list[str] = []
+- last = {"m": (0, 0), "f": (0, 0)}
++ last = {"m": (0, 0), "f": (0, 0), "c": (0, 0)}
++ c_rounds = c_drafted = c_accepted = 0
+ _sync(w)
+ start = time.perf_counter()
+ while len(out) < count and not (stop_eos and out[-1] in w.cfg.eos):
+- arm = choice.pick() if choice is not None else "m"
+ room = count - len(out)
+ t0 = time.perf_counter()
+- if arm == "m":
++ copied = copies.propose(copy_room(copies, count, out)) if copies is not None else []
++ arm = "c" if copied else choice.pick() if choice is not None else "m"
++ if copied:
++ backlog = steps = 0
++ drafts = copied
++ elif arm == "m":
+ backlog = len(m_next)
+ depth = max(1, min(m_policy.next(*last["m"]), room))
+ drafts = draft(e, m_rows[:backlog], m_next, st.pos + 1, depth, sampling, m_policy.confidence)
+@@ -136,17 +144,21 @@ def auto_decode(e: Engine, drafter, pending: int, count: int, sampling: Sampling
+ f_taps[n_f:n_f + keep].copy_(e.tap_rows(keep))
+ n_f += keep
+ t5 = time.perf_counter()
+- if choice is not None:
++ if choice is not None and arm != "c":
+ choice.record(arm, R, steps, backlog, keep)
+ last[arm] = (len(drafts), keep - 1)
+ rounds += 1
+ drafted += len(drafts)
+ accepted += keep - 1
++ if copied:
++ c_rounds, c_drafted, c_accepted = c_rounds + 1, c_drafted + len(drafts), c_accepted + keep - 1
+ depths.append(len(drafts))
+ keeps.append(keep)
+ arms.append(arm)
+ e.follow(sampled[:keep])
+ out.extend(sampled[:keep])
++ if copies is not None:
++ copies.extend(sampled[:keep])
+ if on_tokens is not None:
+ on_tokens(sampled[:keep][:max(0, count - (len(out) - keep))])
+ stages["draft"] += (t1 - t0) + (t5 - t4)
+@@ -158,4 +170,4 @@ def auto_decode(e: Engine, drafter, pending: int, count: int, sampling: Sampling
+ if drafter is not None and n_f:
+ drafter.add_taps(f_taps[:n_f]) # DFlash2's context ends where the committed rows end
+ return DecodeResult(out[:count], seconds, rounds, drafted, accepted, stages, depths, keeps, "".join(arms),
+- 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
+--- 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
+
+ encode_policy(policy) # a bad default fails here, not in the first request
++ from .copy_drafts import CopySettings
++
++ # 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)
+ torch.cuda.set_device(0)
+ self.torch = torch
+ self.rank = rank
+@@ -175,7 +180,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])
+ # 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:
+ 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_*): "
+ 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:
+ if max_tokens <= 1 or (stop_eos and first in self.eos):
+ return stats
+ policy = decode_policy(code)
++ copies = None
++ if policy is not None and self.copy is not None: # prompt and pending token, alike on both ranks
++ from .copy_drafts import CopyDrafts
++
++ 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)
+ elif auto:
+@@ -468,13 +478,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,
+- on_tokens=on_tokens)
++ on_tokens=on_tokens, copies=copies)
+ elif use_dflash:
+ res = dflash_decode(self.e, self.drafter, first, max_tokens, sampling, policy=policy, stop_eos=stop_eos,
+- on_tokens=on_tokens)
++ on_tokens=on_tokens, copies=copies)
+ else:
+ res = mtp_decode(self.e, first, max_tokens, sampling, policy=policy, stop_eos=stop_eos,
+- on_tokens=on_tokens)
++ on_tokens=on_tokens, copies=copies)
+ # 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:
+ sha256=hashlib.sha256(json.dumps(res.tokens).encode()).hexdigest()[:16])
+ if res.arms:
+ stats.update(drafters=res.arms, keeps=res.keeps)
++ if policy is not None:
++ stats.update(drafted=res.drafted, accepted=res.accepted)
++ if copies is not None:
++ stats.update(copy_rounds=res.copy_rounds, copy_drafted=res.copy_drafted, copy_accepted=res.copy_accepted)
+ if res.stages:
+ stats["stages_ms"] = {k: round(v * 1e3, 1) for k, v in res.stages.items()}
+ return stats
diff --git a/patches/0008-glm-prompt-grid.patch b/patches/0008-glm-prompt-grid.patch
new file mode 100644
index 0000000..fb5fb85
--- /dev/null
+++ b/patches/0008-glm-prompt-grid.patch
@@ -0,0 +1,205 @@
+diff --git tensorfold/families/glm5_next/cuda/decode.py tensorfold/families/glm5_next/cuda/decode.py
+index 6bde10d..fdc7c53 100644
+--- tensorfold/families/glm5_next/cuda/decode.py
++++ tensorfold/families/glm5_next/cuda/decode.py
+@@ -84,8 +84,13 @@ class Engine:
+
+ def __init__(self, w: Weights, *, capacity: int = 2560, max_rows: int = 8, prefill_rows: int = PREFILL_ROWS,
+ graphs: bool = False, graph_rows: tuple[int, ...] = (1, 2, 3, 4), long_context: bool = False,
+- taps: tuple[int, ...] = ()) -> None:
++ taps: tuple[int, ...] = (), grid: int = 0) -> None:
++ """``grid``: prompt chunks start on multiples of it (TF_GLM_PROMPT_GRID; 0: anywhere)."""
++
++ if grid and prefill_rows % grid:
++ raise ValueError(f"prompt chunks of {prefill_rows} rows do not tile a {grid}-row grid")
+ self.w = w
++ self.grid = grid
+ 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:
+ # -- 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:
+- """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:
+ drafter.reset()
+ else:
+ begin = len(resume.ids)
++ if e.grid and begin % e.grid:
++ raise ValueError(f"a resumed prefill starts on the {e.grid}-row grid, not at {begin}")
+ 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:
+ chunk = list(prompt[start:start + e.prefill_rows])
+ R = len(chunk)
+ 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()
++ 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 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:
+ commit(w, st, b, R, R)
+ prof.active = False
+ prof.report(len(prompt) - begin)
++ if not sample:
++ return None
+ if e.constraint is not None: # the first token's row, under the reply's grammar
+ 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
+--- tensorfold/families/glm5_next/cuda/engine.py
++++ tensorfold/families/glm5_next/cuda/engine.py
+@@ -35,6 +35,40 @@ def vision_workspace() -> int:
+ return int(value) * 2**20
+
+
++GRIDS = (16, 32, 64, 128) # TF_GLM_PROMPT_GRID's values besides 0 (off)
++
++
++def prompt_grid(prefill_rows: int, value: str | None = None) -> int:
++ """TF_GLM_PROMPT_GRID: 0 (off, the default) or G in ``GRIDS``, which ``prefill_rows`` must be a multiple of.
++
++ With G set, every prompt chunk starts on a multiple of G and a kept prompt state sits at the last multiple of G
++ in the prompt (``grid_point``), so prompt kernels whose rows depend on G-row block alignment resume exactly."""
++
++ value = os.environ.get("TF_GLM_PROMPT_GRID", "") if value is None else value
++ value = value.strip()
++ if value in ("", "0"):
++ return 0
++ if not value.isdecimal() or int(value) not in GRIDS:
++ raise ValueError(f"TF_GLM_PROMPT_GRID: 0 or one of {', '.join(map(str, GRIDS))}, not {value!r}")
++ grid = int(value)
++ 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")
++ return grid
++
++
++def grid_point(n: int, cut: int, grid: int) -> int | None:
++ """Where a drafted request of an n-token prompt resumed at ``cut`` keeps its prompt state, or None for nowhere.
++
++ Off (grid 0) and on-grid prompts: at n. Otherwise at B = floor(n / grid) * grid, when B lies past ``cut`` (so
++ B > 0); the request then prefills up to B, keeps that state, and resumes from it to n."""
++
++ if not grid or n % grid == 0:
++ return n
++ point = n // grid * grid
++ return point if point > cut else None
++
++
+ 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:
+ 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}")
++ # 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)
+ 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:
+ 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])
+ # 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:
+ 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_*): "
+ 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:
+
+ self.drafter = Drafter(drafter, w, capacity=capacity)
+ 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 (),
++ grid=self.grid)
++ 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)
+ if self.drafter is not None:
+ self.drafter.capture()
+ self.costs = self._calibrate()
+@@ -362,6 +402,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)
++ fits = fits and not (self.grid and len(snap.ids) % self.grid) # prompt chunks start on the grid
+ 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:
+ 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)
++ # 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
++ # 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
++ resume, kept = hit, None
++ if point is not None and point < len(prompt):
++ head = list(prompt[:point])
++ prefill(self.e, head, sampling, mtp=use_mtp, drafter=drafter, resume=hit, sample=False)
++ kept = resume = take_snapshot(self.e, head, self.e.last_hidden if use_mtp else None, mtp=use_mtp,
++ 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)
++ if kept is not None:
++ self._remember(kept)
++ elif draft and feed is None and hit is not None: # the resume point is the grid point: keep it newest
++ self.cache = [c for c in self.cache if c is not hit] + [hit]
+ stats: dict[str, Any] = {"prefill_s": prefill_s, "cached": cut}
+ 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
+--- 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:
+
+
+ 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, 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)."""
+
+ c = w.cfg
+@@ -456,6 +456,8 @@ def compute(w: Weights, st: State, b: Buffers, R: int, *, logits: bool = True, n
+ if not logits:
+ return None
+ glue.rmsnorm(b.hidden[:R], w.norm, c.eps, b.fnormed[:R], b.fxs[:R])
++ if not head: # the normed rows (MTP, last_hidden) without the head: None
++ return None
+ if b.prefill: # the head reads the last row only (fnormed keeps every row for the MTP)
+ return mm(b, b.fnormed[R - 1:R], w.head, b.fxs[R - 1:R], b.logits[:1])
+ return mm(b, b.fnormed[:R], w.head, b.fxs[:R], b.logits[:R])
diff --git a/patches/0009-glm-prefill-kernels.patch b/patches/0009-glm-prefill-kernels.patch
new file mode 100644
index 0000000..1f88b28
--- /dev/null
+++ b/patches/0009-glm-prefill-kernels.patch
@@ -0,0 +1,737 @@
+diff --git tensorfold/families/glm5_next/cuda/exl3.cpp tensorfold/families/glm5_next/cuda/exl3.cpp
+index 79210dd..3a392a2 100644
+--- tensorfold/families/glm5_next/cuda/exl3.cpp
++++ tensorfold/families/glm5_next/cuda/exl3.cpp
+@@ -14,7 +14,8 @@ void exl3_down_epilogue_cuda(const at::Tensor&, const at::Tensor&, const at::Ten
+ void exl3_prompt_cuda(const at::Tensor&, const at::Tensor&, const at::Tensor&, const at::Tensor&, const at::Tensor&,
+ const at::Tensor&, const at::Tensor&, const at::Tensor&, const at::Tensor&, const at::Tensor&,
+ const at::Tensor&, const at::Tensor&, at::Tensor&, at::Tensor&, int64_t, int64_t, int64_t, int64_t,
+- double, int64_t);
++ double, int64_t, int64_t, bool);
++void exl3_rot_rows_cuda(const at::Tensor&, int64_t, const at::Tensor&, at::Tensor&, int64_t, int64_t);
+
+ static void check(const at::Tensor& x, at::ScalarType t, const char* name) {
+ TORCH_CHECK(x.is_cuda() && x.scalar_type() == t && x.is_contiguous(), name,
+@@ -52,6 +53,16 @@ void rot_in(const at::Tensor& x, int64_t x_stride, const at::Tensor& pick, const
+ exl3_rot_in_cuda(x, x_stride, pick, suh0, suh1, out0, out1, rows, K, slots);
+ }
+
++// Xh [rows, K] = rot_in's input rotation once a row, for a layer whose experts all share one suh for gate and up.
++void rot_rows(const at::Tensor& x, int64_t x_stride, const at::Tensor& suh, at::Tensor out, int64_t rows, int64_t K) {
++ TORCH_CHECK(x.is_cuda() && x.scalar_type() == at::kBFloat16, "x: bf16 CUDA");
++ check(suh, at::kHalf, "suh");
++ check(out, at::kHalf, "out");
++ TORCH_CHECK(K % 128 == 0 && suh.numel() == K && out.numel() >= rows * K, "rot_rows: shapes");
++ c10::cuda::CUDAGuard guard(x.device());
++ exl3_rot_rows_cuda(x, x_stride, suh, out, rows, K);
++}
++
+ void gateup_epilogue(const at::Tensor& Z, const at::Tensor& pick, const at::Tensor& svh_g, const at::Tensor& svh_u,
+ const at::Tensor& suh_d, at::Tensor xd, int64_t rows, int64_t P, int64_t N, int64_t SK,
+ int64_t slots, double limit) {
+@@ -81,20 +92,23 @@ void prompt(const at::Tensor& Xg, const at::Tensor& Xu, const at::Tensor& Tg, co
+ const at::Tensor& Td, const at::Tensor& items, const at::Tensor& counts, const at::Tensor& members,
+ const at::Tensor& svh_g, const at::Tensor& svh_u, const at::Tensor& suh_d, const at::Tensor& svh_d,
+ at::Tensor xd, at::Tensor y, int64_t D, int64_t N, int64_t E, int64_t max_items, double limit,
+- int64_t pass) {
++ int64_t pass, int64_t slots, bool shx) {
+ const at::cuda::CUDAGuard guard(Xg.device());
+ for (auto* t : {&Xg, &Xu, &svh_g, &svh_u, &suh_d, &svh_d}) check(*t, at::kHalf, "prompt: fp16 input");
+ for (auto* t : {&Tg, &Tu, &Td, &items, &counts, &members}) check(*t, at::kInt, "prompt: int32 input");
+ check(xd, at::kHalf, "prompt: xd");
+ check(y, at::kFloat, "prompt: y");
++ TORCH_CHECK(!shx || Xg.data_ptr() == Xu.data_ptr(), "prompt: shared rows take one Xh for gate and up");
++ TORCH_CHECK(slots > 0, "prompt: slots");
+ exl3_prompt_cuda(Xg, Xu, Tg, Tu, Td, items, counts, members, svh_g, svh_u, suh_d, svh_d, xd, y, D, N, E,
+- max_items, limit, pass);
++ max_items, limit, pass, slots, shx);
+ }
+
+ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
+ m.def("grouped", &grouped);
+ m.def("prompt", &prompt);
+ m.def("rot_in", &rot_in);
++ m.def("rot_rows", &rot_rows);
+ m.def("gateup_epilogue", &gateup_epilogue);
+ m.def("down_epilogue", &down_epilogue);
+ }
+diff --git tensorfold/families/glm5_next/cuda/exl3.cu tensorfold/families/glm5_next/cuda/exl3.cu
+index 7a27c46..46cb22d 100644
+--- tensorfold/families/glm5_next/cuda/exl3.cu
++++ tensorfold/families/glm5_next/cuda/exl3.cu
+@@ -210,15 +210,25 @@ __device__ __forceinline__ void fwht128(float (&v)[4], int lane) {
+
+ // Program (member row, 128-block of K, matrix): Xh[mat][row][block] = fp16((x[row] * suh[mat][e]) @ H) for the
+ // gate and up projections of every routed slot (row, slot) with slot < slots - 1 (the last slot is the shared
+-// expert). One warp per program.
++// expert). One warp per program. ROWS (prompt chunks of a layer whose experts all share one suh for gate and up):
++// program (row, block) writes Xh[row][block] from suh0 = that vector, the same arithmetic as every pair's input of
++// that row, so each pair's fp16 input has the same bits, computed once a row instead of 2 x top_k times.
++template <bool ROWS>
+ __global__ void rot_in_kernel(const __nv_bfloat16* __restrict__ x, int x_stride, const int* __restrict__ pick,
+ const half* __restrict__ suh0, const half* __restrict__ suh1, half* __restrict__ out0,
+ half* __restrict__ out1, int K, int slots) {
+ const int p = blockIdx.x, blk = blockIdx.y, mat = blockIdx.z;
+- const int row = p / slots, slot = p % slots;
+- if (slot == slots - 1) return;
++ int row, e;
++ if (ROWS) {
++ row = p;
++ e = 0;
++ } else {
++ row = p / slots;
++ const int slot = p % slots;
++ if (slot == slots - 1) return;
++ e = pick[row * slots + slot];
++ }
+ const int lane = threadIdx.x;
+- const int e = pick[row * slots + slot];
+ const half* suh = (mat ? suh1 : suh0) + (size_t)e * K + blk * 128 + 4 * lane;
+ const __nv_bfloat16* xr = x + (size_t)row * x_stride + blk * 128 + 4 * lane;
+ float v[4];
+@@ -327,13 +337,15 @@ __device__ __forceinline__ void ldsm_x4(uint32_t (&r)[4], const void* p) {
+ // pass of PM members with NW warps: each warp holds MT = 16 / NW m tiles for all PM members (PM / 8 n blocks), so a
+ // decoded tile feeds PM / 8 mma. PM 64 / 8 warps (two blocks an SM) or PM 128 / 16 warps (one): the same per-element
+ // chains, so the same bits. Every stage brings the members' next PBK k values and the 16 tiles' trellis words into
+-// shared memory (cp.async, PSTAGES deep).
++// shared memory (cp.async, PSTAGES deep). SHX (gate/up of a layer whose experts share one suh for both): gate and up
++// read the same member rows (X0 = X1 = the per-row Xh, the members' rows from xrows), so a stage holds them once.
+ constexpr int PWORDS = 16 * PKT * 32; // a stage's trellis words (16 m tiles x PKT k tiles x 32)
+
+-template <int MATS, int PM, int NW>
++template <int MATS, int PM, int NW, bool SHX = false>
+ struct PromptCfg {
+ static constexpr int MT = 16 / NW, NB = PM / 8, T = NW * 32;
+- static constexpr size_t STAGE_HALVES = (size_t)MATS * PM * PXS + 2 * PWORDS;
++ static constexpr int XM = SHX ? 1 : MATS; // member-row copies a stage holds
++ static constexpr size_t STAGE_HALVES = (size_t)XM * PM * PXS + 2 * PWORDS;
+ };
+
+ // Which (matrix, m tile) warp-tile q (0..15) of block cb is.
+@@ -343,12 +355,12 @@ __device__ __forceinline__ void prompt_tile(int q, int cb, int& mat, int& nt) {
+ nt = MATS == 2 ? cb * 8 + (q & 7) : cb * 16 + q;
+ }
+
+-template <int MATS, int PM, int NW>
++template <int MATS, int PM, int NW, bool SHX = false>
+ __device__ __forceinline__ void prompt_mainloop(const half* __restrict__ X0, const half* __restrict__ X1,
+ const uint32_t* __restrict__ T0, const uint32_t* __restrict__ T1,
+ const int* rows_sh, int cnt, int e, int K, int NTILES, int cb,
+ half* stage, float (&acc)[16 / NW][PM / 8][4]) {
+- using C = PromptCfg<MATS, PM, NW>;
++ using C = PromptCfg<MATS, PM, NW, SHX>;
+ const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31;
+ int mat, nt_unused;
+ prompt_tile<MATS>(warp * C::MT, cb, mat, nt_unused);
+@@ -365,14 +377,14 @@ __device__ __forceinline__ void prompt_mainloop(const half* __restrict__ X0, con
+ auto load = [&](int chunk) {
+ half* dst = stage + (size_t)(chunk % PSTAGES) * C::STAGE_HALVES;
+ const int k0 = chunk * PBK;
+- for (int idx = threadIdx.x; idx < MATS * PM * (PBK / 8); idx += C::T) {
++ for (int idx = threadIdx.x; idx < C::XM * PM * (PBK / 8); idx += C::T) {
+ const int m = idx / (PM * (PBK / 8)), rem = idx % (PM * (PBK / 8)), i = rem / (PBK / 8),
+ j = rem % (PBK / 8);
+ const int r = rows_sh[i];
+ const half* src = (m ? X1 : X0) + (size_t)(r < 0 ? 0 : r) * K + k0 + j * 8;
+ cp_async16(dst + ((size_t)m * PM + i) * PXS + j * 8, src, r >= 0);
+ }
+- uint32_t* wdst = reinterpret_cast<uint32_t*>(dst + (size_t)MATS * PM * PXS);
++ uint32_t* wdst = reinterpret_cast<uint32_t*>(dst + (size_t)C::XM * PM * PXS);
+ for (int idx = threadIdx.x; idx < 16 * PKT * 8; idx += C::T) { // 16 B pieces of 128-B tile words
+ const int q = idx / (PKT * 8), kk = (idx / 8) % PKT, part = idx % 8;
+ int wm, nt;
+@@ -392,8 +404,8 @@ __device__ __forceinline__ void prompt_mainloop(const half* __restrict__ X0, con
+ if (c + PSTAGES - 1 < chunks) load(c + PSTAGES - 1);
+ cp_async_commit();
+ const half* base = stage + (size_t)(c % PSTAGES) * C::STAGE_HALVES;
+- const half* xs = base + (size_t)mat * PM * PXS;
+- const uint32_t* ws = reinterpret_cast<const uint32_t*>(base + (size_t)MATS * PM * PXS);
++ const half* xs = base + (size_t)(SHX ? 0 : mat) * PM * PXS;
++ const uint32_t* ws = reinterpret_cast<const uint32_t*>(base + (size_t)C::XM * PM * PXS);
+ #pragma unroll
+ for (int kk = 0; kk < PKT; ++kk) {
+ uint32_t a[C::MT][4];
+@@ -442,34 +454,41 @@ __device__ __forceinline__ void prompt_spill(float* E, int ES, int col0, const f
+ }
+
+ constexpr int GU_ES = 128 + 4, DN_ES = 256 + 4;
+-template <int PM>
++template <int PM, int XM = 2>
+ constexpr size_t prompt_smem() {
+- // max of: gate/up stages, down stages, gate/up epilogue half (2 x PM/2 x GU_ES), down half (PM/2 x DN_ES)
+- const size_t gu = (size_t)PSTAGES * (2 * PM * PXS + 2 * PWORDS) * 2;
++ // max of: gate/up stages (XM copies of the member rows), down stages, gate/up epilogue half (2 x PM/2 x GU_ES),
++ // down half (PM/2 x DN_ES)
++ const size_t gu = (size_t)PSTAGES * (XM * PM * PXS + 2 * PWORDS) * 2;
+ const size_t ep = (size_t)2 * (PM / 2) * GU_ES * 4;
+ const size_t dn = (size_t)(PM / 2) * DN_ES * 4;
+ return gu > ep ? (gu > dn ? gu : dn) : (ep > dn ? ep : dn);
+ }
+
+-template <int PM, int NW>
++// SHX: Xg = Xu = Xh [rows, K], one row a token (pair p reads row p / slots); otherwise Xg, Xu [pairs, K].
++template <int PM, int NW, bool SHX>
+ __global__ void __launch_bounds__(NW * 32, 16 / NW) prompt_gateup_kernel(
+ const half* __restrict__ Xg, const half* __restrict__ Xu, const uint32_t* __restrict__ Tg,
+ const uint32_t* __restrict__ Tu, const int* __restrict__ items, const int* __restrict__ counts,
+ const int* __restrict__ members, const half* __restrict__ svh_g, const half* __restrict__ svh_u,
+- const half* __restrict__ suh_d, half* __restrict__ xd, int K, int N, int E, float limit) {
++ const half* __restrict__ suh_d, half* __restrict__ xd, int K, int N, int E, float limit, int slots) {
+ constexpr int MT = 16 / NW, PH = PM / 2;
+ extern __shared__ __align__(16) unsigned char smem_raw[];
+ __shared__ int rows_sh[PM];
++ __shared__ int xrows_sh[SHX ? PM : 1]; // SHX: the members' token rows
+ const int cb = blockIdx.x, item = blockIdx.y;
+ if (item >= counts[0]) return;
+ const int e = items[3 * item], first = items[3 * item + 1], cnt = items[3 * item + 2];
+ if (e >= E) return; // the shared expert
+- if (threadIdx.x < PM) rows_sh[threadIdx.x] = (int)threadIdx.x < cnt ? members[first + threadIdx.x] : -1;
++ if (threadIdx.x < PM) {
++ const int p = (int)threadIdx.x < cnt ? members[first + threadIdx.x] : -1;
++ rows_sh[threadIdx.x] = p;
++ if (SHX) xrows_sh[threadIdx.x] = p < 0 ? -1 : p / slots;
++ }
+ __syncthreads();
+ const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31;
+ float acc[MT][PM / 8][4];
+- prompt_mainloop<2, PM, NW>(Xg, Xu, Tg, Tu, rows_sh, cnt, e, K, N >> 4, cb, reinterpret_cast<half*>(smem_raw),
+- acc);
++ prompt_mainloop<2, PM, NW, SHX>(Xg, Xu, Tg, Tu, SHX ? xrows_sh : rows_sh, cnt, e, K, N >> 4, cb,
++ reinterpret_cast<half*>(smem_raw), acc);
+ float* Eg = reinterpret_cast<float*>(smem_raw);
+ int mat, nt;
+ prompt_tile<2>(warp * MT, cb, mat, nt);
+@@ -586,13 +605,24 @@ void exl3_rot_in_cuda(const at::Tensor& x, int64_t x_stride, const at::Tensor& p
+ const at::Tensor& suh1, at::Tensor& out0, at::Tensor& out1, int64_t rows, int64_t K,
+ int64_t slots) {
+ dim3 grid((unsigned)(rows * slots), (unsigned)(K / 128), 2);
+- rot_in_kernel<<<grid, 32, 0, at::cuda::getCurrentCUDAStream()>>>(
++ rot_in_kernel<false><<<grid, 32, 0, at::cuda::getCurrentCUDAStream()>>>(
+ reinterpret_cast<const __nv_bfloat16*>(x.data_ptr()), (int)x_stride, pick.data_ptr<int>(),
+ reinterpret_cast<const half*>(suh0.data_ptr()), reinterpret_cast<const half*>(suh1.data_ptr()),
+ reinterpret_cast<half*>(out0.data_ptr()), reinterpret_cast<half*>(out1.data_ptr()), (int)K, (int)slots);
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
+ }
+
++// Xh [rows, K] fp16 = fp16((x[row] * suh) @ H) block by block, suh [K] fp16: rot_in's arithmetic once a row.
++void exl3_rot_rows_cuda(const at::Tensor& x, int64_t x_stride, const at::Tensor& suh, at::Tensor& out, int64_t rows,
++ int64_t K) {
++ dim3 grid((unsigned)rows, (unsigned)(K / 128), 1);
++ auto s = reinterpret_cast<const half*>(suh.data_ptr());
++ auto o = reinterpret_cast<half*>(out.data_ptr());
++ rot_in_kernel<true><<<grid, 32, 0, at::cuda::getCurrentCUDAStream()>>>(
++ reinterpret_cast<const __nv_bfloat16*>(x.data_ptr()), (int)x_stride, nullptr, s, s, o, o, (int)K, 1);
++ C10_CUDA_KERNEL_LAUNCH_CHECK();
++}
++
+ void exl3_gateup_epilogue_cuda(const at::Tensor& Z, const at::Tensor& pick, const at::Tensor& svh_g,
+ const at::Tensor& svh_u, const at::Tensor& suh_d, at::Tensor& xd, int64_t rows,
+ int64_t P, int64_t N, int64_t SK, int64_t slots, double limit) {
+@@ -620,10 +650,13 @@ static void prompt_launch(const at::Tensor& Xg, const at::Tensor& Xu, const at::
+ const at::Tensor& Td, const at::Tensor& items, const at::Tensor& counts,
+ const at::Tensor& members, const at::Tensor& svh_g, const at::Tensor& svh_u,
+ const at::Tensor& suh_d, const at::Tensor& svh_d, at::Tensor& xd, at::Tensor& y, int64_t D,
+- int64_t N, int64_t E, int64_t max_items, double limit) {
+- constexpr size_t SMEM = prompt_smem<PM>();
++ int64_t N, int64_t E, int64_t max_items, double limit, int64_t slots, bool shx) {
++ constexpr size_t SMEM = prompt_smem<PM>(), SMEM_SHX = prompt_smem<PM, 1>();
+ static bool once = [] {
+- cudaFuncSetAttribute(prompt_gateup_kernel<PM, NW>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int)SMEM);
++ cudaFuncSetAttribute(prompt_gateup_kernel<PM, NW, false>, cudaFuncAttributeMaxDynamicSharedMemorySize,
++ (int)SMEM);
++ cudaFuncSetAttribute(prompt_gateup_kernel<PM, NW, true>, cudaFuncAttributeMaxDynamicSharedMemorySize,
++ (int)SMEM_SHX);
+ cudaFuncSetAttribute(prompt_down_kernel<PM, NW>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int)SMEM);
+ return true;
+ }();
+@@ -631,9 +664,17 @@ static void prompt_launch(const at::Tensor& Xg, const at::Tensor& Xu, const at::
+ auto stream = at::cuda::getCurrentCUDAStream();
+ auto h = [](const at::Tensor& t) { return reinterpret_cast<const half*>(t.data_ptr()); };
+ auto w = [](const at::Tensor& t) { return reinterpret_cast<const uint32_t*>(t.data_ptr()); };
+- prompt_gateup_kernel<PM, NW><<<dim3((unsigned)(N / 128), (unsigned)max_items), NW * 32, SMEM, stream>>>(
+- h(Xg), h(Xu), w(Tg), w(Tu), items.data_ptr<int>(), counts.data_ptr<int>(), members.data_ptr<int>(),
+- h(svh_g), h(svh_u), h(suh_d), reinterpret_cast<half*>(xd.data_ptr()), (int)D, (int)N, (int)E, (float)limit);
++ const dim3 gu_grid((unsigned)(N / 128), (unsigned)max_items);
++ if (shx)
++ prompt_gateup_kernel<PM, NW, true><<<gu_grid, NW * 32, SMEM_SHX, stream>>>(
++ h(Xg), h(Xu), w(Tg), w(Tu), items.data_ptr<int>(), counts.data_ptr<int>(), members.data_ptr<int>(),
++ h(svh_g), h(svh_u), h(suh_d), reinterpret_cast<half*>(xd.data_ptr()), (int)D, (int)N, (int)E,
++ (float)limit, (int)slots);
++ else
++ prompt_gateup_kernel<PM, NW, false><<<gu_grid, NW * 32, SMEM, stream>>>(
++ h(Xg), h(Xu), w(Tg), w(Tu), items.data_ptr<int>(), counts.data_ptr<int>(), members.data_ptr<int>(),
++ h(svh_g), h(svh_u), h(suh_d), reinterpret_cast<half*>(xd.data_ptr()), (int)D, (int)N, (int)E,
++ (float)limit, (int)slots);
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
+ prompt_down_kernel<PM, NW><<<dim3((unsigned)(D / 256), (unsigned)max_items), NW * 32, SMEM, stream>>>(
+ reinterpret_cast<const half*>(xd.data_ptr()), w(Td), items.data_ptr<int>(), counts.data_ptr<int>(),
+@@ -645,14 +686,14 @@ void exl3_prompt_cuda(const at::Tensor& Xg, const at::Tensor& Xu, const at::Tens
+ const at::Tensor& Td, const at::Tensor& items, const at::Tensor& counts,
+ const at::Tensor& members, const at::Tensor& svh_g, const at::Tensor& svh_u,
+ const at::Tensor& suh_d, const at::Tensor& svh_d, at::Tensor& xd, at::Tensor& y, int64_t D,
+- int64_t N, int64_t E, int64_t max_items, double limit, int64_t pass) {
++ int64_t N, int64_t E, int64_t max_items, double limit, int64_t pass, int64_t slots, bool shx) {
+ TORCH_CHECK(D % 256 == 0 && N % 128 == 0 && D % PBK == 0 && N % PBK == 0, "prompt experts: shapes");
+ if (pass == 128)
+ prompt_launch<128, 16>(Xg, Xu, Tg, Tu, Td, items, counts, members, svh_g, svh_u, suh_d, svh_d, xd, y, D, N,
+- E, max_items, limit);
++ E, max_items, limit, slots, shx);
+ else if (pass == 64)
+ prompt_launch<64, 8>(Xg, Xu, Tg, Tu, Td, items, counts, members, svh_g, svh_u, suh_d, svh_d, xd, y, D, N, E,
+- max_items, limit);
++ max_items, limit, slots, shx);
+ else
+ TORCH_CHECK(false, "prompt experts: passes of 64 or 128 members");
+ }
+diff --git tensorfold/families/glm5_next/cuda/exl3_mm.py tensorfold/families/glm5_next/cuda/exl3_mm.py
+index 71cd600..5e21f90 100644
+--- tensorfold/families/glm5_next/cuda/exl3_mm.py
++++ tensorfold/families/glm5_next/cuda/exl3_mm.py
+@@ -2,7 +2,7 @@
+
+ from __future__ import annotations
+
+-from dataclasses import dataclass
++from dataclasses import dataclass, field
+ from functools import lru_cache
+ from pathlib import Path
+
+@@ -43,7 +43,7 @@ def _ext():
+ from tensorfold.cuda.build import load
+
+ here = Path(__file__).parent
+- return load(name="tensorfold_glm_exl3_v14", sources=[str(here / "exl3.cpp"), str(here / "exl3.cu")],
++ return load(name="tensorfold_glm_exl3_v15", sources=[str(here / "exl3.cpp"), str(here / "exl3.cu")],
+ extra_cuda_cflags=["-O3"], verbose=False)
+
+
+@@ -63,10 +63,29 @@ class Exl3Experts:
+ count: int
+ width: int # NI: this rank's share of the expert width
+ dims: int # D
++ # [D] fp16 when every expert's gate and up share one suh bitwise (found at construction; GLM-5.3-Flash's
++ # EXL3 checkpoint, every MoE layer): prompt chunks then rotate each row's input once (``rot_rows``)
++ shared_suh: torch.Tensor | None = field(default=None, init=False)
++
++ def __post_init__(self) -> None:
++ self.shared_suh = shared_suh(self.suh_g, self.suh_u)
+
+ def nbytes(self) -> int:
++ extra = () if self.shared_suh is None else (self.shared_suh,)
+ return sum(t.numel() * t.element_size() for t in (self.gt, self.ut, self.dt, self.suh_g, self.suh_u,
+- self.svh_g, self.svh_u, self.suh_d, self.svh_d))
++ self.svh_g, self.svh_u, self.suh_d, self.svh_d, *extra))
++
++
++def shared_suh(suh_g: torch.Tensor, suh_u: torch.Tensor) -> torch.Tensor | None:
++ """The one input scale vector [D] if every expert's gate and up suh equal it bit for bit (-0 is not +0), else
++ None. Every pair's rotated input x_row * suh @ H is then the row's alone, whatever expert or matrix it feeds."""
++
++ if suh_g.dim() != 2 or suh_g.shape != suh_u.shape or suh_g.dtype != torch.float16 or suh_u.dtype != suh_g.dtype:
++ return None
++ g, u = suh_g.view(torch.int16), suh_u.view(torch.int16)
++ if not (bool(torch.equal(g, g[:1].expand_as(g))) and bool(torch.equal(u, g))):
++ return None
++ return suh_g[0].clone().contiguous()
+
+
+ def words(trellis: torch.Tensor) -> torch.Tensor:
+@@ -96,6 +115,14 @@ def prompt_kernels() -> bool:
+ return os.environ.get("TF_GLM_EXL3_PROMPT", "1") != "0"
+
+
++def row_rotation() -> bool:
++ """TF_GLM_EXL3_ROWROT (default on): prompt chunks of layers whose experts share one gate/up suh rotate each row's
++ input once and load it once for gate and up (the same fp16 inputs, so the same bits); 0: per pair, as decode."""
++ import os
++
++ return os.environ.get("TF_GLM_EXL3_ROWROT", "1") != "0"
++
++
+ class Scratch:
+ """Per-window buffers for up to ``rows`` rows of ``slots`` slots (the last slot is the shared expert's); a
+ prompt window's (``prompt``) kernels keep no split partials."""
+@@ -118,11 +145,17 @@ def routed(x: torch.Tensor, pick: torch.Tensor, plan: grouped.Plan, ex: Exl3Expe
+ slots, P = s.slots, s.rows * s.slots
+ D, NI = ex.dims, ex.width
+ if plan.tile in (64, 128): # a prompt window: the Y^T kernels, an item a pass
+- ext.rot_in(x, x.stride(0), pick, ex.suh_g, ex.suh_u, s.xg, s.xu, R, D, slots)
+- ext.prompt(s.xg, s.xu, ex.gt, ex.ut, ex.dt, plan.items, plan.counts, plan.members, ex.svh_g, ex.svh_u,
++ shx = ex.shared_suh is not None and row_rotation()
++ if shx: # one rotated input a row, read by all its pairs' gate and up
++ ext.rot_rows(x, x.stride(0), ex.shared_suh, s.xg, R, D)
++ xg = xu = s.xg
++ else:
++ ext.rot_in(x, x.stride(0), pick, ex.suh_g, ex.suh_u, s.xg, s.xu, R, D, slots)
++ xg, xu = s.xg, s.xu
++ ext.prompt(xg, xu, ex.gt, ex.ut, ex.dt, plan.items, plan.counts, plan.members, ex.svh_g, ex.svh_u,
+ ex.suh_d, ex.svh_d, s.xd, y, D, NI, ex.count, grouped.max_items(R * slots, plan.experts,
+ plan.tile), float(limit),
+- plan.tile)
++ plan.tile, slots, shx)
+ return
+ 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
+--- 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
+ return out_proj(w, b, o, a.o, None if b.prefill else qmm.group_sums(o, b.xs_ao[:R]), R)
+
+
++def dense_rows(c, R: int, host_pos: int | None) -> int:
++ """Rows of a window from ``host_pos`` that keep dense attention: those before the first position select_tokens
++ gives a sparse count (sparse_attention overwrites every row from there). All R when the position is not known
++ on the host or the config's dense limit is not the selection's."""
++
++ if host_pos is None or c.dense_limit != sparse.SPARSE_FROM:
++ return R
++ 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
+ ol = s.ol[:R]
+ 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.
++ # Rows past the dense limit are recomputed sparsely below, so the dense pass needs only the chunks up to it
++ # and only the rows before it (a row's dense bits do not depend on the rows after it: latent.attention).
++ 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))
+ if sparse_rows:
+ with prof.timed("dsa: select tokens"):
+ mm(b, b.qr[:R], ix.qb, b.xs_qr[:R], b.qi[:R])
+ tokens, counts = sparse.select_tokens(b.qi[:R], b.ikr[:R, c.index_dim:], pk, host_pos, R,
+ pk.shape[0] - 2, pos_dev, bucket=sparse_np)
+ with prof.timed("dsa: sparse attention"):
+- latent.sparse_attention(qa, lc, tokens, counts, ol, scale)
++ if b.prefill and latent.SPARSE_ONEPASS: # prompt rows: one pass a row, no partials (their own bits)
++ latent.sparse_onepass(qa, lc, tokens, counts, ol, scale)
++ else:
++ 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)
+ 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:
+ 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"):
+- b.ey[:R, c.top_k].copy_(b.sy[:R])
+- glue.combine(b.ey[:R], b.wts[:R], b.part[:R])
++ if b.prefill: # the shared row read from sy where it is (the copy's bits, one pass less)
++ glue.combine_shared(b.ey[:R], b.sy[:R], b.wts[:R], b.part[:R])
++ else:
++ b.ey[:R, c.top_k].copy_(b.sy[:R])
++ glue.combine(b.ey[:R], b.wts[:R], b.part[:R])
+ with prof.timed("moe: all-gather"):
+ return gather(w, b, R)
+ with prof.timed("moe: gate/up"):
+diff --git tensorfold/families/glm5_next/cuda/glue.py tensorfold/families/glm5_next/cuda/glue.py
+index 84f0dbe..dbde3f1 100644
+--- tensorfold/families/glm5_next/cuda/glue.py
++++ tensorfold/families/glm5_next/cuda/glue.py
+@@ -439,3 +439,28 @@ def combine(y: torch.Tensor, wts: torch.Tensor, out: torch.Tensor) -> None:
+ rows, d = out.shape
+ block = min(1024, d)
+ _combine[(rows, d // block)](y, wts, out, D=d, SLOTS=wts.shape[1], BLOCK=block, num_warps=4)
++
++
++def _combine_sy(Y, SY, WTS, OUT, D: tl.constexpr, SLOTS: tl.constexpr, BLOCK: tl.constexpr):
++ """``_combine`` with the shared expert's row read from SY [R, D] fp32 instead of Y's last slot: the same terms
++ (w_k y_k, the shared one times its weight 1) added in the same slot order, so the same bits."""
++
++ r = tl.program_id(0)
++ c = tl.program_id(1)
++ d = c * BLOCK + tl.arange(0, BLOCK)
++ acc = tl.zeros((BLOCK,), dtype=tl.float32)
++ for k in tl.static_range(SLOTS - 1):
++ acc = acc + tl.load(Y + (r * SLOTS + k) * D + d).to(tl.float32) * tl.load(WTS + r * SLOTS + k)
++ acc = acc + tl.load(SY + r * D + d).to(tl.float32) * tl.load(WTS + r * SLOTS + SLOTS - 1)
++ tl.store(OUT + r * D + d, acc)
++
++
++def combine_shared(y: torch.Tensor, sy: torch.Tensor, wts: torch.Tensor, out: torch.Tensor) -> None:
++ """combine(y with its last slot replaced by sy): y [R, slots, D] (the last slot not read), sy [R, D] fp32."""
++
++ rows, d = out.shape
++ if y.dtype != torch.float32 or sy.dtype != torch.float32 or not (y.is_contiguous() and sy.is_contiguous()):
++ raise ValueError("combine_shared: contiguous fp32 expert rows")
++ 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
+--- 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):
+ return next_m, l, o
+
+
++def _tile_v(q, kv, vv, m, l, o, valid, SCALE: tl.constexpr):
++ """_tile with the values a column slice vv [KT, VB] of the keys kv [KT, 512]."""
++ scores = tl.dot(q, tl.trans(kv)).to(tl.float32) * SCALE
++ scores = tl.where(valid[None, :], scores, float("-inf"))
++ tile_m = tl.max(scores, 1)
++ active = tile_m != float("-inf")
++ next_m = tl.where(active, tl.maximum(m, tile_m), m)
++ alpha = tl.where(active, tl.where(m == float("-inf"), 0.0, tl.exp(m - next_m)), 1.0)
++ p = tl.where(valid[None, :] & active[:, None], tl.exp(scores - next_m[:, None]), 0.0)
++ o = o * alpha[:, None] + tl.dot(p.to(tl.bfloat16), vv)
++ l = l * alpha + tl.sum(p, 1)
++ return next_m, l, o
++
++
+ @triton.jit
+ def _dense_chunks(QA, LC, POS, PO, PM, PL, R, H: tl.constexpr, LW: tl.constexpr, CH: tl.constexpr,
+ SCALE: tl.constexpr, HBT: tl.constexpr, KTT: tl.constexpr):
+@@ -330,6 +345,78 @@ def _sparse_chunks(QA, LC, TOK, CNT, PO, PM, PL, R, W: tl.constexpr, H: tl.const
+ tl.store(PL + base, l, mask=hok)
+
+
++def _onepass_ids(row, t0, n, KTT: tl.constexpr):
++ """Tile t0's token ids (0 past n, where their rows are masked)."""
++ idx = t0 + tl.arange(0, KTT)
++ return tl.load(row + idx, mask=idx < n, other=0).to(tl.int64)
++
++
++def _onepass_rows(LC, tok, t0, n, k, LW: tl.constexpr, KTT: tl.constexpr):
++ """Tile t0's latent rows [KTT, LW]; rows past n are not read (zeros)."""
++ ok = t0 + tl.arange(0, KTT) < n
++ return tl.load(LC + tok[:, None] * LW + k[None, :], mask=ok[:, None], other=0)
++
++
++def _sparse_onepass(QA, LC, TOK, CNT, OUT, W: tl.constexpr, H: tl.constexpr, LW: tl.constexpr, SCALE: tl.constexpr,
++ HBT: tl.constexpr, KTT: tl.constexpr, SPLIT: tl.constexpr, STAGES: tl.constexpr,
++ PREFETCH: tl.constexpr):
++ """Prompt rows, program (row, head group, latent slice): HBT heads of row r over all its selected tokens in one
++ online softmax, KTT-key tiles in list order (_tile's math), straight to OUT[r, h] bf16: no partials, no merge.
++ PREFETCH: tile t + 1's gather is issued into registers before tile t's dots (a load blocks only at first use),
++ with Triton's pipeliner off; else the loop is left to Triton's pipeliner at STAGES. SPLIT > 1: the program keeps
++ LW / SPLIT output columns and recomputes the full-width scores. PREFETCH never changes the arithmetic; the tile
++ (HBT, KTT, SPLIT) is fixed (ONEPASS_TILE), so a row's bits depend on its q, its token list and the cache only,
++ never on the other rows or R. Rows with CNT 0 are left alone."""
++ r = tl.program_id(0)
++ hb = tl.program_id(1)
++ vs = tl.program_id(2)
++ n = tl.load(CNT + r)
++ if n == 0:
++ return
++ VB: tl.constexpr = LW // SPLIT
++ hh = hb * HBT + tl.arange(0, HBT)
++ hok = hh < H
++ k = tl.arange(0, LW)
++ v = vs * VB + tl.arange(0, VB)
++ q = tl.load(QA + (r * H + hh[:, None]) * LW + k[None, :], mask=hok[:, None], other=0).to(tl.bfloat16)
++ m = tl.full((HBT,), float("-inf"), tl.float32)
++ l = tl.zeros((HBT,), tl.float32)
++ o = tl.zeros((HBT, VB), tl.float32)
++ row = TOK + r * W
++ if PREFETCH:
++ # ids run two tiles ahead and rows one: tile t + 1's gather is issued (its ids already there) before tile t's
++ # dots, so neither load's latency stalls the in-order warp in front of the tensor-core work
++ tok = _onepass_ids(row, 0, n, KTT)
++ kv = _onepass_rows(LC, tok, 0, n, k, LW, KTT)
++ tok_next = _onepass_ids(row, KTT, n, KTT)
++ for t0 in range(0, n, KTT):
++ ok = t0 + tl.arange(0, KTT) < n
++ kv_next = _onepass_rows(LC, tok_next, t0 + KTT, n, k, LW, KTT)
++ tok_after = _onepass_ids(row, t0 + 2 * KTT, n, KTT)
++ if SPLIT == 1:
++ m, l, o = _tile(q, kv.to(tl.bfloat16), m, l, o, ok, SCALE)
++ else:
++ vv = tl.load(LC + tok[:, None] * LW + v[None, :], mask=ok[:, None], other=0).to(tl.bfloat16)
++ m, l, o = _tile_v(q, kv.to(tl.bfloat16), vv, m, l, o, ok, SCALE)
++ tok = tok_next
++ kv = kv_next
++ tok_next = tok_after
++ else:
++ for t0 in tl.range(0, n, KTT, num_stages=STAGES):
++ ok = t0 + tl.arange(0, KTT) < n
++ tok = _onepass_ids(row, t0, n, KTT)
++ kv = _onepass_rows(LC, tok, t0, n, k, LW, KTT)
++ if SPLIT == 1:
++ m, l, o = _tile(q, kv.to(tl.bfloat16), m, l, o, ok, SCALE)
++ else:
++ vv = tl.load(LC + tok[:, None] * LW + v[None, :], mask=ok[:, None], other=0).to(tl.bfloat16)
++ m, l, o = _tile_v(q, kv.to(tl.bfloat16), vv, m, l, o, ok, SCALE)
++ tl.store(OUT + (r * H + hh[:, None]) * LW + v[None, :], (o / l[:, None]).to(tl.bfloat16), mask=hok[:, None])
++
++
+ @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:
+
+
+ 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:
++ """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:
+ raise ValueError(f"latent attention: {R} rows, {nch} chunks, width {LW} past the scratch's "
+ f"{s.rows}, {s.nch}, {s.lw}")
+ 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):
++ 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
+ _merge[(R, H)](po, pm, pl, out, counts, R, H=H, LW=LW, NCH=nch, SPARSE=True, num_warps=4)
+
+
++# prompt chunks' sparse attention in one pass (TF_GLM_SPARSE_ONEPASS=0: the chunk programs and their merge). Fixed
++# tile (heads, keys, latent slices) and pipeline depth, so a row's bits never depend on the chunk it sits in.
++SPARSE_ONEPASS = __import__("os").environ.get("TF_GLM_SPARSE_ONEPASS", "1") != "0"
++ONEPASS_TILE = (32, 32, 1) # heads per program (a rank's 32), keys per tile, latent slices: sets the bits
++ONEPASS_LAUNCH = (8, 1, True) # warps, Triton pipeline stages, register prefetch of the next tile: speed only
++
++
++def sparse_onepass(qa: torch.Tensor, cache: torch.Tensor, tokens: torch.Tensor, counts: torch.Tensor,
++ out: torch.Tensor, scale: float, *, tile: tuple | None = None, launch: tuple | None = None) -> None:
++ """sparse_attention for a prompt chunk's rows: one program a row (and head group) walks every selected token in
++ one online softmax and writes out[r] directly, no fp32 partials; rows with counts 0 are left alone. Other bits
++ than sparse_attention's (one chain instead of merged 512-token chunks), the same for any chunking of the rows.
++ ``tile`` / ``launch`` override ONEPASS_TILE / ONEPASS_LAUNCH (benchmarks)."""
++ R, H, LW = qa.shape
++ if not (qa.is_contiguous() and out.is_contiguous() and tokens.is_contiguous() and cache.stride() == (LW, 1)):
++ raise ValueError("sparse_onepass: expected contiguous queries, output and token lists, cache rows of the width")
++ if R == 0:
++ return
++ hbt, kt, split = tile or ONEPASS_TILE
++ warps, stages, prefetch = launch or ONEPASS_LAUNCH
++ hbt = max(16, min(hbt, triton.next_power_of_2(H))) # tensor-core tiles need 16 rows
++ _sparse_onepass[(R, triton.cdiv(H, hbt), split)](qa, cache, tokens, counts, out, W=tokens.shape[1], H=H, LW=LW,
++ SCALE=scale, HBT=hbt, KTT=kt, SPLIT=split, STAGES=stages,
++ PREFETCH=bool(prefetch), num_warps=warps,
++ num_stages=1 if prefetch else stages)
++
++
+ 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
+--- tensorfold/families/glm5_next/cuda/sparse.py
++++ tensorfold/families/glm5_next/cuda/sparse.py
+@@ -9,6 +9,8 @@ import triton.language as tl
+ POOL = 4
+ 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
+
+
+ @triton.jit
+@@ -165,12 +167,55 @@ def pool_bucket(pos: int, R: int, np_max: int) -> int:
+ return min(np_max, max(1024, 1 << (visible - 1).bit_length()))
+
+
++PROMPT_ROWS = 64 # windows from this many rows (prompt chunks, eager) take the prompt selection below
++
++
++def pool_count(pos: int, R: int, np_max: int) -> int:
++ """Pools a prompt chunk scores: the visible ones rounded up to a multiple of 1,024 (at most ``pool_bucket``)."""
++ visible = (pos + R) // POOL + 1
++ return min(np_max, -(-visible // 1024) * 1024)
++
++
++def score_rows() -> int:
++ """TF_GLM_SCORE_RB: rows a prompt chunk's _scores program takes (1, 2, 4 or 8; each pool tile loaded once for
++ them, the same bits: row r's pool keys are masked to its own pools before the dot). At most 8: a block's key load
++ then stays within the pool cache's rows (capacity // 4 + 2)."""
++ import os
++
++ value = int(os.environ.get("TF_GLM_SCORE_RB", "4"))
++ if value not in (1, 2, 4, 8):
++ raise ValueError(f"TF_GLM_SCORE_RB is 1, 2, 4 or 8, not {value}")
++ return value
++
++
++def _tokens(POOLS, POS, TOK, CNT, W: tl.constexpr, K: tl.constexpr, PL: tl.constexpr, BLOCK: tl.constexpr):
++ """Program r: TOK[r] = the K pools' tokens ascending (pool * PL + j), then the incomplete last pool's visible
++ tokens (-1 past row r's position); CNT[r] = their count when the row has more than K complete pools, else 0."""
++ r = tl.program_id(0).to(tl.int64)
++ q = tl.load(POS).to(tl.int64) + r
++ npool = (q + 1) // PL
++ for c in tl.static_range(0, K * PL, BLOCK):
++ i = c + tl.arange(0, BLOCK)
++ p = tl.load(POOLS + r * K + i // PL)
++ tl.store(TOK + r * W + i, (p * PL + i % PL).to(tl.int32))
++ j = tl.arange(0, 4)
++ jok = j < PL - 1
++ tail = npool * PL + j
++ ok = jok & (tail <= q)
++ tl.store(TOK + r * W + K * PL + j, tl.where(ok, tail, -1).to(tl.int32), mask=jok)
++ n = K * PL + tl.sum(ok.to(tl.int64), 0)
++ tl.store(CNT + r, tl.where(npool > K, n, 0).to(tl.int32))
++
++
+ def select_tokens(qi: torch.Tensor, wts: torch.Tensor, pk: torch.Tensor, pos: int | None, R: int, np_max: int,
+ pos_dev: torch.Tensor, *, bucket: int | None = None) -> tuple[torch.Tensor, torch.Tensor]:
+ """Each row's attended tokens [R, 2051] ascending (-1 padded) and their count past the dense limit; ``bucket`` fixes the pool count for graphs."""
+
+ if qi.stride(0) != qi.shape[1] or wts.stride(1) != 1:
+ raise ValueError("select_tokens: index queries must be contiguous rows, weights unit-stride columns")
++ if bucket is None and pos is not None and R >= PROMPT_ROWS:
++ 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
+ return tokens, counts
+
+
++def _select_prompt(qi: torch.Tensor, wts: torch.Tensor, pk: torch.Tensor, pos: int, R: int, np_max: int,
++ pos_dev: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
++ """select_tokens for a prompt chunk, with select_tokens' counts and, for every counted row, its tokens:
++
++ - it scores NP = pool_count pools, not pool_bucket's power of two: the columns left out lie past every row's
++ visible pools, where _scores writes -inf, and they have the highest indices, so they rank below every column
++ kept (-inf ties go to the lower pool; a negative NaN, the one key below -inf's, is never an arithmetic result
++ on the GPU). A counted row has more than 512 visible pools and NP >= 1024 >= 512, so its best 512 pools, the
++ radix select's threshold and ties are the same. (Rows with count 0, whose tokens nothing reads, may differ.)
++ The scores buffer keeps pool_bucket's size (the allocator's few sizes), used as a contiguous [R, NP] prefix;
++ - _scores takes score_rows() rows a program: a row's keys are masked to its own pools before its dot, as with 1;
++ - one kernel (_tokens) writes tokens and counts with select_tokens' integer formulas."""
++
++ dev = qi.device
++ NP = pool_count(pos, R, np_max)
++ scores = torch.empty((R * pool_bucket(pos, R, np_max),), dtype=torch.float32, device=dev)[:R * NP].view(R, NP)
++ 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
++ rb = score_rows()
++ _scores[(triton.cdiv(R, rb), triton.cdiv(NP, 64))](qi, wts, wts.stride(0), pk, scores, pos_dev, R, NP, D ** -0.5,
++ wscale, H=H, HP=max(16, triton.next_power_of_2(H)), D=D, BP=64,
++ RB=rb, num_warps=4)
++ pools = top_pools(scores, TOPK_POOLS) # ascending pool index
++ del scores
++ 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)
++ _tokens[(R,)](pools, pos_dev, tokens, counts, W=width, K=TOPK_POOLS, PL=POOL, BLOCK=1024, num_warps=4)
++ return tokens, counts
++
++
+ @triton.jit
+ def _gtile(q, k, v, m, l, o, valid, SCALE: tl.constexpr):
+ scores = tl.dot(q, tl.trans(k)).to(tl.float32) * SCALE
diff --git a/patches/0010-glm-hc-split.patch b/patches/0010-glm-hc-split.patch
new file mode 100644
index 0000000..f1c0cd3
--- /dev/null
+++ b/patches/0010-glm-hc-split.patch
@@ -0,0 +1,602 @@
+diff --git tensorfold/cuda/comm.py tensorfold/cuda/comm.py
+index 31a92c1..eb7aa10 100644
+--- tensorfold/cuda/comm.py
++++ tensorfold/cuda/comm.py
+@@ -1,4 +1,5 @@
+-"""NCCL all-gather on the current stream so CUDA graphs capture it; a rank-order sum after it keeps ranks bit-equal."""
++"""NCCL all-gather (and paired send/receive) on the current stream so CUDA graphs capture it; a rank-order sum after
++it keeps ranks bit-equal."""
+
+ from __future__ import annotations
+
+@@ -47,6 +48,11 @@ class NCCL:
+ lib.ncclCommInitRank.argtypes = [ctypes.POINTER(ctypes.c_void_p), ctypes.c_int, _UniqueId, ctypes.c_int]
+ lib.ncclAllGather.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_size_t, ctypes.c_int, ctypes.c_void_p,
+ ctypes.c_void_p]
++ for name in ("ncclSend", "ncclRecv"):
++ getattr(lib, name).argtypes = [ctypes.c_void_p, ctypes.c_size_t, ctypes.c_int, ctypes.c_int,
++ ctypes.c_void_p, ctypes.c_void_p]
++ lib.ncclGroupStart.argtypes = []
++ lib.ncclGroupEnd.argtypes = []
+ 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))
+
++ 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
++ tensors; the peer's matching call has the same count, sizes and dtypes in the same order)."""
++
++ if len(sends) != len(recvs) or peer == self.rank or not 0 <= peer < self.world:
++ raise ValueError("exchange: one receive per send, from another rank")
++ for s, r in zip(sends, recvs):
++ if s.numel() != r.numel() or s.dtype != r.dtype or not (s.is_contiguous() and r.is_contiguous()):
++ raise ValueError("exchange: each send and receive must be contiguous and alike in size and dtype")
++ stream = torch.cuda.current_stream().cuda_stream
++ self._check(self.lib.ncclGroupStart())
++ try:
++ for s, r in zip(sends, recvs):
++ if s.numel():
++ self._check(self.lib.ncclSend(s.data_ptr(), s.numel(), _DTYPES[s.dtype], peer, self.comm, stream))
++ self._check(self.lib.ncclRecv(r.data_ptr(), r.numel(), _DTYPES[r.dtype], peer, self.comm, stream))
++ finally:
++ self._check(self.lib.ncclGroupEnd())
++
+ def barrier(self) -> None:
+ x = torch.zeros((1,), dtype=torch.float32, device="cuda")
+ y = torch.zeros((self.world,), dtype=torch.float32, device="cuda")
+diff --git tensorfold/families/glm5_next/cuda/decode.py tensorfold/families/glm5_next/cuda/decode.py
+index fdc7c53..0591d9f 100644
+--- tensorfold/families/glm5_next/cuda/decode.py
++++ tensorfold/families/glm5_next/cuda/decode.py
+@@ -84,8 +84,9 @@ class Engine:
+
+ def __init__(self, w: Weights, *, capacity: int = 2560, max_rows: int = 8, prefill_rows: int = PREFILL_ROWS,
+ graphs: bool = False, graph_rows: tuple[int, ...] = (1, 2, 3, 4), long_context: bool = False,
+- taps: tuple[int, ...] = (), grid: int = 0) -> None:
+- """``grid``: prompt chunks start on multiples of it (TF_GLM_PROMPT_GRID; 0: anywhere)."""
++ taps: tuple[int, ...] = (), grid: int = 0, split=None) -> None:
++ """``grid``: prompt chunks start on multiples of it (TF_GLM_PROMPT_GRID; 0: anywhere); ``split``: a
++ ``hcsplit.SplitSettings`` (TF_GLM_HC_SPLIT, TF_GLM_PREFILL_OVERLAP) for prompt chunks, None or off: unsplit."""
+
+ if grid and prefill_rows % grid:
+ raise ValueError(f"prompt chunks of {prefill_rows} rows do not tile a {grid}-row grid")
+@@ -98,6 +99,10 @@ class Engine:
+ if taps:
+ self.buf.set_taps(tuple(taps), w.cfg.hidden) # before any graph capture
+ self.pbuf.set_taps(tuple(taps), w.cfg.hidden)
++ if split is not None and split.split:
++ from .hcsplit import HcSplit
++
++ self.pbuf.split = HcSplit(w, self.pbuf, split)
+ self.mbuf = Buffers(w, max_rows, capacity) if w.mtp is not None else None
+ 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
+--- tensorfold/families/glm5_next/cuda/engine.py
++++ tensorfold/families/glm5_next/cuda/engine.py
+@@ -136,9 +136,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,
+- prefill_rows: int | None = None, vision: bool = False, vision_urls: bool = False) -> None:
++ prefill_rows: int | None = None, vision: bool = False, vision_urls: bool = False,
++ split=None) -> None:
+ """``comm``: a communicator with ``all_gather`` and ``barrier`` instead of NCCL between two machines (tests);
+- ``vision``: rank 0 runs the image tower (rank 1 only takes its rows)."""
++ ``vision``: rank 0 runs the image tower (rank 1 only takes its rows); ``split``: a ``hcsplit.SplitSettings``
++ instead of TF_GLM_HC_SPLIT / TF_GLM_PREFILL_OVERLAP (tests)."""
+
+ import torch
+
+@@ -155,6 +157,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)
++ from .hcsplit import SplitSettings
++
++ # TF_GLM_HC_SPLIT=1 / TF_GLM_PREFILL_OVERLAP=1: prompt chunks' hyper-connection glue split by rows between the
++ # ranks (and its exchanges overlapped); the same bits, both ranks must agree (the comparison below)
++ self.split = SplitSettings.from_env() if split is None else split
+ torch.cuda.set_device(0)
+ self.torch = torch
+ self.rank = rank
+@@ -216,7 +223,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()
+ # 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:
+ 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_HC_SPLIT*, TF_GLM_PREFILL_OVERLAP, TF_GLM_OVERLAP_PIECES): "
+ 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)
+ 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)
++ grid=self.grid, split=self.split)
++ if self.e.pbuf.split is not None:
++ self.e.pbuf.split.warm() # both ranks: open the send/receive connection now
++ if rank == 0:
++ print(f"[tensorfold] {self.split.describe()}", flush=True)
+ if 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 tensorfold/families/glm5_next/cuda/forward.py tensorfold/families/glm5_next/cuda/forward.py
+index 6c81ba8..dfd613b 100644
+--- tensorfold/families/glm5_next/cuda/forward.py
++++ tensorfold/families/glm5_next/cuda/forward.py
+@@ -121,6 +121,8 @@ class Buffers:
+ self.tap_at: dict[int, list[int]] = {}
+ self.experts = c.experts
+ self.top_k = c.top_k
++ # TF_GLM_HC_SPLIT: a prompt buffer's row split (``hcsplit.HcSplit``), set by the engine; None runs unsplit
++ self.split = None
+
+ 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
+ return qmm.matmul(x, q, xs, out=out, f32=f32, part=b.sk)
+
+
+-def out_proj(w: Weights, b: Buffers, x: torch.Tensor, q: qmm.Q4, xs: torch.Tensor, R: int) -> torch.Tensor:
+- mm(b, x, q, xs, b.part[:R], f32=True)
+- return gather(w, b, R)
++def partials(w: Weights, b: Buffers, R: int, fill, label: str | None = None) -> torch.Tensor | None:
++ """``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``)."""
++
++ sp = b.split
++ if sp is not None and sp.active:
++ sp.partial(fill)
++ return None
++ fill(0, R)
++ if label is None:
++ return gather(w, b, R)
++ with prof.timed(label):
++ return gather(w, b, R)
++
++
++def out_proj(w: Weights, b: Buffers, x: torch.Tensor, q: qmm.Q4, xs: torch.Tensor, R: int) -> torch.Tensor | None:
++ def fill(lo: int, hi: int) -> None: # rows are independent: any row range gives the same bits
++ mm(b, x[lo:hi], q, None if xs is None else xs[lo:hi], b.part[lo:hi], f32=True)
++
++ return partials(w, b, R, fill)
+
+
+ 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:
+ 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
+- with prof.timed("moe: shared expert"):
+- mm(b, b.normed[:R], s.gu, b.xs[:R], b.sgu[:R])
+- 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"):
+- if b.prefill: # the shared row read from sy where it is (the copy's bits, one pass less)
+- glue.combine_shared(b.ey[:R], b.sy[:R], b.wts[:R], b.part[:R])
+- else:
+- b.ey[:R, c.top_k].copy_(b.sy[:R])
+- glue.combine(b.ey[:R], b.wts[:R], b.part[:R])
+- with prof.timed("moe: all-gather"):
+- return gather(w, b, R)
++
++ def fill(lo: int, hi: int) -> None:
++ with prof.timed("moe: shared expert"):
++ mm(b, b.normed[lo:hi], s.gu, b.xs[lo:hi], b.sgu[lo:hi])
++ 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"):
++ if b.prefill: # the shared row read from sy where it is (the copy's bits, one pass less)
++ glue.combine_shared(b.ey[lo:hi], b.sy[lo:hi], b.wts[lo:hi], b.part[lo:hi])
++ else:
++ 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])
++
++ return partials(w, b, R, fill, "moe: all-gather")
+ with prof.timed("moe: gate/up"):
+ grouped.gate_up(b.normed[:R], m.experts, b.plan, b.eact, R)
+ with prof.timed("moe: down"):
+ grouped.down(b.eact, m.experts, b.plan, b.ey.view(-1, c.hidden), R)
+- with prof.timed("moe: combine"):
+- glue.combine(b.ey[:R], b.wts[:R], b.part[:R])
+- with prof.timed("moe: all-gather"):
+- return gather(w, b, R)
++
++ def fill(lo: int, hi: int) -> None:
++ with prof.timed("moe: combine"):
++ glue.combine(b.ey[lo:hi], b.wts[lo:hi], b.part[lo:hi])
++
++ return partials(w, b, R, fill, "moe: all-gather")
++
++
++def _mixer(layer: LayerW, w: Weights, st: State, b: Buffers, R: int, nch: int | None, host_pos: int | None,
++ sparse_np: int | None) -> torch.Tensor | None:
++ """The layer's KDA or DSA block on b.normed: every rank's partials, or None row-split (``partials``)."""
++
++ if layer.kind == "kda":
++ with prof.timed("kda"):
++ return kda_block(layer, w, st, b, R)
++ di = st.dsa_index[layer.index]
++ with prof.timed("dsa (total)"):
++ return dsa_block(layer, w, st.kc[di], st.vc[di], st.pos_dev, b, R, nch,
++ st.index[di] if st.index is not None else None, host_pos, sparse_np)
++
++
++def _ffn(layer: LayerW, w: Weights, b: Buffers, R: int) -> torch.Tensor | None:
++ with prof.timed("moe (total)" if layer.mlp is None else "mlp"):
++ return mlp_block(layer, w, b, R) if layer.mlp is not None else moe_block(layer, w, b, R)
+
+
+ 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:
+ 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)
+- if layer.kind == "kda":
+- with prof.timed("kda"):
+- g = kda_block(layer, w, st, b, R)
+- else:
+- di = st.dsa_index[layer.index]
+- with prof.timed("dsa (total)"):
+- g = dsa_block(layer, w, st.kc[di], st.vc[di], st.pos_dev, b, R, nch,
+- st.index[di] if st.index is not None else None, host_pos, sparse_np)
++ g = _mixer(layer, w, st, b, R, nch, host_pos, sparse_np)
+ with prof.timed("hc"):
+ 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],
+ b.hcpart[:R], c.eps, c.hc_eps, c.hc_iters, prompt=b.prefill)
+- with prof.timed("moe (total)" if layer.mlp is None else "mlp"):
+- g = mlp_block(layer, w, b, R) if layer.mlp is not None else moe_block(layer, w, b, R)
++ g = _ffn(layer, w, b, R)
+ glue.hc_post(x, x, g, b.post[:R], b.comb[:R])
+
+
++def split_layers(w: Weights, st: State, b: Buffers, R: int, nch: int | None, host_pos: int | None) -> None:
++ """Every layer of a prompt chunk with its hyper-connection glue split by rows between the ranks
++ (``hcsplit``): the first hc_pre runs on every row as unsplit, each later one on this rank's rows, and b.normed,
++ the taps and b.hidden come back whole from the peer. The same bits as the unsplit loop and its final mean."""
++
++ c = w.cfg
++ sp = b.split
++ layers = w.layers
++ sp.begin(R)
++ try:
++ Rp = sp.Rp # R, or R + 1 with a zero pad row for an odd chunk
++ first, h = layers[0], layers[0].attn_hc
++ glue.hc_pre(b.x[:Rp], h.fn, h.base, h.scale, first.in_norm, b.normed[:Rp], b.xs[:Rp], b.post[:Rp],
++ b.comb[:Rp], b.hcpart[:Rp], c.eps, c.hc_eps, c.hc_iters, prompt=True)
++ for i, layer in enumerate(layers):
++ _mixer(layer, w, st, b, R, nch, host_pos, None)
++ with prof.timed("hc"):
++ sp.glue(layer.ffn_hc, layer.post_norm)
++ _ffn(layer, w, b, R)
++ nxt = layers[i + 1] if i + 1 < len(layers) else None
++ with prof.timed("hc (layer end)"):
++ sp.glue(nxt.attn_hc if nxt is not None else None, nxt.in_norm if nxt is not None else None,
++ taps=tuple(b.tap_at.get(layer.index, ())), final=nxt is None)
++ finally:
++ sp.finish()
++
++
+ 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
+ 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)
+- 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 b.prefill and b.split is not None and sparse_np is None and b.split.applies(R):
++ split_layers(w, st, b, R, nch, host_pos) # also leaves the taps and b.hidden[:R]
++ else:
++ for layer in w.layers:
++ 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 tensorfold/families/glm5_next/cuda/glue.py tensorfold/families/glm5_next/cuda/glue.py
+index dbde3f1..620025a 100644
+--- tensorfold/families/glm5_next/cuda/glue.py
++++ tensorfold/families/glm5_next/cuda/glue.py
+@@ -242,6 +242,24 @@ def hc_post(x: torch.Tensor, xout: torch.Tensor, gathered: torch.Tensor, post: t
+ num_warps=4)
+
+
++def hc_post_pair(x: torch.Tensor, xout: torch.Tensor, g0: torch.Tensor, g1: torch.Tensor, post: torch.Tensor,
++ comb: torch.Tensor) -> None:
++ """``hc_post`` of two ranks' fp32 partials [R, D] held apart (rank 0's ``g0``, rank 1's ``g1``): the same kernel
++ with rank 1's rows read at their distance from rank 0's (element offset, may be negative), so the sum (rank 0
++ first) and every bit are hc_post's (TF_GLM_HC_SPLIT)."""
++
++ rows, d = g0.shape
++ if (g1.shape != g0.shape or g0.dtype != torch.float32 or g1.dtype != torch.float32
++ or not (g0.is_contiguous() and g1.is_contiguous())):
++ raise ValueError("hc_post_pair: two contiguous fp32 partials of one shape")
++ if not rows:
++ return
++ s = x.shape[1] // d
++ block = min(1024, d)
++ rs = (g1.data_ptr() - g0.data_ptr()) // g0.element_size()
++ _hc_post[(rows, d // block)](x, xout, g0, post, comb, rs, D=d, S=s, WORLD=2, BLOCK=block, num_warps=4)
++
++
+ @triton.jit
+ def _residual_add(X, XOUT, G, RS, D: tl.constexpr, WORLD: tl.constexpr, BLOCK: tl.constexpr):
+ """Plain residual (the MTP block): X = bf16(X + bf16(partials summed rank 0 first))."""
+diff --git tensorfold/families/glm5_next/cuda/hcsplit.py tensorfold/families/glm5_next/cuda/hcsplit.py
+new file mode 100644
+index 0000000..0002a96
+--- /dev/null
++++ tensorfold/families/glm5_next/cuda/hcsplit.py
+@@ -0,0 +1,246 @@
++"""TF_GLM_HC_SPLIT=1: a prompt chunk's hyper-connection glue split by rows between the two ranks (decode untouched).
++
++Unsplit, each exchange site (after the attention block and after the MLP/MoE block) all-gathers both ranks' fp32
++partials [R, D], and both ranks run hc_post and the next hc_pre over all R rows. Split, rank r owns rows
++[r H, r H + H) (H = R / 2; an odd chunk gets one zero pad row, which nothing reads): each rank sends the peer its
++partial of the peer's rows (fp32), adds the two partials of its own rows rank 0's first (``glue.hc_post_pair``, the
++same kernel as hc_post), runs hc_post and the next hc_pre on its own rows, and swaps its normed rows (bf16) for the
++peer's, so both ranks hold the next block's full input. The residual streams (b.x) stay current for own rows only;
++DFlash2 taps and the final stream mean (b.hidden) are computed on own rows and swapped like the normed rows. Every
++glue kernel is row-independent and the partial sum order is unchanged, so every bit is the unsplit path's.
++
++The group sums b.xs of the normed rows are not swapped: no prompt-chunk matmul reads them (4-bit projections of a
++prompt chunk run ``prefill_matmul``, BF16 and FP8 ones ignore them). The tests compare split and unsplit states bit
++for bit, so a later reader would show up there.
++
++TF_GLM_PREFILL_OVERLAP=1 (with the split) runs the swaps on a second CUDA stream in row pieces: a site computes the
++peer's rows of its partial first, piece by piece, each piece's swap starting as it is done, then its own rows; then
++the glue piece by piece, each piece waiting only for its own partial rows and its normed rows swapped while the next
++piece's glue runs. Events order the two streams; the arithmetic is the same kernels on the same rows.
++
++TF_GLM_HC_EXCHANGE: ``p2p`` (the default) swaps rows with ncclSend/ncclRecv; ``gather`` uses the NCCL all-gather
++instead (whole halves, one piece: the partial halves out of place into the unused all-gather buffer, the bf16 rows in
++place), the same bytes on the wire, for when NCCL's point-to-point path is slower or misbehaves on a fabric."""
++
++from __future__ import annotations
++
++import os
++from dataclasses import dataclass
++from typing import Callable
++
++import torch
++
++from . import glue
++
++EXCHANGES = ("p2p", "gather")
++
++
++def _flag(env, name: str) -> bool:
++ value = str(env.get(name, "") or "0").strip()
++ if value not in ("0", "1"):
++ raise ValueError(f"{name}: 0 or 1, not {value!r}")
++ return value == "1"
++
++
++def _int(env, name: str, default: int, lo: int, hi: int) -> int:
++ value = str(env.get(name, "") or default).strip()
++ if not value.isdecimal() or not lo <= int(value) <= hi:
++ raise ValueError(f"{name}: a whole number from {lo} to {hi}, not {value!r}")
++ return int(value)
++
++
++@dataclass(frozen=True)
++class SplitSettings:
++ """What TF_GLM_HC_SPLIT / TF_GLM_PREFILL_OVERLAP ask for; both ranks must agree (the startup comparison)."""
++
++ split: bool = False
++ overlap: bool = False
++ pieces: int = 2 # TF_GLM_OVERLAP_PIECES: row pieces a site's swaps run in (overlap, p2p only)
++ min_rows: int = 64 # TF_GLM_HC_SPLIT_MIN_ROWS: shorter chunks (a prompt's tail) run unsplit
++ exchange: str = "p2p" # TF_GLM_HC_EXCHANGE: p2p (ncclSend/ncclRecv) or gather (the all-gather)
++
++ @classmethod
++ def from_env(cls, env=None) -> "SplitSettings":
++ env = os.environ if env is None else env
++ split = _flag(env, "TF_GLM_HC_SPLIT")
++ overlap = _flag(env, "TF_GLM_PREFILL_OVERLAP")
++ if overlap and not split:
++ raise ValueError("TF_GLM_PREFILL_OVERLAP=1 overlaps the row-split exchanges: it needs TF_GLM_HC_SPLIT=1")
++ exchange = str(env.get("TF_GLM_HC_EXCHANGE", "") or "p2p").strip()
++ if exchange not in EXCHANGES:
++ raise ValueError(f"TF_GLM_HC_EXCHANGE: {' or '.join(EXCHANGES)}, not {exchange!r}")
++ return cls(split, overlap, _int(env, "TF_GLM_OVERLAP_PIECES", 2, 1, 8),
++ _int(env, "TF_GLM_HC_SPLIT_MIN_ROWS", 64, 2, 16384), exchange)
++
++ def piece_count(self) -> int:
++ return self.pieces if self.overlap and self.exchange == "p2p" else 1
++
++ def code(self) -> list[int]:
++ if not self.split:
++ return [0, 0, 0, 0, 0]
++ return [1, int(self.overlap), self.piece_count(), self.min_rows, EXCHANGES.index(self.exchange)]
++
++ def describe(self) -> str:
++ what = "rows split between the ranks"
++ what += ", exchanges by " + ("send/receive" if self.exchange == "p2p" else "all-gather")
++ if self.overlap:
++ n = self.piece_count()
++ what += f" on a second stream{f' in {n} pieces' if n > 1 else ''}"
++ return f"prompt chunks' hyper-connections: {what} (chunks of {self.min_rows}+ rows)"
++
++
++class HcSplit:
++ """One prompt buffer's row split: rows, pieces, the second stream and its events."""
++
++ def __init__(self, w, b, settings: SplitSettings) -> None:
++ if w.world != 2 or w.comm is None or (settings.exchange == "p2p" and not hasattr(w.comm, "exchange")):
++ raise ValueError("TF_GLM_HC_SPLIT needs two ranks and a communicator with exchange (send/receive), "
++ "or TF_GLM_HC_EXCHANGE=gather")
++ self.w, self.b, self.settings = w, b, settings
++ self.rank, self.peer = w.rank, 1 - w.rank
++ self.gather = settings.exchange == "gather"
++ # the plain NCCL all-gather (RoceComm sends small gathers over RoCE, whose kernel is not written for in place)
++ self.all_gather = getattr(w.comm, "nccl", w.comm).all_gather
++ self.active = False
++ self.R = self.Rp = self.H = 0
++ self.pieces: list[tuple[int, int]] = []
++ self.got: list[torch.Tensor] = []
++ self.stream = None
++ if settings.overlap:
++ self.stream = torch.cuda.Stream(priority=-1)
++ n = settings.piece_count()
++ self.ev_fill = [torch.cuda.Event() for _ in range(n)]
++ self.ev_part = [torch.cuda.Event() for _ in range(n)]
++ self.ev_glue = [torch.cuda.Event() for _ in range(n)]
++ self.ev_done = torch.cuda.Event()
++
++ def applies(self, R: int) -> bool:
++ return R >= self.settings.min_rows and R + (R & 1) <= self.b.rows
++
++ def warm(self) -> None:
++ """Open the NCCL send/receive connection to the peer at startup (both ranks call this together)."""
++
++ if self.gather:
++ return
++ a = torch.zeros((1,), dtype=torch.float32, device="cuda")
++ z = torch.empty_like(a)
++ self.w.comm.exchange([a], [z], self.peer)
++ torch.cuda.synchronize()
++
++ # -- per chunk ------------------------------------------------------------------------------------------------
++ def begin(self, R: int) -> None:
++ b = self.b
++ self.R, self.Rp = R, R + (R & 1)
++ self.H = H = self.Rp // 2
++ n = self.settings.piece_count()
++ size = -(-H // n)
++ if size > 64: # whole 64-row tiles for the glue kernels where possible
++ size = min(H, -(-size // 64) * 64)
++ self.pieces = [(off, min(size, H - off)) for off in range(0, H, size)]
++ # where the peer's partial of each piece of this rank's rows lands: [n, D] fp32 in the all-gather buffer,
++ # unused while split (gather: the peer's slot of the piece's [2, n, D])
++ d = b.part.shape[1]
++ if self.gather:
++ self.got = [b.gath[(2 * off + self.peer * n) * d:(2 * off + self.peer * n + n) * d].view(n, d)
++ for off, n in self.pieces]
++ else:
++ self.got = [b.gath[off * d:(off + n) * d].view(n, d) for off, n in self.pieces]
++ if self.Rp > R: # the pad row: zero streams and partials, never read
++ b.x[R:self.Rp].zero_()
++ b.part[R:self.Rp].zero_()
++ if self.stream is not None:
++ self.stream.wait_stream(torch.cuda.current_stream())
++ self.active = True
++
++ def finish(self) -> None:
++ if self.stream is not None and self.active:
++ torch.cuda.current_stream().wait_stream(self.stream)
++ self.active = False
++
++ def mine(self) -> int:
++ return self.rank * self.H
++
++ def theirs(self) -> int:
++ return self.peer * self.H
++
++ def _fill(self, fill: Callable[[int, int], None], lo: int, hi: int) -> None:
++ hi = min(hi, self.R)
++ if hi > lo:
++ fill(lo, hi)
++
++ def _swap_partial(self, j: int) -> None:
++ """Piece j: this rank's partial of the peer's rows out, the peer's partial of this rank's rows in."""
++
++ off, n = self.pieces[j]
++ lo = self.theirs() + off
++ send = self.b.part[lo:lo + n]
++ if self.gather:
++ d = send.shape[1]
++ self.all_gather(send.reshape(-1), self.b.gath[2 * off * d:2 * (off + n) * d])
++ else:
++ self.w.comm.exchange([send], [self.got[j]], self.peer)
++
++ def _swap_rows(self, j: int, outs: list[torch.Tensor]) -> None:
++ """Piece j of bf16 row buffers: this rank's rows out, the peer's rows in (gather: in place, whole halves)."""
++
++ off, n = self.pieces[j]
++ mine, theirs = self.mine() + off, self.theirs() + off
++ if self.gather: # one piece: rank order is row order
++ for t in outs:
++ self.all_gather(t[mine:mine + n].reshape(-1), t[:self.Rp].reshape(-1))
++ return
++ self.w.comm.exchange([t[mine:mine + n] for t in outs], [t[theirs:theirs + n] for t in outs], self.peer)
++
++ def partial(self, fill: Callable[[int, int], None]) -> None:
++ """This rank's fp32 partial rows (``fill(lo, hi)`` writes b.part[lo:hi]), the peer's rows sent to it and its
++ partial of this rank's rows received (``got``)."""
++
++ theirs, mine = self.theirs(), self.mine()
++ if self.stream is None:
++ fill(0, self.R)
++ for j in range(len(self.pieces)):
++ self._swap_partial(j)
++ return
++ main = torch.cuda.current_stream()
++ for j, (off, n) in enumerate(self.pieces):
++ self._fill(fill, theirs + off, theirs + off + n)
++ self.ev_fill[j].record(main)
++ with torch.cuda.stream(self.stream):
++ self.stream.wait_event(self.ev_fill[j])
++ self._swap_partial(j)
++ self.ev_part[j].record(self.stream)
++ self._fill(fill, mine, mine + self.H)
++
++ def glue(self, hc=None, norm=None, taps: tuple[int, ...] = (), final: bool = False) -> None:
++ """hc_post of this rank's rows, then (in order) the layer's DFlash2 taps, the final stream mean (``final``)
++ and the next hc_pre (``hc``, ``norm``); their rows swapped with the peer's."""
++
++ b, c = self.b, self.w.cfg
++ mine = self.mine()
++ main = torch.cuda.current_stream()
++ outs = [b.taps[slot] for slot in taps] + ([b.hidden] if final else []) + ([b.normed] if hc is not None else [])
++ for j, (off, n) in enumerate(self.pieces):
++ lo, hi = mine + off, mine + off + n
++ if self.stream is not None:
++ main.wait_event(self.ev_part[j])
++ own, got = b.part[lo:hi], self.got[j]
++ g0, g1 = (own, got) if self.rank == 0 else (got, own)
++ x = b.x[lo:hi]
++ glue.hc_post_pair(x, x, g0, g1, b.post[lo:hi], b.comb[lo:hi])
++ for slot in taps:
++ glue.stream_mean(x, b.taps[slot][lo:hi])
++ if final:
++ glue.stream_mean(x, b.hidden[lo:hi])
++ if hc is not None:
++ glue.hc_pre(x, hc.fn, hc.base, hc.scale, norm, b.normed[lo:hi], b.xs[lo:hi], b.post[lo:hi],
++ b.comb[lo:hi], b.hcpart[lo:hi], c.eps, c.hc_eps, c.hc_iters, prompt=True)
++ if self.stream is None:
++ self._swap_rows(j, outs)
++ continue
++ self.ev_glue[j].record(main)
++ with torch.cuda.stream(self.stream):
++ self.stream.wait_event(self.ev_glue[j])
++ self._swap_rows(j, outs)
++ if self.stream is not None:
++ self.ev_done.record(self.stream)
++ main.wait_event(self.ev_done)
diff --git a/patches/0011-glm-draft-sim.patch b/patches/0011-glm-draft-sim.patch
new file mode 100644
index 0000000..f262ddf
--- /dev/null
+++ b/patches/0011-glm-draft-sim.patch
@@ -0,0 +1,1106 @@
+diff --git tensorfold/families/glm5_next/cuda/dflash2.py tensorfold/families/glm5_next/cuda/dflash2.py
+index ebace1f..a6ee808 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,
+
+
+ def _quantize4(w: torch.Tensor) -> qmm.Q4:
+- """bf16 (N, K) -> MLX-style affine 4-bit in groups of 64 along K, tiled (``qmm.quantize4``)."""
++ """bf16 (N, K) -> MLX-style affine 4-bit in groups of 64 along K, tiled: min / max ranges (``qmm.quantize4``) or,
++ with TF_GLM_DRAFT_QUANT=mse, least-squares clipped ones (``qmm.quantize4_mse``). Drafts only: replies keep."""
+
+- return qmm.quantize4(w)
++ return qmm.draft_quantize4(w)
+
+
+ def _mm(x: torch.Tensor, w: qmm.Q4, xs: torch.Tensor | None = None, *, f32: bool = False) -> torch.Tensor:
+diff --git tensorfold/families/glm5_next/cuda/draft_dump.py tensorfold/families/glm5_next/cuda/draft_dump.py
+new file mode 100644
+index 0000000..9d420b9
+--- /dev/null
++++ tensorfold/families/glm5_next/cuda/draft_dump.py
+@@ -0,0 +1,181 @@
++"""TF_GLM_DRAFT_DUMP=<dir>: teacher-forced DFlash2 records for the offline draft simulator (``draft_sim``).
++
++With it set (on both ranks: the engine refuses to start otherwise), a request that would draft with DFlash2 decodes
++one token a round instead, through the same one-row verify as ``serial_decode``, so its reply is serial's
++(``draft: false``). Before each round it runs the DFlash2 block for the pending token as ``dflash_decode`` would and
++records, for the block's positions: the merged candidates and their logits, the selector's edge scores between
++consecutive candidates, the request's keyed Gumbel draws for them, the drafter's projected rows, and the chain the
++production rule (``fc5:0.3``) would propose; after the verify, the target's top-32 logits and the committed token.
++Both ranks run every call (the block and the target's top-32 gather are collectives); rank 0 writes one ``.npz`` per
++request into <dir>. Off (unset), nothing here runs.
++"""
++
++from __future__ import annotations
++
++import hashlib
++import json
++import os
++import time
++from collections.abc import Sequence
++from pathlib import Path
++
++import numpy as np
++import torch
++
++from tensorfold.engine.exact_sampling import Sampling, uniform_rows
++
++from . import dflash2
++from .decode import DecodeResult, _sync, commit
++
++DUMP_ENV = "TF_GLM_DRAFT_DUMP"
++TARGET_K = 32 # the target's top candidates kept a row (>= top_k 20 + MARGIN 8, so its sample re-derives)
++VERSION = 1
++PROD_MOST, PROD_CONFIDENCE = 5, 0.3 # engine.DFLASH_POLICY, the chain recorded as ``prod_chain``
++
++_count = 0
++
++
++def dump_dir(env: dict | None = None) -> Path | None:
++ """TF_GLM_DRAFT_DUMP's directory, or None when unset or empty (off)."""
++
++ value = (os.environ if env is None else env).get(DUMP_ENV, "")
++ return Path(value) if value else None
++
++
++def edges(drafter, tokens: np.ndarray, proj: np.ndarray, anchor: int) -> tuple[np.ndarray, np.ndarray]:
++ """The selector edges Drafter.chain computes, for every pair it could meet: (pending -> depth-0 candidates [K],
++ depth d-1 candidate a -> depth d candidates [D - 1, K, K]); each the chain's own float64 expression (same bits)."""
++
++ depth, k = tokens.shape
++ e0 = drafter.succ[tokens[0]].astype(np.float64) @ (drafter.pred[anchor].astype(np.float64) * proj[0])
++ out = np.zeros((max(depth - 1, 0), k, k), dtype=np.float64)
++ for d in range(1, depth):
++ succ = drafter.succ[tokens[d]].astype(np.float64)
++ for a in range(k):
++ out[d - 1, a] = succ @ (drafter.pred[int(tokens[d - 1, a])].astype(np.float64) * proj[d])
++ return e0, out
++
++
++def target_top(w, row: torch.Tensor, k: int = TARGET_K) -> tuple[np.ndarray, np.ndarray, float]:
++ """The target's top-k over the whole vocabulary of one logits row (this rank's slice [1, V/world]) by (value desc,
++ id asc), and the row's logsumexp; gathered from every rank alike."""
++
++ k = min(k, row.shape[1])
++ x = row.float()
++ vals, ids = torch.topk(x, k, dim=-1)
++ lse = torch.logsumexp(x, dim=-1, keepdim=True)
++ ids = (ids + w.vocab_offset).to(torch.int32)
++ packed = torch.cat([vals, ids.view(torch.float32), lse], dim=1).contiguous()
++ if w.comm is None:
++ g = packed.view(1, -1).cpu()
++ else:
++ got = torch.empty((w.world * packed.numel(),), dtype=torch.float32, device=packed.device)
++ w.comm.all_gather(packed.view(-1), got)
++ g = got.view(w.world, -1).cpu()
++ values = g[:, :k].reshape(-1).numpy().astype(np.float64)
++ tokens = g[:, k:2 * k].contiguous().view(torch.int32).reshape(-1).numpy().astype(np.int64)
++ lses = g[:, 2 * k].numpy().astype(np.float64)
++ order = np.lexsort((tokens, -values))[:k]
++ return tokens[order], values[order], float(np.logaddexp.reduce(lses))
++
++
++def dump_decode(e, drafter, pending: int, count: int, sampling: Sampling | None, *, out_dir: Path | None,
++ stop_eos: bool = False, on_tokens=None, meta: dict | None = None) -> DecodeResult:
++ """``serial_decode``'s tokens (one-row verifies), with the DFlash2 block run and recorded before each; rank 0
++ passes ``out_dir`` and writes the records there, every rank runs the same calls."""
++
++ w, st, b = e.w, e.st, e.buf
++ depth = drafter.block - 1
++ sampled = sampling is not None and sampling.temperature > 0
++ out = [pending]
++ rec: dict[str, list] = {k: [] for k in ("first", "cand_ids", "cand_vals", "proj", "noise", "edge0", "edges",
++ "prod_chain", "tgt_ids", "tgt_vals", "tgt_lse")}
++ stages = {"block": 0.0, "forward": 0.0, "sample": 0.0, "commit": 0.0}
++ _sync(w)
++ start = time.perf_counter()
++ while len(out) < count and not (stop_eos and out[-1] in w.cfg.eos):
++ t0 = time.perf_counter()
++ if drafter.context_end != st.pos:
++ raise RuntimeError(f"draft dump: the drafter's context ends at {drafter.context_end}, "
++ f"the reply at {st.pos}")
++ first = drafter.context_end + 1
++ tokens, values, proj = drafter.candidates(out[-1], depth)
++ e0, ed = edges(drafter, tokens, proj, out[-1])
++ noise = (-np.log(-np.log(uniform_rows(sampling.seed, first + np.arange(depth), tokens)))
++ if sampled else None)
++ most = min(PROD_MOST, depth)
++ chain = drafter.chain(tokens[:most], values[:most], proj[:most], out[-1], first, sampling, PROD_CONFIDENCE)
++ t1 = time.perf_counter()
++ logits = e.forward(e.verify_window([out[-1]]))
++ torch.cuda.synchronize()
++ t2 = time.perf_counter()
++ tok = e.sample(logits[:1], [st.pos + 1], sampling)[0]
++ top_ids, top_vals, lse = target_top(w, logits[:1])
++ e.follow([tok])
++ t3 = time.perf_counter()
++ commit(w, st, b, 1, 1)
++ drafter.add_taps(e.tap_rows(1))
++ t4 = time.perf_counter()
++ stages["block"] += t1 - t0
++ stages["forward"] += t2 - t1
++ stages["sample"] += t3 - t2
++ stages["commit"] += t4 - t3
++ rec["first"].append(first)
++ rec["cand_ids"].append(tokens.astype(np.int32))
++ rec["cand_vals"].append(values.astype(np.float32)) # float32 logits widened by candidates(): exact
++ rec["proj"].append(proj.astype(np.float32))
++ if noise is not None:
++ rec["noise"].append(noise)
++ rec["edge0"].append(e0)
++ rec["edges"].append(ed)
++ rec["prod_chain"].append(chain + [-1] * (depth - len(chain)))
++ rec["tgt_ids"].append(top_ids.astype(np.int32))
++ rec["tgt_vals"].append(top_vals.astype(np.float32))
++ rec["tgt_lse"].append(lse)
++ out.append(tok)
++ if on_tokens is not None:
++ on_tokens([tok])
++ _sync(w)
++ res = DecodeResult(out, time.perf_counter() - start, len(out) - 1, stages=stages)
++ if out_dir is not None:
++ info = dict(meta or {})
++ info.update(version=VERSION, block=drafter.block, selector_top_k=drafter.top_k, edge=dflash2.EDGE,
++ noise=dflash2.NOISE, prod_most=PROD_MOST, prod_confidence=PROD_CONFIDENCE, stop_eos=bool(stop_eos),
++ eos=[int(t) for t in w.cfg.eos], count=int(count), steps=len(out) - 1,
++ seed=int(sampling.seed) if sampling is not None else 0,
++ temperature=float(sampling.temperature) if sampling is not None else 0.0,
++ top_k=int(sampling.top_k) if sampling is not None else 0,
++ top_p=float(sampling.top_p) if sampling is not None else 1.0,
++ min_p=float(sampling.min_p) if sampling is not None else 0.0,
++ sha256=hashlib.sha256(json.dumps(out).encode()).hexdigest()[:16])
++ res.dump_path = str(write(out_dir, info, out, rec, depth, drafter.top_k))
++ return res
++
++
++def write(out_dir: Path, meta: dict, tokens: Sequence[int], rec: dict, depth: int, k: int) -> Path:
++ """One request's records as a compressed .npz (written to a temporary name, then renamed)."""
++
++ global _count
++ _count += 1
++ out_dir.mkdir(parents=True, exist_ok=True)
++ n = len(rec["first"])
++
++ def stack(key, shape, dtype):
++ return np.stack(rec[key]).astype(dtype) if rec[key] else np.zeros((0, *shape), dtype=dtype)
++
++ arrays = dict(meta=np.array(json.dumps(meta)), tokens=np.asarray(tokens, dtype=np.int64),
++ first=np.asarray(rec["first"], dtype=np.int64), cand_ids=stack("cand_ids", (depth, k), np.int32),
++ cand_vals=stack("cand_vals", (depth, k), np.float32),
++ proj=np.stack(rec["proj"]) if rec["proj"] else np.zeros((0, depth, 0), np.float32),
++ noise=stack("noise", (depth, k), np.float64) if rec["noise"] else np.zeros((0,), np.float64),
++ edge0=stack("edge0", (k,), np.float64), edges=stack("edges", (max(depth - 1, 0), k, k), np.float64),
++ prod_chain=stack("prod_chain", (depth,), np.int32), tgt_ids=stack("tgt_ids", (TARGET_K,), np.int32),
++ tgt_vals=stack("tgt_vals", (TARGET_K,), np.float32),
++ tgt_lse=np.asarray(rec["tgt_lse"], dtype=np.float64).reshape(n))
++ name = f"dump-{time.strftime('%Y%m%d-%H%M%S')}-{os.getpid()}-{_count:04d}"
++ tmp = out_dir / f".{name}.tmp.npz"
++ np.savez_compressed(tmp, **arrays)
++ path = out_dir / f"{name}.npz"
++ os.replace(tmp, path)
++ return path
+diff --git tensorfold/families/glm5_next/cuda/draft_sim.py tensorfold/families/glm5_next/cuda/draft_sim.py
+new file mode 100644
+index 0000000..64d4f54
+--- /dev/null
++++ tensorfold/families/glm5_next/cuda/draft_sim.py
+@@ -0,0 +1,775 @@
++"""Offline DFlash2 draft-policy simulator over TF_GLM_DRAFT_DUMP records (``draft_dump``): pure numpy, CPU only.
++
++A dump holds, for every committed position of a serial (``draft: false``-equal) reply, what the DFlash2 block proposed
++there (its merged top-k candidates, their logits, the selector's edge scores, the keyed Gumbel draws of the request)
++and what the target committed. Sampling is keyed by (seed, position, token), so a round that starts at position i and
++proposes a chain keeps exactly the drafts that equal the committed tokens i + 1, i + 2, ... (up to the first mismatch)
++plus one sampled token. A policy's rounds are therefore replayed exactly (up to the drafter's numerics: the dump's
++context taps come from one-row verifies, a live round's from wider windows), and a cost table (verify window V(R)
++for R = 1..8 rows, the block, per-round overhead) turns them into ms a round and tokens a second.
++
++Policies (``parse_policy``):
++ fc<N>:<p> today's rule: up to N drafts while the product of the chain's (noise-free) confidences holds p
++ f<N> N drafts every round
++ fa[:LOW:HIGH] DepthPolicy's adaptive 1-3 drafts
++ nc<N>:<p>[:B] noise-aware product: each draft's confidence is softmax((score + g) / B) at the pick, where g are the
++ target's own keyed Gumbel draws (known before the verify); B defaults to --beta
++ cost<N>:<pred> the depth k <= N maximizing E[tokens | k] / (V(k + 1) + block + overhead), E from the per-draft
++ acceptance predictor <pred>: conf (today's confidence), noisy[:B], const (per-depth rates), logit
++ oracle<N> hindsight: the per-round depths that minimize the reply's total time (an upper bound)
++Any policy takes ``@noise=W,edge=E,trunc=1`` to change the chain's pick: the weight of the keyed noise (0.7 today;
++1.0 is the drafter's estimate of the target's keyed sample), of the selector edges (0.6), and whether picks are cut to
++the drafter's own top-k / top-p nucleus like the target's sampler.
++
++Run: python -m tensorfold.families.glm5_next.cuda.draft_sim DUMP.npz ... [--policy SPEC ...] [--train DUMP ...]
++"""
++
++from __future__ import annotations
++
++import argparse
++import glob
++import json
++import math
++import sys
++from collections.abc import Sequence
++from dataclasses import asdict, dataclass, field, replace
++from pathlib import Path
++
++import numpy as np
++
++# the measured EXL3 + DFlash2 costs (ms): verify windows of 1..8 rows and one DFlash2 block
++VERIFY_MS = (29.2, 35.6, 42.6, 48.8, 53.6, 58.9, 64.5, 66.0)
++BLOCK_MS = 3.08
++EDGE = 0.6 # dflash2.EDGE
++NOISE = 0.7 # dflash2.NOISE
++MARGIN = 8 # exact_sampling.MARGIN
++
++
++# -- dumps ------------------------------------------------------------------------------------------------------------
++@dataclass
++class Dump:
++ """One request's teacher-forced records; step i: pending token tokens[i], drafts for tokens[i + 1 ...]."""
++
++ meta: dict
++ tokens: np.ndarray # [n + 1] int64: the reply (the first token, then one a step)
++ first: np.ndarray # [n] int64: position of draft 0 (the drafter's context_end + 1), = the target's
++ cand_ids: np.ndarray # [n, D, K] int64: merged candidates by (value desc, id asc), D = block - 1
++ cand_vals: np.ndarray # [n, D, K] float64 (float32 logits)
++ edge0: np.ndarray # [n, K] float64: selector edge, pending token -> depth-0 candidates
++ edges: np.ndarray # [n, D - 1, K, K] float64: edge from depth d-1 candidate a to depth d candidate b
++ noise: np.ndarray | None # [n, D, K] float64 keyed Gumbel draws (None: greedy)
++ tgt_ids: np.ndarray # [n, T] int64: the target's top-T at the committed row
++ tgt_vals: np.ndarray # [n, T] float64
++ tgt_lse: np.ndarray # [n] float64: logsumexp of the whole row (raw logits)
++ prod_chain: np.ndarray # [n, D] int64: the engine's own chain under its production rule, -1 padded
++ path: str = ""
++ proj: np.ndarray | None = None # [n, D, rank] float32: the selector's projected rows (edges already hold them)
++
++ @property
++ def n(self) -> int:
++ return int(self.first.shape[0])
++
++ @property
++ def depth(self) -> int:
++ return int(self.cand_ids.shape[1])
++
++ @property
++ def sampled(self) -> bool:
++ return self.noise is not None
++
++ @property
++ def temperature(self) -> float:
++ return float(self.meta["temperature"]) if self.sampled else 1.0
++
++ @property
++ def eos(self) -> frozenset:
++ return frozenset(int(t) for t in self.meta.get("eos", ())) if self.meta.get("stop_eos") else frozenset()
++
++ def room(self, i: int) -> int:
++ """Drafts a round at step i may propose (dflash_decode's count - len(out)): up to the request's max_tokens
++ when the reply ended at an EOS (drafts past it are rejected there), else up to the reply's end."""
++
++ if self.eos and int(self.tokens[-1]) in self.eos and "count" in self.meta:
++ return int(self.meta["count"]) - (i + 1)
++ return self.n - i
++
++ def accepted(self, i: int, drafts: Sequence[int]) -> int:
++ """Drafts a round at step i keeps: equal to the committed tokens, a matched EOS not counted (as the loop)."""
++
++ k = 0
++ for d in drafts:
++ if i + 1 + k > self.n:
++ break
++ t = int(self.tokens[i + 1 + k])
++ if d != t or t in self.eos:
++ break
++ k += 1
++ return k
++
++
++def load_dump(path: str | Path) -> Dump:
++ with np.load(path, allow_pickle=False) as z:
++ meta = json.loads(str(z["meta"]))
++ noise = z["noise"].astype(np.float64) if "noise" in z.files and z["noise"].size else None
++ return Dump(meta, z["tokens"].astype(np.int64), z["first"].astype(np.int64), z["cand_ids"].astype(np.int64),
++ z["cand_vals"].astype(np.float64), z["edge0"].astype(np.float64), z["edges"].astype(np.float64),
++ noise, z["tgt_ids"].astype(np.int64), z["tgt_vals"].astype(np.float64),
++ z["tgt_lse"].astype(np.float64), z["prod_chain"].astype(np.int64), str(path),
++ z["proj"] if "proj" in z.files and z["proj"].size else None)
++
++
++def load_dumps(paths: Sequence[str]) -> list[Dump]:
++ files: list[str] = []
++ for p in paths:
++ q = Path(p)
++ files += sorted(str(f) for f in q.glob("*.npz")) if q.is_dir() else sorted(glob.glob(p)) or [p]
++ return [load_dump(f) for f in files]
++
++
++# -- the chain --------------------------------------------------------------------------------------------------------
++@dataclass(frozen=True)
++class PickRule:
++ edge: float = EDGE
++ noise: float = NOISE
++ trunc: bool = False # cut picks to the drafter's own top-k / top-p nucleus (the target sampler's shape)
++
++
++RULE = PickRule() # today's pick
++
++
++@dataclass
++class Trace:
++ """A chain walked to its full depth (no stop): per depth the pick and what a stop rule or predictor reads."""
++
++ tokens: list[int]
++ j: list[int]
++ score: list[np.ndarray] # (logits + edge * EDGE) / temperature, as Drafter.chain
++ keep: list[np.ndarray] # bool mask of pickable candidates (all, or the nucleus with trunc)
++ noise: np.ndarray | None
++
++
++def _nucleus(score: np.ndarray, top_k: int, top_p: float) -> np.ndarray:
++ order = np.argsort(-score, kind="stable")
++ keep = np.zeros(score.shape, dtype=bool)
++ k = min(top_k, len(score)) if top_k else len(score)
++ s = score[order[:k]]
++ p = np.exp(s - s.max())
++ p /= p.sum()
++ kept = int((np.cumsum(p) < top_p).sum()) + 1 if 0.0 < top_p < 1.0 else k
++ keep[order[:kept]] = True
++ return keep
++
++
++def walk(d: Dump, i: int, depth: int, rule: PickRule = RULE, confidence: float = 0.0) -> Trace:
++ """Drafter.chain at step i, bit for bit with the default rule (same float64 operations in the same order);
++ ``confidence`` > 0 stops as fc does (product of noise-free confidences, the first draft always kept)."""
++
++ depth = min(depth, d.depth)
++ temp = d.temperature
++ tr = Trace([], [], [], [], d.noise[i, :depth] if d.sampled else None)
++ chain = 1.0
++ prev = -1
++ top_k = int(d.meta.get("top_k") or 0)
++ top_p = float(d.meta.get("top_p", 1.0))
++ for k in range(depth):
++ edge = d.edge0[i] if k == 0 else d.edges[i, k - 1, prev]
++ score = (d.cand_vals[i, k] + rule.edge * edge) / temp
++ pick = score + rule.noise * tr.noise[k] if tr.noise is not None else score
++ keep = _nucleus(score, top_k, top_p) if rule.trunc and d.sampled else np.ones(score.shape, dtype=bool)
++ if rule.trunc and d.sampled:
++ pick = np.where(keep, pick, -np.inf)
++ j = int(np.argmax(pick))
++ if confidence > 0:
++ p = np.exp(score - score.max())
++ chain *= float(p[j] / p.sum())
++ if k > 0 and chain < confidence:
++ break
++ prev = j
++ tr.tokens.append(int(d.cand_ids[i, k, j]))
++ tr.j.append(j)
++ tr.score.append(score)
++ tr.keep.append(keep)
++ return tr
++
++
++FEATURES = ("conf", "log_conf", "log_cum_conf", "noisy_prob", "log_noisy_prob", "noisy_margin", "top_gap", "depth",
++ "bias")
++
++
++def features(tr: Trace, beta: float = 1.0) -> np.ndarray:
++ """[depth, len(FEATURES)] for a trace's drafts (see FEATURES); greedy: noise-aware columns equal the plain ones."""
++
++ rows = []
++ cum = 0.0
++ for k, (score, keep, j) in enumerate(zip(tr.score, tr.keep, tr.j)):
++ s = np.where(keep, score, -np.inf)
++ p = np.exp(s - s.max())
++ conf = float(p[j] / p.sum())
++ cum += math.log(max(conf, 1e-300))
++ z = s + tr.noise[k] if tr.noise is not None else s
++ q = _softmax_at(z / beta, j)
++ others = np.delete(z, j)
++ margin = float(z[j] - others.max()) if others.size and np.isfinite(others.max()) else 30.0
++ top = np.sort(s[np.isfinite(s)])[::-1]
++ gap = float(top[0] - top[1]) if top.size > 1 else 30.0
++ rows.append((conf, math.log(max(conf, 1e-300)), cum, q, math.log(max(q, 1e-300)), min(margin, 30.0),
++ min(gap, 30.0), float(k), 1.0))
++ return np.array(rows, dtype=np.float64).reshape(len(rows), len(FEATURES))
++
++
++def _softmax_at(z: np.ndarray, j: int) -> float:
++ e = np.exp(z - z.max())
++ return float(e[j] / e.sum())
++
++
++# -- predictors of a draft's acceptance (given the drafts before it were accepted) -----------------------------------
++class Predictor:
++ name = "?"
++
++ def fit(self, X: np.ndarray, y: np.ndarray) -> Predictor:
++ return self
++
++ def predict(self, X: np.ndarray) -> np.ndarray:
++ raise NotImplementedError
++
++
++class ConfPredictor(Predictor):
++ """Today's belief: a draft is kept with its noise-free confidence."""
++
++ name = "conf"
++
++ def predict(self, X):
++ return X[:, FEATURES.index("conf")]
++
++
++class NoisyPredictor(Predictor):
++ """softmax((score + g) / beta) at the pick: the target's scaled logits taken as the drafter's plus iid Gumbel(beta)
++ errors, the keyed draws g known, make exactly this the probability that the target's keyed sample is the pick.
++ ``fit`` picks beta on a grid by log loss (its features must be made with beta 1)."""
++
++ name = "noisy"
++
++ def __init__(self, beta: float = 1.0) -> None:
++ self.beta = beta
++
++ def predict(self, X):
++ return X[:, FEATURES.index("noisy_prob")]
++
++
++class ConstPredictor(Predictor):
++ """The mean acceptance at each depth (a baseline that knows nothing of the round)."""
++
++ name = "const"
++
++ def __init__(self) -> None:
++ self.rates = np.full(8, 0.5)
++
++ def fit(self, X, y):
++ dep = X[:, FEATURES.index("depth")].astype(int)
++ for k in range(len(self.rates)):
++ m = dep == k
++ self.rates[k] = (y[m].sum() + 1) / (m.sum() + 2)
++ return self
++
++ def predict(self, X):
++ return self.rates[np.minimum(X[:, FEATURES.index("depth")].astype(int), len(self.rates) - 1)]
++
++
++class LogisticPredictor(Predictor):
++ """Logistic regression (Newton / IRLS, a small L2) on chosen FEATURES columns."""
++
++ name = "logit"
++
++ def __init__(self, cols: Sequence[str] = ("log_conf", "log_noisy_prob", "noisy_margin", "top_gap", "depth", "bias"),
++ l2: float = 1e-3) -> None:
++ self.cols = tuple(cols)
++ self.idx = [FEATURES.index(c) for c in self.cols]
++ self.l2 = l2
++ self.w = np.zeros(len(self.idx))
++
++ def fit(self, X, y):
++ A = X[:, self.idx]
++ w = np.zeros(A.shape[1])
++ for _ in range(50):
++ p = 1 / (1 + np.exp(-np.clip(A @ w, -40, 40)))
++ g = A.T @ (p - y) + self.l2 * w
++ H = (A * (p * (1 - p))[:, None]).T @ A + self.l2 * np.eye(len(w))
++ step = np.linalg.solve(H, g)
++ w -= step
++ if np.abs(step).max() < 1e-9:
++ break
++ self.w = w
++ return self
++
++ def predict(self, X):
++ return 1 / (1 + np.exp(-np.clip(X[:, self.idx] @ self.w, -40, 40)))
++
++ def describe(self) -> str:
++ return ", ".join(f"{c} {v:+.3f}" for c, v in zip(self.cols, self.w))
++
++
++def training_rows(dumps: Sequence[Dump], rule: PickRule = RULE, depth: int = 7,
++ beta: float = 1.0) -> tuple[np.ndarray, np.ndarray]:
++ """(X, y) over every step of the dumps: each draft of the full chain while the drafts before it were accepted,
++ labelled 1 when it equals the committed token (a round's conditional acceptance, the quantity E[tokens] needs)."""
++
++ X, y = [], []
++ for d in dumps:
++ for i in range(d.n):
++ tr = walk(d, i, min(depth, d.n - i), rule)
++ if not tr.tokens:
++ continue
++ F = features(tr, beta)
++ kept = d.accepted(i, tr.tokens)
++ rows = min(kept + 1, len(tr.tokens))
++ X.append(F[:rows])
++ y.append((np.arange(rows) < kept).astype(np.float64))
++ if not X:
++ return np.zeros((0, len(FEATURES))), np.zeros(0)
++ return np.concatenate(X), np.concatenate(y)
++
++
++def fit_beta(dumps: Sequence[Dump], rule: PickRule, depth: int = 7,
++ grid: Sequence[float] = (0.25, 0.35, 0.5, 0.7, 1.0, 1.4, 2.0, 2.8, 4.0)) -> tuple[float, float]:
++ """The NoisyPredictor beta with the least log loss on the dumps: (beta, log loss)."""
++
++ best = (1.0, math.inf)
++ for b in grid:
++ X, y = training_rows(dumps, rule, depth, b)
++ if not len(y):
++ break
++ loss = log_loss(NoisyPredictor(b).predict(X), y)
++ if loss < best[1]:
++ best = (b, loss)
++ return best
++
++
++def log_loss(p: np.ndarray, y: np.ndarray) -> float:
++ p = np.clip(p, 1e-6, 1 - 1e-6)
++ return float(-(y * np.log(p) + (1 - y) * np.log(1 - p)).mean()) if len(y) else float("nan")
++
++
++def scores(p: np.ndarray, y: np.ndarray) -> dict:
++ """Log loss, Brier score and the ranking AUC of acceptance predictions."""
++
++ out = {"rows": len(y), "rate": float(y.mean()) if len(y) else float("nan"), "log_loss": log_loss(p, y),
++ "brier": float(((p - y) ** 2).mean()) if len(y) else float("nan")}
++ pos, neg = p[y > 0.5], p[y < 0.5]
++ if len(pos) and len(neg):
++ ranks = np.argsort(np.argsort(np.concatenate([pos, neg]), kind="stable"), kind="stable") + 1.0
++ out["auc"] = float((ranks[:len(pos)].sum() - len(pos) * (len(pos) + 1) / 2) / (len(pos) * len(neg)))
++ return out
++
++
++# -- costs and policies -----------------------------------------------------------------------------------------------
++@dataclass(frozen=True)
++class Costs:
++ verify: tuple[float, ...] = VERIFY_MS # V(R), R = 1..len
++ block: float = BLOCK_MS # one DFlash2 block (a round that drafts)
++ overhead: float = 0.0 # every round: sampling, commit, host work
++ taps_row: float = 0.0 # each kept row's context update
++
++ def round_ms(self, drafted: int, kept: int, drafting: bool) -> float:
++ return self.verify[drafted] + (self.block if drafting else 0.0) + self.overhead + self.taps_row * kept
++
++
++COSTS = Costs()
++
++
++class Policy:
++ """A round's drafts at step i (at most ``room``), then what the round kept."""
++
++ spec = "?"
++ rule = RULE
++
++ def most(self) -> int:
++ raise NotImplementedError
++
++ def propose(self, d: Dump, i: int, room: int, costs: Costs) -> list[int]:
++ raise NotImplementedError
++
++ def record(self, drafted: int, accepted: int) -> None:
++ pass
++
++
++class ProductPolicy(Policy):
++ """fc<N>:<p> (``conf``) and f<N> (p = 0): Drafter.propose with DepthPolicy(N, fixed=True, confidence=p)."""
++
++ def __init__(self, most: int, confidence: float, rule: PickRule = RULE, spec: str = "") -> None:
++ self.n, self.confidence, self.rule, self.spec = most, confidence, rule, spec
++
++ def most(self):
++ return self.n
++
++ def propose(self, d, i, room, costs):
++ depth = min(self.n, room)
++ return walk(d, i, depth, self.rule, self.confidence).tokens if depth > 0 else []
++
++
++class AdaptivePolicy(ProductPolicy):
++ """fa[:LOW:HIGH]: DepthPolicy's running acceptance rate chooses 1, 2 or 3 drafts."""
++
++ def __init__(self, low: float = 0.8, high: float = 0.9, rule: PickRule = RULE, spec: str = "") -> None:
++ super().__init__(3, 0.0, rule, spec)
++ self.low, self.high, self.rate = low, high, 0.8
++ self.first = True
++
++ def propose(self, d, i, room, costs):
++ n = max(1, min(3, 1 if self.rate < self.low else 2 if self.rate < self.high else 3))
++ depth = min(n, room)
++ return walk(d, i, depth, self.rule).tokens if depth > 0 else []
++
++ def record(self, drafted, accepted):
++ if drafted:
++ self.rate = 0.875 * self.rate + 0.125 * (accepted / drafted)
++
++
++class NoisyProductPolicy(ProductPolicy):
++ """nc<N>:<p>[:B]: stop when the product of noise-aware confidences softmax((score + g) / B)[pick] drops below p,
++ always keeping the first draft (the fc rule with the keyed draws taken into account)."""
++
++ def __init__(self, most: int, confidence: float, beta: float, rule: PickRule = RULE, spec: str = "") -> None:
++ super().__init__(most, confidence, rule, spec)
++ self.beta = beta
++
++ def propose(self, d, i, room, costs):
++ depth = min(self.n, room)
++ if depth <= 0:
++ return []
++ tr = walk(d, i, depth, self.rule)
++ q = features(tr, self.beta)[:, FEATURES.index("noisy_prob")]
++ chain, out = 1.0, []
++ for k, t in enumerate(tr.tokens):
++ chain *= q[k]
++ if k > 0 and chain < self.confidence:
++ break
++ out.append(t)
++ return out
++
++
++def best_depth(p: np.ndarray, costs: Costs, drafting_cost: bool = True) -> int:
++ """The k (0..len(p)) maximizing E[tokens | k drafts] / round ms, p the conditional acceptances of the drafts."""
++
++ alive = np.concatenate([[1.0], np.cumprod(p)]) # P(the first j drafts all kept), j = 0..len(p)
++ expect = np.cumsum(alive) # 1 + sum_{j <= k} P(first j kept)
++ ms = np.array([costs.round_ms(k, 1, drafting_cost) for k in range(len(p) + 1)])
++ return int(np.argmax(expect / ms))
++
++
++class CostPolicy(Policy):
++ """cost<N>:<pred>: walk the whole chain, predict each draft's conditional acceptance, keep the most profitable
++ prefix (E[tokens] / ms, the block counted in every round since it ran to decide)."""
++
++ def __init__(self, most: int, predictor: Predictor, beta: float = 1.0, rule: PickRule = RULE,
++ spec: str = "") -> None:
++ self.n, self.predictor, self.beta, self.rule, self.spec = most, predictor, beta, rule, spec
++
++ def most(self):
++ return self.n
++
++ def propose(self, d, i, room, costs):
++ depth = min(self.n, room)
++ if depth <= 0:
++ return []
++ tr = walk(d, i, depth, self.rule)
++ p = self.predictor.predict(features(tr, self.beta))
++ return tr.tokens[:best_depth(p, costs)]
++
++
++# -- the replay -------------------------------------------------------------------------------------------------------
++@dataclass
++class SimResult:
++ spec: str
++ tokens: int = 0 # committed tokens past the first (what DecodeResult.tokens_per_second counts)
++ rounds: int = 0
++ drafted: int = 0
++ accepted: int = 0
++ ms: float = 0.0
++ keeps: list[int] = field(default_factory=list)
++ depths: list[int] = field(default_factory=list)
++
++ def add(self, other: SimResult) -> None:
++ self.tokens += other.tokens
++ self.rounds += other.rounds
++ self.drafted += other.drafted
++ self.accepted += other.accepted
++ self.ms += other.ms
++ self.keeps += other.keeps
++ self.depths += other.depths
++
++ def summary(self) -> dict:
++ r = max(self.rounds, 1)
++ return {"policy": self.spec, "tokens": self.tokens, "rounds": self.rounds,
++ "tokens_per_round": self.tokens / r, "drafts_per_round": self.drafted / r,
++ "accept_rate": self.accepted / self.drafted if self.drafted else 0.0,
++ "ms_per_round": self.ms / r, "tok_per_s": 1e3 * self.tokens / self.ms if self.ms else 0.0}
++
++
++def simulate(d: Dump, policy: Policy, costs: Costs = COSTS) -> SimResult:
++ """dflash_decode's rounds over the dump's reply: every round verifies the pending token and the policy's drafts
++ and keeps the matching prefix plus one sampled token; the reply ends where the dump's does."""
++
++ res = SimResult(policy.spec)
++ i = 0
++ while i < d.n: # out holds tokens[:i + 1]; the loop runs while len(out) < count
++ room = d.room(i)
++ drafts = policy.propose(d, i, room, costs)
++ kept = d.accepted(i, drafts)
++ res.ms += costs.round_ms(len(drafts), kept + 1, min(policy.most(), room) > 0)
++ res.rounds += 1
++ res.drafted += len(drafts)
++ res.accepted += kept
++ res.keeps.append(kept + 1)
++ res.depths.append(len(drafts))
++ policy.record(len(drafts), kept)
++ i += kept + 1
++ res.tokens = min(i, d.n) # a last round whose drafts all held: its extra sample lies past max_tokens
++ return res
++
++
++def oracle(d: Dump, most: int, costs: Costs = COSTS, rule: PickRule = RULE) -> SimResult:
++ """The least total time any per-round depth choice (<= most) of this pick rule could reach, by dynamic
++ programming over positions with hindsight: an upper bound for stop rules."""
++
++ n = d.n
++ run = np.zeros(n, dtype=np.int64) # how many drafts of the full chain at i would be kept
++ for i in range(n):
++ run[i] = d.accepted(i, walk(d, i, min(most, n - i), rule).tokens)
++ best = np.full(n + 1, np.inf)
++ choice = np.zeros(n + 1, dtype=np.int64)
++ best[n] = 0.0
++ for i in range(n - 1, -1, -1):
++ for k in range(min(most, n - i) + 1):
++ kept = min(k, int(run[i]))
++ t = costs.round_ms(k, kept + 1, k > 0) + best[min(i + kept + 1, n)]
++ if t < best[i]:
++ best[i], choice[i] = t, k
++ res = SimResult(f"oracle{most}")
++ i = 0
++ while i < n:
++ k = int(choice[i])
++ kept = min(k, int(run[i]))
++ res.ms += costs.round_ms(k, kept + 1, k > 0)
++ res.rounds += 1
++ res.drafted += k
++ res.accepted += kept
++ res.keeps.append(kept + 1)
++ res.depths.append(k)
++ i += kept + 1
++ res.tokens = min(i, n)
++ return res
++
++
++def parse_rule(text: str) -> PickRule:
++ rule = RULE
++ for part in filter(None, text.split(",")):
++ key, _, value = part.partition("=")
++ if key == "noise":
++ rule = replace(rule, noise=float(value))
++ elif key == "edge":
++ rule = replace(rule, edge=float(value))
++ elif key == "trunc":
++ rule = replace(rule, trunc=value not in ("0", "false", ""))
++ else:
++ raise ValueError(f"pick rule {text!r}: noise=W, edge=E or trunc=0/1")
++ return rule
++
++
++def parse_policy(spec: str, predictors: dict[str, Predictor] | None = None, beta: float = 1.0) -> Policy | str:
++ """A policy from its spec (module docstring); ``oracle<N>`` comes back as its spec (``oracle``, not a Policy)."""
++
++ base, _, rule_text = spec.partition("@")
++ rule = parse_rule(rule_text)
++ predictors = predictors or {}
++ try:
++ if base.startswith("oracle"):
++ return spec
++ if base.startswith("cost"):
++ most, name = base[4:].split(":", 1)
++ key, _, arg = name.partition(":")
++ if key == "noisy":
++ return CostPolicy(int(most), NoisyPredictor(), float(arg) if arg else beta, rule, spec)
++ if key == "conf":
++ return CostPolicy(int(most), ConfPredictor(), beta, rule, spec)
++ if name in predictors:
++ return CostPolicy(int(most), predictors[name], beta, rule, spec)
++ raise ValueError(f"no predictor {name!r} (conf, noisy[:B], or a fitted one: {', '.join(predictors)})")
++ if base.startswith("fa"):
++ parts = base.split(":")
++ low, high = (float(parts[1]), float(parts[2])) if len(parts) == 3 else (0.8, 0.9)
++ return AdaptivePolicy(low, high, rule, spec)
++ if base.startswith("fc"):
++ most, conf = base[2:].split(":")
++ return ProductPolicy(int(most), float(conf), rule, spec)
++ if base.startswith("nc"):
++ parts = base[2:].split(":")
++ return NoisyProductPolicy(int(parts[0]), float(parts[1]), float(parts[2]) if len(parts) > 2 else beta,
++ rule, spec)
++ if base.startswith("f"):
++ return ProductPolicy(int(base[1:]), 0.0, rule, spec)
++ except (IndexError, ValueError) as err:
++ raise ValueError(f"policy {spec!r}: {err}") from None
++ raise ValueError(f"policy {spec!r}: fc<N>:<p>, f<N>, fa[:LOW:HIGH], nc<N>:<p>[:B], cost<N>:<pred>, oracle<N>")
++
++
++def run_policy(dumps: Sequence[Dump], spec: str, costs: Costs, predictors: dict[str, Predictor] | None = None,
++ beta: float = 1.0) -> SimResult:
++ total = SimResult(spec)
++ for d in dumps:
++ pol = parse_policy(spec, predictors, beta)
++ if isinstance(pol, str):
++ base, _, rule_text = spec.partition("@")
++ total.add(oracle(d, int(base[6:] or d.depth), costs, parse_rule(rule_text)))
++ else:
++ total.add(simulate(d, pol, costs))
++ total.spec = spec
++ return total
++
++
++# -- checks -----------------------------------------------------------------------------------------------------------
++def check(d: Dump) -> dict:
++ """Consistency of a dump: its keyed draws, the target's top-T resampling to the committed token, and the sim's
++ replay of the engine's production chain (``prod_chain``, bit for bit)."""
++
++ from tensorfold.engine.exact_sampling import Sampling, choose_rows, uniform_rows
++
++ out = {"file": d.path, "steps": d.n}
++ m = d.meta
++ if d.sampled:
++ s = Sampling(int(m["seed"]), float(m["temperature"]), int(m["top_k"]), float(m["top_p"]),
++ float(m.get("min_p", 0.0)))
++ g = np.stack([-np.log(-np.log(uniform_rows(s.seed, d.first[i] + np.arange(d.depth), d.cand_ids[i])))
++ for i in range(d.n)]) if d.n else d.noise
++ out["noise_ok"] = bool(np.array_equal(g, d.noise))
++ if s.top_k and s.top_k + MARGIN <= d.tgt_ids.shape[1]:
++ w = s.top_k + MARGIN
++ got = [choose_rows(d.tgt_vals[i:i + 1, :w], d.tgt_ids[i:i + 1, :w], [int(d.first[i])], s)[0]
++ for i in range(d.n)]
++ out["target_ok"] = float(np.mean(np.array(got) == d.tokens[1:])) if d.n else 1.0
++ else:
++ order = [np.lexsort((d.tgt_ids[i], -d.tgt_vals[i]))[0] for i in range(d.n)]
++ got = [int(d.tgt_ids[i, o]) for i, o in enumerate(order)]
++ out["target_ok"] = float(np.mean(np.array(got) == d.tokens[1:])) if d.n else 1.0
++ most, conf = int(m.get("prod_most", 5)), float(m.get("prod_confidence", 0.3))
++ same = 0
++ for i in range(d.n):
++ mine = walk(d, i, min(most, d.depth), PickRule(float(m.get("edge", EDGE)), float(m.get("noise", NOISE))),
++ conf).tokens
++ theirs = [int(t) for t in d.prod_chain[i] if t >= 0]
++ same += mine == theirs
++ out["prod_chain_ok"] = same / d.n if d.n else 1.0
++ return out
++
++
++def depth_table(dumps: Sequence[Dump], rule: PickRule = RULE, depth: int = 7) -> list[dict]:
++ """Per depth: how often the full chain's draft is kept given the drafts before it were, and the mean confidences."""
++
++ X, y = training_rows(dumps, rule, depth)
++ rows = []
++ for k in range(depth):
++ mk = X[:, FEATURES.index("depth")] == k
++ if not mk.any():
++ break
++ rows.append({"depth": k + 1, "rows": int(mk.sum()), "kept": float(y[mk].mean()),
++ "conf": float(X[mk, FEATURES.index("conf")].mean()),
++ "noisy_prob": float(X[mk, FEATURES.index("noisy_prob")].mean())})
++ return rows
++
++
++# -- command line -----------------------------------------------------------------------------------------------------
++DEFAULT_POLICIES = ("fc5:0.3", "f1", "f2", "f3", "f4", "f5", "f7", "fc7:0.3", "fc5:0.2", "fc5:0.4", "fa",
++ "fc5:0.3@noise=1.0", "fc5:0.3@noise=1.0,trunc=1", "nc7:0.3", "nc7:0.3@noise=1.0,trunc=1",
++ "cost7:conf", "cost7:noisy", "cost7:const", "cost7:logit", "cost7:logit@noise=1.0,trunc=1",
++ "oracle7")
++
++
++def _split(dumps: list[Dump]) -> tuple[list[Dump], list[Dump], str]:
++ if len(dumps) >= 2:
++ return dumps[0::2], dumps[1::2], "fit on the even-numbered dumps, evaluated on the odd-numbered ones"
++ return dumps, dumps, "one dump: fitted and evaluated on the same records (in-sample)"
++
++
++def main(argv: Sequence[str] | None = None) -> int:
++ head, _, rest = __doc__.partition("\n\n")
++ ap = argparse.ArgumentParser(prog="draft_sim", description=head, epilog=rest,
++ formatter_class=argparse.RawDescriptionHelpFormatter)
++ ap.add_argument("dumps", nargs="+", help=".npz dumps, globs or directories (evaluated on)")
++ ap.add_argument("--train", nargs="*", default=None,
++ help="dumps to fit predictors on (default: every other one of DUMPS, the rest evaluated)")
++ ap.add_argument("--policy", action="append", default=None, help="a policy spec (repeatable; default: a sweep)")
++ ap.add_argument("--verify", default=",".join(map(str, VERIFY_MS)), help="V(R) ms for R = 1..8, comma separated")
++ ap.add_argument("--block", type=float, default=BLOCK_MS, help="DFlash2 block ms")
++ ap.add_argument("--overhead", type=float, default=0.0, help="ms every round beyond V(R) and the block")
++ ap.add_argument("--taps-row", type=float, default=0.0, help="ms a kept row's context update")
++ ap.add_argument("--beta", type=float, default=0.0, help="noise-aware temperature (0: fitted on the train dumps)")
++ ap.add_argument("--check", action="store_true", help="verify each dump's consistency first")
++ ap.add_argument("--json", action="store_true", help="print JSON lines instead of a table")
++ ap.add_argument("--only", choices=("sampled", "greedy"), help="keep only sampled (temperature > 0) or greedy dumps")
++ args = ap.parse_args(argv)
++
++ keep = (lambda d: d.sampled == (args.only == "sampled")) if args.only else (lambda d: True)
++ dumps = [d for d in load_dumps(args.dumps) if keep(d)]
++ if not dumps:
++ print("draft_sim: no dumps", file=sys.stderr)
++ return 1
++ costs = Costs(tuple(float(v) for v in args.verify.split(",")), args.block, args.overhead, args.taps_row)
++ if args.train is not None:
++ train, test, how = [d for d in load_dumps(args.train) if keep(d)], dumps, "fit on --train, evaluated on DUMPS"
++ else:
++ train, test, how = _split(dumps)
++ emit = (lambda obj: print(json.dumps(obj))) if args.json else None
++ if args.check:
++ for d in dumps:
++ c = check(d)
++ emit(c) if emit else print("check", c)
++
++ specs = args.policy or list(DEFAULT_POLICIES)
++ rules = {parse_rule(s.partition("@")[2]) for s in specs}
++ beta = args.beta
++ if beta <= 0:
++ beta, loss = fit_beta(train, PickRule())
++ note = {"beta": beta, "log_loss": loss}
++ emit(note) if emit else print(f"noise-aware beta {beta:g} (log loss {loss:.4f} on the train dumps)")
++ predictors_by_rule: dict[PickRule, dict[str, Predictor]] = {}
++ for rule in rules:
++ Xtr, ytr = training_rows(train, rule, 7, beta)
++ Xte, yte = training_rows(test, rule, 7, beta)
++ fitted: dict[str, Predictor] = {"const": ConstPredictor().fit(Xtr, ytr),
++ "logit": LogisticPredictor().fit(Xtr, ytr)}
++ predictors_by_rule[rule] = fitted
++ report = {"rule": asdict(rule), "split": how}
++ for name, pred in [("conf", ConfPredictor()), ("noisy", NoisyPredictor(beta))] + list(fitted.items()):
++ report[name] = scores(pred.predict(Xte), yte) if len(yte) else {}
++ report["logit_weights"] = fitted["logit"].describe()
++ if emit:
++ emit({"predictors": report})
++ else:
++ print(f"\npredictors ({report['rule']}; {how}):")
++ for name in ("conf", "noisy", "const", "logit"):
++ s = report[name]
++ if s:
++ print(f" {name:6s} rows {s['rows']:6d} kept {s['rate']:.3f} log loss {s['log_loss']:.4f} "
++ f"brier {s['brier']:.4f} auc {s.get('auc', float('nan')):.3f}")
++ print(f" logit weights: {report['logit_weights']}")
++ table = depth_table(test)
++ if emit:
++ emit({"depths": table})
++ else:
++ print("\nper-depth acceptance of the full chain (today's pick), given the drafts before were kept:")
++ for r in table:
++ print(f" depth {r['depth']}: rows {r['rows']:6d} kept {r['kept']:.3f} conf {r['conf']:.3f} "
++ f"noisy {r['noisy_prob']:.3f}")
++ print(f"\n{'policy':34s} {'tok/round':>9s} {'drafts':>7s} {'accept':>7s} {'ms/round':>9s} {'tok/s':>7s}")
++ for spec in specs:
++ rule = parse_rule(spec.partition("@")[2])
++ s = run_policy(test, spec, costs, predictors_by_rule.get(rule), beta).summary()
++ if emit:
++ emit(s)
++ else:
++ print(f"{spec:34s} {s['tokens_per_round']:9.3f} {s['drafts_per_round']:7.2f} {s['accept_rate']:7.3f} "
++ f"{s['ms_per_round']:9.2f} {s['tok_per_s']:7.2f}")
++ return 0
++
++
++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
+--- tensorfold/families/glm5_next/cuda/engine.py
++++ tensorfold/families/glm5_next/cuda/engine.py
+@@ -221,9 +221,17 @@ class GlmEngine:
+ self.limit = self.capacity_plan["context_window"]
+ capacity = self.capacity_plan["cache_slots"]
+ long_context = self.limit > cfg.dense_limit
++ # TF_GLM_DRAFT_DUMP=<dir>: DFlash2 requests decode serially and record the drafter's view for the offline
++ # simulator (``draft_dump``, ``draft_sim``); TF_GLM_DRAFT_QUANT=minmax|mse: how DFlash2's 4-bit copies are made
++ from .draft_dump import dump_dir
++ from .qmm import DRAFT_QUANTS, draft_quant
++
++ self.dump = dump_dir() if drafter is not None and not serial_only else None
++ 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.dump is not None), quant_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)
+@@ -232,7 +240,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_DRAFT_DUMP, "
++ "TF_GLM_DRAFT_QUANT): "
+ 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:
+ self.e.pbuf.split.warm() # both ranks: open the send/receive connection now
+ if rank == 0:
+ print(f"[tensorfold] {self.split.describe()}", flush=True)
++ if 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)
++ if rank == 0 and quant_code:
++ print("[tensorfold] TF_GLM_DRAFT_QUANT=mse: DFlash2's 4-bit copies (and an EXL3 draft head) with "
++ "least-squares clipped ranges", flush=True)
+ 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:
+ 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)
++ elif self.dump is not None and drafter is not None: # serial's reply, the drafter's view recorded
++ from .draft_dump import dump_decode
++
++ meta = None if self.rank else dict(
++ prompt_tokens=len(prompt), cached=cut, policy=list(code), images=feed is not None,
++ prompt_sha256=hashlib.sha256(json.dumps(list(prompt)).encode()).hexdigest()[:16])
++ res = dump_decode(self.e, drafter, first, max_tokens, sampling, stop_eos=stop_eos, on_tokens=on_tokens,
++ out_dir=self.dump if self.rank == 0 else None, meta=meta)
++ if self.rank == 0:
++ stats["draft_dump"] = res.dump_path
+ elif auto:
+ 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
+--- 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:
+ return make_q4(words, scales.contiguous(), biases.contiguous())
+
+
++DRAFT_QUANTS = ("minmax", "mse")
++
++
++def draft_quant(value: str | None = None) -> str:
++ """TF_GLM_DRAFT_QUANT: how the draft-only 4-bit copies (DFlash2's matrices, an EXL3 checkpoint's draft head) are
++ made: minmax (the default: each group's full min / max range, ``quantize4``) or mse (the least-squares clipping of
++ ``quantize4_mse``). Drafts only propose, so either keeps every reply; only acceptance can move."""
++
++ import os
++
++ kind = os.environ.get("TF_GLM_DRAFT_QUANT", "") if value is None else value
++ kind = kind or "minmax"
++ if kind not in DRAFT_QUANTS:
++ raise ValueError(f"TF_GLM_DRAFT_QUANT is minmax or mse, not {kind!r}")
++ return kind
++
++
++def draft_quantize4(w: torch.Tensor, kind: str | None = None) -> Q4:
++ """A draft-only 4-bit copy of bf16 ``w`` by TF_GLM_DRAFT_QUANT (``draft_quant``); never used to verify."""
++
++ return quantize4_mse(w) if draft_quant(kind) == "mse" else quantize4(w)
++
++
+ def make_dense_q4(weight: torch.Tensor) -> "Q4 | F8":
+ 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
+--- 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
+
+ from .exl3_mm import Exl3Experts, words as exl3_words
+ from . import latent
+-from .qmm import B16, F8, Q4, as_i32, dense_kind, make_b16, make_f8, make_q4, quantize4, stack_b16, stack_f8, stack_q4
++from .qmm import (B16, F8, Q4, as_i32, dense_kind, draft_quantize4, make_b16, make_f8, make_q4, stack_b16, stack_f8,
++ stack_q4)
+
+ PREFIX = "model.language_model."
+
+@@ -425,7 +426,8 @@ def load(model_dir: str | Path, *, rank: int, device: str = "cuda") -> Weights:
+ if exl3:
+ raw = rd.get("lm_head.weight")[rank * vl:(rank + 1) * vl].to(dev)
+ head = dense(raw)
+- draft_head = quantize4(raw) # Draft steps use the quantized head; verification keeps the original head.
++ # Draft steps use a 4-bit copy (TF_GLM_DRAFT_QUANT: minmax or mse ranges); verification keeps the head.
++ draft_head = draft_quantize4(raw)
+ else:
+ hw, hs, hb = (rd.get("lm_head." + x) for x in ("weight", "scales", "biases"))
+ head = make_q4(as_i32(hw[rank * vl:(rank + 1) * vl]).to(dev), hs[rank * vl:(rank + 1) * vl].to(dev),
diff --git a/patches/0012-glm-kda-chunked.patch b/patches/0012-glm-kda-chunked.patch
new file mode 100644
index 0000000..3797206
--- /dev/null
+++ b/patches/0012-glm-kda-chunked.patch
@@ -0,0 +1,631 @@
+diff --git tensorfold/families/glm5_next/cuda/forward.py tensorfold/families/glm5_next/cuda/forward.py
+index dfd613b..c4c8ab3 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
+ 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])
++ st.rec[1 - cur, li], pos=st.pos if pre else None)
+ 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)
+diff --git tensorfold/families/glm5_next/cuda/kda.py tensorfold/families/glm5_next/cuda/kda.py
+index b4a8a60..9975ab1 100644
+--- tensorfold/families/glm5_next/cuda/kda.py
++++ tensorfold/families/glm5_next/cuda/kda.py
+@@ -2,6 +2,7 @@
+
+ from __future__ import annotations
+
++import os
+ from functools import lru_cache
+ from pathlib import Path
+
+@@ -56,6 +57,8 @@ def replay_layers(state_in: torch.Tensor, scratch: KDAScratchSet, rows: int, sta
+
+
+ WIDE_ROWS = 64 # windows of this many rows or more (prefill chunks) run the chain in three kernels
++# prompt chunks in chunked (WY) form, 64-row sub-chunks at absolute positions (kda_chunked.py): close, not the same bits
++CHUNKED = os.environ.get("TF_GLM_KDA_CHUNKED", "0") == "1"
+ _tmp: dict = {}
+
+
+@@ -73,9 +76,14 @@ def _wide_scratch(rows: int, heads: int, device) -> tuple[torch.Tensor, torch.Te
+ def chain(p: torch.Tensor, b_off: int, a: torch.Tensor, g: torch.Tensor, conv_state: torch.Tensor,
+ 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,
+- state_out: torch.Tensor, *, wide: bool | None = None) -> torch.Tensor:
+- """Run projection rows p [q | k | v | ... | b at b_off ...] and bf16 gate rows a and g; windows of WIDE_ROWS rows or more take the three-kernel path, same bits."""
++ state_out: torch.Tensor, *, wide: bool | None = None, pos: int | None = None) -> torch.Tensor:
++ """Run projection rows p [q | k | v | ... | b at b_off ...] and bf16 gate rows a and g; windows of WIDE_ROWS rows or more take the three-kernel path, same bits; a prompt chunk (``pos``: its first row's position) takes the chunked form under TF_GLM_KDA_CHUNKED=1 (scratch's k/v/g/b are not written)."""
+
++ if CHUNKED and pos is not None:
++ from . import kda_chunked
++
++ return kda_chunked.chain(p, b_off, a, g, conv_state, conv_w, state_in, a_log, dt_bias, norm_w, eps, lower,
++ rows, scratch.out, state_out, pos)
+ if wide if wide is not None else rows >= WIDE_ROWS:
+ q_tmp, y_tmp = _wide_scratch(rows, a_log.numel(), p.device)
+ _ext().chain_wide(p, p.stride(0), int(b_off), a, a.stride(0), g, g.stride(0), conv_state, conv_w, state_in,
+diff --git tensorfold/families/glm5_next/cuda/kda_chunked.py tensorfold/families/glm5_next/cuda/kda_chunked.py
+new file mode 100644
+index 0000000..0ee9823
+--- /dev/null
++++ tensorfold/families/glm5_next/cuda/kda_chunked.py
+@@ -0,0 +1,574 @@
++"""GLM-5.3-Flash's KDA prompt chunks in chunked (WY) form: sub-chunks of 64 rows at absolute positions, the
++intra-chunk part as matmuls, the 128 x 128 state carried from sub-chunk to sub-chunk.
++
++Per row the definition is kda.cu's (conv + SiLU rounded to bf16, fp32 L2 norms, q times 128^-0.5, beta =
++bf16(sigmoid(b)), log-decay l = lower * sigmoid(exp(A_log) * (a + dt_bias)) per key channel, the delta rule
++S <- S diag(e^l); S <- S + beta (v - S k) k^T; o = S q, o rounded to bf16, then the gated RMSNorm). The state S is
++[value, key] as in kda.cu.
++
++Sub-chunk of rows 0..63 (T = 64), entering state S0, G = cumsum(l) within the sub-chunk (per key channel, <= 0 and
++decreasing: every l is in (lower, 0) = (-5, 0)):
++
++ L[s, j] = beta_s sum_c k_s[c] k_j[c] e^(G_s[c] - G_j[c]) j < s (strictly lower)
++ M[s, j] = sum_c q_s[c] k_j[c] e^(G_s[c] - G_j[c]) j <= s
++ T = (I + L)^-1 (unit lower triangular)
++ W = T (beta * k * e^G), U = T (beta * v) the WY / UT transform
++ V' = U - W S0^T the corrected values ("v_new")
++ O = (q * e^G) S0^T + M V'
++ S_end = S0 diag(e^G_63) + V'^T (k * e^(G_63 - G))
++
++Every exponent above is <= 0 except inside L and M, which are formed as matmuls of row and column factors about a
++reference point: for the rows of 16-row block b, R = G at the block's first row; row factor e^(G_s - R) in
++[e^-75, 1] (15 steps of at most 5), column factor e^(R - G_j) <= 1 for earlier blocks and <= e^75 inside the block
++(< fp32's e^88.7); only blocks j <= b are formed. Their products are true decays (<= 1). T is inverted per 16-row
++diagonal block by forward substitution, then block rows are joined with matmuls (T_bj = -T_bb sum L_bm T_mj).
++Everything is fp32; the matmuls take tl.dot's ``input_precision`` (TF_GLM_KDA_PREC, default tf32x3, about fp32:
++~2e-6 relative against float64; "tf32" is faster and ~5e-4, half a bf16 step).
++
++Kernels (``chain``): _kda_lm (sub-chunk, head, block): the conv, norms, beta and decays of its rows, L and M rows,
++q e^G; _kda_solve (sub-chunk, head): T and the sub-chunk's total log-decay; _kda_wu (sub-chunk, head, block): W, U
++and the keys decayed to the sub-chunk's end; _kda_state (head, 16 value rows): the only sequential part, sub-chunk
++after sub-chunk, V' and the state entering each sub-chunk; _kda_out (sub-chunk, head): O, bf16, the gated RMSNorm.
++q, k, v, G are recomputed from the projection rows where needed rather than kept (registers) or stored (traffic).
++
++Sub-chunks start at absolute positions that are multiples of 64 (``pos`` gives the first row's position); a
++prompt chunk that starts mid-sub-chunk takes a short first sub-chunk (padded rows are zero rows: no decay, no
++key). A row's output depends only on its sub-chunk's rows and the state entering it, so it is the same whichever
++prefill chunk it came in, as long as chunk boundaries are multiples of 64 (a short last sub-chunk included).
++
++The torch functions (``*_reference``) are the CPU references of the tests; ``chain`` runs the Triton kernels.
++"""
++
++from __future__ import annotations
++
++import math
++import os
++
++import torch
++import triton
++import triton.language as tl
++
++DK = DV = 128
++TAPS = 4
++CHUNK = 64 # rows of a sub-chunk (the state is carried between sub-chunks)
++BLOCK = 16 # rows of a reference block inside a sub-chunk (16 x 5 = 80 < 88: no fp32 overflow)
++SCALE = 1.0 / math.sqrt(DK)
++
++
++# -- references (torch, CPU or GPU) ----------------------------------------------------------------------------
++def _bf(x: torch.Tensor) -> torch.Tensor:
++ return x.to(torch.bfloat16).to(x.dtype)
++
++
++def _sigmoid(x: torch.Tensor) -> torch.Tensor:
++ return 1.0 / (1.0 + torch.exp(-x))
++
++
++def prep_reference(p: torch.Tensor, b_off: int, a: torch.Tensor, conv_state: torch.Tensor, conv_w: torch.Tensor,
++ a_log: torch.Tensor, dt_bias: torch.Tensor, lower: float, rows: int):
++ """kda.cu's per-row work in fp32: q, k [rows, H, 128] normalized (q scaled), v [rows, H, 128] (bf16 values),
++ the log-decay l [rows, H, 128] (kda.cu's decay is e^l) and beta [rows, H]."""
++
++ H = a_log.numel()
++ C = 3 * H * DK
++ x = torch.cat([conv_state.float(), p[:rows, :C].float()])
++ w = conv_w.float()
++ acc = torch.zeros((rows, C), dtype=torch.float32, device=p.device)
++ for tap in range(TAPS):
++ acc = acc + w[:, tap] * x[tap:tap + rows]
++ act = _bf(acc / (1.0 + torch.exp(-acc))).view(rows, 3, H, DK)
++
++ def l2(t: torch.Tensor) -> torch.Tensor:
++ return t * (1.0 / torch.sqrt((t * t).sum(-1, keepdim=True) + 1e-6))
++
++ q = l2(act[:, 0]) * torch.tensor(SCALE, dtype=torch.float32)
++ k = l2(act[:, 1])
++ v = act[:, 2].contiguous()
++ rate = torch.exp(a_log.float()).view(1, H, 1)
++ ga = a[:rows].float().view(rows, H, DK) + dt_bias.float().view(1, H, DK)
++ lg = torch.tensor(lower, dtype=torch.float32) * _sigmoid(rate * ga)
++ beta = _bf(_sigmoid(p[:rows, b_off:b_off + H].float()))
++ return q, k, v, lg, beta
++
++
++def recurrent_reference(q, k, v, lg, beta, state, dtype=torch.float64):
++ """The delta rule row by row (kda.cu's chain): read-outs [rows, H, 128] and the final state [H, 128, 128]."""
++
++ q, k, v, beta = (t.to(dtype) for t in (q, k, v, beta))
++ g = torch.exp(lg.to(dtype))
++ S = state.to(dtype).clone()
++ out = torch.empty(v.shape, dtype=dtype, device=v.device)
++ for r in range(q.shape[0]):
++ S = S * g[r][:, None, :]
++ kv = (S * k[r][:, None, :]).sum(-1)
++ delta = (v[r] - kv) * beta[r][:, None]
++ S = S + delta[:, :, None] * k[r][:, None, :]
++ out[r] = (S * q[r][:, None, :]).sum(-1)
++ return out, S
++
++
++def tf32(x: torch.Tensor) -> torch.Tensor:
++ """fp32 -> TF32 (10 mantissa bits, round to nearest, ties away: cvt.rna.tf32.f32), as fp32."""
++
++ i = x.float().contiguous().view(torch.int32)
++ return ((i + 0x1000) & ~0x1FFF).view(torch.float32)
++
++
++def _tri_inverse(Ld: torch.Tensor) -> torch.Tensor:
++ """(I + Ld)^-1 for strictly lower Ld [..., n, n], by forward substitution a row at a time."""
++
++ n = Ld.shape[-1]
++ T = torch.eye(n, dtype=Ld.dtype, device=Ld.device).expand(Ld.shape).clone()
++ for s in range(1, n):
++ T[..., s, :] = -(Ld[..., s, :, None] * T).sum(-2)
++ T[..., s, s] = 1.0
++ return T
++
++
++def chunked_reference(q, k, v, lg, beta, state, pos: int = 0, dtype=torch.float64, mm_round=None, state_round=...):
++ """The chunked algorithm as the kernels run it (sub-chunks at absolute positions, reference blocks, the block
++ triangular inverse): read-outs [rows, H, 128] and the final state. ``mm_round`` rounds matmul inputs (``tf32``
++ emulates tl.dot's TF32 path), ``state_round`` those of the products with the state (default: ``mm_round``)."""
++
++ rows, H, _ = q.shape
++ dev = q.device
++ off = pos % CHUNK
++ nc = -(-(rows + off) // CHUNK)
++ total = nc * CHUNK
++
++ def pad(t):
++ t = t.to(dtype)
++ z = torch.zeros((total,) + tuple(t.shape[1:]), dtype=dtype, device=dev)
++ z[off:off + rows] = t
++ return z.view((nc, CHUNK) + tuple(t.shape[1:])).transpose(1, 2) # [nc, H, 64, ...]
++
++ qc, kc, vc, lc, bc = pad(q), pad(k), pad(v), pad(lg), pad(beta)
++ rnd = mm_round or (lambda x: x)
++ srnd = rnd if state_round is ... else (state_round or (lambda x: x))
++
++ def mm(x, y):
++ return rnd(x) @ rnd(y)
++
++ def mms(x, y):
++ return srnd(x) @ srnd(y)
++
++ t = torch.arange(CHUNK, device=dev)
++ lower_strict = t[:, None] > t[None, :]
++ lower_incl = t[:, None] >= t[None, :]
++ nb = CHUNK // BLOCK
++ S = state.to(dtype).clone() # [H, V, K]
++ out = torch.empty((total, H, DV), dtype=dtype, device=dev)
++ for c in range(nc):
++ qx, kx, vx, lx, bx = qc[c], kc[c], vc[c], lc[c], bc[c] # [H, 64, 128] (beta [H, 64])
++ G = torch.cumsum(lx, dim=1)
++ Akk = torch.zeros((H, CHUNK, CHUNK), dtype=dtype, device=dev)
++ Aqk = torch.zeros_like(Akk)
++ for b in range(nb):
++ rs = slice(b * BLOCK, (b + 1) * BLOCK)
++ R = G[:, b * BLOCK][:, None, :]
++ rf = torch.exp(G[:, rs] - R)
++ cols = (t < (b + 1) * BLOCK)[None, :, None]
++ cf = torch.where(cols, torch.exp(torch.where(cols, R - G, torch.zeros_like(G))), torch.zeros_like(G))
++ kt = (kx * cf).transpose(1, 2)
++ Akk[:, rs] = mm(kx[:, rs] * rf, kt)
++ Aqk[:, rs] = mm(qx[:, rs] * rf, kt)
++ L = torch.where(lower_strict, bx[:, :, None] * Akk, torch.zeros_like(Akk))
++ M = torch.where(lower_incl, Aqk, torch.zeros_like(Aqk))
++ T = torch.zeros_like(L)
++ for b in range(nb):
++ rs = slice(b * BLOCK, (b + 1) * BLOCK)
++ Tbb = _tri_inverse(L[:, rs, rs])
++ X = mm(L[:, rs, :b * BLOCK], T[:, :b * BLOCK, :]) if b else torch.zeros_like(T[:, rs])
++ T[:, rs] = -mm(Tbb, X)
++ T[:, rs, rs] = Tbb
++ eG = torch.exp(G)
++ W = mm(T, bx[:, :, None] * kx * eG)
++ U = mm(T, bx[:, :, None] * vx)
++ gl = G[:, -1:, :]
++ Ke = kx * torch.exp(gl - G)
++ Qt = qx * eG
++ ST = S.transpose(1, 2) # [H, K, V]
++ Vn = U - mms(W, ST)
++ out[c * CHUNK:(c + 1) * CHUNK] = (mms(Qt, ST) + mm(M, Vn)).transpose(0, 1)
++ S = S * torch.exp(gl) + mms(Vn.transpose(1, 2), Ke)
++ return out[off:off + rows], S
++
++
++def gate_norm_reference(y: torch.Tensor, gate: torch.Tensor, norm_w: torch.Tensor, eps: float) -> torch.Tensor:
++ """kda.cu's gated RMSNorm of bf16 read-outs y [rows, H, 128] with gate rows [rows, H * 128]: bf16 [rows, H*128]."""
++
++ rows, H, _ = y.shape
++ yb = _bf(y.float())
++ rinv = 1.0 / torch.sqrt((yb * yb).sum(-1, keepdim=True) / DV + eps)
++ yw = norm_w.float() * (yb * rinv)
++ return (yw * _sigmoid(gate[:rows].float().view(rows, H, DV))).to(torch.bfloat16).view(rows, H * DV)
++
++
++def chain_reference(p, b_off, a, g, conv_state, conv_w, state_in, a_log, dt_bias, norm_w, eps, lower, rows, *,
++ pos: int = 0, chunked: bool = True, dtype=torch.float32, mm_round=None):
++ """A whole prompt chunk: (out bf16 [rows, H * 128], final state fp32 [H, 128, 128], read-outs y [rows, H, 128])."""
++
++ q, k, v, lg, beta = prep_reference(p, b_off, a, conv_state, conv_w, a_log, dt_bias, lower, rows)
++ if chunked:
++ y, S = chunked_reference(q, k, v, lg, beta, state_in, pos, dtype=dtype, mm_round=mm_round)
++ else:
++ y, S = recurrent_reference(q, k, v, lg, beta, state_in, dtype=dtype)
++ return gate_norm_reference(y, g, norm_w, eps), S.float(), y
++
++
++# -- Triton kernels ---------------------------------------------------------------------------------------------
++def _bf16(x):
++ """fp32 rounded to bf16 (to nearest even), as fp32: bit arithmetic, so Triton's CPU interpreter (which truncates
++ in casts) rounds as the GPU does."""
++ b = x.to(tl.uint32, bitcast=True)
++ b = (b + 0x7FFF + ((b >> 16) & 1)) & 0xFFFF0000
++ return b.to(tl.float32, bitcast=True)
++
++
++def _conv_act(P, p_stride, CS, CW, r, valid, ch, C3, BT: tl.constexpr, DK_: tl.constexpr, TAPS_: tl.constexpr):
++ """Depthwise conv over [conv state; P rows] of channels ch for rows r, SiLU, rounded to bf16: [BT, DK] fp32."""
++
++ acc = tl.zeros((BT, DK_), dtype=tl.float32)
++ for tap in tl.static_range(TAPS_):
++ at = r + (tap - (TAPS_ - 1)) # P row (negative: conv state row at + TAPS - 1)
++ from_p = valid & (at >= 0)
++ from_s = valid & (at < 0)
++ xp = tl.load(P + at.to(tl.int64)[:, None] * p_stride + ch[None, :], mask=from_p[:, None], other=0.0)
++ xs = tl.load(CS + (at + (TAPS_ - 1)).to(tl.int64)[:, None] * C3 + ch[None, :], mask=from_s[:, None],
++ other=0.0)
++ x = tl.where(from_s[:, None], xs.to(tl.float32), xp.to(tl.float32))
++ wt = tl.load(CW + ch * TAPS_ + tap).to(tl.float32)
++ acc = acc + wt[None, :] * x
++ act = acc / (1.0 + tl.exp(-acc))
++ return _bf16(act)
++
++
++def _l2(x):
++ ss = tl.sum(x * x, axis=1)
++ return x * (1.0 / tl.sqrt_rn(ss + 1e-6))[:, None]
++
++
++def _row(x, t, s):
++ """Row s of x [n, N] as [N] (a sum with zeros: exact)."""
++ return tl.sum(tl.where((t == s)[:, None], x, 0.0), axis=0)
++
++
++def _tri_inv(Ld, BC: tl.constexpr):
++ """(I + Ld)^-1 of a strictly lower [BC, BC] block by forward substitution."""
++
++ i = tl.arange(0, BC)
++ T = tl.where(i[:, None] == i[None, :], 1.0, 0.0)
++ for s in range(1, BC):
++ lrow = tl.sum(tl.where((i == s)[:, None], Ld, 0.0), axis=0) # Ld[s, :]
++ trow = -tl.sum(lrow[:, None] * T, axis=0) # -sum_m Ld[s, m] T[m, :]
++ T = tl.where((i == s)[:, None], trow[None, :] + tl.where(i == s, 1.0, 0.0)[None, :], T)
++ return T
++
++
++def _dot_k(a, b, NS: tl.constexpr, PREC: tl.constexpr):
++ """a [M, K] @ b [K, N] as a batched dot over NS slices of K, summed: with M = N = 16 a warp then holds a slice of
++ the operands instead of all of K."""
++ M: tl.constexpr = a.shape[0]
++ K: tl.constexpr = a.shape[1]
++ N: tl.constexpr = b.shape[1]
++ a3 = tl.permute(tl.reshape(a, (M, NS, K // NS)), (1, 0, 2))
++ b3 = tl.reshape(b, (NS, K // NS, N))
++ return tl.sum(tl.dot(a3, b3, input_precision=PREC), axis=0)
++
++
++def _gates(A, a_stride, r, valid, hd, ch, rate, dtb, lower, carry):
++ """G for rows r: carry (the running log-decay before them) + their running sum; zero rows outside the chunk."""
++ av = tl.load(A + r.to(tl.int64)[:, None] * a_stride + hd + ch[None, :], mask=valid[:, None], other=0.0)
++ lg = lower * (1.0 / (1.0 + tl.exp(-(rate * (av.to(tl.float32) + dtb[None, :])))))
++ return carry[None, :] + tl.cumsum(tl.where(valid[:, None], lg, 0.0), axis=0)
++
++
++def _beta(P, p_stride, b_off, h, r, valid):
++ braw = tl.load(P + r.to(tl.int64) * p_stride + b_off + h, mask=valid, other=0.0).to(tl.float32)
++ return tl.where(valid, _bf16(1.0 / (1.0 + tl.exp(-braw))), 0.0)
++
++
++def _kda_lm(P, p_stride, b_off, A, a_stride, CS, CW, ALOG, DTB, lower, rows, off, H, QT, L, M,
++ DK_: tl.constexpr, BT: tl.constexpr, BC: tl.constexpr, TAPS_: tl.constexpr, KSPLIT: tl.constexpr,
++ PREC: tl.constexpr):
++ """Program (sub-chunk, head, 16-row block b): block b's rows of L (beta k k decays, strictly lower) and M (q k
++ decays, with the diagonal) against blocks j <= b, and its decayed q (QT = q e^G). Rows outside the prompt chunk
++ are zero rows (no decay, no key). The products are taken about R = G at block b's first row: row factors
++ e^(G - R) in [e^-75, 1], column factors e^(R - G_j) <= 1 for j < b and <= e^75 for j = b (< fp32's e^88.7)."""
++
++ c = tl.program_id(0)
++ h = tl.program_id(1)
++ b = tl.program_id(2)
++ i = tl.arange(0, BC)
++ ch = tl.arange(0, DK_)
++ C3 = 3 * H * DK_
++ hd = h * DK_
++ rate = tl.exp(tl.load(ALOG + h))
++ dtb = tl.load(DTB + hd + ch)
++ r0 = c * BT - off
++ tile = (c.to(tl.int64) * H + h) * BT * BT + (b * BC + i)[:, None] * BT + i[None, :] # + j * BC: tile (b, j)
++
++ carry = tl.zeros((DK_,), dtype=tl.float32)
++ for j in range(0, b):
++ rj = r0 + j * BC + i
++ carry = _row(_gates(A, a_stride, rj, (rj >= 0) & (rj < rows), hd, ch, rate, dtb, lower, carry), i, BC - 1)
++ r = r0 + b * BC + i
++ valid = (r >= 0) & (r < rows)
++ G = _gates(A, a_stride, r, valid, hd, ch, rate, dtb, lower, carry)
++ k = _l2(_conv_act(P, p_stride, CS, CW, r, valid, H * DK_ + hd + ch, C3, BC, DK_, TAPS_))
++ q = _l2(_conv_act(P, p_stride, CS, CW, r, valid, hd + ch, C3, BC, DK_, TAPS_)) * 0.08838834764831845
++ rowbase = (r.to(tl.int64) * H + h) * DK_
++ tl.store(QT + rowbase[:, None] + ch[None, :], q * tl.exp(G), mask=valid[:, None])
++ beta = _beta(P, p_stride, b_off, h, r, valid)
++ R = _row(G, i, 0)
++ rf = tl.exp(G - R[None, :])
++ rk = k * rf
++ rq = q * rf
++
++ col = tl.trans(k * tl.exp(R[None, :] - G)) # the diagonal tile
++ akk = tl.where(i[:, None] > i[None, :], _dot_k(rk, col, KSPLIT, PREC), 0.0)
++ aqk = tl.where(i[:, None] >= i[None, :], _dot_k(rq, col, KSPLIT, PREC), 0.0)
++ tl.store(L + tile + b * BC, beta[:, None] * akk)
++ tl.store(M + tile + b * BC, aqk)
++ carry = tl.zeros((DK_,), dtype=tl.float32)
++ for j in range(0, b):
++ rj = r0 + j * BC + i
++ vj = (rj >= 0) & (rj < rows)
++ Gj = _gates(A, a_stride, rj, vj, hd, ch, rate, dtb, lower, carry)
++ carry = _row(Gj, i, BC - 1)
++ kj = _l2(_conv_act(P, p_stride, CS, CW, rj, vj, H * DK_ + hd + ch, C3, BC, DK_, TAPS_))
++ col = tl.trans(kj * tl.exp(R[None, :] - Gj)) # [DK, BC]
++ tl.store(L + tile + j * BC, beta[:, None] * _dot_k(rk, col, KSPLIT, PREC))
++ tl.store(M + tile + j * BC, _dot_k(rq, col, KSPLIT, PREC))
++
++
++def _kda_solve(A, a_stride, ALOG, DTB, lower, rows, off, H, L, T, GL,
++ DK_: tl.constexpr, BT: tl.constexpr, BC: tl.constexpr, PREC: tl.constexpr):
++ """Program (sub-chunk, head): T = (I + L)^-1 in 16-row blocks (T_bb by forward substitution, T_bj = -T_bb
++ sum_{j<=m<b} L_bm T_mj), and the sub-chunk's total log-decay GL."""
++
++ NB: tl.constexpr = BT // BC
++ c = tl.program_id(0)
++ h = tl.program_id(1)
++ i = tl.arange(0, BC)
++ ch = tl.arange(0, DK_)
++ hd = h * DK_
++ base = (c.to(tl.int64) * H + h) * BT * BT
++ Ts = ()
++ for b in tl.static_range(NB):
++ Lrow = ()
++ for j in tl.static_range(b + 1):
++ Lrow = Lrow + (tl.load(L + base + (b * BC + i)[:, None] * BT + j * BC + i[None, :]),)
++ Tbb = _tri_inv(Lrow[b], BC)
++ Trow = ()
++ for j in tl.static_range(b):
++ X = tl.zeros((BC, BC), dtype=tl.float32)
++ for m in tl.static_range(j, b):
++ X += tl.dot(Lrow[m], Ts[m][j], input_precision=PREC)
++ Trow = Trow + (-tl.dot(Tbb, X, input_precision=PREC),)
++ Trow = Trow + (Tbb,)
++ Ts = Ts + (Trow,)
++ for j in tl.static_range(b + 1):
++ tl.store(T + base + (b * BC + i)[:, None] * BT + j * BC + i[None, :], Trow[j])
++ rate = tl.exp(tl.load(ALOG + h))
++ dtb = tl.load(DTB + hd + ch)
++ carry = tl.zeros((DK_,), dtype=tl.float32)
++ for b in range(0, NB):
++ r = c * BT - off + b * BC + i
++ carry = _row(_gates(A, a_stride, r, (r >= 0) & (r < rows), hd, ch, rate, dtb, lower, carry), i, BC - 1)
++ tl.store(GL + (c.to(tl.int64) * H + h) * DK_ + ch, carry)
++
++
++def _kda_wu(P, p_stride, b_off, A, a_stride, CS, CW, ALOG, DTB, lower, rows, off, H, T, GL, W, U, KE,
++ DK_: tl.constexpr, BT: tl.constexpr, BC: tl.constexpr, TAPS_: tl.constexpr, PREC: tl.constexpr):
++ """Program (sub-chunk, head, 16-row block b): W_b = sum_{j<=b} T_bj (beta k e^G)_j, U_b = sum_{j<=b} T_bj
++ (beta v)_j (the WY / UT transform), and block b's keys decayed to the sub-chunk's end (KE = k e^(GL - G))."""
++
++ c = tl.program_id(0)
++ h = tl.program_id(1)
++ b = tl.program_id(2)
++ i = tl.arange(0, BC)
++ ch = tl.arange(0, DK_)
++ C3 = 3 * H * DK_
++ hd = h * DK_
++ rate = tl.exp(tl.load(ALOG + h))
++ dtb = tl.load(DTB + hd + ch)
++ r0 = c * BT - off
++ gl = tl.load(GL + (c.to(tl.int64) * H + h) * DK_ + ch)
++ tbase = (c.to(tl.int64) * H + h) * BT * BT + (b * BC + i)[:, None] * BT + i[None, :]
++ rb = r0 + b * BC + i
++ vb = (rb >= 0) & (rb < rows)
++ rowbase = (rb.to(tl.int64) * H + h) * DK_
++ wv = tl.zeros((BC, DK_), dtype=tl.float32)
++ uv = tl.zeros((BC, DK_), dtype=tl.float32)
++ carry = tl.zeros((DK_,), dtype=tl.float32)
++ for j in range(0, b + 1):
++ rj = r0 + j * BC + i
++ vj = (rj >= 0) & (rj < rows)
++ Gj = _gates(A, a_stride, rj, vj, hd, ch, rate, dtb, lower, carry)
++ carry = _row(Gj, i, BC - 1)
++ kj = _l2(_conv_act(P, p_stride, CS, CW, rj, vj, H * DK_ + hd + ch, C3, BC, DK_, TAPS_))
++ tl.store(KE + rowbase[:, None] + ch[None, :], kj * tl.exp(gl[None, :] - Gj), mask=(vb & (j == b))[:, None])
++ bj = _beta(P, p_stride, b_off, h, rj, vj)
++ vv = _conv_act(P, p_stride, CS, CW, rj, vj, 2 * H * DK_ + hd + ch, C3, BC, DK_, TAPS_)
++ tbj = tl.load(T + tbase + j * BC)
++ wv += tl.dot(tbj, bj[:, None] * kj * tl.exp(Gj), input_precision=PREC)
++ uv += tl.dot(tbj, bj[:, None] * vv, input_precision=PREC)
++ tl.store(W + rowbase[:, None] + ch[None, :], wv, mask=vb[:, None])
++ tl.store(U + rowbase[:, None] + ch[None, :], uv, mask=vb[:, None])
++
++
++def _kda_state(S_IN, S_OUT, W, U, KE, GL, HB, rows, off, NC, H,
++ DK_: tl.constexpr, DV_: tl.constexpr, BT: tl.constexpr, BC: tl.constexpr, BV: tl.constexpr,
++ PREC: tl.constexpr):
++ """Program (head, value tile): the state S [BV value rows, K] from sub-chunk to sub-chunk (the only sequential
++ part), BC rows at a time: V'^T = U^T - S W^T (written over U), S <- S diag(e^GL) + V'^T KE. Saves each
++ sub-chunk's entering state (HB [NC, H, V, K], the state's layout)."""
++
++ h = tl.program_id(0)
++ v0 = tl.program_id(1) * BV
++ ki = tl.arange(0, DK_)
++ vi = v0 + tl.arange(0, BV)
++ i = tl.arange(0, BC)
++ sbase = h.to(tl.int64) * DV_ * DK_
++ S = tl.load(S_IN + sbase + vi[:, None] * DK_ + ki[None, :]) # [BV, K]
++ for c in range(NC):
++ cb = (c * H + h).to(tl.int64)
++ tl.store(HB + cb * DV_ * DK_ + vi[:, None] * DK_ + ki[None, :], S)
++ nxt = S * tl.exp(tl.load(GL + cb * DK_ + ki))[None, :]
++ for b in tl.static_range(BT // BC):
++ r = c * BT - off + b * BC + i
++ valid = (r >= 0) & (r < rows)
++ rowbase = (r.to(tl.int64) * H + h) * DK_
++ wb = tl.load(W + rowbase[:, None] + ki[None, :], mask=valid[:, None], other=0.0) # [BC, K]
++ ub = tl.load(U + rowbase[:, None] + vi[None, :], mask=valid[:, None], other=0.0) # [BC, BV]
++ vnt = tl.trans(ub) - tl.dot(S, tl.trans(wb), input_precision=PREC) # [BV, BC]
++ tl.store(U + rowbase[:, None] + vi[None, :], tl.trans(vnt), mask=valid[:, None])
++ kb = tl.load(KE + rowbase[:, None] + ki[None, :], mask=valid[:, None], other=0.0) # [BC, K]
++ nxt += tl.dot(vnt, kb, input_precision=PREC)
++ S = nxt
++ tl.store(S_OUT + sbase + vi[:, None] * DK_ + ki[None, :], S)
++
++
++def _kda_out(QT, U, M, HB, G, g_stride, NW, eps, OUT, rows, off, H,
++ DK_: tl.constexpr, DV_: tl.constexpr, BT: tl.constexpr, BC: tl.constexpr, KS: tl.constexpr,
++ PREC: tl.constexpr):
++ """Program (sub-chunk, head): read-outs O = QT S0^T + M V' rounded to bf16, then the gated RMSNorm."""
++
++ c = tl.program_id(0)
++ h = tl.program_id(1)
++ t = tl.arange(0, BT)
++ i = tl.arange(0, BC)
++ ks = tl.arange(0, KS)
++ vi = tl.arange(0, DV_)
++ r = c * BT - off + t
++ valid = (r >= 0) & (r < rows)
++ rowbase = (r.to(tl.int64) * H + h) * DK_
++ cb = (c * H + h).to(tl.int64)
++ o = tl.zeros((BT, DV_), dtype=tl.float32)
++ for k0 in tl.static_range(0, DK_, KS):
++ qt = tl.load(QT + rowbase[:, None] + k0 + ks[None, :], mask=valid[:, None], other=0.0) # [BT, KS]
++ hs = tl.load(HB + cb * DV_ * DK_ + vi[:, None] * DK_ + k0 + ks[None, :]) # [DV, KS]
++ o += tl.dot(qt, tl.trans(hs), input_precision=PREC)
++ for j in tl.static_range(BT // BC):
++ mq = tl.load(M + cb * BT * BT + t[:, None] * BT + (j * BC + i)[None, :], mask=(t >= j * BC)[:, None],
++ other=0.0) # tiles above the diagonal: 0
++ rj = c * BT - off + j * BC + i
++ vn = tl.load(U + ((rj.to(tl.int64) * H + h) * DK_)[:, None] + vi[None, :],
++ mask=((rj >= 0) & (rj < rows))[:, None], other=0.0)
++ o += tl.dot(mq, vn, input_precision=PREC)
++ y = _bf16(o)
++ rinv = 1.0 / tl.sqrt_rn(tl.sum(y * y, axis=1) / DV_ + eps)
++ yw = tl.load(NW + vi).to(tl.float32)[None, :] * (y * rinv[:, None])
++ gate = tl.load(G + r.to(tl.int64)[:, None] * g_stride + h * DV_ + vi[None, :], mask=valid[:, None], other=0.0)
++ res = yw * (1.0 / (1.0 + tl.exp(-gate.to(tl.float32))))
++ tl.store(OUT + r.to(tl.int64)[:, None] * (H * DV_) + h * DV_ + vi[None, :], _bf16(res).to(tl.bfloat16),
++ mask=valid[:, None])
++
++
++# -- launcher ---------------------------------------------------------------------------------------------------
++PREC = os.environ.get("TF_GLM_KDA_PREC", "tf32x3") # tl.dot input precision: tf32x3 (~fp32), tf32, ieee
++BV = int(os.environ.get("TF_GLM_KDA_BV", "16")) # value rows of the state per sequential program
++STATE_ROWS = int(os.environ.get("TF_GLM_KDA_STATE_ROWS", "32")) # rows per step of the sequential kernel
++KSPLIT = int(os.environ.get("TF_GLM_KDA_KSPLIT", "4")) # K slices of the 16 x 16 x 128 products (1: one dot)
++_scratch: dict = {}
++
++
++class ChunkScratch:
++ """Intermediates of a prompt chunk of up to ``rows`` rows (one set per head count and device, shared by layers)."""
++
++ def __init__(self, rows: int, heads: int, device) -> None:
++ f32 = torch.float32
++ nc = -(-(rows + CHUNK - 1) // CHUNK) # room for a short first sub-chunk
++ self.rows, self.nc = rows, nc
++ self.qt = torch.empty((rows, heads, DK), dtype=f32, device=device)
++ self.w = torch.empty((rows, heads, DK), dtype=f32, device=device)
++ self.u = torch.empty((rows, heads, DV), dtype=f32, device=device)
++ self.ke = torch.empty((rows, heads, DK), dtype=f32, device=device)
++ self.m = torch.empty((nc, heads, CHUNK, CHUNK), dtype=f32, device=device)
++ self.l = torch.empty((nc, heads, CHUNK, CHUNK), dtype=f32, device=device)
++ self.t = torch.empty((nc, heads, CHUNK, CHUNK), dtype=f32, device=device)
++ self.gl = torch.empty((nc, heads, DK), dtype=f32, device=device)
++ self.hb = torch.empty((nc, heads, DV, DK), dtype=f32, device=device)
++
++
++def scratch_for(rows: int, heads: int, device) -> ChunkScratch:
++ key = (heads, str(device))
++ s = _scratch.get(key)
++ if s is None or s.rows < rows:
++ s = ChunkScratch(max(rows, CHUNK), heads, device)
++ _scratch[key] = s
++ return s
++
++
++def chain(p: torch.Tensor, b_off: int, a: torch.Tensor, g: torch.Tensor, conv_state: torch.Tensor,
++ 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, out: torch.Tensor, state_out: torch.Tensor,
++ pos: int = 0, *, prec: str | None = None, bv: int | None = None) -> torch.Tensor:
++ """kda.chain for a prompt chunk in chunked form: projection rows p [q | k | v | ... | b at b_off ...], bf16 gate
++ rows a (decay) and g (output gate), conv state [3, 3 H 128] (read, not shifted), state_in -> state_out
++ [H, 128, 128]; ``pos`` is the first row's absolute position. Writes out[:rows] (bf16 [rows, H * 128])."""
++
++ H = a_log.numel()
++ rows = int(rows)
++ if rows < 1 or p.shape[0] < rows or out.shape[0] < rows:
++ raise ValueError("rows")
++ if conv_w.shape != (3 * H * DK, TAPS) or conv_state.shape[0] != TAPS - 1:
++ raise ValueError("the chunked KDA path is written for 4-tap convolutions of 3 x H x 128 channels")
++ for x in (conv_state, conv_w, state_in, state_out, out, dt_bias, a_log, norm_w):
++ if not x.is_contiguous():
++ raise ValueError("conv state, conv weight, states, out and the per-head weights must be contiguous")
++ if p.stride(1) != 1 or a.stride(1) != 1 or g.stride(1) != 1:
++ raise ValueError("projection and gate rows must be contiguous along the channels")
++ prec = prec or PREC
++ bv = bv or BV
++ off = int(pos) % CHUNK
++ nc = -(-(rows + off) // CHUNK)
++ s = scratch_for(rows, H, p.device)
++ nb = CHUNK // BLOCK
++ _kda_lm[(nc, H, nb)](p, p.stride(0), int(b_off), a, a.stride(0), conv_state, conv_w, a_log, dt_bias, float(lower),
++ rows, off, H, s.qt, s.l, s.m,
++ DK_=DK, BT=CHUNK, BC=BLOCK, TAPS_=TAPS, KSPLIT=KSPLIT, PREC=prec, num_warps=4)
++ _kda_solve[(nc, H)](a, a.stride(0), a_log, dt_bias, float(lower), rows, off, H, s.l, s.t, s.gl,
++ DK_=DK, BT=CHUNK, BC=BLOCK, PREC=prec, num_warps=4)
++ _kda_wu[(nc, H, nb)](p, p.stride(0), int(b_off), a, a.stride(0), conv_state, conv_w, a_log, dt_bias, float(lower),
++ rows, off, H, s.t, s.gl, s.w, s.u, s.ke,
++ DK_=DK, BT=CHUNK, BC=BLOCK, TAPS_=TAPS, PREC=prec, num_warps=4)
++ _kda_state[(H, DV // bv)](state_in, state_out, s.w, s.u, s.ke, s.gl, s.hb, rows, off, nc, H,
++ DK_=DK, DV_=DV, BT=CHUNK, BC=STATE_ROWS, BV=bv, PREC=prec, num_warps=8, num_stages=1)
++ _kda_out[(nc, H)](s.qt, s.u, s.m, s.hb, g, g.stride(0), norm_w, float(eps), out, rows, off, H,
++ DK_=DK, DV_=DV, BT=CHUNK, BC=BLOCK, KS=32, PREC=prec, num_warps=8)
++ return out[:rows]
diff --git a/patches/0013-glm-decode-rounds.patch b/patches/0013-glm-decode-rounds.patch
new file mode 100644
index 0000000..486eedf
--- /dev/null
+++ b/patches/0013-glm-decode-rounds.patch
@@ -0,0 +1,831 @@
+diff --git tensorfold/cuda/geometry.py tensorfold/cuda/geometry.py
+index 908f94e..82b565f 100644
+--- tensorfold/cuda/geometry.py
++++ tensorfold/cuda/geometry.py
+@@ -7,6 +7,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)
+
+
+ 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
+ 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
+- 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)
+ fixed += linear * rows * (3 * lh * ld + 2 * ld + lh) * 2
+ fixed += linear * rows * lh * (12 * ld + 4)
+diff --git tensorfold/families/glm5_next/cuda/copy_drafts.py tensorfold/families/glm5_next/cuda/copy_drafts.py
+index 25e4be7..3aa3b25 100644
+--- tensorfold/families/glm5_next/cuda/copy_drafts.py
++++ tensorfold/families/glm5_next/cuda/copy_drafts.py
+@@ -16,7 +16,7 @@ from typing import Sequence
+ import numpy as np
+
+ MATCH = 8 # the context's last this many tokens must have occurred before (TF_GLM_COPY_MATCH)
+-MOST = 5 # drafts a round: 5 keeps the verify window (6 rows) within the captured graphs (TF_GLM_COPY_MAX)
++MOST = 5 # drafts a round (TF_GLM_COPY_MAX, up to 15): graphs cover windows of 8 rows, wider ones run eagerly
+
+
+ @dataclass(frozen=True)
+diff --git tensorfold/families/glm5_next/cuda/decode.py tensorfold/families/glm5_next/cuda/decode.py
+index 0591d9f..52a5182 100644
+--- tensorfold/families/glm5_next/cuda/decode.py
++++ tensorfold/families/glm5_next/cuda/decode.py
+@@ -84,9 +84,11 @@ class Engine:
+
+ def __init__(self, w: Weights, *, capacity: int = 2560, max_rows: int = 8, prefill_rows: int = PREFILL_ROWS,
+ graphs: bool = False, graph_rows: tuple[int, ...] = (1, 2, 3, 4), long_context: bool = False,
+- taps: tuple[int, ...] = (), grid: int = 0, split=None) -> None:
++ taps: tuple[int, ...] = (), grid: int = 0, split=None, mtp_rows: int | None = None) -> None:
+ """``grid``: prompt chunks start on multiples of it (TF_GLM_PROMPT_GRID; 0: anywhere); ``split``: a
+- ``hcsplit.SplitSettings`` (TF_GLM_HC_SPLIT, TF_GLM_PREFILL_OVERLAP) for prompt chunks, None or off: unsplit."""
++ ``hcsplit.SplitSettings`` (TF_GLM_HC_SPLIT, TF_GLM_PREFILL_OVERLAP) for prompt chunks, None or off: unsplit;
++ ``mtp_rows``: rows of an MTP step (its absorb chunks; default ``max_rows``): draft chains take one row a step,
++ so the MTP buffers need not be as wide as the verify windows."""
+
+ if grid and prefill_rows % grid:
+ raise ValueError(f"prompt chunks of {prefill_rows} rows do not tile a {grid}-row grid")
+@@ -103,7 +105,7 @@ class Engine:
+ from .hcsplit import HcSplit
+
+ self.pbuf.split = HcSplit(w, self.pbuf, split)
+- self.mbuf = Buffers(w, max_rows, capacity) if w.mtp is not None else None
++ self.mbuf = Buffers(w, min(mtp_rows or max_rows, max_rows), capacity) if w.mtp is not None else None
+ self.st = State(w, capacity, max_rows)
+ self.last_hidden: torch.Tensor | None = None
+ self.constraint = self.window = None # a request's grammar, and the next sample's rows under it
+@@ -113,7 +115,8 @@ class Engine:
+ if graphs:
+ from .graphs import Graphs
+
+- self.graphs = Graphs(self, graph_rows, graph_rows)
++ mtp_graphs = tuple(r for r in graph_rows if self.mbuf is None or r <= self.mbuf.rows)
++ self.graphs = Graphs(self, tuple(r for r in graph_rows if r <= max_rows), mtp_graphs)
+ self.reset()
+
+ def reset(self) -> None:
+@@ -390,6 +393,8 @@ class DecodeResult:
+ rounds: int
+ drafted: int = 0
+ accepted: int = 0
++ # seconds by stage: "forward" the verify windows' GPU time (CUDA events), "sample" from a window's launch to its
++ # tokens (waiting for the window included: no sync of its own), "draft" and "commit" host time
+ 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:
+ torch.cuda.synchronize()
+
+
++class _Clock:
++ """A verify window's GPU time between two CUDA events, read after the round's sample has waited for the window
++ anyway (so timing adds no host-device sync); wall time where there is no GPU (the CPU tests' fake engines)."""
++
++ def __init__(self) -> None:
++ self.cuda = torch.cuda.is_available()
++ if self.cuda:
++ self.a = torch.cuda.Event(enable_timing=True)
++ self.b = torch.cuda.Event(enable_timing=True)
++ self.t = self.dt = 0.0
++
++ def start(self) -> None:
++ if self.cuda:
++ self.a.record()
++ else:
++ self.t = time.perf_counter()
++
++ def stop(self) -> None:
++ if self.cuda:
++ self.b.record()
++ else:
++ self.dt = time.perf_counter() - self.t
++
++ def seconds(self) -> float:
++ """Only after something has waited for the work queued before ``stop`` (the sample's device-to-host copy)."""
++ return self.a.elapsed_time(self.b) / 1e3 if self.cuda else self.dt
++
++
++class _Late:
++ """``on_tokens`` one round late: a round's tokens go to the caller once the next verify window is queued on the
++ GPU (``flush`` right after ``Engine.forward``), so the server's work on them (detokenizing, stop strings, the
++ stream write) runs while the GPU verifies instead of between rounds, where the GPU would wait for it. The loops
++ never read on_tokens' result (both ranks decode to the end), so only when the tokens arrive changes: one round
++ later, all of them before the loop returns (``flush`` again at its end)."""
++
++ def __init__(self, on_tokens) -> None:
++ self.fn, self.held = on_tokens, None
++
++ def __call__(self, tokens) -> None:
++ if self.fn is not None:
++ self.flush()
++ self.held = list(tokens)
++
++ def flush(self) -> None:
++ if self.held is not None:
++ held, self.held = self.held, None
++ self.fn(held)
++
++
+ @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
+ w, st, b = e.w, e.st, e.buf
+ out = [pending]
+ stages = dict(forward=0.0, sample=0.0, commit=0.0)
++ clock, late = _Clock(), _Late(on_tokens)
+ _sync(w)
+ start = time.perf_counter()
+ while len(out) < count and not (stop_eos and out[-1] in w.cfg.eos):
+- t0 = time.perf_counter()
++ clock.start()
+ logits = e.forward(e.verify_window([out[-1]]))
+- torch.cuda.synchronize()
++ clock.stop()
++ late.flush() # the last step's token, while this step runs
+ t1 = time.perf_counter()
+ tok = e.sample(logits[:1], [st.pos + 1], sampling)[0]
+ e.follow([tok])
+ t2 = time.perf_counter()
+ commit(w, st, b, 1, 1)
+ t3 = time.perf_counter()
+- stages["forward"] += t1 - t0
++ stages["forward"] += clock.seconds()
+ stages["sample"] += t2 - t1
+ stages["commit"] += t3 - t2
+ out.append(tok)
+- if on_tokens is not None:
+- on_tokens([tok])
++ late([tok])
++ late.flush()
+ _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, *
+ c_rounds = c_drafted = c_accepted = 0
+ depths: list[int] = []
+ keeps: list[int] = []
++ clock, late = _Clock(), _Late(on_tokens)
+ _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, *
+ 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):
+- t0 = time.perf_counter()
+ tokens = e.verify_window([out[-1]] + drafts)
+ drafts = tokens[1:]
+ R = len(tokens)
++ clock.start()
+ logits = e.forward(tokens)
+- torch.cuda.synchronize()
++ clock.stop()
++ late.flush() # the last round's tokens, while this window runs
+ 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, *
+ out.extend(sampled[:keep])
+ if copies is not None:
+ copies.extend(sampled[:keep])
+- if on_tokens is not None:
+- on_tokens(sampled[:keep][:max(0, count - (len(out) - keep))])
+- stages["forward"] += t1 - t0
++ late(sampled[:keep][:max(0, count - (len(out) - keep))])
++ stages["forward"] += clock.seconds()
+ 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, *
+ 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
++ late.flush()
+ _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
+ c_rounds = c_drafted = c_accepted = 0
+ depths: list[int] = []
+ keeps: list[int] = []
++ clock, late = _Clock(), _Late(on_tokens)
+ _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
+ tokens = e.verify_window([out[-1]] + drafts)
+ drafts = tokens[1:]
+ R = len(tokens)
++ clock.start()
+ logits = e.forward(tokens)
+- torch.cuda.synchronize()
++ clock.stop()
++ late.flush() # the last round's tokens, while this window runs
+ 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
+ out.extend(sampled[:keep])
+ if copies is not None:
+ copies.extend(sampled[:keep])
+- if on_tokens is not None:
+- on_tokens(sampled[:keep][:max(0, count - (len(out) - keep))])
++ late(sampled[:keep][:max(0, count - (len(out) - keep))])
+ stages["draft"] += (t1 - t0) + (t5 - t4)
+- stages["forward"] += t2 - t1
++ stages["forward"] += clock.seconds()
+ stages["sample"] += t3 - t2
+ stages["commit"] += t4 - t3
+ # a copied round's acceptance does not move DFlash2's depth
+ depth = min(policy.next(*((0, 0) if copied else (len(drafts), keep - 1))), count - len(out))
++ late.flush()
+ _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)
+diff --git tensorfold/families/glm5_next/cuda/dflash2.py tensorfold/families/glm5_next/cuda/dflash2.py
+index a6ee808..427d7f6 100644
+--- tensorfold/families/glm5_next/cuda/dflash2.py
++++ tensorfold/families/glm5_next/cuda/dflash2.py
+@@ -166,7 +166,11 @@ class DraftLayer:
+ 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:
++ """``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)."""
++
+ path = Path(draft_dir)
+ cfg = json.loads((path / "config.json").read_text())
+ dc = cfg["dflash_config"]
+@@ -252,11 +256,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)
+- self.packed: torch.Tensor | None = None # [world, block - 1, 2 * top_k] after a pass
+- self.proj: torch.Tensor | None = None # [block - 1, selector rank] fp32
++ # a pass's candidates (every rank's [block - 1, 2 * top_k], values then ids as fp32 bits) and projected rows
++ # [block - 1, selector rank] fp32 in one device buffer, read back by one pinned copy (``candidates``)
++ self.gathered = self.world if self.world > 1 and w.comm is not None else 1
++ self.cand_n = self.gathered * (n - 1) * 2 * self.top_k
++ cuda = torch.cuda.is_available()
++ self.cand = torch.zeros((self.cand_n + (n - 1) * self.hproj.shape[0],), dtype=torch.float32, device=dev)
++ self.cand_host = torch.zeros(self.cand.shape, dtype=torch.float32, pin_memory=cuda)
++ self.cand_ready = torch.cuda.Event() if cuda else None
++ self.packed = self.cand[:self.cand_n].view(self.gathered, n - 1, 2 * self.top_k)
++ self.proj = self.cand[self.cand_n:].view(n - 1, self.hproj.shape[0])
+ self.pool = None
+ self.block_graph = None
+ self.tap_graphs: dict[int, torch.cuda.CUDAGraph] = {}
++ self.tap_rows = min(max(self.block, int(tap_rows)), self.tap_in.shape[0])
+
+ 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:
+ 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()
+- if self.world > 1 and self.w.comm is not None:
+- got = torch.empty((self.world * packed.numel(),), dtype=torch.float32, device=self.dev)
+- self.w.comm.all_gather(packed.view(-1), got)
+- self.packed = got.view(self.world, n - 1, 2 * self.top_k)
++ if self.gathered > 1:
++ self.w.comm.all_gather(packed.view(-1), self.cand[:self.cand_n])
+ else:
+- self.packed = packed.view(1, n - 1, 2 * self.top_k)
+- self.proj = F.linear(h, self.hproj).float()
++ self.cand[:self.cand_n].copy_(packed.view(-1))
++ self.proj.copy_(F.linear(h, self.hproj).float())
+
+ @torch.no_grad()
+ def capture(self) -> None:
+- """CUDA graphs for the block pass and for context updates of 1..block rows (both ranks together)."""
++ """CUDA graphs for the block pass and for context updates of 1..tap_rows rows (both ranks together)."""
+
+ self.pool = torch.cuda.graph_pool_handle()
+ self.reset()
+ self.tap_in.zero_()
+ self.ids[0] = 0
+- for n in range(1, self.block + 1):
++ for n in range(1, self.tap_rows + 1):
+ for _ in range(2):
+ self._taps_compute(n)
+ torch.cuda.synchronize()
+@@ -413,7 +424,15 @@ class Drafter:
+ self.block_graph.replay()
+ else:
+ self._block_compute()
+- g = self.packed[:, :depth].cpu()
++ # one pinned copy of candidates and projected rows (two .cpu() calls were two syncs and two pageable copies)
++ if self.cand_ready is not None:
++ self.cand_host.copy_(self.cand, non_blocking=True)
++ self.cand_ready.record()
++ self.cand_ready.synchronize()
++ else:
++ 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]
+ 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:
+ 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)
+- return tokens, values, self.proj[:depth].cpu().numpy().astype(np.float64)
++ 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,
+ sampling: Sampling | None, confidence: float = 0.0) -> list[int]:
+diff --git tensorfold/families/glm5_next/cuda/drafter_choice.py tensorfold/families/glm5_next/cuda/drafter_choice.py
+index b14a7e9..01ad045 100644
+--- tensorfold/families/glm5_next/cuda/drafter_choice.py
++++ tensorfold/families/glm5_next/cuda/drafter_choice.py
+@@ -8,7 +8,7 @@ import torch
+
+ from tensorfold.engine.exact_sampling import Sampling
+
+-from .decode import DecodeResult, DepthPolicy, Engine, _sync, absorb, copy_room, draft
++from .decode import DecodeResult, DepthPolicy, Engine, _Clock, _Late, _sync, absorb, copy_room, draft
+ from .forward import commit
+
+
+@@ -91,6 +91,7 @@ def auto_decode(e: Engine, drafter, pending: int, count: int, sampling: Sampling
+ arms: list[str] = []
+ last = {"m": (0, 0), "f": (0, 0), "c": (0, 0)}
+ c_rounds = c_drafted = c_accepted = 0
++ clock, late = _Clock(), _Late(on_tokens)
+ _sync(w)
+ start = time.perf_counter()
+ while len(out) < count and not (stop_eos and out[-1] in w.cfg.eos):
+@@ -119,8 +120,10 @@ def auto_decode(e: Engine, drafter, pending: int, count: int, sampling: Sampling
+ tokens = e.verify_window([out[-1]] + drafts)
+ drafts = tokens[1:]
+ R = len(tokens)
++ clock.start()
+ logits = e.forward(tokens)
+- torch.cuda.synchronize()
++ clock.stop()
++ late.flush() # the last round's tokens, while this window runs
+ t2 = time.perf_counter()
+ sampled = e.sample(logits[:R], [st.pos + 1 + r for r in range(R)], sampling)
+ keep = 1
+@@ -159,12 +162,12 @@ def auto_decode(e: Engine, drafter, pending: int, count: int, sampling: Sampling
+ out.extend(sampled[:keep])
+ if copies is not None:
+ copies.extend(sampled[:keep])
+- if on_tokens is not None:
+- on_tokens(sampled[:keep][:max(0, count - (len(out) - keep))])
++ late(sampled[:keep][:max(0, count - (len(out) - keep))])
+ stages["draft"] += (t1 - t0) + (t5 - t4)
+- stages["forward"] += t2 - t1
++ stages["forward"] += clock.seconds()
+ stages["sample"] += t3 - t2
+ stages["commit"] += t4 - t3
++ late.flush()
+ _sync(w)
+ 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
+--- tensorfold/families/glm5_next/cuda/engine.py
++++ tensorfold/families/glm5_next/cuda/engine.py
+@@ -14,8 +14,9 @@ from typing import Any, Callable
+ DEFAULT_POLICY = "auto"
+ DFLASH_POLICY = "fc5:0.3" # DFlash2 drafts every round: up to 5 while their probability product holds 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) # verify windows captured as CUDA graphs
+-MAX_ROWS = 8 # the widest verify window (a pending token and up to 7 drafts)
++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)
++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:
+ explicit = context is not None if context_explicit is None else bool(context_explicit)
+ from . import LATENT
+
+- from .qmm import dense_kind, fp8_weights, q4_weights
++ from .qmm import KVB_KINDS, dense_kind, fp8_weights, kvb_kind, kvb_weights, q4_weights
+
+ # TF_GLM_DENSE=fp8 (an EXL3 checkpoint): its BF16 matrices take a byte a value, which the estimate counts
+ weights_estimate = split_weights(rule)
+@@ -191,6 +192,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:
+ 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]
++ 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]
+ # 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:
+ 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): "
+ f"rank 0 {both[0][:-1]}, rank 1 {both[1][:-1]}; pull the draft model on both machines "
+@@ -263,10 +267,11 @@ class GlmEngine:
+ if drafter is not None:
+ from .dflash2 import Drafter
+
+- self.drafter = Drafter(drafter, w, capacity=capacity)
+- 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.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, mtp_rows=MTP_ROWS)
+ 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:
+ return [int(t) for t in rng.integers(0, vocab, n)]
+
+ prefill(e, tokens(64), None, mtp=True, drafter=self.drafter)
+- hidden = e.pbuf.fnormed[:MAX_ROWS].clone() # rows for timing the draft steps
++ hidden = e.pbuf.fnormed[:8].clone() # rows for timing the draft steps
+ one, six = tokens(1), tokens(6)
+ start = st.mtp_len
+
+@@ -335,7 +340,10 @@ class GlmEngine:
+ st.set_mtp_len(start)
+ st.mtp_drafted = 0
+
+- pieces: dict[str, tuple] = {f"v{r}": (lambda w=tokens(r): e.forward(w), None) for r in range(1, MAX_ROWS + 1)}
++ # the verify windows the drafters' rounds use (MTP chains of 3, DFlash2 blocks of 5: the captured graphs);
++ # wider (copied) windows are not the choice's, and their eager launches would bend the fitted line
++ widest = max(GRAPH_ROWS)
++ pieces: dict[str, tuple] = {f"v{r}": (lambda w=tokens(r): e.forward(w), None) for r in range(1, widest + 1)}
+ 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:
+ e.reset()
+ if self.drafter is not None:
+ self.drafter.reset()
+- rows = list(range(2, MAX_ROWS + 1))
++ rows = list(range(2, widest + 1))
+ ys = [both[f"v{r}"] for r in rows]
+ 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
+--- tensorfold/families/glm5_next/cuda/latent.py
++++ tensorfold/families/glm5_next/cuda/latent.py
+@@ -76,6 +76,46 @@ class AbsorbQ4:
+ return sum(t.numel() * t.element_size() for t in (self.wkw, self.wks, self.wkb, self.wvw, self.wvs, self.wvb))
+
+
++F8_BLOCK = 128 # latent columns a scale covers (qmm.make_f8's block)
++
++
++class AbsorbF8:
++ """kv_b split per head as FP8 e4m3 (TF_GLM_KVB=fp8): wk [H, qk_dim, latent], wv [H, v_dim, latent] and fp32
++ scales [H, dim, latent / 128], qmm.make_f8's rows as they are (W ~ q * scale). Lossy; half AbsorbW's bytes."""
++
++ def __init__(self, k, v, heads: int) -> None:
++ def per_head(q):
++ return (q.weight.reshape(heads, -1, q.k).contiguous(),
++ q.scale.reshape(heads, -1, q.k // F8_BLOCK).contiguous())
++
++ self.wk, self.sk = per_head(k)
++ self.wv, self.sv = per_head(v)
++ self.heads, self.qk_dim, self.lw = self.wk.shape
++ self.v_dim = self.wv.shape[1]
++ if self.lw % F8_BLOCK or self.wv.shape[2] != self.lw:
++ raise ValueError("AbsorbF8: expected 128-column blocks along the latent")
++
++ def nbytes(self) -> int:
++ return sum(t.numel() * t.element_size() for t in (self.wk, self.sk, self.wv, self.sv))
++
++
++def from_bf16(k_rows: torch.Tensor, v_rows: torch.Tensor, heads: int, kind: str = "bf16"):
++ """An EXL3 checkpoint's kv_b rows (bf16, head order: k_rows [heads * qk_dim, latent], v_rows alike) as the latent
++ path holds them for TF_GLM_KVB ``kind``: AbsorbW (bf16, as stored), AbsorbF8 (fp8) or AbsorbQ4 (q4, MSE-searched
++ groups of 64 along the latent). A latent width the format does not tile stays bf16."""
++
++ from . import qmm
++
++ if kind not in ("bf16", "fp8", "q4"):
++ raise ValueError(f"kv_b as bf16, fp8 or q4, not {kind!r}")
++ lw = k_rows.shape[1]
++ if kind == "fp8" and lw % F8_BLOCK == 0:
++ return AbsorbF8(qmm.make_f8(k_rows), qmm.make_f8(v_rows), heads)
++ if kind == "q4" and lw % 64 == 0:
++ return AbsorbQ4(qmm.quantize4_mse_raw(k_rows), qmm.quantize4_mse_raw(v_rows), heads)
++ return AbsorbW.from_rows(k_rows, v_rows, heads)
++
++
+ # ----------------------------------------------------------------------------------------- absorb, expand ---
+
+ @triton.jit
+@@ -154,6 +194,43 @@ def _expand_v4(OL, WW, WS, WB, OUT, R, H: tl.constexpr, DV: tl.constexpr, LW: tl
+ tl.store(OUT + (r * H + h) * DV + n, acc.to(tl.bfloat16))
+
+
++def _absorb_q8(Q, WK, SK, QA, R, H: tl.constexpr, D: tl.constexpr, LW: tl.constexpr, BN: tl.constexpr):
++ """_absorb_q over FP8 weights: the program's [D, BN] block (inside one 128-column scale block) dequantized to
++ fp32 once, then each row's one sum over k, whatever R is."""
++
++ h = tl.program_id(0)
++ n0 = tl.program_id(1) * BN
++ KB: tl.constexpr = LW // 128
++ k = tl.arange(0, D)
++ n = n0 + tl.arange(0, BN)
++ w = tl.load(WK + (h * D + k[:, None]) * LW + n[None, :]).to(tl.bfloat16).to(tl.float32) # [D, BN], exact
++ s = tl.load(SK + (h * D + k) * KB + n0 // 128) # [D]
++ w = w * s[:, None]
++ for r in range(R):
++ q = tl.load(Q + (r * H + h) * D + k).to(tl.float32)
++ acc = tl.sum(q[:, None] * w, axis=0)
++ tl.store(QA + (r * H + h) * LW + n, acc.to(tl.bfloat16))
++
++
++def _expand_v8(OL, WV, SV, OUT, R, H: tl.constexpr, DV: tl.constexpr, LW: tl.constexpr, BN: tl.constexpr):
++ """_expand_v over FP8 weights: the program's [BN, LW] rows dequantized to fp32 once (a scale a 128 block), then
++ each row's output as one fp32 sum over the latent, whatever R is."""
++
++ h = tl.program_id(0)
++ n = tl.program_id(1) * BN + tl.arange(0, BN)
++ KB: tl.constexpr = LW // 128
++ k = tl.arange(0, LW)
++ w = tl.load(WV + (h * DV + n[:, None]) * LW + k[None, :]).to(tl.bfloat16).to(tl.float32) # [BN, LW], exact
++ s = tl.load(SV + (h * DV + n[:, None]) * KB + (k // 128)[None, :]) # [BN, LW]
++ w = w * s
++ for r in range(R):
++ x = tl.load(OL + (r * H + h) * LW + k).to(tl.float32)
++ acc = tl.sum(w * x[None, :], axis=1)
++ tl.store(OUT + (r * H + h) * DV + n, acc.to(tl.bfloat16))
++
++
+ @triton.jit
+ def _absorb_mma(Q, WK, QA, R, H: tl.constexpr, D: tl.constexpr, LW: tl.constexpr, BM: tl.constexpr,
+ BN: tl.constexpr, BK: tl.constexpr):
+@@ -191,10 +268,56 @@ def _expand_mma(OL, WV, OUT, R, H: tl.constexpr, DV: tl.constexpr, LW: tl.conste
+ tl.store(OUT + (rm[:, None] * H + h) * DV + n[None, :], acc.to(tl.bfloat16), mask=ok[:, None])
+
+
++def _absorb_mma8(Q, WK, SK, QA, R, H: tl.constexpr, D: tl.constexpr, LW: tl.constexpr, BM: tl.constexpr,
++ BN: tl.constexpr, BK: tl.constexpr):
++ """_absorb_mma over FP8 weights: each [BK, BN] tile (inside one 128-column scale block) dequantized to bf16 in
++ registers (a scale a k row), then the same tensor-core chain; a row's bits do not depend on the other rows."""
++
++ h = tl.program_id(0)
++ rm = tl.program_id(1) * BM + tl.arange(0, BM)
++ n0 = tl.program_id(2) * BN
++ n = n0 + tl.arange(0, BN)
++ kk = tl.arange(0, BK)
++ KB: tl.constexpr = LW // 128
++ ok = rm < R
++ acc = tl.zeros((BM, BN), dtype=tl.float32)
++ for k0 in range(0, D, BK):
++ q = tl.load(Q + (rm[:, None] * H + h) * D + k0 + kk[None, :], mask=ok[:, None], other=0.0)
++ w = tl.load(WK + (h * D + k0 + kk[:, None]) * LW + n[None, :]).to(tl.bfloat16).to(tl.float32)
++ s = tl.load(SK + (h * D + k0 + kk) * KB + n0 // 128)
++ acc = tl.dot(q, (w * s[:, None]).to(tl.bfloat16), acc)
++ tl.store(QA + (rm[:, None] * H + h) * LW + n[None, :], acc.to(tl.bfloat16), mask=ok[:, None])
++
++
++def _expand_mma8(OL, WV, SV, OUT, R, H: tl.constexpr, DV: tl.constexpr, LW: tl.constexpr, BM: tl.constexpr,
++ BN: tl.constexpr, BK: tl.constexpr):
++ """_expand_mma over FP8 weights: each k step's product (bf16 inputs, the e4m3 values exact in bf16) times its
++ 128-column block's scale per output, as qmm._fmm; a row's bits do not depend on the other rows."""
++
++ h = tl.program_id(0)
++ rm = tl.program_id(1) * BM + tl.arange(0, BM)
++ n = tl.program_id(2) * BN + tl.arange(0, BN)
++ kk = tl.arange(0, BK)
++ KB: tl.constexpr = LW // 128
++ ok = rm < R
++ acc = tl.zeros((BM, BN), dtype=tl.float32)
++ for k0 in range(0, LW, BK):
++ o = tl.load(OL + (rm[:, None] * H + h) * LW + k0 + kk[None, :], mask=ok[:, None], other=0.0)
++ w = tl.load(WV + (h * DV + n[:, None]) * LW + k0 + kk[None, :]).to(tl.bfloat16)
++ s = tl.load(SV + (h * DV + n) * KB + k0 // 128)
++ acc = acc + tl.dot(o, tl.trans(w)) * s[None, :]
++ tl.store(OUT + (rm[:, None] * H + h) * DV + n[None, :], acc.to(tl.bfloat16), mask=ok[:, None])
++
++
+ # prompt chunks' tiles (rows, columns, k) and (warps, stages); fixed, so a row's bits never depend on the chunk
+ PROMPT_MMA = __import__("os").environ.get("TF_GLM_LATENT_MMA", "1") != "0" # 0: prompts on the decode kernels
+ MMA_TILE = (64, 128, 64)
+ MMA_LAUNCH = (4, 3)
++F8_ABSORB_BN = 64 # FP8 absorb columns per decode program: 64-byte weight rows, inside one scale block
++if F8_BLOCK % MMA_TILE[1] or F8_BLOCK % MMA_TILE[2] or F8_BLOCK % F8_ABSORB_BN:
++ raise ValueError("the FP8 absorb tiles must sit inside 128-column scale blocks")
+
+
+ def row_block(R: int) -> int:
+@@ -212,6 +335,15 @@ def absorb_q(q: torch.Tensor, a, out: torch.Tensor, *, prompt: bool = False) ->
+ _absorb_mma[(H, triton.cdiv(R, BM), a.lw // BN)](q, a.wk, out, R, H=H, D=D, LW=a.lw, BM=BM, BN=BN, BK=BK,
+ num_warps=warps, num_stages=stages)
+ return out
++ if isinstance(a, AbsorbF8):
++ if prompt and q.is_contiguous():
++ BM, BN, BK = MMA_TILE
++ warps, stages = MMA_LAUNCH
++ _absorb_mma8[(H, triton.cdiv(R, BM), a.lw // BN)](q, a.wk, a.sk, out, R, H=H, D=D, LW=a.lw, BM=BM, BN=BN,
++ BK=BK, num_warps=warps, num_stages=stages)
++ return out
++ _absorb_q8[(H, a.lw // F8_ABSORB_BN)](q, a.wk, a.sk, out, R, H=H, D=D, LW=a.lw, BN=F8_ABSORB_BN, num_warps=4)
++ return out
+ if isinstance(a, AbsorbQ4):
+ rb = row_block(R)
+ _absorb_q4[(H, a.lw // 64, triton.cdiv(R, rb))](q, a.wkw, a.wks, a.wkb, out, R, H=H, D=D, LW=a.lw, RB=rb,
+@@ -231,6 +363,17 @@ def expand_v(o_lat: torch.Tensor, a, out: torch.Tensor, *, prompt: bool = False)
+ _expand_mma[(H, triton.cdiv(R, BM), a.v_dim // BN)](o_lat, a.wv, out, R, H=H, DV=a.v_dim, LW=a.lw, BM=BM,
+ BN=BN, BK=BK, num_warps=warps, num_stages=stages)
+ return out
++ if isinstance(a, AbsorbF8):
++ if prompt and o_lat.is_contiguous():
++ BM, BN, BK = MMA_TILE
++ warps, stages = MMA_LAUNCH
++ _expand_mma8[(H, triton.cdiv(R, BM), a.v_dim // BN)](o_lat, a.wv, a.sv, out, R, H=H, DV=a.v_dim, LW=a.lw,
++ BM=BM, BN=BN, BK=BK, num_warps=warps,
++ num_stages=stages)
++ return out
++ BN = 16
++ _expand_v8[(H, a.v_dim // BN)](o_lat, a.wv, a.sv, out, R, H=H, DV=a.v_dim, LW=a.lw, BN=BN, num_warps=4)
++ return out
+ if isinstance(a, AbsorbQ4):
+ 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
+--- 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:
+ """TF_GLM_DENSE=q4: bf16 weights as affine 4-bit groups of 64, each group's range the one of ``grid`` clippings
+ (1.0 down to 0.55 of its min / max) with the least squared error, scale and bias as stored (bf16). Lossy."""
+
++ return make_q4(*quantize4_mse_raw(w, chunk, grid))
++
++
++def quantize4_mse_raw(w: torch.Tensor, chunk: int = 4096,
++ grid: int = 16) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
++ """``quantize4_mse``'s groups in MLX's layout, untiled: words [n, k / 8] int32 (8 nibbles low to high), scales and
++ biases [n, k / 64] bf16 (what ``latent.AbsorbQ4`` reads)."""
++
+ n, k = w.shape
+ words = torch.empty((n, k // 8), dtype=torch.int32, device=w.device)
+ scales = torch.empty((n, k // 64), dtype=torch.bfloat16, device=w.device)
+@@ -208,7 +216,7 @@ def quantize4_mse(w: torch.Tensor, chunk: int = 4096, grid: int = 16) -> Q4:
+ for j in range(8):
+ part |= q[..., j] << (4 * j)
+ words[r:r + chunk], scales[r:r + chunk], biases[r:r + chunk] = part, best_s, best_b
+- return make_q4(words, scales.contiguous(), biases.contiguous())
++ return words, scales.contiguous(), biases.contiguous()
+
+
+ DRAFT_QUANTS = ("minmax", "mse")
+@@ -509,6 +517,42 @@ def dense_kind() -> str:
+ return kind
+
+
++KVB_KINDS = ("bf16", "fp8", "q4")
++
++
++def kvb_kind(env=None) -> str:
++ """TF_GLM_KVB: how an EXL3 checkpoint's kv_b_proj is held for the latent path's absorb and expand (the kernels
++ every decode round runs once a DSA layer): bf16 (as stored, the default), fp8 (e4m3, an fp32 scale per row and
++ 128 latent columns, ``make_f8``'s layout) or q4 (MSE-searched affine groups of 64 along the latent, the MLX
++ checkpoint's kernels). fp8 and q4 are lossy, like the rest of TF_GLM_DENSE; a row's bits still never depend on its
++ window's other rows, so drafted replies equal serial ones under each."""
++
++ import os
++
++ kind = (os.environ if env is None else env).get("TF_GLM_KVB", "bf16").strip() or "bf16"
++ if kind not in KVB_KINDS:
++ raise ValueError(f"TF_GLM_KVB is bf16, fp8 or q4, not {kind!r}")
++ return kind
++
++
++def kvb_weights(base, kind: str):
++ """A split_weights transform for TF_GLM_KVB: kv_b_proj at a byte a value plus fp32 scales a 128 block (fp8), or
++ half a byte plus a bf16 scale and bias a group of 64 (q4); the latent path then holds no other copy of it."""
++
++ def transform(name: str, info: dict) -> tuple[int, int]:
++ total, extra = base(name, info)
++ shape = info.get("shape") or []
++ if kind == "bf16" or not total or "kv_b_proj" not in name or info.get("dtype") != "BF16" or len(shape) != 2:
++ return total, extra
++ n = total // 2
++ if kind == "fp8" and shape[-1] % F8_BLOCK == 0:
++ return n + n // F8_BLOCK * 4, extra
++ if kind == "q4" and shape[-1] % 64 == 0:
++ return n // 2 + n // 64 * 4, extra
++ return total, extra
++ return transform
++
++
+ # The matrices TF_GLM_DENSE=fp8 converts (weights.py's q4 / stack / head), for the startup memory estimate
+ _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
+--- 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
+
+ from .exl3_mm import Exl3Experts, words as exl3_words
+ from . import latent
+-from .qmm import (B16, F8, Q4, as_i32, dense_kind, draft_quantize4, make_b16, make_f8, make_q4, stack_b16, stack_f8,
+- stack_q4)
++from .qmm import (B16, F8, Q4, as_i32, dense_kind, draft_quantize4, kvb_kind, make_b16, make_f8, make_q4, stack_b16,
++ stack_f8, stack_q4)
+
+ PREFIX = "model.language_model."
+
+@@ -148,12 +148,12 @@ class DSAW:
+ q_norm: torch.Tensor
+ kv_norm: torch.Tensor
+ q_b: Q4
+- kv_k: Q4 # key rows of kv_b for the local heads
+- kv_v: Q4 # value rows
++ kv_k: Q4 | None # key rows of kv_b for the local heads (TF_GLM_LATENT=0 only)
++ kv_v: Q4 | None # value rows (TF_GLM_LATENT=0 only)
+ o: Q4
+ heads: int
+ index: IndexW | None = None
+- absorb: object = None # latent.AbsorbW: kv_b split per head, for attention on the latent cache
++ absorb: object = None # latent.AbsorbW / AbsorbF8 / AbsorbQ4: kv_b split per head, for the latent cache
+
+
+ @dataclass
+@@ -222,7 +222,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()
+- elif isinstance(t, (Q4, B16, F8, grouped.Experts, Exl3Experts, HCW, KDAW, DSAW, MLPW, MoEW, LayerW, MTPW, IndexW)):
++ elif isinstance(t, (Q4, B16, F8, grouped.Experts, Exl3Experts, HCW, KDAW, DSAW, MLPW, MoEW, LayerW, MTPW,
++ IndexW, latent.AbsorbW, latent.AbsorbQ4, latent.AbsorbF8)):
+ 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:
+ big, big_stack = make_dense_q4, stack_dense_q4
+ else:
+ big, big_stack = dense, dense_stack
++ kvb = kvb_kind() if exl3 else "bf16" # an MLX checkpoint's kv_b is 4-bit as stored
+
+ 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:
+ 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)
++ # the latent path reads kv_b only through ``absorb``: the per-head key and value matrices (kv_k, kv_v) exist
++ # only without it (TF_GLM_LATENT=0), so they take no memory beside it
++ kv_k = kv_v = None
+ if exl3:
+ w = t(p + "kv_b_proj.weight")
+- kv_k, kv_v = dense(w[krows]), dense(w[vrows])
+- full_k, full_v = (lambda: w[krows].float()), (lambda: w[vrows].float())
++ if not latent.ENABLED:
++ kv_k, kv_v = dense(w[krows]), dense(w[vrows])
+ else:
+ w, s, b = trip(p + "kv_b_proj")
+- kv_k = make_q4(w[krows], s[krows], b[krows])
+- kv_v = make_q4(w[vrows], s[vrows], b[vrows])
++ if not latent.ENABLED:
++ kv_k = make_q4(w[krows], s[krows], b[krows])
++ kv_v = make_q4(w[vrows], s[vrows], b[vrows])
+ if not latent.ENABLED:
+ absorb = None
+- elif exl3:
+- absorb = latent.AbsorbW.from_rows(full_k(), full_v(), HL)
++ elif exl3: # TF_GLM_KVB: bf16 as stored, or fp8 / q4 (lossy, half / a quarter the bytes)
++ absorb = latent.from_bf16(w[krows], w[vrows], HL, kvb)
+ elif cfg.group_size == 64: # the checkpoint's own 4-bit rows, read as they are stored
+ absorb = latent.AbsorbQ4((w[krows], s[krows], b[krows]), (w[vrows], s[vrows], b[vrows]), HL)
+ else:
diff --git a/patches/0014-glm-kda-chunked-gb10.patch b/patches/0014-glm-kda-chunked-gb10.patch
new file mode 100644
index 0000000..36b0a5e
--- /dev/null
+++ b/patches/0014-glm-kda-chunked-gb10.patch
@@ -0,0 +1,377 @@
+diff --git tensorfold/families/glm5_next/cuda/kda_chunked.py tensorfold/families/glm5_next/cuda/kda_chunked.py
+index 0ee9823..09cb28b 100644
+--- tensorfold/families/glm5_next/cuda/kda_chunked.py
++++ tensorfold/families/glm5_next/cuda/kda_chunked.py
+@@ -18,12 +18,17 @@ decreasing: every l is in (lower, 0) = (-5, 0)):
+ S_end = S0 diag(e^G_63) + V'^T (k * e^(G_63 - G))
+
+ Every exponent above is <= 0 except inside L and M, which are formed as matmuls of row and column factors about a
+-reference point: for the rows of 16-row block b, R = G at the block's first row; row factor e^(G_s - R) in
+-[e^-75, 1] (15 steps of at most 5), column factor e^(R - G_j) <= 1 for earlier blocks and <= e^75 inside the block
+-(< fp32's e^88.7); only blocks j <= b are formed. Their products are true decays (<= 1). T is inverted per 16-row
+-diagonal block by forward substitution, then block rows are joined with matmuls (T_bj = -T_bb sum L_bm T_mj).
+-Everything is fp32; the matmuls take tl.dot's ``input_precision`` (TF_GLM_KDA_PREC, default tf32x3, about fp32:
+-~2e-6 relative against float64; "tf32" is faster and ~5e-4, half a bf16 step).
++reference row p: e^(G_s - G_j) = e^(G_s - G_p) e^(G_p - G_j). Each exponent is summed outward from its reference
++(forward from p, backward from p, backward from the sub-chunk's end for k e^(G_63 - G)), never taken as a difference
++of G's: all l have one sign, so a partial sum's rounding error is a few ulps of the partial sum itself, while G
++reaches -320 in a sub-chunk and a difference of two G's would carry ulp(320) = 3e-5 into decays near 1 (the first
++version did: 10x the error of kda.cu's chain). For the rows of 16-row block b against earlier blocks p = the
++block's first row (both factors <= 1: errors a few ulps of the decay's own exponent); inside the diagonal tile p =
++the first row of the row's 4-row group (column factors <= e^15 for the rows after p: errors a few ulps of 30). Only
++blocks j <= b are formed. T is inverted per 16-row diagonal block by forward substitution, then block rows are
++joined with matmuls (T_bj = -T_bb sum L_bm T_mj). Everything is fp32; the matmuls take tl.dot's
++``input_precision`` (TF_GLM_KDA_PREC, default tf32x3, about fp32: read-outs ~3e-7 relative against float64 on the
++tests' inputs, kda.cu's chain ~1e-7; "tf32" is faster and ~5e-4, half a bf16 step).
+
+ Kernels (``chain``): _kda_lm (sub-chunk, head, block): the conv, norms, beta and decays of its rows, L and M rows,
+ q e^G; _kda_solve (sub-chunk, head): T and the sub-chunk's total log-decay; _kda_wu (sub-chunk, head, block): W, U
+@@ -47,11 +52,13 @@ import os
+ import torch
+ import triton
+ import triton.language as tl
++from triton.language.extra import libdevice
+
+ DK = DV = 128
+ TAPS = 4
+ CHUNK = 64 # rows of a sub-chunk (the state is carried between sub-chunks)
+-BLOCK = 16 # rows of a reference block inside a sub-chunk (16 x 5 = 80 < 88: no fp32 overflow)
++BLOCK = 16 # rows of a block inside a sub-chunk (the tiles of L, M and T)
++GROUP = 4 # rows about one reference row inside a diagonal tile
+ SCALE = 1.0 / math.sqrt(DK)
+
+
+@@ -156,8 +163,13 @@ def chunked_reference(q, k, v, lg, beta, state, pos: int = 0, dtype=torch.float6
+ lower_strict = t[:, None] > t[None, :]
+ lower_incl = t[:, None] >= t[None, :]
+ nb = CHUNK // BLOCK
++ i = torch.arange(BLOCK, device=dev)[None, :, None]
+ S = state.to(dtype).clone() # [H, V, K]
+ out = torch.empty((total, H, DV), dtype=dtype, device=dev)
++
++ def rcumsum(x):
++ return torch.flip(torch.cumsum(torch.flip(x, [1]), 1), [1])
++
+ for c in range(nc):
+ qx, kx, vx, lx, bx = qc[c], kc[c], vc[c], lc[c], bc[c] # [H, 64, 128] (beta [H, 64])
+ G = torch.cumsum(lx, dim=1)
+@@ -165,13 +177,25 @@ def chunked_reference(q, k, v, lg, beta, state, pos: int = 0, dtype=torch.float6
+ Aqk = torch.zeros_like(Akk)
+ for b in range(nb):
+ rs = slice(b * BLOCK, (b + 1) * BLOCK)
+- R = G[:, b * BLOCK][:, None, :]
+- rf = torch.exp(G[:, rs] - R)
+- cols = (t < (b + 1) * BLOCK)[None, :, None]
+- cf = torch.where(cols, torch.exp(torch.where(cols, R - G, torch.zeros_like(G))), torch.zeros_like(G))
+- kt = (kx * cf).transpose(1, 2)
+- Akk[:, rs] = mm(kx[:, rs] * rf, kt)
+- Aqk[:, rs] = mm(qx[:, rs] * rf, kt)
++ lb = lx[:, rs]
++ for g in range(BLOCK // GROUP): # the diagonal tile, about each group's row
++ p = g * GROUP
++ fwd = torch.cumsum(torch.where(i > p, lb, 0.0), 1)
++ back = rcumsum(torch.where(i <= p, lb, 0.0)) - lb
++ rf = torch.where((i >= p) & (i < p + GROUP), torch.exp(fwd), 0.0)
++ cf = torch.where(i < p, torch.exp(back), torch.where(i < p + GROUP, torch.exp(-fwd), 0.0))
++ kt = (kx[:, rs] * cf).transpose(1, 2)
++ Akk[:, rs, rs] += mm(kx[:, rs] * rf, kt)
++ Aqk[:, rs, rs] += mm(qx[:, rs] * rf, kt)
++ rf = torch.exp(torch.cumsum(torch.where(i > 0, lb, 0.0), 1)) # earlier blocks, about the block's row 0
++ carry = lb[:, :1]
++ for j in range(b - 1, -1, -1):
++ cs = slice(j * BLOCK, (j + 1) * BLOCK)
++ rev = rcumsum(lx[:, cs])
++ kt = (kx[:, cs] * torch.exp(carry + (rev - lx[:, cs]))).transpose(1, 2)
++ Akk[:, rs, cs] = mm(kx[:, rs] * rf, kt)
++ Aqk[:, rs, cs] = mm(qx[:, rs] * rf, kt)
++ carry = carry + rev[:, :1]
+ L = torch.where(lower_strict, bx[:, :, None] * Akk, torch.zeros_like(Akk))
+ M = torch.where(lower_incl, Aqk, torch.zeros_like(Aqk))
+ T = torch.zeros_like(L)
+@@ -185,7 +209,7 @@ def chunked_reference(q, k, v, lg, beta, state, pos: int = 0, dtype=torch.float6
+ W = mm(T, bx[:, :, None] * kx * eG)
+ U = mm(T, bx[:, :, None] * vx)
+ gl = G[:, -1:, :]
+- Ke = kx * torch.exp(gl - G)
++ Ke = kx * torch.exp(rcumsum(lx) - lx) # GL - G, summed backward from the end
+ Qt = qx * eG
+ ST = S.transpose(1, 2) # [H, K, V]
+ Vn = U - mms(W, ST)
+@@ -217,6 +241,29 @@ def chain_reference(p, b_off, a, g, conv_state, conv_w, state_in, a_log, dt_bias
+
+
+ # -- Triton kernels ---------------------------------------------------------------------------------------------
++# The per-row values rounded to bf16 (conv + SiLU, beta) must be kda.cu's bits: a value rounded the other way at a
++# bf16 tie moves a key by 2^-8 in one channel, a beta by 2^-8 of the whole update, far above fp32 noise (and the
++# read-out of a row whose RMSNorm is eps-dominated carries it into the output). kda.cu is built with --fmad=false and
++# uses CUDA's expf and IEEE division: the kernels that compute these values launch with enable_fp_fusion=False and
++# take libdevice's expf (the same algorithm) and div_rn. Triton's interpreter has no libdevice: it takes tl.exp.
++_PRECISE = tl.constexpr(os.environ.get("TRITON_INTERPRET", "0") != "1")
++
++
++def _expf(x):
++ """CUDA's expf (libdevice) on the GPU, tl.exp under the interpreter."""
++ if _PRECISE:
++ return libdevice.exp(x)
++ else:
++ return tl.exp(x)
++
++
++def _sigmoid_f(x):
++ """kda.cu's sigmoidf_: 1 / (1 + expf(-x)), IEEE division."""
++ return tl.math.div_rn(1.0, 1.0 + _expf(-x))
++
++
+ @triton.jit
+ def _bf16(x):
+ """fp32 rounded to bf16 (to nearest even), as fp32: bit arithmetic, so Triton's CPU interpreter (which truncates
+@@ -241,14 +288,14 @@ def _conv_act(P, p_stride, CS, CW, r, valid, ch, C3, BT: tl.constexpr, DK_: tl.c
+ x = tl.where(from_s[:, None], xs.to(tl.float32), xp.to(tl.float32))
+ wt = tl.load(CW + ch * TAPS_ + tap).to(tl.float32)
+ acc = acc + wt[None, :] * x
+- act = acc / (1.0 + tl.exp(-acc))
++ act = tl.math.div_rn(acc, 1.0 + _expf(-acc))
+ return _bf16(act)
+
+
+ @triton.jit
+ def _l2(x):
+ ss = tl.sum(x * x, axis=1)
+- return x * (1.0 / tl.sqrt_rn(ss + 1e-6))[:, None]
++ return x * tl.math.div_rn(1.0, tl.sqrt_rn(ss + 1e-6))[:, None]
+
+
+ @triton.jit
+@@ -282,28 +329,38 @@ def _dot_k(a, b, NS: tl.constexpr, PREC: tl.constexpr):
+ return tl.sum(tl.dot(a3, b3, input_precision=PREC), axis=0)
+
+
++def _logdecay(A, a_stride, r, valid, hd, ch, rate, dtb, lower):
++ """The log-decays l of rows r [BC, DK] (in (lower, 0)); zero rows outside the chunk."""
++ av = tl.load(A + r.to(tl.int64)[:, None] * a_stride + hd + ch[None, :], mask=valid[:, None], other=0.0)
++ lg = lower * _sigmoid_f(rate * (av.to(tl.float32) + dtb[None, :]))
++ return tl.where(valid[:, None], lg, 0.0)
++
++
+ @triton.jit
+ def _gates(A, a_stride, r, valid, hd, ch, rate, dtb, lower, carry):
+ """G for rows r: carry (the running log-decay before them) + their running sum; zero rows outside the chunk."""
+- av = tl.load(A + r.to(tl.int64)[:, None] * a_stride + hd + ch[None, :], mask=valid[:, None], other=0.0)
+- lg = lower * (1.0 / (1.0 + tl.exp(-(rate * (av.to(tl.float32) + dtb[None, :])))))
+- return carry[None, :] + tl.cumsum(tl.where(valid[:, None], lg, 0.0), axis=0)
++ return carry[None, :] + tl.cumsum(_logdecay(A, a_stride, r, valid, hd, ch, rate, dtb, lower), axis=0)
+
+
+ @triton.jit
+ def _beta(P, p_stride, b_off, h, r, valid):
+ braw = tl.load(P + r.to(tl.int64) * p_stride + b_off + h, mask=valid, other=0.0).to(tl.float32)
+- return tl.where(valid, _bf16(1.0 / (1.0 + tl.exp(-braw))), 0.0)
++ return tl.where(valid, _bf16(_sigmoid_f(braw)), 0.0)
+
+
+ @triton.jit
+ def _kda_lm(P, p_stride, b_off, A, a_stride, CS, CW, ALOG, DTB, lower, rows, off, H, QT, L, M,
+- DK_: tl.constexpr, BT: tl.constexpr, BC: tl.constexpr, TAPS_: tl.constexpr, KSPLIT: tl.constexpr,
+- PREC: tl.constexpr):
++ DK_: tl.constexpr, BT: tl.constexpr, BC: tl.constexpr, GR: tl.constexpr, TAPS_: tl.constexpr,
++ KSPLIT: tl.constexpr, PREC: tl.constexpr):
+ """Program (sub-chunk, head, 16-row block b): block b's rows of L (beta k k decays, strictly lower) and M (q k
+ decays, with the diagonal) against blocks j <= b, and its decayed q (QT = q e^G). Rows outside the prompt chunk
+- are zero rows (no decay, no key). The products are taken about R = G at block b's first row: row factors
+- e^(G - R) in [e^-75, 1], column factors e^(R - G_j) <= 1 for j < b and <= e^75 for j = b (< fp32's e^88.7)."""
++ are zero rows (no decay, no key).
++
++ A decay e^(G_s - G_j) is formed as e^(G_s - G_p) e^(G_p - G_j) about a reference row p, each exponent summed
++ outward from p (its rounding error a few ulps of its own size, never of G's): p = the block's first row for
++ earlier blocks (both factors <= 1: the error is a few ulps of the decay's own exponent), p = the first row of s's
++ GR-row group inside the diagonal tile (column factors <= e^(5 (GR - 1)), errors a few ulps of 10 (GR - 1))."""
+
+ c = tl.program_id(0)
+ h = tl.program_id(1)
+@@ -312,43 +369,52 @@ def _kda_lm(P, p_stride, b_off, A, a_stride, CS, CW, ALOG, DTB, lower, rows, off
+ ch = tl.arange(0, DK_)
+ C3 = 3 * H * DK_
+ hd = h * DK_
+- rate = tl.exp(tl.load(ALOG + h))
++ rate = _expf(tl.load(ALOG + h))
+ dtb = tl.load(DTB + hd + ch)
+ r0 = c * BT - off
+ tile = (c.to(tl.int64) * H + h) * BT * BT + (b * BC + i)[:, None] * BT + i[None, :] # + j * BC: tile (b, j)
+
+- carry = tl.zeros((DK_,), dtype=tl.float32)
+- for j in range(0, b):
+- rj = r0 + j * BC + i
+- carry = _row(_gates(A, a_stride, rj, (rj >= 0) & (rj < rows), hd, ch, rate, dtb, lower, carry), i, BC - 1)
+ r = r0 + b * BC + i
+ valid = (r >= 0) & (r < rows)
+- G = _gates(A, a_stride, r, valid, hd, ch, rate, dtb, lower, carry)
++ lb = _logdecay(A, a_stride, r, valid, hd, ch, rate, dtb, lower)
+ k = _l2(_conv_act(P, p_stride, CS, CW, r, valid, H * DK_ + hd + ch, C3, BC, DK_, TAPS_))
+ q = _l2(_conv_act(P, p_stride, CS, CW, r, valid, hd + ch, C3, BC, DK_, TAPS_)) * 0.08838834764831845
+- rowbase = (r.to(tl.int64) * H + h) * DK_
+- tl.store(QT + rowbase[:, None] + ch[None, :], q * tl.exp(G), mask=valid[:, None])
+ beta = _beta(P, p_stride, b_off, h, r, valid)
+- R = _row(G, i, 0)
+- rf = tl.exp(G - R[None, :])
++
++ # the diagonal tile in GR-row groups: rows s of group g about p = the group's first row
++ akk = tl.zeros((BC, BC), dtype=tl.float32)
++ aqk = tl.zeros((BC, BC), dtype=tl.float32)
++ for g in tl.static_range(BC // GR):
++ fwd = tl.cumsum(tl.where(i[:, None] > g * GR, lb, 0.0), axis=0) # G_t - G_p, t >= p
++ back = tl.cumsum(tl.where(i[:, None] <= g * GR, lb, 0.0), axis=0, reverse=True) - lb # G_p - G_t, t < p
++ rf = tl.where(((i >= g * GR) & (i < g * GR + GR))[:, None], tl.exp(fwd), 0.0)
++ cf = tl.where((i < g * GR)[:, None], tl.exp(back), tl.where((i < g * GR + GR)[:, None], tl.exp(-fwd), 0.0))
++ col = tl.trans(k * cf)
++ akk += _dot_k(k * rf, col, KSPLIT, PREC)
++ aqk += _dot_k(q * rf, col, KSPLIT, PREC)
++ tl.store(L + tile + b * BC, tl.where(i[:, None] > i[None, :], beta[:, None] * akk, 0.0))
++ tl.store(M + tile + b * BC, tl.where(i[:, None] >= i[None, :], aqk, 0.0))
++
++ # earlier blocks, nearest first, about p = the block's first row
++ fwd = tl.cumsum(tl.where(i[:, None] > 0, lb, 0.0), axis=0) # G_s - G_p
++ rf = tl.exp(fwd)
+ rk = k * rf
+ rq = q * rf
+-
+- col = tl.trans(k * tl.exp(R[None, :] - G)) # the diagonal tile
+- akk = tl.where(i[:, None] > i[None, :], _dot_k(rk, col, KSPLIT, PREC), 0.0)
+- aqk = tl.where(i[:, None] >= i[None, :], _dot_k(rq, col, KSPLIT, PREC), 0.0)
+- tl.store(L + tile + b * BC, beta[:, None] * akk)
+- tl.store(M + tile + b * BC, aqk)
+- carry = tl.zeros((DK_,), dtype=tl.float32)
+- for j in range(0, b):
++ carry = _row(lb, i, 0) # G_p - G_t for t = the previous block's last row
++ for jj in range(0, b):
++ j = b - 1 - jj
+ rj = r0 + j * BC + i
+ vj = (rj >= 0) & (rj < rows)
+- Gj = _gates(A, a_stride, rj, vj, hd, ch, rate, dtb, lower, carry)
+- carry = _row(Gj, i, BC - 1)
++ lj = _logdecay(A, a_stride, rj, vj, hd, ch, rate, dtb, lower)
++ rev = tl.cumsum(lj, axis=0, reverse=True)
+ kj = _l2(_conv_act(P, p_stride, CS, CW, rj, vj, H * DK_ + hd + ch, C3, BC, DK_, TAPS_))
+- col = tl.trans(kj * tl.exp(R[None, :] - Gj)) # [DK, BC]
++ col = tl.trans(kj * tl.exp(carry[None, :] + (rev - lj))) # e^(G_p - G_t) <= 1, [DK, BC]
+ tl.store(L + tile + j * BC, beta[:, None] * _dot_k(rk, col, KSPLIT, PREC))
+ tl.store(M + tile + j * BC, _dot_k(rq, col, KSPLIT, PREC))
++ carry += _row(rev, i, 0)
++ # carry = G_p, the running log-decay through the block's first row
++ rowbase = (r.to(tl.int64) * H + h) * DK_
++ tl.store(QT + rowbase[:, None] + ch[None, :], q * tl.exp(carry[None, :] + fwd), mask=valid[:, None])
+
+
+ @triton.jit
+@@ -380,7 +446,7 @@ def _kda_solve(A, a_stride, ALOG, DTB, lower, rows, off, H, L, T, GL,
+ Ts = Ts + (Trow,)
+ for j in tl.static_range(b + 1):
+ tl.store(T + base + (b * BC + i)[:, None] * BT + j * BC + i[None, :], Trow[j])
+- rate = tl.exp(tl.load(ALOG + h))
++ rate = _expf(tl.load(ALOG + h))
+ dtb = tl.load(DTB + hd + ch)
+ carry = tl.zeros((DK_,), dtype=tl.float32)
+ for b in range(0, NB):
+@@ -390,11 +456,13 @@ def _kda_solve(A, a_stride, ALOG, DTB, lower, rows, off, H, L, T, GL,
+
+
+ @triton.jit
+-def _kda_wu(P, p_stride, b_off, A, a_stride, CS, CW, ALOG, DTB, lower, rows, off, H, T, GL, W, U, KE,
++def _kda_wu(P, p_stride, b_off, A, a_stride, CS, CW, ALOG, DTB, lower, rows, off, H, T, W, U, KE,
+ DK_: tl.constexpr, BT: tl.constexpr, BC: tl.constexpr, TAPS_: tl.constexpr, PREC: tl.constexpr):
+ """Program (sub-chunk, head, 16-row block b): W_b = sum_{j<=b} T_bj (beta k e^G)_j, U_b = sum_{j<=b} T_bj
+- (beta v)_j (the WY / UT transform), and block b's keys decayed to the sub-chunk's end (KE = k e^(GL - G))."""
++ (beta v)_j (the WY / UT transform), and block b's keys decayed to the sub-chunk's end (KE = k e^(GL - G), the
++ exponent summed backward from the end: a few ulps of its own size)."""
+
++ NB: tl.constexpr = BT // BC
+ c = tl.program_id(0)
+ h = tl.program_id(1)
+ b = tl.program_id(2)
+@@ -402,24 +470,30 @@ def _kda_wu(P, p_stride, b_off, A, a_stride, CS, CW, ALOG, DTB, lower, rows, off
+ ch = tl.arange(0, DK_)
+ C3 = 3 * H * DK_
+ hd = h * DK_
+- rate = tl.exp(tl.load(ALOG + h))
++ rate = _expf(tl.load(ALOG + h))
+ dtb = tl.load(DTB + hd + ch)
+ r0 = c * BT - off
+- gl = tl.load(GL + (c.to(tl.int64) * H + h) * DK_ + ch)
+ tbase = (c.to(tl.int64) * H + h) * BT * BT + (b * BC + i)[:, None] * BT + i[None, :]
+ rb = r0 + b * BC + i
+ vb = (rb >= 0) & (rb < rows)
+ rowbase = (rb.to(tl.int64) * H + h) * DK_
++ later = tl.zeros((DK_,), dtype=tl.float32) # log-decay of the blocks after b, last first
++ for jj in range(0, NB - 1 - b):
++ rj = r0 + (NB - 1 - jj) * BC + i
++ later += tl.sum(_logdecay(A, a_stride, rj, (rj >= 0) & (rj < rows), hd, ch, rate, dtb, lower), axis=0)
+ wv = tl.zeros((BC, DK_), dtype=tl.float32)
+ uv = tl.zeros((BC, DK_), dtype=tl.float32)
+ carry = tl.zeros((DK_,), dtype=tl.float32)
+ for j in range(0, b + 1):
+ rj = r0 + j * BC + i
+ vj = (rj >= 0) & (rj < rows)
+- Gj = _gates(A, a_stride, rj, vj, hd, ch, rate, dtb, lower, carry)
++ lj = _logdecay(A, a_stride, rj, vj, hd, ch, rate, dtb, lower)
++ Gj = carry[None, :] + tl.cumsum(lj, axis=0)
+ carry = _row(Gj, i, BC - 1)
+ kj = _l2(_conv_act(P, p_stride, CS, CW, rj, vj, H * DK_ + hd + ch, C3, BC, DK_, TAPS_))
+- tl.store(KE + rowbase[:, None] + ch[None, :], kj * tl.exp(gl[None, :] - Gj), mask=(vb & (j == b))[:, None])
++ if j == b:
++ ke = kj * tl.exp(later[None, :] + (tl.cumsum(lj, axis=0, reverse=True) - lj)) # GL - G
++ tl.store(KE + rowbase[:, None] + ch[None, :], ke, mask=vb[:, None])
+ bj = _beta(P, p_stride, b_off, h, rj, vj)
+ vv = _conv_act(P, p_stride, CS, CW, rj, vj, 2 * H * DK_ + hd + ch, C3, BC, DK_, TAPS_)
+ tbj = tl.load(T + tbase + j * BC)
+@@ -491,10 +565,10 @@ def _kda_out(QT, U, M, HB, G, g_stride, NW, eps, OUT, rows, off, H,
+ mask=((rj >= 0) & (rj < rows))[:, None], other=0.0)
+ o += tl.dot(mq, vn, input_precision=PREC)
+ y = _bf16(o)
+- rinv = 1.0 / tl.sqrt_rn(tl.sum(y * y, axis=1) / DV_ + eps)
++ rinv = tl.math.div_rn(1.0, tl.sqrt_rn(tl.sum(y * y, axis=1) * (1.0 / DV_) + eps))
+ yw = tl.load(NW + vi).to(tl.float32)[None, :] * (y * rinv[:, None])
+ gate = tl.load(G + r.to(tl.int64)[:, None] * g_stride + h * DV_ + vi[None, :], mask=valid[:, None], other=0.0)
+- res = yw * (1.0 / (1.0 + tl.exp(-gate.to(tl.float32))))
++ res = yw * _sigmoid_f(gate.to(tl.float32))
+ tl.store(OUT + r.to(tl.int64)[:, None] * (H * DV_) + h * DV_ + vi[None, :], _bf16(res).to(tl.bfloat16),
+ mask=valid[:, None])
+
+@@ -504,6 +578,10 @@ PREC = os.environ.get("TF_GLM_KDA_PREC", "tf32x3") # tl.dot input precision
+ BV = int(os.environ.get("TF_GLM_KDA_BV", "16")) # value rows of the state per sequential program
+ STATE_ROWS = int(os.environ.get("TF_GLM_KDA_STATE_ROWS", "32")) # rows per step of the sequential kernel
+ KSPLIT = int(os.environ.get("TF_GLM_KDA_KSPLIT", "4")) # K slices of the 16 x 16 x 128 products (1: one dot)
++# (num_warps, num_stages) per kernel. One stage everywhere: GB10 (sm_121) gives a block 99 KiB of shared memory
++# (101,376 B), and pipelined loads of the per-block loops need up to 154 KiB.
++LAUNCH = {"lm": (8, 1), "solve": (4, 1), "wu": (8, 1), "state": (8, 1), "out": (8, 1)}
++_EXACT = dict(enable_fp_fusion=False, enable_reflect_ftz=False) # kda.cu's arithmetic (see _PRECISE)
+ _scratch: dict = {}
+
+
+@@ -561,14 +639,19 @@ def chain(p: torch.Tensor, b_off: int, a: torch.Tensor, g: torch.Tensor, conv_st
+ nb = CHUNK // BLOCK
+ _kda_lm[(nc, H, nb)](p, p.stride(0), int(b_off), a, a.stride(0), conv_state, conv_w, a_log, dt_bias, float(lower),
+ rows, off, H, s.qt, s.l, s.m,
+- DK_=DK, BT=CHUNK, BC=BLOCK, TAPS_=TAPS, KSPLIT=KSPLIT, PREC=prec, num_warps=4)
++ DK_=DK, BT=CHUNK, BC=BLOCK, GR=GROUP, TAPS_=TAPS, KSPLIT=KSPLIT, PREC=prec,
++ num_warps=LAUNCH["lm"][0], num_stages=LAUNCH["lm"][1], **_EXACT)
+ _kda_solve[(nc, H)](a, a.stride(0), a_log, dt_bias, float(lower), rows, off, H, s.l, s.t, s.gl,
+- DK_=DK, BT=CHUNK, BC=BLOCK, PREC=prec, num_warps=4)
++ DK_=DK, BT=CHUNK, BC=BLOCK, PREC=prec, num_warps=LAUNCH["solve"][0],
++ num_stages=LAUNCH["solve"][1], **_EXACT)
+ _kda_wu[(nc, H, nb)](p, p.stride(0), int(b_off), a, a.stride(0), conv_state, conv_w, a_log, dt_bias, float(lower),
+- rows, off, H, s.t, s.gl, s.w, s.u, s.ke,
+- DK_=DK, BT=CHUNK, BC=BLOCK, TAPS_=TAPS, PREC=prec, num_warps=4)
++ rows, off, H, s.t, s.w, s.u, s.ke,
++ DK_=DK, BT=CHUNK, BC=BLOCK, TAPS_=TAPS, PREC=prec, num_warps=LAUNCH["wu"][0],
++ num_stages=LAUNCH["wu"][1], **_EXACT)
+ _kda_state[(H, DV // bv)](state_in, state_out, s.w, s.u, s.ke, s.gl, s.hb, rows, off, nc, H,
+- DK_=DK, DV_=DV, BT=CHUNK, BC=STATE_ROWS, BV=bv, PREC=prec, num_warps=8, num_stages=1)
++ DK_=DK, DV_=DV, BT=CHUNK, BC=STATE_ROWS, BV=bv, PREC=prec,
++ num_warps=LAUNCH["state"][0], num_stages=LAUNCH["state"][1])
+ _kda_out[(nc, H)](s.qt, s.u, s.m, s.hb, g, g.stride(0), norm_w, float(eps), out, rows, off, H,
+- DK_=DK, DV_=DV, BT=CHUNK, BC=BLOCK, KS=32, PREC=prec, num_warps=8)
++ DK_=DK, DV_=DV, BT=CHUNK, BC=BLOCK, KS=32, PREC=prec, num_warps=LAUNCH["out"][0],
++ num_stages=LAUNCH["out"][1], **_EXACT)
+ return out[:rows]
diff --git a/patches/0015-glm-shared-prefix.patch b/patches/0015-glm-shared-prefix.patch
new file mode 100644
index 0000000..fe309f7
--- /dev/null
+++ b/patches/0015-glm-shared-prefix.patch
@@ -0,0 +1,417 @@
+diff --git tensorfold/families/glm5_next/cuda/decode.py tensorfold/families/glm5_next/cuda/decode.py
+index 52a5182..64f5be7 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]:
+ return views
+
+
+-def save_rows(e: Engine, snap: Snapshot) -> None:
+- """Copy a snapshot's attention rows out of the live caches before another conversation overwrites them; DFlash2 caches are not kept."""
+- views = _row_views(e.st, len(snap.ids), max(snap.mtp_len, 0))
++def _drafter_views(drafter, n: int) -> list[torch.Tensor]:
++ """DFlash2's context rows a snapshot of n tokens depends on: its sliding window's keys and values before n (every
++ later query sits at n or past it, and masks older rows), per draft layer."""
++ lo = max(0, n - drafter.window - 1)
++ return [c[:, lo:n] for c in drafter.kc] + [c[:, lo:n] for c in drafter.vc]
++
++
++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:
++ views += _drafter_views(drafter, n)
++ return views
++
++
++def save_rows(e: Engine, snap: Snapshot, drafter=None) -> None:
++ """Copy a snapshot's attention rows out of the live caches before another conversation overwrites them; DFlash2's
++ context goes with them only given ``drafter`` (TF_GLM_SHARED_PREFIX), otherwise the snapshot no longer fits it."""
++ views = _saved_views(e, snap, drafter)
+ 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
++ if drafter is None or snap.drafter_end != len(snap.ids):
++ snap.drafter_end = -1
+
+
+-def row_bytes(e: Engine, snap: Snapshot) -> int:
++def row_bytes(e: Engine, snap: Snapshot, drafter=None) -> int:
+ """What ``save_rows`` would copy for this snapshot."""
+- return sum(v.numel() * v.element_size() for v in _row_views(e.st, len(snap.ids), max(snap.mtp_len, 0)))
++ return sum(v.numel() * v.element_size() for v in _saved_views(e, snap, drafter))
+
+
+ def snapshot_bytes(snap: Snapshot) -> int:
+@@ -301,9 +320,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)
+
+
+-def load_rows(e: Engine, snap: Snapshot) -> None:
+- """Put a saved snapshot's attention rows back into the live caches."""
+- for dst, src in zip(_row_views(e.st, len(snap.ids), max(snap.mtp_len, 0)), snap.rows):
++def load_rows(e: Engine, snap: Snapshot, drafter=None) -> None:
++ """Put a saved snapshot's attention rows (and DFlash2's, when it saved them: the same ``drafter``) back."""
++ views = _saved_views(e, snap, drafter)
++ if len(views) != len(snap.rows):
++ raise ValueError("a saved snapshot's rows do not match the caches they go back to")
++ for dst, src in zip(views, snap.rows):
+ dst.copy_(src)
+
+
+diff --git tensorfold/families/glm5_next/cuda/engine.py tensorfold/families/glm5_next/cuda/engine.py
+index d770cff..ddb968f 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:
+ return point if point > cut else None
+
+
++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)
++
++
++def shared_prefix(value: str | None = None) -> int:
++ """TF_GLM_SHARED_PREFIX: 0 (off, the default), or the fewest tokens past a request's resume point a shared-prefix
++ state must add (1 or on: 256; else 16 or more).
++
++ On, a drafted text request also keeps its state where its prompt stops sharing a kept one and at the end of its
++ system block (its first user message), each on the prompt grid, so a later prompt sharing only that prefix resumes
++ from it; saved states keep DFlash2's context window too."""
++
++ value = os.environ.get("TF_GLM_SHARED_PREFIX", "") if value is None else value
++ value = value.strip().lower()
++ if value in ("", "0", "off"):
++ return 0
++ if value in ("1", "on"):
++ return SHARED_DEFAULT
++ if not value.isdecimal() or int(value) < SHARED_MIN:
++ raise ValueError(f"TF_GLM_SHARED_PREFIX: 0 (off), 1 (on: {SHARED_DEFAULT} tokens) or the fewest tokens a "
++ f"shared-prefix state adds past a request's resume point, {SHARED_MIN} or more; not {value!r}")
++ return int(value)
++
++
++def common_prefix(a, b) -> int:
++ """How many leading tokens two id sequences (lists or int64 arrays) share."""
++
++ import numpy as np
++
++ n = min(len(a), len(b))
++ if n == 0:
++ return 0
++ x = np.asarray(a[:n], dtype=np.int64)
++ y = np.asarray(b[:n], dtype=np.int64)
++ diff = np.flatnonzero(x != y)
++ return int(diff[0]) if len(diff) else n
++
++
++def shared_points(prompt: list[int], cut: int, point: int | None, grid: int, least: int, known,
++ opener: int | None = None) -> list[int]:
++ """Where a request resumed at ``cut``, keeping its own state at ``point`` (``grid_point``), also keeps shared-prefix
++ states: at the longest prefix it shares with any of ``known`` (id sequences: the kept prompts; not the live reply,
++ which a conversation's next prompt extends anyway) and at its first ``opener`` token (the end of the system block),
++ each rounded down to the grid, kept when it adds at least ``least`` tokens past ``cut`` (and past the other point)
++ and lies short of ``point``. Sorted, at most SHARED_MOST."""
++
++ if not least or point is None:
++ return []
++ import numpy as np
++
++ arr = np.asarray(prompt, dtype=np.int64)
++ # only a sequence longer than cut + least can share enough (known may hold int64 arrays of the ids)
++ wanted = [max((common_prefix(arr, ids) for ids in known if len(ids) >= cut + least), default=0)]
++ if opener is not None:
++ at = np.flatnonzero(arr == opener)
++ if len(at):
++ wanted.append(int(at[0]))
++ out: list[int] = []
++ for p in sorted(p // grid * grid if grid else p for p in wanted):
++ if p - (out[-1] if out else cut) >= least and p < point:
++ out.append(p)
++ return out[-SHARED_MOST:]
++
++
++def user_opener(model_dir: Path) -> int | None:
++ """The id of GLM's ``<|user|>`` role token (the first one ends the system block), or None without a tokenizer."""
++
++ path = Path(model_dir) / "tokenizer.json"
++ if not path.is_file():
++ return None
++ try:
++ added = json.loads(path.read_text()).get("added_tokens", [])
++ except (OSError, ValueError):
++ return None
++ return next((int(t["id"]) for t in added if t.get("content") == "<|user|>"), None)
++
++
+ 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:
+ class GlmEngine:
+ """GLM-5.3-Flash on two ranks (this one ``rank``): weights, MTP and DFlash2 drafting, per-request policies."""
+
++ 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
++
+ 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:
+ 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)
++ # TF_GLM_SHARED_PREFIX: kept states where prompts stop sharing, and saved states keep DFlash2's window; rank 0
++ # picks the points (the header carries them), but both ranks save and evict alike, so both must agree
++ self.shared = shared_prefix()
+ 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:
+ # 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]
+ # 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:
+ 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): "
+ 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:
+ 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)
++ # rank 0: the role token whose first appearance ends a prompt's system block (a shared-prefix point)
++ self.opener = user_opener(model_dir) if self.shared and rank == 0 else None
++ if rank == 0 and self.shared:
++ print(f"[tensorfold] shared-prefix prompt states: kept where a prompt stops sharing another and at the end "
++ f"of its system block, when they add {self.shared}+ tokens (TF_GLM_SHARED_PREFIX)", flush=True)
+ if self.drafter is not None:
+ self.drafter.capture()
+ self.costs = self._calibrate()
+@@ -465,6 +554,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
+
++ drafter = self._kept_drafter()
+ live = self.live
+ dropped = False
+
+@@ -478,7 +568,7 @@ class GlmEngine:
+ if live[:n] != snap.ids: # its rows are already gone: nothing to resume from
+ self._drop(snap)
+ continue
+- need = row_bytes(self.e, snap)
++ need = row_bytes(self.e, snap, drafter=drafter)
+ 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:
+ self._drop(snap)
+ dropped = True
+ continue
+- save_rows(self.e, snap)
++ save_rows(self.e, snap, drafter=drafter)
+ if dropped:
+ import torch
+
+ torch.cuda.empty_cache() # give the freed rows back rather than keep them in torch's pool
+
++ def _kept_drafter(self):
++ """The drafter whose context window saved snapshots keep (TF_GLM_SHARED_PREFIX), or None: they drop it."""
++
++ return getattr(self, "drafter", None) if self.shared else None
++
++ def _shared(self, prompt: list[int], hit) -> list[int]:
++ """Rank 0: the shared-prefix points a drafted text request keeps (``shared_points``), sent to rank 1."""
++
++ if not self.shared:
++ return []
++ import numpy as np
++
++ cut = len(hit.ids) if hit is not None else 0
++ known = []
++ for c in self.cache: # a kept prompt's ids as an array, made once (ids never change)
++ if getattr(c, "ids_array", None) is None:
++ c.ids_array = np.asarray(c.ids, dtype=np.int64)
++ known.append(c.ids_array)
++ return shared_points(prompt, cut, grid_point(len(prompt), cut, self.grid), self.grid, self.shared, known,
++ self.opener)
++
+ def _held_bytes(self) -> int:
+ from .decode import snapshot_bytes
+
+ 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],
+- code: list[int], hit, draft: bool, constraint=None, feed=None) -> dict[str, Any]:
++ code: list[int], hit, draft: bool, constraint=None, feed=None, shared=()) -> dict[str, Any]:
++ """``shared``: rank 0's shared-prefix points (``_shared``), which both ranks keep states at."""
++
+ self.e.constraint, self.e.window = constraint, None # both ranks walk and mask the same rows
+ try:
+- return self._run_once(prompt, max_tokens, sampling, stop_eos, on_tokens, code, hit, draft, feed)
++ return self._run_once(prompt, max_tokens, sampling, stop_eos, on_tokens, code, hit, draft, feed, shared)
+ finally:
+ self.e.constraint = self.e.window = None
+
+ 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]:
++ feed=None, shared=()) -> dict[str, Any]:
+ 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:
+ 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:
+- load_rows(self.e, hit)
++ load_rows(self.e, hit, drafter=self._kept_drafter())
+ 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:
+ # 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
+- resume, kept = hit, None
++ # TF_GLM_SHARED_PREFIX: rank 0's shared-prefix points (past the resume point, short of ``point``) are kept the
++ # same way, each prefilled to as a prompt of its length and resumed from, so fresh and resumed prompts pass
++ # through the same states there too
++ stops = sorted(p for p in set(shared) if point is not None and cut < p < point)
++ stats: dict[str, Any] = {"shared": list(stops)} if stops else {}
+ if point is not None and point < len(prompt):
+- head = list(prompt[:point])
+- prefill(self.e, head, sampling, mtp=use_mtp, drafter=drafter, resume=hit, sample=False)
+- kept = resume = take_snapshot(self.e, head, self.e.last_hidden if use_mtp else None, mtp=use_mtp,
+- drafter=drafter)
++ stops.append(point)
++ resume, kept = hit, []
++ for stop in stops:
++ head = list(prompt[:stop])
++ prefill(self.e, head, sampling, mtp=use_mtp, drafter=drafter, resume=resume, sample=False)
++ resume = take_snapshot(self.e, head, self.e.last_hidden if use_mtp else None, mtp=use_mtp,
++ drafter=drafter)
++ kept.append(resume)
+ first = prefill(self.e, prompt, sampling, mtp=use_mtp, drafter=drafter, resume=resume, feed=feed)
+ prefill_s = time.perf_counter() - t0
+ if point == len(prompt):
+- kept = take_snapshot(self.e, prompt, self.e.last_hidden if use_mtp else None, mtp=use_mtp,
+- drafter=drafter)
+- if kept is not None:
+- self._remember(kept)
+- elif draft and feed is None and hit is not None: # the resume point is the grid point: keep it newest
++ kept.append(take_snapshot(self.e, prompt, self.e.last_hidden if use_mtp else None, mtp=use_mtp,
++ drafter=drafter))
++ if self.shared and draft and feed is None and hit is not None: # what it resumed from is used again
++ self.cache = [c for c in self.cache if c is not hit] + [hit]
++ for snap in kept:
++ self._remember(snap)
++ if not kept and draft and feed is None and hit is not None: # the resume point is the grid point: newest
+ self.cache = [c for c in self.cache if c is not hit] + [hit]
+- stats: dict[str, Any] = {"prefill_s": prefill_s, "cached": cut}
++ stats.update(prefill_s=prefill_s, cached=cut)
+ on_tokens([first])
+ if max_tokens <= 1 or (stop_eos and first in self.eos):
+ return stats
+@@ -634,12 +757,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
++ shared = self._shared(list(prompt), hit) if draft and feed is None else []
+ seed = (sampling.seed if sampling else 0) & 0xFFFFFFFFFFFFFFFF
+ header = [max_tokens, int(stop_eos), int(draft), len(hit.ids) if hit is not None else 0,
+ seed & 0x7FFFFFFF, (seed >> 31) & 0x7FFFFFFF, seed >> 62,
+ *_f64_ints(sampling.temperature if sampling else 0.0), int(sampling.top_k) if sampling else 0,
+ *_f64_ints(sampling.top_p if sampling else 1.0), *_f64_ints(sampling.min_p if sampling else 0.0),
+- int(constraint is not None), len(positions)] + code
++ int(constraint is not None), len(positions),
++ *(shared + [0] * SHARED_MOST)[:SHARED_MOST]] + code
+ from tensorfold.engine.grammar import pack
+
+ self._share(header)
+@@ -648,7 +773,8 @@ class GlmEngine:
+ self._share(pack(constraint))
+ if positions:
+ self._share(positions)
+- stats = self._run(list(prompt), max_tokens, sampling, stop_eos, on_tokens, code, hit, draft, constraint, feed)
++ stats = self._run(list(prompt), max_tokens, sampling, stop_eos, on_tokens, code, hit, draft, constraint, feed,
++ shared)
+ 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:
+ def follow(self) -> None:
+ """Rank 1: mirror every request rank 0 serves, forever."""
+
++ while True:
++ self.follow_one()
++
++ def follow_one(self) -> None:
++ """Rank 1: mirror one request rank 0 serves."""
++
+ from tensorfold.engine.exact_sampling import Sampling
+
+- while True:
+- (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)
+- packed = self._share(None) if shaped else []
+- constraint = None
+- if packed: # compiled here as on rank 0
+- from tensorfold.engine import grammar
+-
+- constraint = grammar.compiler(self, self.model_dir, self.eos).follow(packed)
+- feed = VisionFeed(self, self._share(None), None) if images else None
+- 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))
+- if temperature > 0 else None)
+- hit = None
+- if cached:
+- hit = next((c for c in self.cache if len(c.ids) == cached and prompt[:cached] == c.ids), None)
+- if hit is None:
+- raise RuntimeError(f"rank 1 has no snapshot of the {cached} tokens rank 0 resumes from")
+- self._run(prompt, max_tokens, sampling, bool(stop_eos), lambda new: None, code, hit, bool(draft),
+- constraint, feed)
+- if hasattr(self.comm, "check"):
+- self.comm.check()
++ (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:]
++ prompt = self._share(None)
++ packed = self._share(None) if shaped else []
++ constraint = None
++ if packed: # compiled here as on rank 0
++ from tensorfold.engine import grammar
++
++ constraint = grammar.compiler(self, self.model_dir, self.eos).follow(packed)
++ feed = VisionFeed(self, self._share(None), None) if images else None
++ 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))
++ if temperature > 0 else None)
++ hit = None
++ if cached:
++ hit = next((c for c in self.cache if len(c.ids) == cached and prompt[:cached] == c.ids), None)
++ if hit is None:
++ raise RuntimeError(f"rank 1 has no snapshot of the {cached} tokens rank 0 resumes from")
++ self._run(prompt, max_tokens, sampling, bool(stop_eos), lambda new: None, code, hit, bool(draft),
++ constraint, feed, shared)
++ if hasattr(self.comm, "check"):
++ self.comm.check()
+
+
+ class VisionFeed:
diff --git a/patches/0016-glm-decode-kernels.patch b/patches/0016-glm-decode-kernels.patch
new file mode 100644
index 0000000..8e258f0
--- /dev/null
+++ b/patches/0016-glm-decode-kernels.patch
@@ -0,0 +1,600 @@
+diff --git tensorfold/cuda/kernels/qmm.cpp tensorfold/cuda/kernels/qmm.cpp
+index c46571f..c94e59b 100644
+--- tensorfold/cuda/kernels/qmm.cpp
++++ tensorfold/cuda/kernels/qmm.cpp
+@@ -3,6 +3,8 @@
+
+ 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&,
++ at::Tensor&, const at::Tensor&, int, int, bool, int);
+ 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
+ static_cast<int>(bm), f32, reduce);
+ }
+
++// ``qmm`` for decode rows (M <= 16, groups of 64, K slices reduced) on tile config ``cfg`` (same bits, other speed).
++void qmm_cfg(const at::Tensor& x, const at::Tensor& xs, const at::Tensor& w, const at::Tensor& scales,
++ const at::Tensor& biases, at::Tensor& out, const c10::optional<at::Tensor>& part, int64_t n, int64_t sk,
++ bool f32, int64_t cfg) {
++ TORCH_CHECK(x.is_cuda() && x.scalar_type() == at::kBFloat16 && x.dim() == 2 && x.size(0) >= 1 &&
++ x.size(0) <= 16 && x.stride(1) == 1 && x.stride(0) >= x.size(1), "x: (M <= 16, K) bf16");
++ TORCH_CHECK(reinterpret_cast<uintptr_t>(x.data_ptr()) % 16 == 0 && (x.size(0) == 1 || x.stride(0) % 8 == 0),
++ "x rows must start on 16-byte boundaries");
++ const int64_t m = x.size(0), k = x.size(1), kg = k / 64, npad = (n + 127) / 128 * 128;
++ TORCH_CHECK(k % 64 == 0 && sk >= 1 && kg % sk == 0, "K splits into whole groups a slice");
++ TORCH_CHECK(xs.is_cuda() && xs.is_contiguous() && xs.scalar_type() == at::kFloat && xs.size(0) == m &&
++ xs.size(1) == kg, "xs: (M, K / 64) fp32");
++ TORCH_CHECK(w.is_cuda() && w.is_contiguous() && w.scalar_type() == at::kInt && w.numel() == npad * k / 8,
++ "packed weight does not match n and K");
++ TORCH_CHECK(scales.stride(1) == 1 && biases.stride(1) == 1 && scales.stride(0) >= npad &&
++ biases.stride(0) == scales.stride(0) && scales.scalar_type() == at::kBFloat16 &&
++ biases.scalar_type() == at::kBFloat16 && scales.size(0) == kg && scales.size(1) == npad,
++ "scales and biases: (K / 64, n padded to 128) bf16");
++ TORCH_CHECK(out.is_cuda() && out.is_contiguous() && out.size(0) == m && out.size(1) == n &&
++ out.scalar_type() == (f32 ? at::kFloat : at::kBFloat16), "out: (M, n)");
++ c10::cuda::CUDAGuard guard(x.device());
++ at::Tensor p;
++ if (sk > 8) {
++ 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");
++ }
++ qmm_cfg_cuda(x, xs, w, scales, biases, out, p, static_cast<int>(n), static_cast<int>(sk), f32,
++ static_cast<int>(cfg));
++}
++
+ // 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&
+
+ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
+ m.def("qmm", &qmm);
++ m.def("qmm_cfg", &qmm_cfg);
+ m.def("qmm_prefill", &qmm_prefill);
+ 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
+--- 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
+ }
+ }
+
++// Decode rows (a 16-row tile) on other column tiles, warps and stage counts: every output's chain (groups in order
++// within its K slice, slices added in order) is qmm_kernel's, so every choice gives the same bits.
++template <bool F32, bool CLUSTER>
++void dispatch_cfg(int cfg, const at::Tensor& x, const at::Tensor& xs, const at::Tensor& w, const at::Tensor& s,
++ const at::Tensor& b, at::Tensor& out, const at::Tensor& part, int N, int SK) {
++ switch (cfg) {
++ case 0: launch<64, 16, 64, 1, 4, 4, F32, CLUSTER>(x, xs, w, s, b, out, part, N, SK); break;
++ case 1: launch<64, 16, 128, 1, 4, 4, F32, CLUSTER>(x, xs, w, s, b, out, part, N, SK); break;
++ case 2: launch<64, 16, 128, 1, 8, 4, F32, CLUSTER>(x, xs, w, s, b, out, part, N, SK); break;
++ case 3: launch<64, 16, 64, 1, 4, 8, F32, CLUSTER>(x, xs, w, s, b, out, part, N, SK); break;
++ case 4: launch<64, 16, 128, 1, 4, 6, F32, CLUSTER>(x, xs, w, s, b, out, part, N, SK); break;
++ case 5: launch<64, 16, 64, 1, 2, 6, F32, CLUSTER>(x, xs, w, s, b, out, part, N, SK); break;
++ case 6: launch<64, 16, 128, 1, 8, 6, F32, CLUSTER>(x, xs, w, s, b, out, part, N, SK); break;
++ case 7: launch<64, 16, 64, 1, 4, 6, F32, CLUSTER>(x, xs, w, s, b, out, part, N, SK); break;
++ case 8: launch<64, 16, 64, 1, 4, 4, F32, CLUSTER, true>(x, xs, w, s, b, out, part, N, SK); break;
++ 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;
++ default: TORCH_CHECK(false, "qmm_cfg: tile config 0-11");
++ }
++}
++
+ } // namespace
+
++// ``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;
++ 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);
++ else dispatch_cfg<false, false>(cfg, x, xs, w, scales, biases, out, part, N, SK); }
++ if (SK > 1 && !cluster) {
++ const long long total = static_cast<long long>(M) * N;
++ const int threads = 256;
++ const int blocks = static_cast<int>((total + threads - 1) / threads);
++ auto stream = at::cuda::getCurrentCUDAStream();
++ if (f32) reduce_kernel<true><<<blocks, threads, 0, stream>>>(part.data_ptr<float>(), out.data_ptr(), total, SK);
++ else reduce_kernel<false><<<blocks, threads, 0, stream>>>(part.data_ptr<float>(), out.data_ptr(), total, SK);
++ C10_CUDA_KERNEL_LAUNCH_CHECK();
++ }
++}
++
+ void qmm_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, int gs, int bm,
+ bool f32, bool reduce) {
+diff --git tensorfold/cuda/kernels/qmm.py tensorfold/cuda/kernels/qmm.py
+index 8792eb5..da21210 100644
+--- tensorfold/cuda/kernels/qmm.py
++++ tensorfold/cuda/kernels/qmm.py
+@@ -16,7 +16,7 @@ def _ext():
+ from tensorfold.cuda.build import load
+
+ here = Path(__file__).parent
+- return load(name="tensorfold_qmm_v3", sources=[str(here / "qmm.cpp"), str(here / "qmm.cu"),
++ return load(name="tensorfold_qmm_v4", sources=[str(here / "qmm.cpp"), str(here / "qmm.cu"),
+ str(here / "qmm_prefill.cu"), str(here / "qmm_prefill8.cu")],
+ extra_cuda_cflags=["-O3"], verbose=False)
+
+@@ -138,8 +138,10 @@ def group_sums(x: torch.Tensor, gs: int = 64) -> torch.Tensor:
+
+
+ def matmul(x: torch.Tensor, q: Q4, xs: torch.Tensor | None = None, *, sk: int | None = None, f32: bool = False,
+- out: torch.Tensor | None = None, part: torch.Tensor | None = None, reduce: bool = True) -> torch.Tensor:
+- """x @ q.T as (M, n) bf16, or unrounded fp32 with ``f32``; ``reduce=False`` returns K slices to add in order."""
++ out: torch.Tensor | None = None, part: torch.Tensor | None = None, reduce: bool = True,
++ variant: int | None = None) -> torch.Tensor:
++ """x @ q.T as (M, n) bf16, or unrounded fp32 with ``f32``; ``reduce=False`` returns K slices to add in order;
++ ``variant``: decode rows (up to 16, groups of 64) on another tile config (``qmm_cfg``: the same bits)."""
+
+ if x.dtype != torch.bfloat16 or x.dim() != 2 or x.shape[1] != q.k:
+ raise ValueError(f"matmul: x must be (M, {q.k}) bf16")
+@@ -153,6 +155,9 @@ def matmul(x: torch.Tensor, q: Q4, xs: torch.Tensor | None = None, *, sk: int |
+ out = torch.empty((m, q.n), dtype=torch.float32 if f32 else torch.bfloat16, device=x.device)
+ if sk > 1 and not reduce and part is None:
+ part = torch.empty((sk, m, q.n), dtype=torch.float32, device=x.device)
++ if variant is not None and reduce and m <= 16 and q.gs == 64:
++ _ext().qmm_cfg(x, xs, q.weight, q.scales, q.biases, out, part, q.n, sk, f32, int(variant))
++ return out
+ _ext().qmm(x, xs, q.weight, q.scales, q.biases, out, part, q.n, sk, q.gs, bucket(m), f32, reduce)
+ 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
+--- tensorfold/families/glm5_next/cuda/decode.py
++++ tensorfold/families/glm5_next/cuda/decode.py
+@@ -96,6 +96,10 @@ class Engine:
+ self.grid = grid
+ w.meta["long_context"] = long_context
+ self.rows, self.prefill_rows = max_rows, prefill_rows
++ if any(l.kind == "kda" for l in w.layers): # the wide KDA chain's scratch, before any capture
++ from . import kda as kda_mod
++
++ kda_mod.reserve(max(max_rows, prefill_rows), w.cfg.lin_heads // w.world, w.device)
+ self.buf = Buffers(w, max_rows, capacity)
+ self.pbuf = Buffers(w, prefill_rows, capacity, prefill=True)
+ if taps:
+diff --git tensorfold/families/glm5_next/cuda/exl3.cpp tensorfold/families/glm5_next/cuda/exl3.cpp
+index 3a392a2..9755ea8 100644
+--- tensorfold/families/glm5_next/cuda/exl3.cpp
++++ tensorfold/families/glm5_next/cuda/exl3.cpp
+@@ -16,6 +16,10 @@ void exl3_prompt_cuda(const at::Tensor&, const at::Tensor&, const at::Tensor&, c
+ const at::Tensor&, const at::Tensor&, at::Tensor&, at::Tensor&, int64_t, int64_t, int64_t, int64_t,
+ double, int64_t, int64_t, bool);
+ void exl3_rot_rows_cuda(const at::Tensor&, int64_t, const at::Tensor&, at::Tensor&, int64_t, int64_t);
++void exl3_dec_cuda(const at::Tensor&, const at::Tensor&, const at::Tensor&, const at::Tensor&, const at::Tensor&,
++ const at::Tensor&, const at::Tensor&, at::Tensor&, int64_t, int64_t, int64_t, int64_t, int64_t,
++ int64_t, int64_t, int64_t, int64_t, bool, const at::Tensor&, const at::Tensor&,
++ const at::Tensor&, at::Tensor&, double, at::Tensor&);
+
+ static void check(const at::Tensor& x, at::ScalarType t, const char* name) {
+ TORCH_CHECK(x.is_cuda() && x.scalar_type() == t && x.is_contiguous(), name,
+@@ -104,6 +108,27 @@ void prompt(const at::Tensor& Xg, const at::Tensor& Xu, const at::Tensor& Tg, co
+ max_items, limit, pass, slots, shx);
+ }
+
++// Decode windows: the grouped kernel's sums; fuse 1 writes Y (down, its epilogue fused), 2 writes Xd
++// (gate/up, the epilogue run by each (item, n block)'s last block; ``done`` zeroed ints, reset by the kernel).
++void dec(const at::Tensor& X0, const at::Tensor& X1, const at::Tensor& T0, const at::Tensor& T1, const at::Tensor& items,
++ const at::Tensor& counts, const at::Tensor& members, at::Tensor Z, int64_t mats, int64_t K, int64_t N,
++ int64_t P, int64_t SK, int64_t max_items, int64_t slots, int64_t fuse, bool xrow,
++ const at::Tensor& sv0, const at::Tensor& sv1, const at::Tensor& su2, at::Tensor out, double limit,
++ at::Tensor done) {
++ const int64_t E = T0.size(0);
++ for (auto* t : {&X0, &X1, &sv0, &sv1, &su2}) check(*t, at::kHalf, "dec: fp16 input");
++ for (auto* t : {&T0, &T1, &items, &counts, &members}) check(*t, at::kInt, "dec: int32 input");
++ check(done, at::kInt, "done");
++ check(Z, at::kFloat, "Z");
++ TORCH_CHECK(fuse == 1 || Z.numel() >= mats * SK * P * N, "Z too small");
++ TORCH_CHECK(fuse != 1 || (out.scalar_type() == at::kFloat && out.numel() >= P * N), "dec: Y fp32 [P, N]");
++ TORCH_CHECK(fuse != 2 || (out.scalar_type() == at::kHalf && out.numel() >= P * N &&
++ done.numel() >= max_items * (N / 128)), "dec: Xd fp16 [P, N] and done counts");
++ c10::cuda::CUDAGuard guard(X0.device());
++ exl3_dec_cuda(X0, X1, T0, T1, items, counts, members, Z, mats, K, N, P, SK, max_items, E, slots, fuse, xrow,
++ sv0, sv1, su2, out, limit, done);
++}
++
+ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
+ m.def("grouped", &grouped);
+ m.def("prompt", &prompt);
+@@ -111,4 +136,5 @@ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
+ m.def("rot_rows", &rot_rows);
+ m.def("gateup_epilogue", &gateup_epilogue);
+ m.def("down_epilogue", &down_epilogue);
++ m.def("dec", &dec);
+ }
+diff --git tensorfold/families/glm5_next/cuda/exl3.cu tensorfold/families/glm5_next/cuda/exl3.cu
+index 46cb22d..19357c7 100644
+--- tensorfold/families/glm5_next/cuda/exl3.cu
++++ tensorfold/families/glm5_next/cuda/exl3.cu
+@@ -306,6 +306,187 @@ __global__ void down_epilogue_kernel(const float* __restrict__ Z, const int* __r
+ for (int j = 0; j < 4; ++j) o[j] = v[j] * HAD_SCALE * __half2float(svh_d[(size_t)e * D + n + j]);
+ }
+
++// ---- decode windows: grouped_kernel's arithmetic with its epilogues fused -------------------------------------
++// Every mma chain, warp sum and split sum is grouped_kernel's (non-SEQ, register prefetch of the next k step): a
++// warp runs k tiles kt0 .. kt0 + STEPS - 1 of its split in order from zero, the warps are added in warp order, the
++// splits in split order from 0. What changes:
++// FUSE 1 (the down projection, SK = 1): the block's 128 columns are one Hadamard block, so it applies
++// down_epilogue_kernel's arithmetic to its own sums and writes Y, no Z round trip, no epilogue launch;
++// FUSE 2 (gate and up): each block still writes its Z partial; the last of the 2 * SK blocks of an (item, n block)
++// to finish (an atomic count, reset for the next launch) runs gateup_epilogue_kernel's arithmetic on the item's
++// rows and 128 columns, reading the partials in split order: the same sums whichever block finishes last.
++// XROW: X holds one row a token (rot_rows, a layer whose experts share one suh), pair p reads row p / slots.
++template <int NT, int W, int STEPS, int FUSE, bool XROW>
++__global__ void __launch_bounds__(W * 32) dec_kernel(
++ const half* __restrict__ X0, const half* __restrict__ X1, const uint32_t* __restrict__ T0,
++ const uint32_t* __restrict__ T1, const int* __restrict__ items, const int* __restrict__ counts,
++ const int* __restrict__ members, float* __restrict__ Z, int K, int N, int P, int SK, int E, int slots,
++ const half* __restrict__ sv0, const half* __restrict__ sv1, const half* __restrict__ su2, void* __restrict__ out,
++ float limit, int* __restrict__ done) {
++ static_assert(FUSE == 0 || NT * 16 == 128, "a fused epilogue needs one 128-column Hadamard block a program");
++ const int item = blockIdx.x, nblock = blockIdx.y;
++ if (item >= counts[0]) return;
++ const int e = items[3 * item], first = items[3 * item + 1], cnt = items[3 * item + 2];
++ if (e >= E) return; // the shared expert (id E) is not EXL3
++ const int mat = blockIdx.z / SK, split = blockIdx.z % SK;
++ const half* X = mat ? X1 : X0;
++ const uint32_t* T = mat ? T1 : T0;
++ const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31;
++ const int g = lane >> 2, t = lane & 3;
++ const int KT = K >> 4, NTILES = N >> 4;
++
++ __shared__ int rows_sh[16];
++ __shared__ float red[W][16][NT * 16];
++ if (threadIdx.x < 16) rows_sh[threadIdx.x] = (int)threadIdx.x < cnt ? members[first + threadIdx.x] : -1;
++ __syncthreads();
++ const int r0 = rows_sh[g], r1 = rows_sh[g + 8];
++ const int xr0 = r0 < 0 ? 0 : (XROW ? r0 / slots : r0), xr1 = r1 < 0 ? 0 : (XROW ? r1 / slots : r1);
++ const half* x0 = X + (size_t)xr0 * K + 2 * t;
++ const half* x1 = X + (size_t)xr1 * K + 2 * t;
++ const int nt0 = nblock * NT;
++ const int kt0 = split * (KT / SK) + warp * STEPS;
++ const uint32_t* tile = T + (((size_t)e * KT + kt0) * NTILES + nt0) * 32 + lane;
++
++ float acc[NT][2][4];
++#pragma unroll
++ for (int i = 0; i < NT; ++i)
++#pragma unroll
++ for (int h = 0; h < 2; ++h)
++#pragma unroll
++ for (int c = 0; c < 4; ++c) acc[i][h][c] = 0.f;
++
++ // grouped_kernel's PF loop as it is (a runtime loop: unrolling it measured slower)
++ uint32_t words[NT], a[4];
++#pragma unroll
++ for (int i = 0; i < NT; ++i) words[i] = __ldg(tile + i * 32);
++ {
++ const int k = kt0 * 16;
++ a[0] = load_pair(x0 + k, r0 >= 0); a[1] = load_pair(x1 + k, r1 >= 0);
++ a[2] = load_pair(x0 + k + 8, r0 >= 0); a[3] = load_pair(x1 + k + 8, r1 >= 0);
++ }
++ for (int kt = kt0; kt < kt0 + STEPS; ++kt) {
++ uint32_t nw[NT], na[4];
++ const bool more = kt + 1 < kt0 + STEPS;
++ if (more) {
++ const uint32_t* next = tile + (size_t)NTILES * 32;
++#pragma unroll
++ for (int i = 0; i < NT; ++i) nw[i] = __ldg(next + i * 32);
++ const int k = (kt + 1) * 16;
++ na[0] = load_pair(x0 + k, r0 >= 0); na[1] = load_pair(x1 + k, r1 >= 0);
++ na[2] = load_pair(x0 + k + 8, r0 >= 0); na[3] = load_pair(x1 + k + 8, r1 >= 0);
++ }
++#pragma unroll
++ for (int i = 0; i < NT; ++i) {
++ uint32_t b0[2], b1[2];
++ decode_tile(words[i], lane, b0, b1);
++ mma16816(acc[i][0], a, b0);
++ mma16816(acc[i][1], a, b1);
++ }
++ if (more) {
++#pragma unroll
++ for (int i = 0; i < NT; ++i) words[i] = nw[i];
++#pragma unroll
++ for (int c = 0; c < 4; ++c) a[c] = na[c];
++ }
++ tile += (size_t)NTILES * 32;
++ }
++
++#pragma unroll
++ for (int i = 0; i < NT; ++i)
++#pragma unroll
++ for (int h = 0; h < 2; ++h) {
++ const int col = i * 16 + h * 8 + 2 * t;
++ red[warp][g][col] = acc[i][h][0];
++ red[warp][g][col + 1] = acc[i][h][1];
++ red[warp][g + 8][col] = acc[i][h][2];
++ red[warp][g + 8][col + 1] = acc[i][h][3];
++ }
++ __syncthreads();
++
++ if constexpr (FUSE == 1) {
++ // down_epilogue_kernel on this block's sums: v = 0 + (the warps' sums in warp order), rotated, times svh
++ const half* svh_d = sv0;
++ float* y = reinterpret_cast<float*>(out);
++ for (int i = warp; i < cnt; i += W) {
++ const int p = rows_sh[i];
++ const int n = nt0 * 16 + 4 * lane;
++ float v[4];
++#pragma unroll
++ for (int j = 0; j < 4; ++j) {
++ float s = red[0][i][4 * lane + j];
++#pragma unroll
++ for (int w = 1; w < W; ++w) s += red[w][i][4 * lane + j];
++ float z = 0.f;
++ z += s;
++ v[j] = z;
++ }
++ fwht128(v, lane);
++ float* o = y + (size_t)p * N + n;
++#pragma unroll
++ for (int j = 0; j < 4; ++j) o[j] = v[j] * HAD_SCALE * __half2float(svh_d[(size_t)e * N + n + j]);
++ }
++ return;
++ } else {
++ constexpr int OUT = 16 * NT * 16 / (W * 32);
++#pragma unroll
++ for (int j = 0; j < OUT; ++j) {
++ const int idx = threadIdx.x + j * W * 32;
++ const int row = idx / (NT * 16), col = idx % (NT * 16);
++ const int r = rows_sh[row];
++ float s = red[0][row][col];
++#pragma unroll
++ for (int w = 1; w < W; ++w) s += red[w][row][col];
++ if (r >= 0) Z[(((size_t)mat * SK + split) * P + r) * N + nt0 * 16 + col] = s;
++ }
++ if constexpr (FUSE == 2) {
++ __shared__ int last;
++ __threadfence(); // this block's partials before its count
++ __syncthreads();
++ if (threadIdx.x == 0) {
++ int* c = done + (size_t)item * gridDim.y + nblock;
++ last = atomicAdd(c, 1) == 2 * SK - 1;
++ if (last) *c = 0; // the next launch starts from zero
++ }
++ __syncthreads();
++ if (!last) return;
++ __threadfence(); // every block's partials are visible from here
++ const half* svh_g = sv0;
++ const half* svh_u = sv1;
++ const half* suh_d = su2;
++ half* xd = reinterpret_cast<half*>(out);
++ for (int i = warp; i < cnt; i += W) {
++ const int p = rows_sh[i];
++ const int n = nt0 * 16 + 4 * lane;
++ float gv[4], uv[4];
++#pragma unroll
++ for (int j = 0; j < 4; ++j) {
++ float sg = 0.f, su = 0.f;
++ for (int s = 0; s < SK; ++s) {
++ sg += __ldcg(Z + ((size_t)(0 * SK + s) * P + p) * N + n + j);
++ su += __ldcg(Z + ((size_t)(1 * SK + s) * P + p) * N + n + j);
++ }
++ gv[j] = sg;
++ uv[j] = su;
++ }
++ fwht128(gv, lane);
++ fwht128(uv, lane);
++ float v[4];
++#pragma unroll
++ for (int j = 0; j < 4; ++j) {
++ float gg = fminf(bf16r(gv[j] * HAD_SCALE * __half2float(svh_g[(size_t)e * N + n + j])), limit);
++ float uu = fminf(fmaxf(bf16r(uv[j] * HAD_SCALE * __half2float(svh_u[(size_t)e * N + n + j])),
++ -limit), limit);
++ float act = bf16r(bf16r(gg / (1.f + expf(-gg))) * uu);
++ v[j] = act * __half2float(suh_d[(size_t)e * N + n + j]);
++ }
++ fwht128(v, lane);
++ half* o = xd + (size_t)p * N + n;
++#pragma unroll
++ for (int j = 0; j < 4; ++j) o[j] = __float2half_rn(v[j] * HAD_SCALE);
++ }
++ }
++ }
++}
+
+ // ---- prompt chunks: Y^T = W^T X^T --------------------------------------------------------------------------------
+ // A decoded trellis tile is, reordered, an m16n8k16 A fragment of W^T (lane (g, t): a0 = b0[0], a1 = b1[0],
+@@ -643,6 +824,35 @@ void exl3_down_epilogue_cuda(const at::Tensor& Z, const at::Tensor& pick, const
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
+ }
+
++// Decode windows (items of up to 16 pairs): ``dec_kernel`` with NT 8, 4 warps and 16 k steps a warp (both of GLM's
++// expert matmuls: gate/up K 4096 in 4 splits, down K 1024 in 1). fuse 0: Z as exl3_grouped_cuda; 1: Y (down); 2: Xd
++// (gate/up; ``done`` holds max_items * N / 128 zeroed ints).
++void exl3_dec_cuda(const at::Tensor& X0, const at::Tensor& X1, const at::Tensor& T0, const at::Tensor& T1,
++ const at::Tensor& items, const at::Tensor& counts, const at::Tensor& members, at::Tensor& Z,
++ int64_t mats, int64_t K, int64_t N, int64_t P, int64_t SK, int64_t max_items, int64_t E,
++ int64_t slots, int64_t fuse, bool xrow, const at::Tensor& sv0, const at::Tensor& sv1,
++ const at::Tensor& su2, at::Tensor& out, double limit, at::Tensor& done) {
++ constexpr int NT = 8, W = 4, STEPS = 16;
++ TORCH_CHECK(K % (16 * SK * W) == 0 && K / (16 * SK * W) == STEPS && N % (16 * NT) == 0,
++ "decode expert kernel: 16 k steps a warp");
++ TORCH_CHECK(fuse != 1 || (SK == 1 && mats == 1), "the fused down epilogue takes one split of one matrix");
++ TORCH_CHECK(fuse != 2 || mats == 2, "the fused gate/up epilogue takes gate and up");
++ dim3 grid((unsigned)max_items, (unsigned)(N / (16 * NT)), (unsigned)(mats * SK));
++ auto stream = at::cuda::getCurrentCUDAStream();
++ auto h = [](const at::Tensor& t) { return reinterpret_cast<const half*>(t.data_ptr()); };
++ auto w = [](const at::Tensor& t) { return reinterpret_cast<const uint32_t*>(t.data_ptr()); };
++#define DEC(F_, XR_) \
++ dec_kernel<NT, W, STEPS, F_, XR_><<<grid, W * 32, 0, stream>>>( \
++ h(X0), h(X1), w(T0), w(T1), items.data_ptr<int>(), counts.data_ptr<int>(), members.data_ptr<int>(), \
++ Z.data_ptr<float>(), (int)K, (int)N, (int)P, (int)SK, (int)E, (int)slots, h(sv0), h(sv1), h(su2), \
++ out.data_ptr(), (float)limit, done.data_ptr<int>())
++ if (fuse == 0) { if (xrow) DEC(0, true); else DEC(0, false); }
++ else if (fuse == 1) { if (xrow) DEC(1, true); else DEC(1, false); }
++ else { if (xrow) DEC(2, true); else DEC(2, false); }
++#undef DEC
++ C10_CUDA_KERNEL_LAUNCH_CHECK();
++}
++
+ // Prompt chunks (a plan of PM-pair items, PM 64 or 128): Xd [P, N] = the gate/up epilogue of Xg/Xu's pairs;
+ // Y [P, D] = the down epilogue.
+ template <int PM, int NW>
+diff --git tensorfold/families/glm5_next/cuda/exl3_mm.py tensorfold/families/glm5_next/cuda/exl3_mm.py
+index 5e21f90..c872731 100644
+--- tensorfold/families/glm5_next/cuda/exl3_mm.py
++++ tensorfold/families/glm5_next/cuda/exl3_mm.py
+@@ -4,6 +4,7 @@ from __future__ import annotations
+
+ from dataclasses import dataclass, field
+ from functools import lru_cache
++import os
+ from pathlib import Path
+
+ import torch
+@@ -31,6 +32,20 @@ def _nfirst() -> bool:
+ return os.environ.get("TF_GLM_EXL3_NFIRST", "1") != "0"
+
+
++def dec_settings() -> tuple[bool, int, bool]:
++ """Decode windows' EXL3 path. TF_GLM_EXL3_DEC (default on): ``dec``, grouped_kernel's sums with the down
++ projection's epilogue fused into it (one launch less a layer, no Z round trip); TF_GLM_EXL3_FUSE: 1 (default) the
++ down epilogue, 2 gate/up's too (the last of an item's blocks runs it: measured slower), 0 neither;
++ TF_GLM_EXL3_XROW (default on): a layer whose experts share one gate/up suh rotates each row's input once
++ (rot_rows: the same fp16 inputs). Every setting gives the same bits; TF_GLM_EXL3_DEC=0: the grouped kernel and
++ its epilogue kernels."""
++ on = os.environ.get("TF_GLM_EXL3_DEC", "1") != "0"
++ fuse = int(os.environ.get("TF_GLM_EXL3_FUSE", "1"))
++ if fuse not in (0, 1, 2, 3):
++ raise ValueError(f"TF_GLM_EXL3_FUSE is 0 to 3, not {fuse}")
++ return on, fuse, os.environ.get("TF_GLM_EXL3_XROW", "1") != "0"
++
++
+ def _seq() -> bool:
+ """TF_GLM_EXL3_SEQ (default on): prompt chunks sum a matmul's K splits in one program (same bits)."""
+ import os
+@@ -43,7 +58,7 @@ def _ext():
+ from tensorfold.cuda.build import load
+
+ here = Path(__file__).parent
+- return load(name="tensorfold_glm_exl3_v15", sources=[str(here / "exl3.cpp"), str(here / "exl3.cu")],
++ return load(name="tensorfold_glm_exl3_v17", sources=[str(here / "exl3.cpp"), str(here / "exl3.cu")],
+ extra_cuda_cflags=["-O3"], verbose=False)
+
+
+@@ -134,6 +149,9 @@ class Scratch:
+ self.xu = torch.zeros((P, dims), dtype=torch.float16, device=device)
+ self.xd = torch.zeros((P, width), dtype=torch.float16, device=device)
+ self.z = torch.zeros((1 if prompt else 2 * sk * P * max(width, dims),), dtype=torch.float32, device=device)
++ # decode windows' fused gate/up epilogue: a finished-block count per (item, 128 columns), reset by the kernel
++ self.done = torch.zeros((1 if prompt else (P + P // grouped.TILE + 1) * max(1, width // 128),),
++ dtype=torch.int32, device=device)
+ self.rows, self.slots = rows, slots
+
+
+@@ -160,6 +178,24 @@ def routed(x: torch.Tensor, pick: torch.Tensor, plan: grouped.Plan, ex: Exl3Expe
+ if plan.tile != grouped.TILE:
+ raise ValueError("the EXL3 kernel takes items of 16 pairs")
+ items = grouped.max_items(R * slots, plan.experts)
++ dec, fuse, xrow = dec_settings()
++ if dec and R < PROMPT_ROWS and GATEUP_CFG == (8, 4, 4) and DOWN_CFG == (8, 4, 1) and D == 4096 and NI == 1024:
++ xrow = xrow and ex.shared_suh is not None
++ if xrow: # one rotated input a row, read by all its pairs' gate and up
++ ext.rot_rows(x, x.stride(0), ex.shared_suh, s.xg, R, D)
++ xg = xu = s.xg
++ else:
++ ext.rot_in(x, x.stride(0), pick, ex.suh_g, ex.suh_u, s.xg, s.xu, R, D, slots)
++ xg, xu = s.xg, s.xu
++ ext.dec(xg, xu, ex.gt, ex.ut, plan.items, plan.counts, plan.members, s.z, 2, D, NI, P, 4, items, slots,
++ 2 if fuse & 2 else 0, xrow, ex.svh_g, ex.svh_u, ex.suh_d, s.xd, float(limit), s.done)
++ if not fuse & 2:
++ ext.gateup_epilogue(s.z, pick, ex.svh_g, ex.svh_u, ex.suh_d, s.xd, R, P, NI, 4, slots, float(limit))
++ ext.dec(s.xd, s.xd, ex.dt, ex.dt, plan.items, plan.counts, plan.members, s.z, 1, NI, D, P, 1, items, slots,
++ 1 if fuse & 1 else 0, False, ex.svh_d, ex.svh_d, ex.svh_d, y, 0.0, s.done)
++ if not fuse & 1:
++ ext.down_epilogue(s.z, pick, ex.svh_d, y, R, P, D, 1, slots)
++ return
+ ext.rot_in(x, x.stride(0), pick, ex.suh_g, ex.suh_u, s.xg, s.xu, R, D, slots)
+ nfirst = R >= PROMPT_ROWS and _nfirst()
+ nt, w, sk = GATEUP_CFG
+diff --git tensorfold/families/glm5_next/cuda/kda.py tensorfold/families/glm5_next/cuda/kda.py
+index 9975ab1..bd3a28e 100644
+--- tensorfold/families/glm5_next/cuda/kda.py
++++ tensorfold/families/glm5_next/cuda/kda.py
+@@ -56,23 +56,39 @@ def replay_layers(state_in: torch.Tensor, scratch: KDAScratchSet, rows: int, sta
+ scratch.rows * H, L, H, int(rows), state_out)
+
+
+-WIDE_ROWS = 64 # windows of this many rows or more (prefill chunks) run the chain in three kernels
++# windows of this many rows or more run the chain in three kernels (prep / step / out: 8 blocks a head instead of one;
++# chain_kernel's bits). TF_GLM_KDA_WIDE_ROWS, default 1: every window (decode windows measured 4-36% faster at 1-8
++# rows on GB10); 64: the one-block chain below 64 rows, as before.
++WIDE_ROWS = int(os.environ.get("TF_GLM_KDA_WIDE_ROWS", "1"))
+ # prompt chunks in chunked (WY) form, 64-row sub-chunks at absolute positions (kda_chunked.py): close, not the same bits
+ CHUNKED = os.environ.get("TF_GLM_KDA_CHUNKED", "0") == "1"
+ _tmp: dict = {}
++_outgrown: list = []
+
+
+ def _wide_scratch(rows: int, heads: int, device) -> tuple[torch.Tensor, torch.Tensor]:
+- """The normalized q and the read-out of a long window, shared by every layer (they run one after another)."""
++ """The normalized q and the read-out of a long window, shared by every layer (they run one after another).
++ ``reserve`` sizes them before any CUDA graph is captured: a graph keeps the addresses it was captured with."""
++ device = torch.device(device)
++ if device.type == "cuda" and device.index is None:
++ device = torch.device("cuda", torch.cuda.current_device())
+ key = (heads, device)
+ q, y = _tmp.get(key, (None, None))
+ if q is None or q.shape[0] < rows:
++ if q is not None: # a captured graph may still use the smaller pair: keep it alive
++ _outgrown.append((q, y))
+ q = torch.empty((rows, heads, DK), dtype=torch.float32, device=device)
+ y = torch.empty((rows, heads, DV), dtype=torch.bfloat16, device=device)
+ _tmp[key] = (q, y)
+ return q, y
+
+
++def reserve(rows: int, heads: int, device) -> None:
++ """The wide path's scratch for windows of up to ``rows`` rows, allocated now (before graph capture)."""
++
++ _wide_scratch(rows, heads, device)
++
++
+ def chain(p: torch.Tensor, b_off: int, a: torch.Tensor, g: torch.Tensor, conv_state: torch.Tensor,
+ 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
+--- 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:
+ raise ValueError(f"matmul: x {tuple(x.shape)} {x.dtype} does not match K={q.k}")
+ if out is not None and (out.shape != (x.shape[0], q.n) or not out.is_contiguous()):
+ raise ValueError(f"matmul: out {tuple(out.shape)} must be a contiguous ({x.shape[0]}, {q.n})")
+- return shared.matmul(x, q, group_sums(x) if xs is None else xs, sk=split_k(q.n, q.k), f32=f32, out=out)
++ return shared.matmul(x, q, group_sums(x) if xs is None else xs, sk=split_k(q.n, q.k), f32=f32, out=out,
++ variant=dec_tile(q.n, q.k) if x.shape[0] <= 16 else None)
++
++
++# Decode rows (up to 16) of a Q4 matmul on another column tile / warp / stage count (``shared.qmm_cfg``): every
++# output keeps its chain, so every choice gives the same bits. By per-rank shape (n, k), measured on GB10.
++DEC_TILES: dict[tuple[int, int], int] = {(4096, 4096): 2, (2048, 4096): 2, (8192, 1536): 2, (4096, 8192): 4,
++ (4096, 1024): 6}
++_dec_env: tuple[str, dict] = ("", {})
++
++
++def dec_tile(n: int, k: int) -> int | None:
++ """TF_GLM_Q4_TILE: unset or "table" the table above, "stock" none, a number that config for every shape."""
++
++ import os
++
++ global _dec_env
++ value = os.environ.get("TF_GLM_Q4_TILE", "") or "table"
++ if value != _dec_env[0]:
++ table = DEC_TILES if value == "table" else {} if value == "stock" else None
++ _dec_env = (value, table if table is not None else {"all": int(value)})
++ table = _dec_env[1]
++ return table.get("all", table.get((n, k)))
+
+
+ def b16_split_k(n: int, k: int) -> int:
diff --git a/patches/0017-glm-overlap-priority.patch b/patches/0017-glm-overlap-priority.patch
new file mode 100644
index 0000000..f40e0a8
--- /dev/null
+++ b/patches/0017-glm-overlap-priority.patch
@@ -0,0 +1,15 @@
+diff --git tensorfold/families/glm5_next/cuda/hcsplit.py tensorfold/families/glm5_next/cuda/hcsplit.py
+index 0002a96..a294319 100644
+--- tensorfold/families/glm5_next/cuda/hcsplit.py
++++ tensorfold/families/glm5_next/cuda/hcsplit.py
+@@ -107,7 +107,9 @@ class HcSplit:
+ self.got: list[torch.Tensor] = []
+ self.stream = None
+ if settings.overlap:
+- self.stream = torch.cuda.Stream(priority=-1)
++ # TF_GLM_OVERLAP_PRIORITY: the side stream's priority (-1 high, 0 normal); a high-priority stream in the
++ # process may cost decode rounds (graphs on the default stream) a little: measured per boot
++ self.stream = torch.cuda.Stream(priority=-1 if os.environ.get("TF_GLM_OVERLAP_PRIORITY", "-1").strip() != "0" else 0)
+ n = settings.piece_count()
+ self.ev_fill = [torch.cuda.Event() for _ in range(n)]
+ self.ev_part = [torch.cuda.Event() for _ in range(n)]
diff --git a/patches/0018-glm-noise-policies.patch b/patches/0018-glm-noise-policies.patch
new file mode 100644
index 0000000..2e214e0
--- /dev/null
+++ b/patches/0018-glm-noise-policies.patch
@@ -0,0 +1,237 @@
+diff --git tensorfold/families/glm5_next/cuda/decode.py tensorfold/families/glm5_next/cuda/decode.py
+index 2debdad..2c20f11 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
+
+
+ class DepthPolicy:
+- """Choose a fixed draft count or adapt it to running acceptance."""
++ """Choose a fixed draft count or adapt it to running acceptance. DFlash2 stop rules within a round: the product of
++ the chain's confidences holds ``confidence``; with ``beta`` > 0 those confidences are noise-aware
++ (``dflash2.noisy_confidence``), and with ``round_ms`` too (ms of a round of k drafts, k = 0..) the chain is cut
++ where E[tokens] / ms is largest instead. MTP chains ignore ``beta`` and ``round_ms``."""
+
+ def __init__(self, most: int = 3, fixed: bool = False, low: float = 0.8, high: float = 0.9,
+- confidence: float = 0.0) -> None:
++ confidence: float = 0.0, beta: float = 0.0, round_ms: tuple[float, ...] | None = None) -> None:
+ self.most, self.fixed, self.low, self.high = most, fixed, low, high
+ self.confidence = confidence
++ self.beta, self.round_ms = beta, round_ms
+ self.rate = 0.8
+
++ @property
++ def chain_rule(self) -> dict:
++ """Drafter.propose's keyword arguments for the noise-aware rules (none for the others)."""
++
++ return {"beta": self.beta, "round_ms": self.round_ms} if self.beta > 0 else {}
++
+ 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
+ if copied:
+ drafts = copied
+ else:
+- drafts = drafter.propose(out[-1], depth, sampling, policy.confidence) if depth > 0 else []
++ drafts = (drafter.propose(out[-1], depth, sampling, policy.confidence, **policy.chain_rule)
++ if depth > 0 else [])
+ t1 = time.perf_counter()
+ 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
+--- tensorfold/families/glm5_next/cuda/dflash2.py
++++ tensorfold/families/glm5_next/cuda/dflash2.py
+@@ -21,6 +21,31 @@ from .weights import Weights
+ EDGE = 0.6 # the selector's edge score weight in a chain pick
+ NOISE = 0.7 # the target's keyed noise weight when sampling
+ NO_LIMIT = 1e30
++# the noise-aware stop rules' temperature B (fnc<N>:<p>, fcost<N>:noisy): draft_sim's NoisyPredictor beta, fitted by
++# log loss (``fit_beta``, its grid) on the 9 teacher-forced dumps of 2026-09-30 (7 sampled prose, 2 greedy code):
++# 2.0 on all of them, on the sampled ones alone and on the greedy ones alone (a finer grid: 1.8, log loss -0.2%)
++NOISY_BETA = 2.0
++
++
++def noisy_confidence(score: np.ndarray, noise: np.ndarray | None, j: int, beta: float) -> float:
++ """softmax((score + g) / beta) at the pick j, g the target's keyed Gumbel draws for the candidates (None: greedy,
++ softmax(score / beta)): the chance the target's keyed sample is the pick when its scaled logits are the drafter's
++ plus iid Gumbel(beta) errors. draft_sim's ``noisy_prob`` feature, the same float64 operations in the same order."""
++
++ z = score + noise if noise is not None else score
++ z = z / beta
++ e = np.exp(z - z.max())
++ return float(e[j] / e.sum())
++
++
++def best_depth(q, round_ms) -> int:
++ """The k (0..len(q)) maximizing E[tokens | k drafts] / round_ms[k], q the drafts' conditional acceptances
++ (``draft_sim.best_depth`` with round_ms[k] = its Costs.round_ms(k, 1, True))."""
++
++ alive = np.concatenate([[1.0], np.cumprod(np.asarray(q, dtype=np.float64))])
++ expect = np.cumsum(alive)
++ ms = np.asarray(round_ms[:len(q) + 1], dtype=np.float64)
++ return int(np.argmax(expect / ms))
+
+
+ @triton.jit
+@@ -444,8 +469,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,
+- sampling: Sampling | None, confidence: float = 0.0) -> list[int]:
+- """Choose candidates with selector edges and target keyed noise; stop below cumulative confidence, always keeping the first draft."""
++ sampling: Sampling | None, confidence: float = 0.0, *, beta: float = 0.0,
++ round_ms: tuple[float, ...] | None = None) -> list[int]:
++ """Choose candidates with selector edges and target keyed noise; stop below cumulative confidence, always
++ keeping the first draft. ``beta`` > 0: the confidences are noise-aware (``noisy_confidence``); with
++ ``round_ms`` (ms of a round of k drafts, k = 0..) the chain is walked whole and cut at ``best_depth`` of
++ them instead (``confidence`` unused). Only where the chain stops changes: the picks are the same."""
+
+ depth = tokens.shape[0]
+ sampled = sampling is not None and sampling.temperature > 0
+@@ -453,27 +482,44 @@ class Drafter:
+ noise = None
+ if sampled:
+ noise = -np.log(-np.log(uniform_rows(sampling.seed, first + np.arange(depth), tokens)))
++ noisy = beta > 0
+ out: list[int] = []
++ conf: list[float] = []
+ prev, chain = anchor, 1.0
+ for d in range(depth):
+ edge = self.succ[tokens[d]].astype(np.float64) @ (self.pred[prev].astype(np.float64) * proj[d])
+ score = (values[d] + EDGE * edge) / temp
+ pick = score + NOISE * noise[d] if noise is not None else score
+ j = int(np.argmax(pick))
+- if confidence > 0:
++ if noisy:
++ c = noisy_confidence(score, noise[d] if noise is not None else None, j, beta)
++ if round_ms is not None:
++ conf.append(c)
++ else:
++ chain *= c
++ if d > 0 and chain < confidence:
++ break
++ elif confidence > 0:
+ p = np.exp(score - score.max())
+ chain *= float(p[j] / p.sum())
+ if d > 0 and chain < confidence:
+ break
+ prev = int(tokens[d, j])
+ out.append(prev)
++ if noisy and round_ms is not None:
++ out = out[:best_depth(conf, round_ms)]
+ return out
+
+- def propose(self, pending: int, depth: int, sampling: Sampling | None, confidence: float = 0.0) -> list[int]:
+- """Up to ``depth`` drafts for the positions after the pending token (which sits at context_end)."""
++ def propose(self, pending: int, depth: int, sampling: Sampling | None, confidence: float = 0.0, *,
++ beta: float = 0.0, round_ms: tuple[float, ...] | None = None) -> list[int]:
++ """Up to ``depth`` drafts for the positions after the pending token (which sits at context_end); ``beta``,
++ ``round_ms``: the noise-aware stop rules (``chain``)."""
+
+ depth = min(depth, self.block - 1)
+ if depth < 1 or self.context_end == 0:
+ return []
+ tokens, values, proj = self.candidates(pending, depth)
++ if beta > 0:
++ return self.chain(tokens, values, proj, pending, self.context_end + 1, sampling, confidence, beta=beta,
++ 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
+--- 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:
+
+
+ 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."""
++ """Encode policy kind, maximum drafts, and two parameters in millionths as four integers, with 10 added to kind for DFlash2.
++
++ DFlash2 only: ``fncN:P[:B]`` (kind 16: the fcN:P product of noise-aware confidences, B their temperature,
++ default ``dflash2.NOISY_BETA``) and ``fcostN:noisy[:B]`` (kind 17: the depth k <= N maximizing E[tokens] / round
++ ms by the startup cost table, E from the same confidences; N up to the captured verify windows' drafts)."""
+
+ spec = str(spec).strip()
+ bad = ValueError(f"draft policy {spec!r}: expected auto[:E:EVERY:MARGIN], 0, N, a[:LOW:HIGH], cN:P, or one of "
+- f"these after f (N from 1 to {MAX_ROWS - 1})")
++ f"these after f (N from 1 to {MAX_ROWS - 1}), fncN:P[:B] or fcostN:noisy[:B] "
++ f"(N up to {len(GRAPH_ROWS) - 1})")
+ try:
+ if spec == "auto" or spec.startswith("auto:"):
+ parts = spec.split(":")
+@@ -163,6 +168,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))]
++ if spec.startswith(("fnc", "fcost")):
++ return _encode_noisy(spec[1:], bad)
+ 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]:
+ return [1 if most > 0 else 0, most, 0, 0]
+
+
+-def decode_policy(code: list[int]):
+- """Decode a serial, MTP, or automatic policy, retaining exploration, sampling, and margin settings."""
++def _encode_noisy(spec: str, bad: ValueError) -> list[int]:
++ """``ncN:P[:B]`` -> [16, N, P, B] and ``costN:noisy[:B]`` -> [17, N, B, 0], P and B in millionths (DFlash2 only)."""
++
++ from .dflash2 import NOISY_BETA
++
++ cost = spec.startswith("cost")
++ parts = spec[4 if cost else 2:].split(":")
++ if len(parts) not in (2, 3) or (cost and parts[1] != "noisy"):
++ raise bad
++ most = int(parts[0])
++ beta = float(parts[2]) if len(parts) == 3 else NOISY_BETA
++ if not 0 < most <= len(GRAPH_ROWS) - 1 or not 0 < beta <= 1000 or round(beta * 1e6) < 1:
++ raise bad
++ if cost:
++ return [17, most, int(round(beta * 1e6)), 0]
++ conf = float(parts[1])
++ if not 0 <= conf <= 1:
++ raise bad
++ return [16, most, int(round(conf * 1e6)), int(round(beta * 1e6))]
++
++
++def decode_policy(code: list[int], costs: dict | None = None):
++ """Decode a serial, MTP, or automatic policy, retaining exploration, sampling, and margin settings; ``costs``: the
++ startup cost table (``GlmEngine._calibrate``) the fcost rule weighs a round's depths by."""
+
+ from .decode import DepthPolicy
+
+@@ -199,9 +228,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)
++ if kind == 6:
++ return DepthPolicy(min(most, MAX_ROWS - 1), fixed=True, confidence=a / 1e6, beta=b / 1e6)
++ if kind == 7:
++ if costs is None:
++ raise ValueError("the fcost policy needs the engine's cost table")
++ return DepthPolicy(min(most, MAX_ROWS - 1), fixed=True, beta=a / 1e6, round_ms=round_costs(costs))
+ return DepthPolicy(min(most, MAX_ROWS - 1), fixed=True) if kind == 1 else None
+
+
++def round_costs(costs: dict) -> tuple[float, ...]:
++ """ms of a DFlash2 round of k drafts, k = 0 .. len(verify) - 1: the verify window of k + 1 rows, the block and a
++ kept row's context update, as draft_sim's Costs(verify, block, 0.0, taps_row).round_ms(k, 1, True)."""
++
++ return tuple(v + costs["block"] + 0.0 + costs["taps_row"] * 1 for v in costs["verify"])
++
++
+ def _f64_ints(x: float) -> list[int]:
+ return list(struct.unpack("<2i", struct.pack("<d", float(x))))
+
+@@ -674,7 +716,7 @@ class GlmEngine:
+ on_tokens([first])
+ if max_tokens <= 1 or (stop_eos and first in self.eos):
+ return stats
+- policy = decode_policy(code)
++ 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
+ from .copy_drafts import CopyDrafts
diff --git a/patches/0019-glm-decode-kernels2.patch b/patches/0019-glm-decode-kernels2.patch
new file mode 100644
index 0000000..1e1a691
--- /dev/null
+++ b/patches/0019-glm-decode-kernels2.patch
@@ -0,0 +1,269 @@
+diff --git tensorfold/cuda/kernels/qmm.cu tensorfold/cuda/kernels/qmm.cu
+index 2828909..5853a81 100644
+--- tensorfold/cuda/kernels/qmm.cu
++++ tensorfold/cuda/kernels/qmm.cu
+@@ -56,9 +56,15 @@ __global__ void __launch_bounds__(WM * WN * 32) qmm_kernel(
+ unsigned char* pw = p + T::X;
+ constexpr int TILE_BYTES = 64 * GS / 2; // one stored 64-column tile's group block
+ for (int c = tid; c < T::W / 16; c += T::THREADS) {
+- const int t = c / (TILE_BYTES / 16), off = c % (TILE_BYTES / 16);
+- const size_t tile = static_cast<size_t>(n0 / 64 + t) * KG + g;
+- cp16(pw + c * 16, reinterpret_cast<const unsigned char*>(w) + tile * TILE_BYTES + off * 16);
++ if constexpr (BN >= 64) {
++ const int t = c / (TILE_BYTES / 16), off = c % (TILE_BYTES / 16);
++ const size_t tile = static_cast<size_t>(n0 / 64 + t) * KG + g;
++ cp16(pw + c * 16, reinterpret_cast<const unsigned char*>(w) + tile * TILE_BYTES + off * 16);
++ } else { // part of a stored tile: its n8 tiles are contiguous
++ const size_t tile = static_cast<size_t>(n0 / 64) * KG + g;
++ cp16(pw + c * 16, reinterpret_cast<const unsigned char*>(w) + tile * TILE_BYTES + (n0 % 64) * GS / 2 +
++ c * 16);
++ }
+ }
+ 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::
+ 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;
+- default: TORCH_CHECK(false, "qmm_cfg: tile config 0-11");
++ case 12: launch<64, 16, 32, 1, 4, 4, F32, CLUSTER>(x, xs, w, s, b, out, part, N, SK); break;
++ case 13: launch<64, 16, 32, 1, 2, 6, F32, CLUSTER>(x, xs, w, s, b, out, part, N, SK); break;
++ case 14: launch<64, 16, 32, 1, 4, 8, F32, CLUSTER>(x, xs, w, s, b, out, part, N, SK); break;
++ case 15: launch<64, 16, 32, 1, 1, 6, F32, CLUSTER>(x, xs, w, s, b, out, part, N, SK); break;
++ default: TORCH_CHECK(false, "qmm_cfg: tile config 0-15");
+ }
+ }
+
+diff --git tensorfold/families/glm5_next/cuda/forward.py tensorfold/families/glm5_next/cuda/forward.py
+index c4c8ab3..7f56f87 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:
+ 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"):
+- if b.prefill: # the shared row read from sy where it is (the copy's bits, one pass less)
++ # 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
++ if b.prefill or __import__("os").environ.get("TF_GLM_COMBINE_SY", "1") != "0":
+ glue.combine_shared(b.ey[lo:hi], b.sy[lo:hi], b.wts[lo:hi], b.part[lo:hi])
+ else:
+ b.ey[lo:hi, c.top_k].copy_(b.sy[lo:hi])
+diff --git tensorfold/families/glm5_next/cuda/glue.py tensorfold/families/glm5_next/cuda/glue.py
+index 620025a..ae13bb7 100644
+--- tensorfold/families/glm5_next/cuda/glue.py
++++ tensorfold/families/glm5_next/cuda/glue.py
+@@ -186,6 +186,23 @@ def _hc_partial_mma(X, FN, PART, R, WIDE: tl.constexpr, NB: tl.constexpr, BM: tl
+ HC_MMA = __import__("os").environ.get("TF_GLM_HC_MMA", "1") != "0" # prompt rows' mixing dots on the tensor cores
+
+
++def hc_dec() -> bool:
++ """TF_GLM_HC_DEC (default on): decode rows' mixing dots in hc.cu, 48 blocks a row instead of 16, _hc_partial's
++ bits; 0: _hc_partial."""
++ return __import__("os").environ.get("TF_GLM_HC_DEC", "1") != "0"
++
++
++@__import__("functools").lru_cache(maxsize=1)
++def _hc_ext():
++ from pathlib import Path
++
++ from tensorfold.cuda.build import load
++
++ here = Path(__file__).parent
++ return load(name="tensorfold_glm_hc_v2", sources=[str(here / "hc.cpp"), str(here / "hc.cu")],
++ extra_cuda_cflags=["-O3"], verbose=False)
++
++
+ def hc_pre(x: torch.Tensor, fn: torch.Tensor, base: torch.Tensor, scale: torch.Tensor, norm_w: torch.Tensor,
+ out: torch.Tensor, xs: torch.Tensor, post: torch.Tensor, comb: torch.Tensor, part: torch.Tensor,
+ eps: float, hc_eps: float, iters: int, *, prompt: bool = False) -> None:
+@@ -198,6 +215,9 @@ def hc_pre(x: torch.Tensor, fn: torch.Tensor, base: torch.Tensor, scale: torch.T
+ if prompt and HC_MMA and x.is_contiguous():
+ _hc_partial_mma[(triton.cdiv(rows, 64), HC_BLOCKS)](x, fn, part, rows, WIDE=wide, NB=HC_BLOCKS, BM=64, BK=64,
+ num_warps=4, num_stages=3)
++ elif (hc_dec() and wide == 16384 and fn.shape[0] == 24 and HC_BLOCKS == 16 and x.is_contiguous()
++ and fn.is_contiguous() and part.is_contiguous()):
++ _hc_ext().hc_partial(x, fn, part, rows) # _hc_partial's bits on 48 blocks a row
+ else:
+ _hc_partial[(rows, HC_BLOCKS)](x, fn, part, WIDE=wide, NB=HC_BLOCKS, SUB=128, num_warps=4)
+ _hc_finish[(rows,)](x, part, base, scale, norm_w, out, xs, post, comb, eps, hc_eps, D=d, S=s, NB=HC_BLOCKS,
+diff --git tensorfold/families/glm5_next/cuda/hc.cpp tensorfold/families/glm5_next/cuda/hc.cpp
+new file mode 100644
+index 0000000..4c0cd6a
+--- /dev/null
++++ tensorfold/families/glm5_next/cuda/hc.cpp
+@@ -0,0 +1,21 @@
++#include <torch/extension.h>
++#include <c10/cuda/CUDAGuard.h>
++
++void hc_partial_cuda(const at::Tensor&, const at::Tensor&, at::Tensor&, int64_t);
++
++// PART [rows, 16, 32] fp32 = glue._hc_partial's output for x [rows, 16384] bf16 and fn [24, 16384] bf16.
++void hc_partial(const at::Tensor& x, const at::Tensor& fn, at::Tensor part, int64_t rows) {
++ TORCH_CHECK(x.is_cuda() && x.scalar_type() == at::kBFloat16 && x.is_contiguous() && x.size(1) == 16384,
++ "hc_partial: x [rows, 16384] bf16, contiguous");
++ TORCH_CHECK(fn.is_cuda() && fn.scalar_type() == at::kBFloat16 && fn.is_contiguous() && fn.size(0) == 24 &&
++ fn.size(1) == 16384, "hc_partial: fn [24, 16384] bf16");
++ TORCH_CHECK(part.is_cuda() && part.scalar_type() == at::kFloat && part.is_contiguous() &&
++ part.numel() >= rows * 16 * 32, "hc_partial: part [rows, 16, 32] fp32");
++ TORCH_CHECK(rows >= 1 && x.size(0) >= rows, "hc_partial: rows");
++ c10::cuda::CUDAGuard guard(x.device());
++ hc_partial_cuda(x, fn, part, rows);
++}
++
++PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
++ m.def("hc_partial", &hc_partial);
++}
+diff --git tensorfold/families/glm5_next/cuda/hc.cu tensorfold/families/glm5_next/cuda/hc.cu
+new file mode 100644
+index 0000000..2236475
+--- /dev/null
++++ tensorfold/families/glm5_next/cuda/hc.cu
+@@ -0,0 +1,97 @@
++// GLM-5.3-Flash's hyper-connection mixing dots for decode rows (hc_pre's first half) with more blocks than
++// glue._hc_partial, reproducing its bits: that Triton kernel (4 warps, a [32, 128] bf16 tile in the blocked layout
++// sizePerThread [1, 8], threadsPerWarp [2, 16]) sums, for each of 8 steps of 128 inputs, a row's 8 products per
++// thread in input order (products of bf16 values are exact in fp32, so fused or not), then across the 16 lanes of
++// the row with butterflies 8, 4, 2, 1, and adds the steps to a zero accumulator in order; the sum of squares keeps
++// one input per thread (4 warps x 32 lanes), adds the 8 steps' squares to zero in order, then butterflies 16 .. 1
++// within each warp and (w0 + w2) + (w1 + w3) across the warps. PART [rows, 16 blocks, 32]: the 24 dots, then the sum.
++
++#include <ATen/ATen.h>
++#include <ATen/cuda/CUDAContext.h>
++#include <cuda_bf16.h>
++
++namespace {
++
++constexpr int WIDE = 16384, NB = 16, KB = WIDE / NB, SUB = 128, STEPS = KB / SUB, ROWS = 24;
++
++__device__ __forceinline__ void unpack8(const uint4 v, float (&f)[8]) {
++ const uint32_t w[4] = {v.x, v.y, v.z, v.w};
++#pragma unroll
++ for (int i = 0; i < 4; ++i) {
++ f[2 * i] = __uint_as_float(w[i] << 16);
++ f[2 * i + 1] = __uint_as_float(w[i] & 0xffff0000u);
++ }
++}
++
++// Block (K block, part, row group): warps 0..7 the dots of mixing rows 8 part .. 8 part + 7 (their weights read once
++// for up to RPB rows), warp 8 of part 0 the squares.
++constexpr int RPB = 4;
++
++__global__ void __launch_bounds__(288) hc_partial_kernel(const __nv_bfloat16* __restrict__ X,
++ const __nv_bfloat16* __restrict__ FN, float* __restrict__ part,
++ int rows) {
++ const int b = blockIdx.x, p = blockIdx.y, r0 = blockIdx.z * RPB;
++ const int r1 = min(r0 + RPB, rows);
++ const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31;
++ if (warp < 8) {
++ const int m = p * 8 + warp;
++ const int h = lane >> 4, l = lane & 15;
++ const __nv_bfloat16* wr = FN + (size_t)m * WIDE + b * KB;
++ float wf[4][8];
++#pragma unroll
++ for (int i = 0; i < 4; ++i) // steps 2 i + h, inputs 8 l .. 8 l + 7 of the step
++ unpack8(__ldg(reinterpret_cast<const uint4*>(wr + (2 * i + h) * SUB + 8 * l)), wf[i]);
++ for (int r = r0; r < r1; ++r) {
++ const __nv_bfloat16* xr = X + (size_t)r * WIDE + b * KB;
++ uint4 xv[4];
++#pragma unroll
++ for (int i = 0; i < 4; ++i) xv[i] = __ldg(reinterpret_cast<const uint4*>(xr + (2 * i + h) * SUB + 8 * l));
++ float s[4];
++#pragma unroll
++ for (int i = 0; i < 4; ++i) {
++ float xf[8];
++ unpack8(xv[i], xf);
++ float a = __fmul_rn(wf[i][0], xf[0]);
++#pragma unroll
++ for (int j = 1; j < 8; ++j) a = __fmaf_rn(wf[i][j], xf[j], a);
++#pragma unroll
++ for (int o = 8; o; o >>= 1) a = __fadd_rn(a, __shfl_xor_sync(0xffffffffu, a, o));
++ s[i] = a;
++ }
++ float acc = 0.f;
++#pragma unroll
++ for (int i = 0; i < 4; ++i) {
++ acc = __fadd_rn(acc, s[i]); // step 2 i (half 0)
++ acc = __fadd_rn(acc, __shfl_sync(0xffffffffu, s[i], 16)); // step 2 i + 1 (half 1)
++ }
++ if (lane == 0) part[((size_t)r * NB + b) * 32 + m] = acc;
++ }
++ } else if (p == 0) {
++ for (int r = r0; r < r1; ++r) {
++ const __nv_bfloat16* xr = X + (size_t)r * WIDE + b * KB;
++ float w[4];
++#pragma unroll
++ for (int j = 0; j < 4; ++j) { // the Triton kernel's warp j: input 32 j + lane of each step
++ float ss = 0.f;
++#pragma unroll
++ for (int t = 0; t < STEPS; ++t) {
++ const float x = __bfloat162float(xr[t * SUB + 32 * j + lane]);
++ ss = __fmaf_rn(x, x, ss);
++ }
++#pragma unroll
++ for (int o = 16; o; o >>= 1) ss = __fadd_rn(ss, __shfl_xor_sync(0xffffffffu, ss, o));
++ w[j] = ss;
++ }
++ if (lane == 0) part[((size_t)r * NB + b) * 32 + ROWS] = __fadd_rn(__fadd_rn(w[0], w[2]), __fadd_rn(w[1], w[3]));
++ }
++ }
++}
++
++} // namespace
++
++void hc_partial_cuda(const at::Tensor& x, const at::Tensor& fn, at::Tensor& part, int64_t rows) {
++ hc_partial_kernel<<<dim3(NB, 3, (unsigned)((rows + RPB - 1) / RPB)), 288, 0, at::cuda::getCurrentCUDAStream()>>>(
++ reinterpret_cast<const __nv_bfloat16*>(x.data_ptr()), reinterpret_cast<const __nv_bfloat16*>(fn.data_ptr()),
++ part.data_ptr<float>(), (int)rows);
++ 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
+--- 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
+ tl.store(OUT + (r * H + h) * LW + k, (o / l).to(tl.bfloat16))
+
+
++def chunk_stages() -> int:
++ """TF_GLM_LATENT_STAGES (default 3): Triton pipeline depth of the dense / sparse chunk programs' key tiles: the
++ loads only, the same bits (1: none, as before; 4 does not fit in shared memory)."""
++ return int(__import__("os").environ.get("TF_GLM_LATENT_STAGES", "3"))
++
++
+ class LatentScratch:
+ """Chunk partials for up to rows x heads x chunks, the absorbed queries and the attended latents."""
+
+@@ -615,7 +621,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,
+- CH=CHUNK, SCALE=scale, HBT=hb, KTT=KT, num_warps=8, num_stages=1)
++ CH=CHUNK, SCALE=scale, HBT=hb, KTT=KT, num_warps=8,
++ num_stages=chunk_stages())
+ _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
+ 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,
+- CH=CHUNK, SCALE=scale, HBT=hb, KTT=KT, num_warps=8, num_stages=1)
++ CH=CHUNK, SCALE=scale, HBT=hb, KTT=KT, num_warps=8,
++ num_stages=chunk_stages())
+ _merge[(R, H)](po, pm, pl, out, counts, R, H=H, LW=LW, NCH=nch, SPARSE=True, num_warps=4)
+
+
+diff --git tensorfold/families/glm5_next/cuda/qmm.py tensorfold/families/glm5_next/cuda/qmm.py
+index 7330c93..65e7921 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:
+ # Decode rows (up to 16) of a Q4 matmul on another column tile / warp / stage count (``shared.qmm_cfg``): every
+ # output keeps its chain, so every choice gives the same bits. By per-rank shape (n, k), measured on GB10.
+ DEC_TILES: dict[tuple[int, int], int] = {(4096, 4096): 2, (2048, 4096): 2, (8192, 1536): 2, (4096, 8192): 4,
+- (4096, 1024): 6}
++ (4096, 1024): 2}
+ _dec_env: tuple[str, dict] = ("", {})
+
+
diff --git a/patches/0020-glm-prompt-experts-order.patch b/patches/0020-glm-prompt-experts-order.patch
new file mode 100644
index 0000000..5e90cb9
--- /dev/null
+++ b/patches/0020-glm-prompt-experts-order.patch
@@ -0,0 +1,320 @@
+diff --git tensorfold/families/glm5_next/cuda/exl3.cpp tensorfold/families/glm5_next/cuda/exl3.cpp
+index 9755ea8..908afbe 100644
+--- tensorfold/families/glm5_next/cuda/exl3.cpp
++++ tensorfold/families/glm5_next/cuda/exl3.cpp
+@@ -14,7 +14,7 @@ void exl3_down_epilogue_cuda(const at::Tensor&, const at::Tensor&, const at::Ten
+ void exl3_prompt_cuda(const at::Tensor&, const at::Tensor&, const at::Tensor&, const at::Tensor&, const at::Tensor&,
+ const at::Tensor&, const at::Tensor&, const at::Tensor&, const at::Tensor&, const at::Tensor&,
+ const at::Tensor&, const at::Tensor&, at::Tensor&, at::Tensor&, int64_t, int64_t, int64_t, int64_t,
+- double, int64_t, int64_t, bool);
++ double, int64_t, int64_t, bool, const c10::optional<at::Tensor>&);
+ void exl3_rot_rows_cuda(const at::Tensor&, int64_t, const at::Tensor&, at::Tensor&, int64_t, int64_t);
+ void exl3_dec_cuda(const at::Tensor&, const at::Tensor&, const at::Tensor&, const at::Tensor&, const at::Tensor&,
+ const at::Tensor&, const at::Tensor&, at::Tensor&, int64_t, int64_t, int64_t, int64_t, int64_t,
+@@ -96,7 +96,7 @@ void prompt(const at::Tensor& Xg, const at::Tensor& Xu, const at::Tensor& Tg, co
+ const at::Tensor& Td, const at::Tensor& items, const at::Tensor& counts, const at::Tensor& members,
+ const at::Tensor& svh_g, const at::Tensor& svh_u, const at::Tensor& suh_d, const at::Tensor& svh_d,
+ at::Tensor xd, at::Tensor y, int64_t D, int64_t N, int64_t E, int64_t max_items, double limit,
+- int64_t pass, int64_t slots, bool shx) {
++ int64_t pass, int64_t slots, bool shx, c10::optional<at::Tensor> order) {
+ const at::cuda::CUDAGuard guard(Xg.device());
+ for (auto* t : {&Xg, &Xu, &svh_g, &svh_u, &suh_d, &svh_d}) check(*t, at::kHalf, "prompt: fp16 input");
+ for (auto* t : {&Tg, &Tu, &Td, &items, &counts, &members}) check(*t, at::kInt, "prompt: int32 input");
+@@ -104,8 +104,9 @@ void prompt(const at::Tensor& Xg, const at::Tensor& Xu, const at::Tensor& Tg, co
+ check(y, at::kFloat, "prompt: y");
+ TORCH_CHECK(!shx || Xg.data_ptr() == Xu.data_ptr(), "prompt: shared rows take one Xh for gate and up");
+ TORCH_CHECK(slots > 0, "prompt: slots");
++ if (order.has_value()) check(*order, at::kInt, "prompt: order");
+ exl3_prompt_cuda(Xg, Xu, Tg, Tu, Td, items, counts, members, svh_g, svh_u, suh_d, svh_d, xd, y, D, N, E,
+- max_items, limit, pass, slots, shx);
++ max_items, limit, pass, slots, shx, order);
+ }
+
+ // Decode windows: the grouped kernel's sums; fuse 1 writes Y (down, its epilogue fused), 2 writes Xd
+diff --git tensorfold/families/glm5_next/cuda/exl3.cu tensorfold/families/glm5_next/cuda/exl3.cu
+index 19357c7..363fa23 100644
+--- tensorfold/families/glm5_next/cuda/exl3.cu
++++ tensorfold/families/glm5_next/cuda/exl3.cu
+@@ -41,6 +41,18 @@ __device__ __forceinline__ void decode_tile(uint32_t w, int lane, uint32_t (&b0)
+ b1[1] = mcg2((w >> 4) & 0xffffu, w & 0xffffu);
+ }
+
++// decode_tile's values with fewer integer instructions (the prompt kernels): the byte-aligned 16-bit states taken
++// with one PRMT each and w >> 4 shared by two states. The same states, so the same bits.
++__device__ __forceinline__ void decode_tile_p(uint32_t w, int lane, uint32_t (&b0)[2], uint32_t (&b1)[2]) {
++ const uint32_t p = __shfl_sync(0xffffffffu, w, (lane + 31) & 31);
++ const uint32_t s = __funnelshift_r(w, p, 20);
++ const uint32_t t = w >> 4;
++ b0[0] = mcg2(__byte_perm(s, 0u, 0x4421), (s >> 4) & 0xffffu); // (s >> 8) & 0xffff, (s >> 4) & 0xffff
++ b0[1] = mcg2(s & 0xffffu, w >> 16);
++ b1[0] = mcg2(__byte_perm(t, 0u, 0x4421), __byte_perm(w, 0u, 0x4421)); // (w >> 12) & 0xffff, (w >> 8) & 0xffff
++ b1[1] = mcg2(__byte_perm(t, 0u, 0x4410), w & 0xffffu); // (w >> 4) & 0xffff, w & 0xffff
++}
++
+ __device__ __forceinline__ void mma16816(float (&d)[4], const uint32_t (&a)[4], const uint32_t (&b)[2]) {
+ asm volatile("mma.sync.aligned.m16n8k16.row.col.f32.f16.f16.f32 {%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, "
+ "{%0,%1,%2,%3};\n"
+@@ -593,7 +605,7 @@ __device__ __forceinline__ void prompt_mainloop(const half* __restrict__ X0, con
+ #pragma unroll
+ for (int i = 0; i < C::MT; ++i) {
+ uint32_t b0[2], b1[2];
+- decode_tile(ws[((size_t)(warp * C::MT + i) * PKT + kk) * 32 + lane], lane, b0, b1);
++ decode_tile_p(ws[((size_t)(warp * C::MT + i) * PKT + kk) * 32 + lane], lane, b0, b1);
+ a[i][0] = b0[0]; a[i][1] = b1[0]; a[i][2] = b0[1]; a[i][3] = b1[1];
+ }
+ #pragma unroll
+@@ -603,10 +615,11 @@ __device__ __forceinline__ void prompt_mainloop(const half* __restrict__ X0, con
+ const int row = jb * 16 + (lane & 7) + ((lane >> 4) & 1) * 8;
+ ldsm_x4(r, xs + (size_t)row * PXS + kk * 16 + ((lane >> 3) & 1) * 8);
+ const uint32_t bl[2] = {r[0], r[1]}, bh[2] = {r[2], r[3]};
++ const bool upper = jb * 16 + 8 < cnt; // members 8..15 of the block (else zero rows)
+ #pragma unroll
+ for (int i = 0; i < C::MT; ++i) {
+ mma16816(acc[i][2 * jb], a[i], bl);
+- mma16816(acc[i][2 * jb + 1], a[i], bh);
++ if (upper) mma16816(acc[i][2 * jb + 1], a[i], bh);
+ }
+ }
+ }
+@@ -645,19 +658,84 @@ constexpr size_t prompt_smem() {
+ return gu > ep ? (gu > dn ? gu : dn) : (ep > dn ? ep : dn);
+ }
+
++// The launch order of a prompt plan's items (ORDER): the items of experts that take one item (their weights come
++// from DRAM, few mma) and of experts that take several (their passes run together and share the weights through L2:
++// mostly mma) merged evenly, each list in plan order, so DRAM and the tensor cores stay busy together instead of in
++// turns. Only which block runs which item changes: every output keeps its bits. The shared expert's items (id E, the
++// plan's last) are left out: order[slot] = item for slot < the routed items, -1 after. One block.
++__global__ void __launch_bounds__(1024) prompt_order_kernel(const int* __restrict__ items,
++ const int* __restrict__ counts, int* __restrict__ order,
++ int cap, int E) {
++ __shared__ int wsum[32];
++ __shared__ int routed;
++ const int all = min(counts[0], cap);
++ const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5;
++ if (tid == 0) routed = 0;
++ __syncthreads();
++ for (int i = tid; i < all; i += 1024) // items are in expert order: the routed ones come first
++ if (items[3 * i] < E && (i + 1 == all || items[3 * (i + 1)] >= E)) routed = i + 1;
++ __syncthreads();
++ const int n = routed;
++ const int per = (n + 1023) / 1024;
++ const int lo = min(n, tid * per), hi = min(n, lo + per);
++ auto heavy = [&](int i) {
++ const int e = items[3 * i];
++ return (i > 0 && items[3 * (i - 1)] == e) || (i + 1 < n && items[3 * (i + 1)] == e);
++ };
++ int h = 0;
++ for (int i = lo; i < hi; ++i) h += heavy(i);
++ int v = h;
++#pragma unroll
++ for (int o = 1; o < 32; o <<= 1) {
++ const int u = __shfl_up_sync(0xffffffffu, v, o);
++ if (lane >= o) v += u;
++ }
++ if (lane == 31) wsum[warp] = v;
++ __syncthreads();
++ if (warp == 0) {
++ int w = wsum[lane];
++#pragma unroll
++ for (int o = 1; o < 32; o <<= 1) {
++ const int u = __shfl_up_sync(0xffffffffu, w, o);
++ if (lane >= o) w += u;
++ }
++ wsum[lane] = w;
++ }
++ __syncthreads();
++ const int nh = wsum[31], nl = n - nh;
++ int rh = (warp ? wsum[warp - 1] : 0) + v - h; // heavy items before lo
++ for (int i = lo; i < hi; ++i) {
++ if (heavy(i)) { // heavy rank r sits at (r + 1/2) / nh; lights before it: strictly
++ const int r = rh++;
++ const long long X = (2LL * r + 1) * nl;
++ const int cl = X > nh ? (int)min((long long)nl, (X - nh + 2LL * nh - 1) / (2LL * nh)) : 0;
++ order[r + cl] = i;
++ } else { // light rank l at (l + 1/2) / nl; heavies at or before it
++ const int l = i - rh;
++ const long long Y = (2LL * l + 1) * nh;
++ const int ch = Y >= nl ? (int)min((long long)nh, (Y - nl) / (2LL * nl) + 1) : 0;
++ order[l + ch] = i;
++ }
++ }
++ for (int i = n + tid; i < all; i += 1024) order[i] = -1;
++}
++
+ // SHX: Xg = Xu = Xh [rows, K], one row a token (pair p reads row p / slots); otherwise Xg, Xu [pairs, K].
+ template <int PM, int NW, bool SHX>
+ __global__ void __launch_bounds__(NW * 32, 16 / NW) prompt_gateup_kernel(
+ const half* __restrict__ Xg, const half* __restrict__ Xu, const uint32_t* __restrict__ Tg,
+ const uint32_t* __restrict__ Tu, const int* __restrict__ items, const int* __restrict__ counts,
+ const int* __restrict__ members, const half* __restrict__ svh_g, const half* __restrict__ svh_u,
+- const half* __restrict__ suh_d, half* __restrict__ xd, int K, int N, int E, float limit, int slots) {
++ const half* __restrict__ suh_d, half* __restrict__ xd, int K, int N, int E, float limit, int slots,
++ const int* __restrict__ order) {
+ constexpr int MT = 16 / NW, PH = PM / 2;
+ extern __shared__ __align__(16) unsigned char smem_raw[];
+ __shared__ int rows_sh[PM];
+ __shared__ int xrows_sh[SHX ? PM : 1]; // SHX: the members' token rows
+- const int cb = blockIdx.x, item = blockIdx.y;
+- if (item >= counts[0]) return;
++ const int cb = blockIdx.x;
++ if ((int)blockIdx.y >= counts[0]) return;
++ const int item = order ? order[blockIdx.y] : blockIdx.y;
++ if (item < 0) return; // ORDER leaves the shared expert's items out
+ const int e = items[3 * item], first = items[3 * item + 1], cnt = items[3 * item + 2];
+ if (e >= E) return; // the shared expert
+ if (threadIdx.x < PM) {
+@@ -699,9 +777,12 @@ __global__ void __launch_bounds__(NW * 32, 16 / NW) prompt_gateup_kernel(
+ v[j] = act * __half2float(suh_d[(size_t)e * N + n + j]);
+ }
+ fwht128(v, lane);
+- half* o = xd + (size_t)p * N + n;
+-#pragma unroll
+- for (int j = 0; j < 4; ++j) o[j] = __float2half_rn(v[j] * HAD_SCALE);
++ const half2 o01 = __halves2half2(__float2half_rn(v[0] * HAD_SCALE), __float2half_rn(v[1] * HAD_SCALE));
++ const half2 o23 = __halves2half2(__float2half_rn(v[2] * HAD_SCALE), __float2half_rn(v[3] * HAD_SCALE));
++ uint2 packed;
++ packed.x = *reinterpret_cast<const uint32_t*>(&o01);
++ packed.y = *reinterpret_cast<const uint32_t*>(&o23);
++ *reinterpret_cast<uint2*>(xd + (size_t)p * N + n) = packed;
+ }
+ } // halves
+ }
+@@ -710,12 +791,14 @@ template <int PM, int NW>
+ __global__ void __launch_bounds__(NW * 32, 16 / NW) prompt_down_kernel(
+ const half* __restrict__ Xd, const uint32_t* __restrict__ Td, const int* __restrict__ items,
+ const int* __restrict__ counts, const int* __restrict__ members, const half* __restrict__ svh_d,
+- float* __restrict__ y, int K, int D, int E) {
++ float* __restrict__ y, int K, int D, int E, const int* __restrict__ order) {
+ constexpr int MT = 16 / NW, PH = PM / 2;
+ extern __shared__ __align__(16) unsigned char smem_raw[];
+ __shared__ int rows_sh[PM];
+- const int cb = blockIdx.x, item = blockIdx.y;
+- if (item >= counts[0]) return;
++ const int cb = blockIdx.x;
++ if ((int)blockIdx.y >= counts[0]) return;
++ const int item = order ? order[blockIdx.y] : blockIdx.y;
++ if (item < 0) return;
+ const int e = items[3 * item], first = items[3 * item + 1], cnt = items[3 * item + 2];
+ if (e >= E) return;
+ if (threadIdx.x < PM) rows_sh[threadIdx.x] = (int)threadIdx.x < cnt ? members[first + threadIdx.x] : -1;
+@@ -738,9 +821,11 @@ __global__ void __launch_bounds__(NW * 32, 16 / NW) prompt_down_kernel(
+ #pragma unroll
+ for (int j = 0; j < 4; ++j) v[j] = Ed[(size_t)i * DN_ES + blk * 128 + 4 * lane + j];
+ fwht128(v, lane);
+- float* o = y + (size_t)p * D + n;
+-#pragma unroll
+- for (int j = 0; j < 4; ++j) o[j] = v[j] * HAD_SCALE * __half2float(svh_d[(size_t)e * D + n + j]);
++ const uint2 sv = *reinterpret_cast<const uint2*>(svh_d + (size_t)e * D + n);
++ const half2 s01 = *reinterpret_cast<const half2*>(&sv.x), s23 = *reinterpret_cast<const half2*>(&sv.y);
++ *reinterpret_cast<float4*>(y + (size_t)p * D + n) =
++ make_float4(v[0] * HAD_SCALE * __low2float(s01), v[1] * HAD_SCALE * __high2float(s01),
++ v[2] * HAD_SCALE * __low2float(s23), v[3] * HAD_SCALE * __high2float(s23));
+ }
+ }
+ } // halves
+@@ -860,7 +945,8 @@ static void prompt_launch(const at::Tensor& Xg, const at::Tensor& Xu, const at::
+ const at::Tensor& Td, const at::Tensor& items, const at::Tensor& counts,
+ const at::Tensor& members, const at::Tensor& svh_g, const at::Tensor& svh_u,
+ const at::Tensor& suh_d, const at::Tensor& svh_d, at::Tensor& xd, at::Tensor& y, int64_t D,
+- int64_t N, int64_t E, int64_t max_items, double limit, int64_t slots, bool shx) {
++ int64_t N, int64_t E, int64_t max_items, double limit, int64_t slots, bool shx,
++ const int* order) {
+ constexpr size_t SMEM = prompt_smem<PM>(), SMEM_SHX = prompt_smem<PM, 1>();
+ static bool once = [] {
+ cudaFuncSetAttribute(prompt_gateup_kernel<PM, NW, false>, cudaFuncAttributeMaxDynamicSharedMemorySize,
+@@ -879,16 +965,16 @@ static void prompt_launch(const at::Tensor& Xg, const at::Tensor& Xu, const at::
+ prompt_gateup_kernel<PM, NW, true><<<gu_grid, NW * 32, SMEM_SHX, stream>>>(
+ h(Xg), h(Xu), w(Tg), w(Tu), items.data_ptr<int>(), counts.data_ptr<int>(), members.data_ptr<int>(),
+ h(svh_g), h(svh_u), h(suh_d), reinterpret_cast<half*>(xd.data_ptr()), (int)D, (int)N, (int)E,
+- (float)limit, (int)slots);
++ (float)limit, (int)slots, order);
+ else
+ prompt_gateup_kernel<PM, NW, false><<<gu_grid, NW * 32, SMEM, stream>>>(
+ h(Xg), h(Xu), w(Tg), w(Tu), items.data_ptr<int>(), counts.data_ptr<int>(), members.data_ptr<int>(),
+ h(svh_g), h(svh_u), h(suh_d), reinterpret_cast<half*>(xd.data_ptr()), (int)D, (int)N, (int)E,
+- (float)limit, (int)slots);
++ (float)limit, (int)slots, order);
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
+ prompt_down_kernel<PM, NW><<<dim3((unsigned)(D / 256), (unsigned)max_items), NW * 32, SMEM, stream>>>(
+ reinterpret_cast<const half*>(xd.data_ptr()), w(Td), items.data_ptr<int>(), counts.data_ptr<int>(),
+- members.data_ptr<int>(), h(svh_d), y.data_ptr<float>(), (int)N, (int)D, (int)E);
++ members.data_ptr<int>(), h(svh_d), y.data_ptr<float>(), (int)N, (int)D, (int)E, order);
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
+ }
+
+@@ -896,14 +982,25 @@ void exl3_prompt_cuda(const at::Tensor& Xg, const at::Tensor& Xu, const at::Tens
+ const at::Tensor& Td, const at::Tensor& items, const at::Tensor& counts,
+ const at::Tensor& members, const at::Tensor& svh_g, const at::Tensor& svh_u,
+ const at::Tensor& suh_d, const at::Tensor& svh_d, at::Tensor& xd, at::Tensor& y, int64_t D,
+- int64_t N, int64_t E, int64_t max_items, double limit, int64_t pass, int64_t slots, bool shx) {
++ int64_t N, int64_t E, int64_t max_items, double limit, int64_t pass, int64_t slots, bool shx,
++ const c10::optional<at::Tensor>& order_buf) {
+ TORCH_CHECK(D % 256 == 0 && N % 128 == 0 && D % PBK == 0 && N % PBK == 0, "prompt experts: shapes");
++ const int* order = nullptr;
++ if (order_buf.has_value()) {
++ TORCH_CHECK(order_buf->numel() >= max_items, "prompt experts: order buffer too small");
++ int* o = order_buf->data_ptr<int>();
++ prompt_order_kernel<<<1, 1024, 0, at::cuda::getCurrentCUDAStream()>>>(items.data_ptr<int>(),
++ counts.data_ptr<int>(), o,
++ (int)max_items, (int)E);
++ C10_CUDA_KERNEL_LAUNCH_CHECK();
++ order = o;
++ }
+ if (pass == 128)
+ prompt_launch<128, 16>(Xg, Xu, Tg, Tu, Td, items, counts, members, svh_g, svh_u, suh_d, svh_d, xd, y, D, N,
+- E, max_items, limit, slots, shx);
++ E, max_items, limit, slots, shx, order);
+ else if (pass == 64)
+ prompt_launch<64, 8>(Xg, Xu, Tg, Tu, Td, items, counts, members, svh_g, svh_u, suh_d, svh_d, xd, y, D, N, E,
+- max_items, limit, slots, shx);
++ max_items, limit, slots, shx, order);
+ else
+ TORCH_CHECK(false, "prompt experts: passes of 64 or 128 members");
+ }
+diff --git tensorfold/families/glm5_next/cuda/exl3_mm.py tensorfold/families/glm5_next/cuda/exl3_mm.py
+index c872731..f519b9f 100644
+--- tensorfold/families/glm5_next/cuda/exl3_mm.py
++++ tensorfold/families/glm5_next/cuda/exl3_mm.py
+@@ -58,7 +58,7 @@ def _ext():
+ from tensorfold.cuda.build import load
+
+ here = Path(__file__).parent
+- return load(name="tensorfold_glm_exl3_v17", sources=[str(here / "exl3.cpp"), str(here / "exl3.cu")],
++ return load(name="tensorfold_glm_exl3_v18", sources=[str(here / "exl3.cpp"), str(here / "exl3.cu")],
+ extra_cuda_cflags=["-O3"], verbose=False)
+
+
+@@ -130,6 +130,14 @@ def prompt_kernels() -> bool:
+ return os.environ.get("TF_GLM_EXL3_PROMPT", "1") != "0"
+
+
++def item_order() -> bool:
++ """TF_GLM_EXL3_ORDER (default on): prompt kernels run the items of single-item experts (DRAM-bound) and of
++ multi-item experts (mma-bound, weights shared through L2) interleaved; 0: plan order. The same bits either way."""
++ import os
++
++ return os.environ.get("TF_GLM_EXL3_ORDER", "1") != "0"
++
++
+ def row_rotation() -> bool:
+ """TF_GLM_EXL3_ROWROT (default on): prompt chunks of layers whose experts share one gate/up suh rotate each row's
+ input once and load it once for gate and up (the same fp16 inputs, so the same bits); 0: per pair, as decode."""
+@@ -153,6 +161,8 @@ class Scratch:
+ self.done = torch.zeros((1 if prompt else (P + P // grouped.TILE + 1) * max(1, width // 128),),
+ dtype=torch.int32, device=device)
+ self.rows, self.slots = rows, slots
++ # a prompt plan's launch order (item_order): room for any plan of up to 1,024 experts in items of >= 16 pairs
++ self.order = torch.zeros((P // 16 + 1024 if prompt else 1,), dtype=torch.int32, device=device)
+
+
+ def routed(x: torch.Tensor, pick: torch.Tensor, plan: grouped.Plan, ex: Exl3Experts, s: Scratch, y: torch.Tensor,
+@@ -173,7 +183,7 @@ def routed(x: torch.Tensor, pick: torch.Tensor, plan: grouped.Plan, ex: Exl3Expe
+ ext.prompt(xg, xu, ex.gt, ex.ut, ex.dt, plan.items, plan.counts, plan.members, ex.svh_g, ex.svh_u,
+ ex.suh_d, ex.svh_d, s.xd, y, D, NI, ex.count, grouped.max_items(R * slots, plan.experts,
+ plan.tile), float(limit),
+- plan.tile, slots, shx)
++ plan.tile, slots, shx, s.order if item_order() else None)
+ return
+ if plan.tile != grouped.TILE:
+ raise ValueError("the EXL3 kernel takes items of 16 pairs")
diff --git a/patches/0021-glm-dflash-policy-env.patch b/patches/0021-glm-dflash-policy-env.patch
new file mode 100644
index 0000000..0941897
--- /dev/null
+++ b/patches/0021-glm-dflash-policy-env.patch
@@ -0,0 +1,24 @@
+diff --git tensorfold/families/glm5_next/cuda/engine.py tensorfold/families/glm5_next/cuda/engine.py
+index f50b3a1..edcf082 100644
+--- tensorfold/families/glm5_next/cuda/engine.py
++++ tensorfold/families/glm5_next/cuda/engine.py
+@@ -12,7 +12,9 @@ from pathlib import Path
+ from typing import Any, Callable
+
+ DEFAULT_POLICY = "auto"
+-DFLASH_POLICY = "fc5:0.3" # DFlash2 drafts every round: up to 5 while their probability product holds 0.3
++# DFlash2 drafts every round: by default up to 5 while their probability product holds 0.3; TF_GLM_DFLASH_POLICY picks
++# another DFlash2 policy (e.g. fnc7:0.3, the noise-aware stop rule) for requests that name none
++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)
+@@ -276,6 +278,8 @@ class GlmEngine:
+ from tensorfold.cuda.geometry import PREFILL_ROWS, draft_geometry, 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:
++ raise ValueError(f"TF_GLM_DFLASH_POLICY={DFLASH_POLICY!r}: a DFlash2 policy (f...), e.g. fc5:0.3 or fnc7:0.3")
+ from .copy_drafts import CopySettings
+
+ # TF_GLM_COPY_DRAFTS=1: a reply that repeats earlier text drafts its continuation (prompt lookup) ahead of
diff --git a/patches/0022-glm-overlap-normal-priority.patch b/patches/0022-glm-overlap-normal-priority.patch
new file mode 100644
index 0000000..59ccd10
--- /dev/null
+++ b/patches/0022-glm-overlap-normal-priority.patch
@@ -0,0 +1,18 @@
+diff --git tensorfold/families/glm5_next/cuda/hcsplit.py tensorfold/families/glm5_next/cuda/hcsplit.py
+index a294319..17acbf9 100644
+--- tensorfold/families/glm5_next/cuda/hcsplit.py
++++ tensorfold/families/glm5_next/cuda/hcsplit.py
+@@ -107,9 +107,10 @@ class HcSplit:
+ self.got: list[torch.Tensor] = []
+ self.stream = None
+ if settings.overlap:
+- # TF_GLM_OVERLAP_PRIORITY: the side stream's priority (-1 high, 0 normal); a high-priority stream in the
+- # process may cost decode rounds (graphs on the default stream) a little: measured per boot
+- self.stream = torch.cuda.Stream(priority=-1 if os.environ.get("TF_GLM_OVERLAP_PRIORITY", "-1").strip() != "0" else 0)
++ # TF_GLM_OVERLAP_PRIORITY: the side stream's priority, 0 (normal, the default) or -1 (high). Two Sparks, two
++ # boots each: prefill the same, decode rounds after a high-priority prompt ~0.5-1% slower
++ high = os.environ.get("TF_GLM_OVERLAP_PRIORITY", "0").strip() == "-1"
++ self.stream = torch.cuda.Stream(priority=-1 if high else 0)
+ n = settings.piece_count()
+ self.ev_fill = [torch.cuda.Event() for _ in range(n)]
+ self.ev_part = [torch.cuda.Event() for _ in range(n)]
diff --git a/patches/0023-glm-idle-doorbell.patch b/patches/0023-glm-idle-doorbell.patch
new file mode 100644
index 0000000..6253555
--- /dev/null
+++ b/patches/0023-glm-idle-doorbell.patch
@@ -0,0 +1,58 @@
+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/0024-server-effort-max.patch
new file mode 100644
index 0000000..0d6dbfe
--- /dev/null
+++ b/patches/0024-server-effort-max.patch
@@ -0,0 +1,37 @@
+diff --git tensorfold/server/request_options.py tensorfold/server/request_options.py
+index 4e2b39e..a83156a 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]:
+ return parsed
+
+
+-EFFORTS = ("none", "minimal", "low", "medium", "high", "xhigh")
++EFFORTS = ("none", "minimal", "low", "medium", "high", "xhigh", "max")
+
+
+ def effort_levels(template: str | None) -> frozenset[str]:
+- """The efforts a chat template names: Qwen3.8's low, medium and xhigh; GLM-5.3's low and high."""
++ """The efforts a chat template names: Qwen3.8's low, medium and xhigh; GLM-5.3's low, high and max."""
+
+- return frozenset(re.findall(r"""['"](minimal|low|medium|high|xhigh)['"]""", template or ""))
++ 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())
+ 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["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/0025-cuda-memory-reserve.patch b/patches/0025-cuda-memory-reserve.patch
new file mode 100644
index 0000000..ed39182
--- /dev/null
+++ b/patches/0025-cuda-memory-reserve.patch
@@ -0,0 +1,40 @@
+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/0026-glm-prompt-select-rows.patch b/patches/0026-glm-prompt-select-rows.patch
new file mode 100644
index 0000000..70747cc
--- /dev/null
+++ b/patches/0026-glm-prompt-select-rows.patch
@@ -0,0 +1,62 @@
+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
+--- 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
+
+ dev = qi.device
+ NP = pool_count(pos, R, np_max)
+- scores = torch.empty((R * pool_bucket(pos, R, np_max),), dtype=torch.float32, device=dev)[:R * NP].view(R, NP)
++ # rows go through in blocks of SELECT_ROWS: every block scores the chunk's NP pools (the same columns, so the same
++ # bits a row), and the fp32 scores take SELECT_ROWS rows, not the chunk's, of the capacity-sized memory
++ B = min(R, SELECT_ROWS)
++ buf = torch.empty((B * pool_bucket(pos, R, np_max),), dtype=torch.float32, device=dev)
+ 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
+ rb = score_rows()
+- _scores[(triton.cdiv(R, rb), triton.cdiv(NP, 64))](qi, wts, wts.stride(0), pk, scores, pos_dev, R, NP, D ** -0.5,
+- wscale, H=H, HP=max(16, triton.next_power_of_2(H)), D=D, BP=64,
+- RB=rb, num_warps=4)
+- pools = top_pools(scores, TOPK_POOLS) # ascending pool index
+- del scores
+ 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)
+- _tokens[(R,)](pools, pos_dev, tokens, counts, W=width, K=TOPK_POOLS, PL=POOL, BLOCK=1024, num_warps=4)
++ for a in range(0, R, B):
++ n = min(B, R - a)
++ at = pos_dev if a == 0 else pos_dev + a
++ scores = buf[:n * NP].view(n, NP)
++ _scores[(triton.cdiv(n, rb), triton.cdiv(NP, 64))](qi[a:a + n], wts[a:a + n], wts.stride(0), pk, scores, at, n,
++ NP, D ** -0.5, wscale, H=H,
++ HP=max(16, triton.next_power_of_2(H)), D=D, BP=64, RB=rb,
++ num_warps=4)
++ 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)
+ return tokens, counts
+
+
diff --git a/patches/0027-glm-dflash2-ring.patch b/patches/0027-glm-dflash2-ring.patch
new file mode 100644
index 0000000..7fc9020
--- /dev/null
+++ b/patches/0027-glm-dflash2-ring.patch
@@ -0,0 +1,402 @@
+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/0028-glm-multi-kda.patch b/patches/0028-glm-multi-kda.patch
new file mode 100644
index 0000000..890717c
--- /dev/null
+++ b/patches/0028-glm-multi-kda.patch
@@ -0,0 +1,448 @@
+diff --git tensorfold/families/glm5_next/cuda/forward.py tensorfold/families/glm5_next/cuda/forward.py
+index 7f56f87..5980279 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:
+ TAPS=taps, BLOCK=1024, num_warps=4)
+
+
++def _conv_shift_seg(CONV, PROJ, SEG, conv_slot, conv_layer, proj_layer, proj_row, C: tl.constexpr,
++ TAPS: tl.constexpr, COLS: tl.constexpr, BLOCK: tl.constexpr):
++ """Program (layer, channel block, segment): ``_conv_shift`` of the segment's conv slot over its own rows."""
++
++ l = tl.program_id(0).to(tl.int64)
++ c = tl.program_id(1) * BLOCK + tl.arange(0, BLOCK)
++ e = SEG + tl.program_id(2) * COLS
++ row0 = tl.load(e + 0).to(tl.int64)
++ rows = tl.load(e + 1)
++ cslot = tl.load(e + 4).to(tl.int64)
++ keep = tl.load(e + 5)
++ if rows > 0:
++ conv = CONV + cslot * conv_slot
++ proj = PROJ + row0 * proj_row
++ v0 = _row(conv, proj, l, keep, c, conv_layer, proj_layer, proj_row, C, TAPS)
++ v1 = _row(conv, proj, l, keep + 1, c, conv_layer, proj_layer, proj_row, C, TAPS)
++ v2 = _row(conv, proj, l, keep + 2, c, conv_layer, proj_layer, proj_row, C, TAPS)
++ tl.store(conv + l * conv_layer + c, v0, mask=c < C)
++ tl.store(conv + l * conv_layer + C + c, v1, mask=c < C)
++ tl.store(conv + l * conv_layer + 2 * C + c, v2, mask=c < C)
++
++
++def conv_shift_segments(conv: torch.Tensor, proj: torch.Tensor, seg: torch.Tensor) -> None:
++ """``_shift_conv`` per segment of a multi-stream window: conv [conv slots, L, 3, C] (in place; each [3, C]
++ contiguous), proj [L, R, W >= C] the window's projection rows; segment i (``kda.segment_table``) has its conv
++ slot take rows keep .. keep + 2 of [conv[slot]; its own proj rows]. Segments of 0 rows are skipped."""
++
++ _, n, taps, C = conv.shape
++ if taps != 3:
++ raise ValueError("the conv shift kernel is written for 4-tap convolutions")
++ if conv.stride(3) != 1 or conv.stride(2) != C:
++ raise ValueError("each conv slot's [3, C] window must be contiguous")
++ if seg.dtype != torch.int32 or seg.dim() != 2 or seg.shape[1] != kda_mod.SEG_COLS or not seg.is_contiguous():
++ raise ValueError("segments: a contiguous int32 [nseg, SEG_COLS] table")
++ _conv_shift_seg[(n, triton.cdiv(C, 1024), seg.shape[0])](
++ conv, proj, seg, conv.stride(0), conv.stride(1), proj.stride(0), proj.stride(1), C=C, TAPS=taps,
++ COLS=kda_mod.SEG_COLS, BLOCK=1024, num_warps=4)
++
++
+ @torch.no_grad()
+ def commit(w: Weights, st: State, b: Buffers, R: int, keep: int) -> None:
+ """Keep the last forward's first ``keep`` rows; a prompt chunk keeps all, its KDA layers already committed."""
+diff --git tensorfold/families/glm5_next/cuda/kda.cpp tensorfold/families/glm5_next/cuda/kda.cpp
+index 4a1315b..c40f527 100644
+--- tensorfold/families/glm5_next/cuda/kda.cpp
++++ tensorfold/families/glm5_next/cuda/kda.cpp
+@@ -14,6 +14,15 @@ void kda_replay_cuda(const at::Tensor&, const at::Tensor&, const at::Tensor&, co
+ void kda_replay_layers_cuda(const at::Tensor&, int64_t, const at::Tensor&, const at::Tensor&, const at::Tensor&,
+ const at::Tensor&, int64_t, int64_t, int64_t, int64_t, int64_t, at::Tensor&);
+
++void kda_chain_wide_segments_cuda(const at::Tensor&, int64_t, const at::Tensor&, int64_t, int64_t, const at::Tensor&,
++ int64_t, const at::Tensor&, int64_t, const at::Tensor&, int64_t, const at::Tensor&,
++ at::Tensor&, int64_t, int64_t, const at::Tensor&, const at::Tensor&,
++ const at::Tensor&, double, double, int64_t, at::Tensor&, at::Tensor&, at::Tensor&,
++ at::Tensor&, at::Tensor&, at::Tensor&, at::Tensor&);
++void kda_replay_layers_segments_cuda(const at::Tensor&, int64_t, at::Tensor&, int64_t, int64_t, int64_t,
++ const at::Tensor&, const at::Tensor&, const at::Tensor&, const at::Tensor&,
++ int64_t, int64_t, int64_t, int64_t);
++
+ static void check(const at::Tensor& x, at::ScalarType t, const char* name) {
+ TORCH_CHECK(x.is_cuda() && x.scalar_type() == t, name, ": expected a CUDA tensor of the right dtype");
+ }
+@@ -97,9 +106,77 @@ void replay_layers(const at::Tensor& state_in, int64_t state_stride, const at::T
+ rows, state_out);
+ }
+
++static void check_segments(const at::Tensor& seg) {
++ TORCH_CHECK(seg.is_cuda() && seg.scalar_type() == at::kInt && seg.dim() == 2 && seg.size(1) == 6 &&
++ seg.is_contiguous(), "segments: a contiguous CUDA int32 [nseg, 6] table "
++ "(first row, rows, state slot, parity, conv slot, keep)");
++}
++
++// rec [slots, 2, H, 128, 128] (this layer's states; each [H, 128, 128] contiguous), conv [slots, 3, 3 H 128]
++// (this layer's conv windows; each [3, C] contiguous). Segment i runs rows row0 .. row0 + rows - 1 of P/A/G from
++// rec[slot, parity] and conv[conv slot] into rec[slot, 1 - parity]; conv is read only.
++void chain_wide_segments(const at::Tensor& seg, const at::Tensor& P, int64_t p_stride, int64_t b_off,
++ const at::Tensor& A, int64_t a_stride, const at::Tensor& G, int64_t g_stride,
++ const at::Tensor& conv, const at::Tensor& cw, at::Tensor rec, const at::Tensor& a_log,
++ const at::Tensor& dt_bias, const at::Tensor& norm_w, double eps, double lower, int64_t rows,
++ at::Tensor out, at::Tensor k_save, at::Tensor v_save, at::Tensor g_save, at::Tensor b_save,
++ at::Tensor q_tmp, at::Tensor y_tmp) {
++ check_segments(seg);
++ check(P, at::kBFloat16, "P");
++ check(A, at::kBFloat16, "A");
++ check(G, at::kBFloat16, "G");
++ check(conv, at::kBFloat16, "conv state");
++ check(cw, at::kBFloat16, "conv weight");
++ check(rec, at::kFloat, "state");
++ check(out, at::kBFloat16, "out");
++ check(k_save, at::kFloat, "k");
++ check(v_save, at::kBFloat16, "v");
++ check(g_save, at::kFloat, "g");
++ check(b_save, at::kFloat, "beta");
++ check(q_tmp, at::kFloat, "q scratch");
++ check(y_tmp, at::kBFloat16, "read-out scratch");
++ const int64_t H = a_log.numel();
++ TORCH_CHECK(cw.is_contiguous() && out.is_contiguous(), "conv weight and out must be contiguous");
++ TORCH_CHECK(conv.dim() == 3 && conv.size(1) == 3 && conv.size(2) == 3 * H * 128 && conv.stride(2) == 1 &&
++ conv.stride(1) == 3 * H * 128, "conv state [slots, 3, 3*H*128], each slot contiguous");
++ TORCH_CHECK(rec.dim() == 5 && rec.size(1) == 2 && rec.size(2) == H && rec.size(3) == 128 && rec.size(4) == 128 &&
++ rec.stride(4) == 1 && rec.stride(3) == 128 && rec.stride(2) == 128 * 128,
++ "state [slots, 2, H, 128, 128], each [H, 128, 128] contiguous");
++ TORCH_CHECK(dt_bias.numel() == H * 128 && norm_w.numel() == 128, "dt_bias [H*128], norm [128]");
++ TORCH_CHECK(cw.size(0) == 3 * H * 128 && cw.size(1) == 4, "conv weight [3*H*128, 4]");
++ TORCH_CHECK(rows >= 1 && P.size(0) >= rows && out.size(0) >= rows, "rows");
++ TORCH_CHECK(k_save.numel() >= rows * H * 128 && q_tmp.numel() >= rows * H * 128 &&
++ y_tmp.numel() >= rows * H * 128 && b_save.numel() >= rows * H, "scratch rows");
++ c10::cuda::CUDAGuard guard(P.device());
++ kda_chain_wide_segments_cuda(seg, seg.size(0), P, p_stride, b_off, A, a_stride, G, g_stride, conv,
++ conv.stride(0), cw, rec, rec.stride(0), rec.stride(1), a_log, dt_bias, norm_w, eps,
++ lower, rows, out, k_save, v_save, g_save, b_save, q_tmp, y_tmp);
++}
++
++// rec [slots, 2, layers, H, 128, 128] (each [H, 128, 128] contiguous); segment i with keep < rows replays its
++// first ``keep`` saved rows of every layer from rec[slot, parity] into rec[slot, 1 - parity].
++void replay_layers_segments(const at::Tensor& seg, at::Tensor rec, const at::Tensor& k_save, const at::Tensor& v_save,
++ const at::Tensor& g_save, const at::Tensor& b_save, int64_t kv_stride, int64_t b_stride,
++ int64_t layers, int64_t heads) {
++ check_segments(seg);
++ check(rec, at::kFloat, "state");
++ check(k_save, at::kFloat, "k");
++ check(v_save, at::kBFloat16, "v");
++ check(g_save, at::kFloat, "g");
++ check(b_save, at::kFloat, "beta");
++ TORCH_CHECK(rec.dim() == 6 && rec.size(1) == 2 && rec.size(2) >= layers && rec.size(3) == heads &&
++ rec.size(4) == 128 && rec.size(5) == 128 && rec.stride(5) == 1 && rec.stride(4) == 128 &&
++ rec.stride(3) == 128 * 128, "state [slots, 2, layers, H, 128, 128], each [H, 128, 128] contiguous");
++ c10::cuda::CUDAGuard guard(rec.device());
++ kda_replay_layers_segments_cuda(seg, seg.size(0), rec, rec.stride(0), rec.stride(1), rec.stride(2), k_save,
++ v_save, g_save, b_save, kv_stride, b_stride, layers, heads);
++}
++
+ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
+ m.def("chain", &chain);
+ m.def("chain_wide", &chain_wide);
+ m.def("replay", &replay);
+ m.def("replay_layers", &replay_layers);
++ m.def("chain_wide_segments", &chain_wide_segments);
++ m.def("replay_layers_segments", &replay_layers_segments);
+ }
+diff --git tensorfold/families/glm5_next/cuda/kda.cu tensorfold/families/glm5_next/cuda/kda.cu
+index 4d458e0..91ac58a 100644
+--- tensorfold/families/glm5_next/cuda/kda.cu
++++ tensorfold/families/glm5_next/cuda/kda.cu
+@@ -352,6 +352,181 @@ __global__ void __launch_bounds__(128) out_kernel(
+ out[(size_t)r * H * DV + h * DV + t] = __float2bfloat16_rn(yw * sigmoidf_(gate));
+ }
+
++// Several streams' windows in one launch. A segment table (int32 [nseg, SEG_COLS]: first row, rows, state slot,
++// parity, conv slot, keep) cuts the window's rows into streams; each segment reads its conv taps from its own
++// conv slot and runs the recurrence from rec[slot, parity] into rec[slot, 1 - parity]. Per row the arithmetic is
++// the solo kernels' line for line (same ``update``), so a segment's bits equal a solo run of its rows. A segment
++// of 0 rows is skipped: a table sized for the most streams serves fewer (grids stay fixed for CUDA graphs).
++constexpr int SEG_COLS = 6, SEG_ROW0 = 0, SEG_ROWS = 1, SEG_SLOT = 2, SEG_PARITY = 3, SEG_CONV = 4, SEG_KEEP = 5;
++
++// prep_kernel for block (row, head) of the whole window; the row's conv taps come from its segment.
++__global__ void __launch_bounds__(512) prep_seg_kernel(
++ int H, const int* __restrict__ seg, int nseg, const __nv_bfloat16* __restrict__ P, int p_stride, int b_off,
++ const __nv_bfloat16* __restrict__ A, int a_stride, const __nv_bfloat16* __restrict__ conv,
++ size_t conv_slot_stride, const __nv_bfloat16* __restrict__ cw, const float* __restrict__ a_log,
++ const float* __restrict__ dt_bias, float lower, float* __restrict__ q_out, float* __restrict__ k_save,
++ __nv_bfloat16* __restrict__ v_save, float* __restrict__ g_save, float* __restrict__ b_save) {
++ const int C = 3 * H * DK;
++ const int r = blockIdx.x, h = blockIdx.y;
++ int row0 = -1, cslot = 0;
++ for (int i = 0; i < nseg; ++i) {
++ const int* e = seg + i * SEG_COLS;
++ if (r >= e[SEG_ROW0] && r < e[SEG_ROW0] + e[SEG_ROWS]) { row0 = e[SEG_ROW0]; cslot = e[SEG_CONV]; }
++ }
++ if (row0 < 0) return; // a row no segment covers
++ const int rr = r - row0; // the row within its stream's window
++ const __nv_bfloat16* cs = conv + (size_t)cslot * conv_slot_stride;
++ const __nv_bfloat16* Ps = P + (size_t)row0 * p_stride;
++ const int t = threadIdx.x, warp = t >> 5, lane = t & 31;
++ __shared__ float qs[DK], ks[DK];
++ const size_t base = ((size_t)r * H + h) * DK;
++ if (t < 3 * DK) {
++ const int c = (t / DK) * H * DK + h * DK + (t % DK);
++ float acc = 0.0f;
++#pragma unroll
++ for (int tap = 0; tap < TAPS; ++tap) {
++ const int at = rr + tap;
++ const float x = at < TAPS - 1 ? __bfloat162float(cs[(size_t)at * C + c])
++ : __bfloat162float(Ps[(size_t)(at - (TAPS - 1)) * p_stride + c]);
++ acc = acc + __bfloat162float(cw[(size_t)c * TAPS + tap]) * x;
++ }
++ const float act = bf(acc / (1.0f + expf(-acc)));
++ if (t < DK) qs[t] = act;
++ else if (t < 2 * DK) ks[t - DK] = act;
++ else v_save[base + t - 2 * DK] = __float2bfloat16_rn(act);
++ } else {
++ const int i = t - 3 * DK;
++ const float decay_rate = expf(a_log[h]);
++ const float a = __bfloat162float(A[(size_t)r * a_stride + h * DK + i]) + dt_bias[h * DK + i];
++ g_save[base + i] = expf(lower * sigmoidf_(decay_rate * a));
++ if (i == 0) b_save[r * H + h] = bf(sigmoidf_(__bfloat162float(P[(size_t)r * p_stride + b_off + h])));
++ }
++ __syncthreads();
++ if (warp < 2) {
++ const float* x = warp == 0 ? qs : ks;
++ float v4[4], ss = 0.0f;
++#pragma unroll
++ for (int i = 0; i < 4; ++i) { v4[i] = x[lane * 4 + i]; ss = ss + v4[i] * v4[i]; }
++ ss = warp_sum(ss);
++ float inv = 1.0f / sqrtf(ss + 1e-6f);
++ float* dst = warp == 0 ? q_out : k_save;
++#pragma unroll
++ for (int i = 0; i < 4; ++i) {
++ float y = v4[i] * inv;
++ if (warp == 0) y = y * (1.0f / sqrtf((float)DK));
++ dst[base + lane * 4 + i] = y;
++ }
++ }
++}
++
++// step_kernel for block (segment x head, part): the segment's rows from rec[slot, parity] into rec[slot, 1 - parity].
++template <int WARPS, int TR>
++__global__ void __launch_bounds__(WARPS * 32) step_seg_kernel(
++ int H, const int* __restrict__ seg, float* __restrict__ rec, size_t slot_stride, size_t parity_stride,
++ const float* __restrict__ q_in, const float* __restrict__ k_save, const __nv_bfloat16* __restrict__ v_save,
++ const float* __restrict__ g_save, const float* __restrict__ b_save, __nv_bfloat16* __restrict__ y_out) {
++ constexpr int NT = WARPS * 32, VR = WARPS * 4;
++ const int* e = seg + (blockIdx.x / H) * SEG_COLS;
++ const int row0 = e[SEG_ROW0], rows = e[SEG_ROWS], slot = e[SEG_SLOT], parity = e[SEG_PARITY];
++ if (rows <= 0) return;
++ const float* state_in = rec + (size_t)slot * slot_stride + (size_t)parity * parity_stride;
++ float* state_out = rec + (size_t)slot * slot_stride + (size_t)(1 - parity) * parity_stride;
++ const int h = blockIdx.x % H, v0 = blockIdx.y * VR;
++ const int lw = threadIdx.x >> 5, lane = threadIdx.x & 31, warp = blockIdx.y * WARPS + lw;
++ __shared__ __align__(16) float kt[TR][DK];
++ __shared__ __align__(16) float qt[TR][DK];
++ __shared__ __align__(16) float gt[TR][DK];
++ __shared__ __align__(16) float vt[TR][VR];
++ __shared__ float bt[TR];
++ float s[4][4];
++ const size_t sbase = (size_t)h * DV * DK;
++#pragma unroll
++ for (int j = 0; j < 4; ++j)
++#pragma unroll
++ for (int i = 0; i < 4; ++i) s[j][i] = state_in[sbase + (size_t)(warp * 4 + j) * DK + lane * 4 + i];
++ for (int r0 = 0; r0 < rows; r0 += TR) {
++ const int n = rows - r0 < TR ? rows - r0 : TR;
++ __syncthreads();
++ for (int x = threadIdx.x; x < n * DK; x += NT) {
++ const int rr = x / DK, c = x % DK;
++ const size_t base = ((size_t)(row0 + r0 + rr) * H + h) * DK + c;
++ kt[rr][c] = k_save[base];
++ qt[rr][c] = q_in[base];
++ gt[rr][c] = g_save[base];
++ }
++ for (int x = threadIdx.x; x < n * VR; x += NT) {
++ const int rr = x / VR, c = x % VR;
++ vt[rr][c] = __bfloat162float(v_save[((size_t)(row0 + r0 + rr) * H + h) * DV + v0 + c]);
++ }
++ if (threadIdx.x < n) bt[threadIdx.x] = b_save[(row0 + r0 + threadIdx.x) * H + h];
++ __syncthreads();
++ for (int rr = 0; rr < n; ++rr) {
++ const float4 k4 = reinterpret_cast<const float4*>(kt[rr])[lane];
++ const float4 q4 = reinterpret_cast<const float4*>(qt[rr])[lane];
++ const float4 g4 = reinterpret_cast<const float4*>(gt[rr])[lane];
++ const float4 v4 = reinterpret_cast<const float4*>(vt[rr])[lw];
++ float kk[4] = {k4.x, k4.y, k4.z, k4.w}, qq[4] = {q4.x, q4.y, q4.z, q4.w};
++ float gg[4] = {g4.x, g4.y, g4.z, g4.w}, vv[4] = {v4.x, v4.y, v4.z, v4.w};
++ update(s, kk, gg, vv, 0, bt[rr]);
++#pragma unroll
++ for (int j = 0; j < 4; ++j) {
++ float o = 0.0f;
++#pragma unroll
++ for (int i = 0; i < 4; ++i) o = o + s[j][i] * qq[i];
++ o = warp_sum(o);
++ if (lane == 0)
++ y_out[((size_t)(row0 + r0 + rr) * H + h) * DV + warp * 4 + j] = __float2bfloat16_rn(o);
++ }
++ }
++ }
++#pragma unroll
++ for (int j = 0; j < 4; ++j)
++#pragma unroll
++ for (int i = 0; i < 4; ++i) state_out[sbase + (size_t)(warp * 4 + j) * DK + lane * 4 + i] = s[j][i];
++}
++
++// replay_layers_kernel for block (segment, layer, head): the segment's first ``keep`` rows from rec[slot, parity]
++// into rec[slot, 1 - parity]; keep == rows (the chain already left that state) or rows == 0 skips the segment.
++__global__ void __launch_bounds__(1024) replay_layers_seg_kernel(
++ int H, int layers, const int* __restrict__ seg, float* __restrict__ rec, size_t slot_stride,
++ size_t parity_stride, size_t layer_stride, const float* __restrict__ k_save,
++ const __nv_bfloat16* __restrict__ v_save, const float* __restrict__ g_save, const float* __restrict__ b_save,
++ size_t kv_stride, size_t b_stride) {
++ const int* e = seg + (blockIdx.x / (layers * H)) * SEG_COLS;
++ const int row0 = e[SEG_ROW0], rows = e[SEG_ROWS], slot = e[SEG_SLOT], parity = e[SEG_PARITY];
++ const int keep = e[SEG_KEEP];
++ if (rows <= 0 || keep < 0 || keep >= rows) return;
++ const int layer = (blockIdx.x / H) % layers, h = blockIdx.x % H;
++ const int t = threadIdx.x, warp = t >> 5, lane = t & 31;
++ __shared__ float vs[DV];
++ float s[4][4];
++ const float* sin = rec + (size_t)slot * slot_stride + (size_t)parity * parity_stride + layer * layer_stride;
++ float* sout = rec + (size_t)slot * slot_stride + (size_t)(1 - parity) * parity_stride + layer * layer_stride;
++ const float* ks = k_save + layer * kv_stride + (size_t)row0 * H * DK;
++ const __nv_bfloat16* vsv = v_save + layer * kv_stride + (size_t)row0 * H * DV;
++ const float* gsv = g_save + layer * kv_stride + (size_t)row0 * H * DK;
++ const float* bsv = b_save + layer * b_stride + (size_t)row0 * H;
++ const size_t sbase = (size_t)h * DV * DK;
++#pragma unroll
++ for (int j = 0; j < 4; ++j)
++#pragma unroll
++ for (int i = 0; i < 4; ++i) s[j][i] = sin[sbase + (size_t)(warp * 4 + j) * DK + lane * 4 + i];
++ for (int r = 0; r < keep; ++r) {
++ const size_t base = ((size_t)r * H + h) * DK;
++ if (t < DV) vs[t] = __bfloat162float(vsv[base + t]);
++ __syncthreads();
++ float kk[4], gg[4];
++#pragma unroll
++ for (int i = 0; i < 4; ++i) { kk[i] = ks[base + lane * 4 + i]; gg[i] = gsv[base + lane * 4 + i]; }
++ update(s, kk, gg, vs, warp, bsv[r * H + h]);
++ __syncthreads();
++ }
++#pragma unroll
++ for (int j = 0; j < 4; ++j)
++#pragma unroll
++ for (int i = 0; i < 4; ++i) sout[sbase + (size_t)(warp * 4 + j) * DK + lane * 4 + i] = s[j][i];
++}
++
+ } // namespace
+
+ template <typename T>
+@@ -417,3 +592,43 @@ void kda_chain_wide_cuda(const at::Tensor& P, int64_t p_stride, int64_t b_off, c
+ ptr<__nv_bfloat16>(norm_w), (float)eps, ptr<__nv_bfloat16>(out));
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
+ }
++
++void kda_chain_wide_segments_cuda(const at::Tensor& seg, int64_t nseg, const at::Tensor& P, int64_t p_stride,
++ int64_t b_off, const at::Tensor& A, int64_t a_stride, const at::Tensor& G,
++ int64_t g_stride, const at::Tensor& conv, int64_t conv_slot_stride,
++ const at::Tensor& cw, at::Tensor& rec, int64_t slot_stride, int64_t parity_stride,
++ const at::Tensor& a_log, const at::Tensor& dt_bias, const at::Tensor& norm_w,
++ double eps, double lower, int64_t rows, at::Tensor& out, at::Tensor& k_save,
++ at::Tensor& v_save, at::Tensor& g_save, at::Tensor& b_save, at::Tensor& q_tmp,
++ at::Tensor& y_tmp) {
++ auto stream = at::cuda::getCurrentCUDAStream();
++ const int H = (int)a_log.numel();
++ const dim3 grid((unsigned)rows, (unsigned)H);
++ prep_seg_kernel<<<grid, 512, 0, stream>>>(
++ H, ptr<int>(seg), (int)nseg, ptr<__nv_bfloat16>(P), (int)p_stride, (int)b_off, ptr<__nv_bfloat16>(A),
++ (int)a_stride, ptr<__nv_bfloat16>(conv), (size_t)conv_slot_stride, ptr<__nv_bfloat16>(cw), ptr<float>(a_log),
++ ptr<float>(dt_bias), (float)lower, ptr<float>(q_tmp), ptr<float>(k_save), ptr<__nv_bfloat16>(v_save),
++ ptr<float>(g_save), ptr<float>(b_save));
++ C10_CUDA_KERNEL_LAUNCH_CHECK();
++ constexpr int WARPS = 4, TR = 16;
++ step_seg_kernel<WARPS, TR><<<dim3((unsigned)(nseg * H), DV / 4 / WARPS), WARPS * 32, 0, stream>>>(
++ H, ptr<int>(seg), ptr<float>(rec), (size_t)slot_stride, (size_t)parity_stride, ptr<float>(q_tmp),
++ ptr<float>(k_save), ptr<__nv_bfloat16>(v_save), ptr<float>(g_save), ptr<float>(b_save),
++ ptr<__nv_bfloat16>(y_tmp));
++ C10_CUDA_KERNEL_LAUNCH_CHECK();
++ out_kernel<<<grid, DV, 0, stream>>>(H, ptr<__nv_bfloat16>(y_tmp), ptr<__nv_bfloat16>(G), (int)g_stride,
++ ptr<__nv_bfloat16>(norm_w), (float)eps, ptr<__nv_bfloat16>(out));
++ C10_CUDA_KERNEL_LAUNCH_CHECK();
++}
++
++void kda_replay_layers_segments_cuda(const at::Tensor& seg, int64_t nseg, at::Tensor& rec, int64_t slot_stride,
++ int64_t parity_stride, int64_t layer_stride, const at::Tensor& k_save,
++ const at::Tensor& v_save, const at::Tensor& g_save, const at::Tensor& b_save,
++ int64_t kv_stride, int64_t b_stride, int64_t layers, int64_t heads) {
++ auto stream = at::cuda::getCurrentCUDAStream();
++ replay_layers_seg_kernel<<<(unsigned)(nseg * layers * heads), 1024, 0, stream>>>(
++ (int)heads, (int)layers, ptr<int>(seg), ptr<float>(rec), (size_t)slot_stride, (size_t)parity_stride,
++ (size_t)layer_stride, ptr<float>(k_save), ptr<__nv_bfloat16>(v_save), ptr<float>(g_save), ptr<float>(b_save),
++ (size_t)kv_stride, (size_t)b_stride);
++ C10_CUDA_KERNEL_LAUNCH_CHECK();
++}
+diff --git tensorfold/families/glm5_next/cuda/kda.py tensorfold/families/glm5_next/cuda/kda.py
+index bd3a28e..394dcd0 100644
+--- tensorfold/families/glm5_next/cuda/kda.py
++++ tensorfold/families/glm5_next/cuda/kda.py
+@@ -114,3 +114,64 @@ def chain(p: torch.Tensor, b_off: int, a: torch.Tensor, g: torch.Tensor, conv_st
+
+ def replay(state_in: torch.Tensor, scratch: KDAScratch, rows: int, state_out: torch.Tensor) -> None:
+ _ext().replay(state_in, scratch.k, scratch.v, scratch.g, scratch.b, int(rows), state_out)
++
++
++# -- several streams in one window ----------------------------------------------------------------------------
++# A verify window holding several streams' rows back to back ([s1 rows][s2 rows]...) runs as segments: an int32
++# CUDA table [nseg, SEG_COLS] of (first row, rows, state slot, parity, conv slot, keep). Segment i runs from
++# rec[slot, parity] with conv[conv slot]'s taps into rec[slot, 1 - parity]; its outputs and states are the bits of a
++# solo ``chain(..., wide=True)`` / ``replay_layers`` of its rows. A segment of 0 rows is skipped, so a table sized for
++# the most streams (and the grids a CUDA graph captured) serves fewer: rewrite the table in place between replays.
++SEG_COLS = 6
++SEG_ROW0, SEG_ROWS, SEG_SLOT, SEG_PARITY, SEG_CONV, SEG_KEEP = range(SEG_COLS)
++
++
++def segment_table(segments, device, out: torch.Tensor | None = None) -> torch.Tensor:
++ """The table of ``segments`` [(rows, state slot, parity[, conv slot[, keep]])] laid back to back from row 0;
++ conv slot defaults to the state slot, keep to rows. With ``out`` ([n >= len, SEG_COLS] int32) it is written in
++ place (rows past the list become empty segments) and returned."""
++
++ rows_ = []
++ row0 = 0
++ for s in segments:
++ rows, slot, parity = int(s[0]), int(s[1]), int(s[2])
++ conv = int(s[3]) if len(s) > 3 and s[3] is not None else slot
++ keep = int(s[4]) if len(s) > 4 and s[4] is not None else rows
++ if rows < 0 or parity not in (0, 1) or not 0 <= keep <= rows:
++ raise ValueError(f"bad segment {s!r}")
++ rows_.append([row0, rows, slot, parity, conv, keep])
++ row0 += rows
++ n = len(rows_) if out is None else out.shape[0]
++ if len(rows_) > n:
++ raise ValueError(f"{len(rows_)} segments do not fit a table of {n}")
++ rows_ += [[row0, 0, 0, 0, 0, 0]] * (n - len(rows_))
++ host = torch.tensor(rows_, dtype=torch.int32).reshape(n, SEG_COLS)
++ if out is None:
++ return host.to(device)
++ out.copy_(host, non_blocking=False)
++ return out
++
++
++def chain_segments(seg: torch.Tensor, p: torch.Tensor, b_off: int, a: torch.Tensor, g: torch.Tensor,
++ conv: torch.Tensor, conv_w: torch.Tensor, rec: torch.Tensor, a_log: torch.Tensor,
++ dt_bias: torch.Tensor, norm_w: torch.Tensor, eps: float, lower: float, rows: int,
++ scratch: KDAScratch) -> torch.Tensor:
++ """One layer's window of ``rows`` rows cut into the segments ``seg`` (``segment_table``): p/a/g as in ``chain``;
++ conv [conv slots, 3, 3 H 128] this layer's conv windows (read only; ``conv_shift_segments`` after the commit);
++ rec [state slots, 2, H, 128, 128] this layer's states (e.g. ``rec[:, :, layer]``). The three-kernel path
++ (``chain_wide``) for any window."""
++
++ q_tmp, y_tmp = _wide_scratch(rows, a_log.numel(), p.device)
++ _ext().chain_wide_segments(seg, p, p.stride(0), int(b_off), a, a.stride(0), g, g.stride(0), conv, conv_w, rec,
++ a_log, dt_bias, norm_w, float(eps), float(lower), int(rows), scratch.out, scratch.k,
++ scratch.v, scratch.g, scratch.b, q_tmp, y_tmp)
++ return scratch.out[:rows]
++
++
++def replay_layers_segments(seg: torch.Tensor, rec: torch.Tensor, scratch: KDAScratchSet) -> None:
++ """Every segment with keep < rows: every layer's state after its first ``keep`` rows, rec[slot, parity] ->
++ rec[slot, 1 - parity] (rec [state slots, 2, layers, H, 128, 128]); keep == rows leaves the chain's state."""
++
++ L, H = scratch.layers, scratch.heads
++ _ext().replay_layers_segments(seg, rec, scratch.k, scratch.v, scratch.g, scratch.b, scratch.rows * H * DK,
++ scratch.rows * H, L, H)
diff --git a/patches/0029-glm-multi-dflash2.patch b/patches/0029-glm-multi-dflash2.patch
new file mode 100644
index 0000000..dca381a
--- /dev/null
+++ b/patches/0029-glm-multi-dflash2.patch
@@ -0,0 +1,516 @@
+diff --git tensorfold/families/glm5_next/cuda/dflash2.py tensorfold/families/glm5_next/cuda/dflash2.py
+index 20ed740..a96d90f 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:
+
+ @triton.jit
+ def _dconv_kernel(X, DYN, BASE, RES, OUT, D: tl.constexpr, G: tl.constexpr, GS: tl.constexpr,
+- BRANCH: tl.constexpr, HAS_RES: tl.constexpr, BLOCK: tl.constexpr):
+- """Two-tap grouped dynamic convolution over the block (row r mixes rows r and r - 1), plus the residual."""
++ BRANCH: tl.constexpr, HAS_RES: tl.constexpr, BLOCK: tl.constexpr, SEG: tl.constexpr = 0):
++ """Two-tap grouped dynamic convolution over the block (row r mixes rows r and r - 1), plus the residual; SEG > 0:
++ the rows are blocks of SEG rows side by side (``dflash2_multi``), each block's first row mixing no row before."""
+
+ row = tl.program_id(0)
+ c = tl.program_id(1) * BLOCK + tl.arange(0, BLOCK)
+ ok = c < D
+ x = tl.load(X + row * D + c, mask=ok, other=0.0).to(tl.float32)
+- prev = tl.load(X + (row - 1) * D + c, mask=ok & (row > 0), other=0.0).to(tl.float32)
++ if SEG > 0:
++ has_prev = row % SEG != 0
++ else:
++ has_prev = row > 0
++ prev = tl.load(X + (row - 1) * D + c, mask=ok & has_prev, other=0.0).to(tl.float32)
+ 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
+
+
+ def _dconv(x: torch.Tensor, dyn: torch.Tensor, base: torch.Tensor, branch: int, group_size: int,
+- residual: torch.Tensor | None = None) -> torch.Tensor:
++ residual: torch.Tensor | None = None, seg: int = 0) -> torch.Tensor:
+ rows, d = x.shape
+ x = x.contiguous()
+ out = torch.empty_like(x)
+ block = 1024
+ _dconv_kernel[(rows, triton.cdiv(d, block))](x, dyn.contiguous(), base, residual if residual is not None else x,
+ out, D=d, G=d // group_size, GS=group_size, BRANCH=branch,
+- HAS_RES=residual is not None, BLOCK=block, num_warps=4)
++ HAS_RES=residual is not None, BLOCK=block, SEG=seg, num_warps=4)
+ return out
+
+
+@@ -184,6 +189,20 @@ def _mm(x: torch.Tensor, w: qmm.Q4, xs: torch.Tensor | None = None, *, f32: bool
+ return qmm.matmul(x, w, xs, f32=f32)
+
+
++def merge_candidates(g: torch.Tensor, proj: torch.Tensor, k: int) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
++ """A block pass's host rows -> (ids [depth, k], logits, projected rows): ``g`` [ranks, depth, 2 * k] (each rank's
++ top-k values, then ids as fp32 bits), merged by value then id over the ranks; ``proj`` [depth, selector rank]."""
++
++ 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])],
++ dim=1).numpy().astype(np.int64)
++ if g.shape[0] > 1:
++ 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)
++ return tokens, values, proj.numpy().astype(np.float64) # astype copies: nothing keeps the host buffer
++
++
+ @dataclass
+ class DraftLayer:
+ in_norm: torch.Tensor
+@@ -485,15 +504,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]
+- 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])],
+- dim=1).numpy().astype(np.int64)
+- if g.shape[0] > 1:
+- 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)
+- return tokens, values, proj.numpy().astype(np.float64) # astype copies: nothing keeps cand_host
++ return merge_candidates(g, proj, self.top_k)
+
+ 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,
+diff --git tensorfold/families/glm5_next/cuda/dflash2_multi.py tensorfold/families/glm5_next/cuda/dflash2_multi.py
+new file mode 100644
+index 0000000..10c53b5
+--- /dev/null
++++ tensorfold/families/glm5_next/cuda/dflash2_multi.py
+@@ -0,0 +1,428 @@
++"""DFlash2 for several streams at once: one drafter's weights, a context ring per stream, block passes and context
++updates of several streams in one launch sequence, each stream's candidates the bits of its own solo ``Drafter``.
++
++Every kernel of a block pass is row-independent (the 4-bit matmuls run the same groups and K slices at any row
++count, ``qmm``; norms, rotary, the dynamic convolutions per block, ``_prep``) except the block attention, which reads
++each stream's own ring (a per-segment slot and position table), and the two ops whose kernels could depend on the row
++count (cuBLAS's selector projection and ``torch.topk``), which run per stream on that stream's rows alone. Context
++updates stack every stream's kept rows; each row carries its own position and ring destination.
++
++API (both ranks call it identically, the same streams in the same order):
++
++ md = MultiDrafter(drafter, streams=4) # drafter: a dflash2.Drafter (its weights are shared)
++ ctx = md.contexts[i] # stream i's DraftContext (duck-types a Drafter's context for
++ # decode.prefill / take_snapshot / restore: add_taps, reset,
++ # context_end, pos_dev, kc, vc, ring, window)
++ chains = md.propose([DraftRequest(ctx, pending, depth, sampling, confidence, ...), ...])
++ md.commit([(ctx, taps), ...]) # each stream's kept rows' taps [n, 5 * D], after verify
++ md.capture() # CUDA graphs: block passes of 1..streams, updates by row bucket
++"""
++
++from __future__ import annotations
++
++from dataclasses import dataclass
++from typing import Sequence
++
++import numpy as np
++import torch
++import torch.nn.functional as F
++import triton
++import triton.language as tl
++
++from tensorfold.engine.exact_sampling import Sampling
++
++from . import glue
++from .dflash2 import NO_LIMIT, Drafter, _dconv, _mm, merge_candidates
++
++
++def _dattn_seg_kernel(Q, K, V, OUT, POS, SLOT, window, scale, L, SLOT_ROWS,
++ N: tl.constexpr, G: tl.constexpr, NH: tl.constexpr, HD: tl.constexpr, CAP: tl.constexpr,
++ BK: tl.constexpr, CAUSAL: tl.constexpr, RING: tl.constexpr):
++ """``dflash2._dattn_kernel`` for block ``seg`` (program 1) of L rows side by side: its queries at rows seg * N of
++ Q [heads, L, HD], its context in slot SLOT[seg] (rows slot * CAP .. of K / V [kv heads, SLOT_ROWS, HD]) at
++ position POS[seg]. The same loop and arithmetic as the solo kernel, so each block gets its solo bits."""
++
++ kvh = tl.program_id(0)
++ seg = tl.program_id(1)
++ M: tl.constexpr = G * N
++ m = tl.arange(0, M)
++ qh = kvh * G + m // N
++ qr = m % N
++ d = tl.arange(0, HD)
++ q = tl.load(Q + (qh[:, None] * L + seg * N + qr[:, None]) * HD + d[None, :])
++ s = tl.load(POS + seg).to(tl.int32)
++ base = kvh.to(tl.int64) * SLOT_ROWS + tl.load(SLOT + seg).to(tl.int64) * CAP
++ klen = s + N
++ qpos = s + qr
++ m_i = tl.full([M], -1e30, tl.float32)
++ l_i = tl.zeros([M], tl.float32)
++ acc = tl.zeros([M, HD], tl.float32)
++ 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
++ if RING:
++ row = kk % CAP
++ else:
++ row = kk
++ k = tl.load(K + (base + row[:, None]) * HD + d[None, :], mask=kin[:, None], other=0.0)
++ v = tl.load(V + (base + 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:
++ ok = ok & (kk[None, :] <= qpos[:, None])
++ sc = tl.where(ok, sc, float("-inf"))
++ m_new = tl.maximum(m_i, tl.max(sc, axis=1))
++ alpha = tl.exp(m_i - m_new)
++ p = tl.exp(sc - m_new[:, None])
++ l_i = l_i * alpha + tl.sum(p, axis=1)
++ acc = acc * alpha[:, None] + tl.dot(p.to(tl.bfloat16), v)
++ m_i = m_new
++ out = acc / l_i[:, None]
++ tl.store(OUT + (seg * N + qr[:, None]) * (NH * HD) + qh[:, None] * HD + d[None, :], out.to(tl.bfloat16))
++
++
++class DraftContext:
++ """One stream's DFlash2 context: its slot of the shared ring pool (``kc`` / ``vc`` per layer are views
++ [kv heads, ring rows, head_dim]) and where its committed rows end. Stands in for a solo ``Drafter`` wherever one
++ stream's context is handled on its own (``decode.prefill``, ``take_snapshot``, ``restore``)."""
++
++ def __init__(self, owner: "MultiDrafter", slot: int) -> None:
++ d = owner.d
++ self.owner, self.slot = owner, slot
++ self.ring, self.window, self.block, self.capacity = d.ring, d.window, d.block, d.capacity
++ self.tap_layers = d.tap_layers
++ cap = owner.cap
++ self.kc = [c[:, slot * cap:(slot + 1) * cap] for c in owner.kc]
++ self.vc = [c[:, slot * cap:(slot + 1) * cap] for c in owner.vc]
++ self.pos_dev = owner.pos[slot:slot + 1] # the device mirror of context_end (restore fills it)
++ self.context_end = 0
++
++ def reset(self) -> None:
++ self.context_end = 0
++ self.pos_dev.zero_()
++
++ def add_taps(self, taps: torch.Tensor) -> None:
++ """This stream's committed rows' taps alone (a prompt's chunks): ``MultiDrafter.commit`` of one stream."""
++ self.owner.commit([(self, taps)])
++
++ def propose(self, pending: int, depth: int, sampling: Sampling | None, confidence: float = 0.0, *,
++ beta: float = 0.0, round_ms: tuple[float, ...] | None = None) -> list[int]:
++ return self.owner.propose([DraftRequest(self, pending, depth, sampling, confidence, beta, round_ms)])[0]
++
++
++@dataclass
++class DraftRequest:
++ """One stream's draft for a round: ``Drafter.propose``'s arguments with the stream's context."""
++
++ ctx: DraftContext
++ pending: int
++ depth: int
++ sampling: Sampling | None = None
++ confidence: float = 0.0
++ beta: float = 0.0
++ round_ms: tuple[float, ...] | None = None
++
++
++class MultiDrafter:
++ """Up to ``streams`` DFlash2 streams over one ``Drafter``'s weights (its own context buffers stay unused).
++
++ The ring pool per layer is [kv heads, streams * cap + trash, head_dim]: stream i's rows at i * cap .. (the
++ drafter's ring, or a flat capacity + block when it has none), then ``trash`` rows that padded context updates
++ (a captured row bucket larger than the rows kept) write to."""
++
++ def __init__(self, drafter: Drafter, streams: int = 4, *, tap_rows: int | None = None) -> None:
++ d = self.d = drafter
++ if streams < 1:
++ raise ValueError("a multi-stream drafter needs at least one stream")
++ self.streams = streams
++ self.dev = d.dev
++ self.block = d.block
++ self.cap = d.cap
++ n = self.block
++ # context updates: rows per launch (every stream's kept rows stacked), padded to a multiple of the block
++ rows = max(64, streams * (tap_rows or d.tap_rows))
++ self.t_max = -(-rows // n) * n
++ self.trash = self.t_max
++ self.slot_rows = streams * self.cap + self.trash
++ KV, hd = d.kvh, d.hd
++ self.kc = [torch.zeros((KV, self.slot_rows, hd), dtype=torch.bfloat16, device=self.dev) for _ in d.layers]
++ self.vc = [torch.zeros((KV, self.slot_rows, hd), dtype=torch.bfloat16, device=self.dev) for _ in d.layers]
++ self.pos = torch.zeros((streams + 1,), dtype=torch.int64, device=self.dev) # + the trash entry
++ self.contexts = [DraftContext(self, i) for i in range(streams)]
++ pinned = torch.cuda.is_available()
++ # block passes: [pending x streams | slot x streams | position x streams]
++ self.b_meta = torch.zeros((3 * streams,), dtype=torch.int64, device=self.dev)
++ self.b_host = torch.zeros((3 * streams,), dtype=torch.int64, pin_memory=pinned)
++ self.ids = torch.full((streams * n,), d.mask_id, dtype=torch.int32, device=self.dev)
++ self.ar = torch.arange(max(64, n), device=self.dev)
++ # context updates: [position x t_max | destination row x t_max | slot x streams | end x streams]
++ T = self.t_max
++ self.t_meta = torch.zeros((2 * T + 2 * streams,), dtype=torch.int64, device=self.dev)
++ self.t_host = torch.zeros((2 * T + 2 * streams,), dtype=torch.int64, pin_memory=pinned)
++ self.t_ready = torch.cuda.Event() if pinned else None
++ self.tap_in = torch.zeros((T, d.tap_in.shape[1]), dtype=torch.bfloat16, device=self.dev)
++ m = n - 1
++ self.cand_n = d.gathered * streams * m * 2 * d.top_k
++ self.cand = torch.zeros((self.cand_n + streams * m * d.hproj.shape[0],), dtype=torch.float32,
++ device=self.dev)
++ self.cand_host = torch.zeros(self.cand.shape, dtype=torch.float32, pin_memory=pinned)
++ self.cand_ready = torch.cuda.Event() if pinned else None
++ self.proj = self.cand[self.cand_n:].view(streams * m, d.hproj.shape[0])
++ self.pool = None
++ self.block_graphs: dict[int, torch.cuda.CUDAGraph] = {}
++ self.tap_graphs: dict[int, torch.cuda.CUDAGraph] = {}
++ self.buckets = list(range(n, T + 1, n))
++
++ def nbytes(self) -> int:
++ """The pool's context rows (the weights are the drafter's)."""
++ return 2 * sum(t.numel() * 2 for t in self.kc)
++
++ def reset(self) -> None:
++ for c in self.contexts:
++ c.reset()
++
++ # -- pieces -------------------------------------------------------------------------------------------------
++ def _rotary(self, pos: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
++ phase = pos.to(torch.float32)[:, None] * self.d.inv_freq[None, :]
++ return phase.cos().contiguous(), phase.sin().contiguous()
++
++ def _local(self, pos: torch.Tensor) -> torch.Tensor:
++ return pos % self.d.ring if self.d.ring else pos
++
++ def _layer(self, i: int, x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor, idx: torch.Tensor, S: int,
++ pos: torch.Tensor, slot: torch.Tensor) -> torch.Tensor:
++ """``Drafter._layer`` over S blocks side by side; the attention reads each block's own slot."""
++
++ d = self.d
++ L = d.layers[i]
++ n = self.block
++ rows = x.shape[0]
++ normed, xs = d._norm(x, L.in_norm)
++ dyn = _mm(normed, L.a_kp, xs)
++ q, k, v = d._prep(_mm(_dconv(normed, dyn, L.a_base, 0, d.gs, seg=n), L.qkv), L, cos, sin, d.heads)
++ self.kc[i].index_copy_(1, idx, k)
++ self.vc[i].index_copy_(1, idx, v)
++ out = torch.empty((rows, d.heads * d.hd), dtype=torch.bfloat16, device=self.dev)
++ _dattn_seg_kernel[(d.kvh, S)](q, self.kc[i], self.vc[i], out, pos, slot, d.window, d.hd ** -0.5, rows,
++ self.slot_rows, N=n, G=d.heads // d.kvh, NH=d.heads, HD=d.hd, CAP=self.cap,
++ BK=64, CAUSAL=d.causal, RING=bool(d.ring), num_warps=4)
++ x = _dconv(d._row(out, L.o), dyn, L.a_base, 1, d.gs, x, seg=n)
++ normed, xs = d._norm(x, L.post_norm)
++ dyn = _mm(normed, L.m_kp, xs)
++ gu = _mm(_dconv(normed, dyn, L.m_base, 0, d.gs, seg=n), L.gu)
++ act = torch.empty((rows, d.inter), dtype=torch.bfloat16, device=self.dev)
++ axs = torch.empty((rows, d.inter // 64), dtype=torch.float32, device=self.dev)
++ glue.swiglu(gu, act, axs, NO_LIMIT)
++ return _dconv(d._row(act, L.down, axs), dyn, L.m_base, 1, d.gs, x, seg=n)
++
++ def _block_compute(self, S: int) -> None:
++ """S streams' blocks [pending, mask x (block - 1)] at their committed lengths (``b_meta``), then each
++ stream's candidates and projected rows as its solo pass leaves them, stream s at rows s * (block - 1)."""
++
++ d, w = self.d, self.d.w
++ n, St = self.block, self.streams
++ pend, slot, pos = self.b_meta[:S], self.b_meta[St:St + S], self.b_meta[2 * St:2 * St + S]
++ self.ids.view(St, n)[:S, 0].copy_(pend)
++ rowpos = (pos[:, None] + self.ar[:n][None, :]).reshape(-1)
++ idx = (slot[:, None] * self.cap + self._local(rowpos).view(S, n)).reshape(-1)
++ R = S * n
++ x = torch.empty((R, d.D), dtype=torch.bfloat16, device=self.dev)
++ glue.embed(self.ids[:R], w.embed, d.D, 1, x)
++ cos, sin = self._rotary(rowpos)
++ for i in range(len(d.layers)):
++ x = self._layer(i, x, cos, sin, idx, S, pos, slot)
++ m, k = n - 1, d.top_k
++ h, hs = d._norm(x.view(S, n, d.D)[:, 1:].reshape(S * m, d.D), d.norm)
++ logits = _mm(h, w.draft_head if w.draft_head is not None else w.head, hs).float()
++ packed = torch.empty((S * m, 2 * k), dtype=torch.float32, device=self.dev)
++ for s in range(S): # torch.topk and cuBLAS may pick kernels by row count: one stream each
++ rows = slice(s * m, (s + 1) * m)
++ vals, local = torch.topk(logits[rows], k, dim=-1)
++ gids = (local + w.vocab_offset).to(torch.int32)
++ packed[rows] = torch.cat([vals, gids.view(torch.float32)], dim=1)
++ self.proj[rows].copy_(F.linear(h[rows], d.hproj).float())
++ size = d.gathered * S * m * 2 * k
++ if d.gathered > 1:
++ w.comm.all_gather(packed.view(-1), self.cand[:size])
++ else:
++ self.cand[:size].copy_(packed.view(-1))
++
++ def _taps_compute(self, T: int) -> None:
++ """Context updates of T stacked rows (``t_meta``: each row's position and destination), then each updated
++ stream's device end."""
++
++ d, St, Tm = self.d, self.streams, self.t_max
++ pos, idx = self.t_meta[:T], self.t_meta[Tm:Tm + T]
++ ctx, _ = d._norm(_mm(self.tap_in[:T], d.fc), d.hidden_norm)
++ cos, sin = self._rotary(pos)
++ for i, L in enumerate(d.layers):
++ _, k, v = d._prep(_mm(ctx, L.kv), L, cos, sin, 0)
++ self.kc[i].index_copy_(1, idx, k)
++ self.vc[i].index_copy_(1, idx, v)
++ self.pos.index_copy_(0, self.t_meta[2 * Tm:2 * Tm + St], self.t_meta[2 * Tm + St:2 * Tm + 2 * St])
++
++ # -- graphs -------------------------------------------------------------------------------------------------
++ def _trash_tables(self) -> None:
++ """Tables that send every row to the trash rows (captures and their warm-ups touch no stream)."""
++
++ St, Tm = self.streams, self.t_max
++ self.b_meta.zero_()
++ self.b_meta[St:2 * St].fill_(St) # slot St: rows St * cap .., the trash (block < trash)
++ self.t_meta.zero_()
++ self.t_meta[Tm:2 * Tm].copy_(St * self.cap + torch.arange(Tm, device=self.dev))
++ self.t_meta[2 * Tm:2 * Tm + St].fill_(St) # the trash end
++
++ @torch.no_grad()
++ def capture(self) -> None:
++ """CUDA graphs for block passes of 1..streams streams and context updates of each row bucket (a multiple of
++ the block up to ``t_max``), both ranks together. Stream contexts are left as they were."""
++
++ ends = [c.context_end for c in self.contexts]
++ saved = self.pos.clone()
++ self.pool = torch.cuda.graph_pool_handle()
++ self._trash_tables()
++ for T in self.buckets:
++ for _ in range(2):
++ self._taps_compute(T)
++ torch.cuda.synchronize()
++ g = torch.cuda.CUDAGraph()
++ with torch.cuda.graph(g, pool=self.pool):
++ self._taps_compute(T)
++ self.tap_graphs[T] = g
++ for S in range(1, self.streams + 1):
++ for _ in range(2):
++ self._block_compute(S)
++ torch.cuda.synchronize()
++ g = torch.cuda.CUDAGraph()
++ with torch.cuda.graph(g, pool=self.pool):
++ self._block_compute(S)
++ self.block_graphs[S] = g
++ torch.cuda.synchronize()
++ self.pos.copy_(saved)
++ for c, e in zip(self.contexts, ends):
++ c.context_end = e
++
++ def drop_graphs(self) -> None:
++ self.block_graphs, self.tap_graphs = {}, {}
++
++ # -- the context ---------------------------------------------------------------------------------------------
++ def _launch_taps(self, pieces: list[tuple[DraftContext, torch.Tensor, int]]) -> None:
++ St, Tm = self.streams, self.t_max
++ if self.t_ready is not None:
++ self.t_ready.synchronize() # the last update's table has left t_host
++ h = self.t_host
++ h[2 * Tm:2 * Tm + St].fill_(St)
++ h[2 * Tm + St:].zero_()
++ off = 0
++ for j, (c, part, p0) in enumerate(pieces):
++ r = part.shape[0]
++ self.tap_in[off:off + r].copy_(part)
++ p = torch.arange(p0, p0 + r, dtype=torch.int64)
++ h[off:off + r] = p
++ h[Tm + off:Tm + off + r] = c.slot * self.cap + (p % self.d.ring if self.d.ring else p)
++ h[2 * Tm + j], h[2 * Tm + St + j] = c.slot, p0 + r
++ off += r
++ T = off
++ g = None
++ if self.tap_graphs:
++ T = next(b for b in self.buckets if b >= off)
++ g = self.tap_graphs[T]
++ if T > off: # padded rows: the trash
++ h[off:T] = 0
++ h[Tm + off:Tm + T] = St * self.cap + torch.arange(off, T, dtype=torch.int64)
++ self.t_meta.copy_(h, non_blocking=True)
++ if self.t_ready is not None:
++ self.t_ready.record()
++ if g is not None:
++ g.replay()
++ else:
++ self._taps_compute(T)
++ for c, part, p0 in pieces:
++ c.context_end = p0 + part.shape[0]
++
++ @torch.no_grad()
++ def commit(self, items: Sequence[tuple[DraftContext, torch.Tensor]]) -> None:
++ """Each stream's committed rows' taps [n, 5 * D] (bf16) at its positions context_end, context_end + 1, ...:
++ every stream's rows stacked into launches of up to ``t_max`` rows."""
++
++ seen: set[int] = set()
++ for c, taps in items:
++ if c.owner is not self or c.slot in seen:
++ raise ValueError("commit takes each of this drafter's streams at most once")
++ seen.add(c.slot)
++ if c.context_end + taps.shape[0] > c.capacity:
++ raise ValueError("drafter context past its capacity")
++ pieces: list[tuple[DraftContext, torch.Tensor, int]] = []
++ used = 0
++ for c, taps in items:
++ start, end = 0, c.context_end
++ while start < taps.shape[0]:
++ take = min(taps.shape[0] - start, self.t_max - used)
++ pieces.append((c, taps[start:start + take], end))
++ start, end, used = start + take, end + take, used + take
++ if used == self.t_max:
++ self._launch_taps(pieces)
++ pieces, used = [], 0
++ if pieces:
++ self._launch_taps(pieces)
++
++ # -- drafts -------------------------------------------------------------------------------------------------
++ @torch.no_grad()
++ def candidates(self, reqs: Sequence[tuple[DraftContext, int, int]]) -> list[tuple[np.ndarray, ...]]:
++ """(stream, pending, depth) -> each stream's ``Drafter.candidates(pending, depth)``: one batched pass."""
++
++ S, St = len(reqs), self.streams
++ if not 1 <= S <= St:
++ raise ValueError(f"a block pass takes 1..{St} streams, got {S}")
++ if len({c.slot for c, _, _ in reqs}) != S or any(c.owner is not self for c, _, _ in reqs):
++ raise ValueError("a block pass takes each of this drafter's streams at most once")
++ h = self.b_host
++ for s, (c, pending, _) in enumerate(reqs):
++ h[s], h[St + s], h[2 * St + s] = int(pending), c.slot, c.context_end
++ self.b_meta.copy_(h, non_blocking=True)
++ g = self.block_graphs.get(S)
++ if g is not None:
++ g.replay()
++ else:
++ self._block_compute(S)
++ if self.cand_ready is not None:
++ self.cand_host.copy_(self.cand, non_blocking=True)
++ self.cand_ready.record()
++ self.cand_ready.synchronize()
++ else:
++ self.cand_host.copy_(self.cand)
++ d = self.d
++ m, k = self.block - 1, d.top_k
++ g_all = self.cand_host[:d.gathered * S * m * 2 * k].view(d.gathered, S * m, 2 * k)
++ p_all = self.cand_host[self.cand_n:].view(St * m, -1)
++ out = []
++ for s, (_, _, depth) in enumerate(reqs):
++ out.append(merge_candidates(g_all[:, s * m:s * m + depth], p_all[s * m:s * m + depth], k))
++ return out
++
++ def propose(self, reqs: Sequence[DraftRequest]) -> list[list[int]]:
++ """Each stream's ``Drafter.propose``: streams with a depth and a context share one block pass; the others
++ get [] (as a solo drafter runs none for them)."""
++
++ out: list[list[int]] = [[] for _ in reqs]
++ live = []
++ for i, r in enumerate(reqs):
++ depth = min(r.depth, self.block - 1)
++ if depth >= 1 and r.ctx.context_end > 0:
++ live.append((i, depth))
++ if not live:
++ return out
++ got = self.candidates([(reqs[i].ctx, reqs[i].pending, depth) for i, depth in live])
++ for (i, _), (tokens, values, proj) in zip(live, got):
++ r = reqs[i]
++ first = r.ctx.context_end + 1
++ if r.beta > 0:
++ out[i] = self.d.chain(tokens, values, proj, r.pending, first, r.sampling, r.confidence, beta=r.beta,
++ round_ms=r.round_ms)
++ else:
++ out[i] = self.d.chain(tokens, values, proj, r.pending, first, r.sampling, r.confidence)
++ return out
diff --git a/patches/0030-glm-mtp-off.patch b/patches/0030-glm-mtp-off.patch
new file mode 100644
index 0000000..8307fb9
--- /dev/null
+++ b/patches/0030-glm-mtp-off.patch
@@ -0,0 +1,172 @@
+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/0031-glm-lean-prompt-scratch.patch b/patches/0031-glm-lean-prompt-scratch.patch
new file mode 100644
index 0000000..506abc0
--- /dev/null
+++ b/patches/0031-glm-lean-prompt-scratch.patch
@@ -0,0 +1,237 @@
+diff --git tensorfold/cuda/geometry.py tensorfold/cuda/geometry.py
+index dcf1610..49f10d0 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,
+ + 12 * streams + 64)
+
+
++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
++ 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:
++ 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)."""
++ one; GLM's TF_GLM_MTP can leave it out); ``onepass``: prompt chunks' sparse latent attention keeps no partials
++ (TF_GLM_SPARSE_ONEPASS); an EXL3 checkpoint's ``exl3_prompt``: prompt chunks run the prompt expert kernels
++ (TF_GLM_EXL3_PROMPT: no split-K sums), ``prompt_split_k``: the prompt buffers keep split-K partials for BF16 / FP8
++ projections (``forward.Buffers.sk``)."""
+ 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
+ # 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
++ # 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)
++ fixed += exl3_expert_scratch(prefill_rows, slots, d, width, prompt=exl3_prompt)
++ fixed += 8 * prefill_rows * 16384 * 4 if prompt_split_k else 0
+ 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, 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 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
+ return Geometry(bytes_at, reserve, minimum_slots)
+
+
+-def mla_chunk_scratch(t: dict, world: int, capacity: int, *, latent: bool, prefill_rows: int = PREFILL_ROWS) -> int:
+- """A prompt chunk's transient bytes: token selection (fp32 pool scores, chosen pools, token lists), then sparse attention's partials."""
++def mla_chunk_scratch(t: dict, world: int, capacity: int, *, latent: bool, prefill_rows: int = PREFILL_ROWS,
++ onepass: bool = False) -> int:
++ """A prompt chunk's transient bytes: token selection (fp32 pool scores, chosen pools, token lists), then sparse
++ attention's partials, which the latent path's one-pass kernel (``onepass``) does not allocate."""
+
+ heads, topk = int(t["num_attention_heads"]) // world, int(t.get("index_topk", 2048))
+ # 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 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
+--- tensorfold/families/glm5_next/cuda/engine.py
++++ tensorfold/families/glm5_next/cuda/engine.py
+@@ -376,11 +376,15 @@ class GlmEngine:
+ weights_estimate = lambda name, info: ((math.prod(info["shape"]) * 2, 0)
+ if name.startswith("model.visual.") else text_weights(name, info))
+
++ from .exl3_mm import prompt_kernels
++ from .latent import SPARSE_ONEPASS
++
+ 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,
+- mtp=self.mtp_on)
++ mtp=self.mtp_on, onepass=SPARSE_ONEPASS, exl3_prompt=prompt_kernels(),
++ prompt_split_k=cfg.quant == "exl3" and dense_kind() != "q4")
+ 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,
+diff --git tensorfold/families/glm5_next/cuda/forward.py tensorfold/families/glm5_next/cuda/forward.py
+index 5980279..d2e45c5 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
+ from .weights import LayerW, Weights
+
+
++# rows a prompt chunk's dense latent attention runs at once (its partials' rows; the startup estimate's)
++from tensorfold.cuda.geometry import MLA_PROMPT_ATT_ROWS as PROMPT_ATT_ROWS # noqa: E402
++
++
++def prompt_split_k(w: Weights) -> bool:
++ """Whether a prompt chunk's projections take split-K partials: an EXL3 checkpoint's BF16 / FP8 ones do; 4-bit
++ ones (an MLX checkpoint, TF_GLM_DENSE=q4, read off the first layer's input projection) run without."""
++
++ if w.cfg.quant != "exl3":
++ return False
++ first = next((l.kda.proj if l.kda is not None else l.dsa.proj for l in w.layers
++ if getattr(l, "kda", None) is not None or getattr(l, "dsa", None) is not None), None)
++ return not isinstance(first, qmm.Q4)
++
++
+ 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:
+ 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 (``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)
++ 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:
+ # rank partials
+ self.part = torch.empty((rows, D), dtype=f32, device=dev)
+ self.gath = torch.empty((w.world * rows * D,), dtype=f32, device=dev)
+- self.sk = torch.empty((1 if prefill and not exl3 else 8 * rows * 16384,), dtype=f32, device=dev)
++ # split-K partials of BF16 / FP8 projections (``mm``): a prompt chunk's 4-bit ones run the prompt matmul, which
++ # keeps none, so an MLX checkpoint's and TF_GLM_DENSE=q4's prompt buffers hold none (the FP8 head's one row
++ # allocates its few itself); a partials buffer holds scratch only, so where it lives never changes a bit
++ self.sk = torch.empty((1 if prefill and not prompt_split_k(w) else 8 * rows * 16384,), dtype=f32, device=dev)
+ # 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:
+ return min(R, max(0, sparse.SPARSE_FROM - host_pos))
+
+
++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)
++ 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)
++ 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).
+ 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],
++ 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
+--- tensorfold/families/glm5_next/cuda/latent.py
++++ tensorfold/families/glm5_next/cuda/latent.py
+@@ -594,13 +594,16 @@ 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 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):
diff --git a/patches/0032-glm-multi-dsa.patch b/patches/0032-glm-multi-dsa.patch
new file mode 100644
index 0000000..a8648c6
--- /dev/null
+++ b/patches/0032-glm-multi-dsa.patch
@@ -0,0 +1,667 @@
+diff --git tensorfold/families/glm5_next/cuda/forward.py tensorfold/families/glm5_next/cuda/forward.py
+index d2e45c5..1a8894f 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
+ return out_proj(w, b, o, a.o, qmm.group_sums(o, b.xs_ao[:R]), R)
+
+
++def dsa_segments(layer: LayerW, w: Weights, lc: torch.Tensor, b: Buffers, R: int, rows, sel=None, index=None, *,
++ select: bool = True) -> torch.Tensor | None:
++ """dsa_block on the latent cache for a multi-stream window (``rows``: segments.SegRows, already set): several
++ streams' rows back to back, each stream's latents (lc), index keys, gates and pooled keys (index: arenas) in
++ its own extent. Each segment's rows get the bits of that segment alone through dsa_block (the projections,
++ absorb and expand keep rows apart; the attention kernels are latent.seg_* / sparse.seg_*). Graphs: one per R
++ covers every position mix. ``select`` False skips the token selection (eager windows with no sparse row:
++ ``rows.any_sparse()``); ``sel``: segments.SelectScratch, needed with an index."""
++
++ c = w.cfg
++ a = layer.dsa
++ if a.absorb is None:
++ raise ValueError("segmented windows need the latent cache (TF_GLM_LATENT=1)")
++ mm(b, b.normed[:R], a.proj, b.xs[:R], b.dp[:R])
++ glue.rmsnorm(b.dp[:R, :c.q_lora], a.q_norm, c.eps, b.qr[:R], b.xs_qr[:R])
++ glue.rmsnorm(b.dp[:R, c.q_lora:], a.kv_norm, c.eps, b.lat[:R], b.xs_lat[:R])
++ HL = a.heads
++ mm(b, b.qr[:R], a.q_b, b.xs_qr[:R], b.q[:R].view(R, HL * c.qk_dim))
++ s = b.lat_s
++ with prof.timed("dsa: latent write"):
++ latent.seg_latent_write(b.lat[:R], lc, rows)
++ tokens = counts = None
++ if index is not None:
++ ik, ig, pk = index
++ ix = a.index
++ with prof.timed("dsa: indexer update"):
++ mm(b, b.normed[:R], ix.kw, b.xs[:R], b.ikr[:R])
++ glue.router(b.normed[:R], ix.gate, b.igr[:R])
++ sparse.seg_index_update(b.ikr[:R, :c.index_dim], b.igr[:R], ix.ln_w, ix.ln_b, ix.ape, ik, ig, pk, rows)
++ if select:
++ with prof.timed("dsa: select tokens"):
++ mm(b, b.qr[:R], ix.qb, b.xs_qr[:R], b.qi[:R])
++ 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])
++ with prof.timed("dsa: attention"):
++ ol = latent.seg_attention(qa, lc, rows, tokens, counts, s, scale=c.qk_dim ** -0.5, out=s.ol[:R])
++ with prof.timed("dsa: expand"):
++ o = latent.expand_v(ol, a.absorb, b.vn[:R]).view(R, HL * c.v_dim)
++ return out_proj(w, b, o, a.o, qmm.group_sums(o, b.xs_ao[:R]), R)
++
++
+ def mlp_block(layer: LayerW, w: Weights, b: Buffers, R: int) -> torch.Tensor:
+ m = layer.mlp
+ mm(b, b.normed[:R], m.gu, b.xs[:R], b.gu[:R])
+diff --git tensorfold/families/glm5_next/cuda/latent.py tensorfold/families/glm5_next/cuda/latent.py
+index 3026586..1cecc96 100644
+--- tensorfold/families/glm5_next/cuda/latent.py
++++ tensorfold/families/glm5_next/cuda/latent.py
+@@ -676,3 +676,114 @@ def sparse_onepass(qa: torch.Tensor, cache: torch.Tensor, tokens: torch.Tensor,
+
+ def chunks_for(length: int) -> int:
+ return triton.cdiv(length, CHUNK)
++
++
++# ------------------------------------------------------------------------------------- multi-stream windows ---
++# A window of several streams' rows back to back ([s1: rows][s2: rows]...), each stream's latents in its own extent
++# of a shared arena [P, LW]: per-row device tables (``segments.SegRows``: position, extent base, dense or sparse)
++# drive the kernels below. Every row keeps the arithmetic, tiles and head blocks of today's single-stream kernels,
++# so a segment's rows get the bits of that segment run alone on its extent (tests/cuda/test_glm_attn_segments.py).
++# Cache reads and writes go through _lat_get / _lat_put (the one place a quantized cache plugs in).
++
++def _lat_get(LC, rows, ok, k, RS: tl.constexpr):
++ """Cache rows ``rows`` (int64 [n]) as a bf16 tile [n, LW]; rows with ok false are not read (zeros)."""
++ return tl.load(LC + rows[:, None] * RS + k[None, :], mask=ok[:, None], other=0).to(tl.bfloat16)
++
++
++def _lat_put(LC, row, k, x, RS: tl.constexpr):
++ """Cache row ``row`` (int64) <- x [LW] (bf16)."""
++ tl.store(LC + row * RS + k, x)
++
++
++def _seg_lat_write(LAT, lat_stride, LC, POS, BASE, LW: tl.constexpr):
++ """Row r -> arena row base[r] + pos[r]."""
++ r = tl.program_id(0)
++ row = tl.load(BASE + r).to(tl.int64) + tl.load(POS + r).to(tl.int64)
++ k = tl.arange(0, LW)
++ _lat_put(LC, row, k, tl.load(LAT + r * lat_stride + k), LW)
++
++
++def seg_latent_write(lat: torch.Tensor, cache: torch.Tensor, rows) -> None:
++ """lat [R, latent] bf16 rows into the arena at each row's base + pos (``rows``: segments.SegRows)."""
++ _seg_lat_write[(lat.shape[0],)](lat, lat.stride(0), cache, rows.pos, rows.base, LW=cache.shape[1], num_warps=4)
++
++
++def _seg_chunks(QA, LC, POS, BASE, SPR, TOK, CNT, PO, PM, PL, R, W: tl.constexpr, H: tl.constexpr,
++ LW: tl.constexpr, CH: tl.constexpr, SCALE: tl.constexpr, HBT: tl.constexpr, KTT: tl.constexpr):
++ """Program (row, head block, chunk): _dense_chunks for a dense row (keys base + 0 .. base + pos[r], its own
++ limit), _sparse_chunks for a sparse one (keys base + its selected tokens, list order): the same tiles, masks and
++ _tile math either way, so a row's partials are those of its single-stream kernel."""
++ r = tl.program_id(0)
++ hb = tl.program_id(1)
++ c = tl.program_id(2)
++ B = tl.load(BASE + r).to(tl.int64)
++ sp = tl.load(SPR + r) != 0
++ n = tl.where(sp, tl.load(CNT + r, mask=sp, other=0), tl.load(POS + r) + 1) # selected tokens, or keys 0 .. pos
++ hh = hb * HBT + tl.arange(0, HBT)
++ hok = hh < H
++ k = tl.arange(0, LW)
++ m = tl.full((HBT,), float("-inf"), tl.float32)
++ l = tl.zeros((HBT,), tl.float32)
++ o = tl.zeros((HBT, LW), tl.float32)
++ if c * CH < n:
++ q = tl.load(QA + (r * H + hh[:, None]) * LW + k[None, :], mask=hok[:, None], other=0).to(tl.bfloat16)
++ for t in range(CH // KTT):
++ idx = c * CH + t * KTT + tl.arange(0, KTT)
++ ok = idx < n
++ tok = tl.load(TOK + r * W + idx, mask=ok & sp, other=0).to(tl.int64)
++ tok = tl.where(sp, tok, idx.to(tl.int64))
++ kv = _lat_get(LC, B + tok, ok, k, LW)
++ m, l, o = _tile(q, kv, m, l, o, ok, SCALE)
++ base = (c * R + r) * H + hh
++ tl.store(PO + base[:, None] * LW + k[None, :], o, mask=hok[:, None])
++ tl.store(PM + base, m, mask=hok)
++ tl.store(PL + base, l, mask=hok)
++
++
++def seg_chunks() -> int:
++ """Chunks a segmented window's rows take: a sparse row's 2,051 selected tokens, a dense row's keys up to
++ SPARSE_FROM - 1 (both 5 of 512); chunks past a row's keys are empty (merged as nothing, the same bits)."""
++ from .sparse import SPARSE_FROM, TOKENS
++
++ return triton.cdiv(max(SPARSE_FROM, TOKENS), CHUNK)
++
++
++SEG_WIDE_ROWS = 8 # segmented windows from this many rows take 32-head tiles (keys read once; fewer programs)
++
++
++def seg_head_block(R: int) -> int:
++ """Heads per program of a segmented window: 16 for a few rows (more programs in flight), a rank's 32 from
++ SEG_WIDE_ROWS (each key tile read once for them). 16- and 32-row tiles give a row the same bits (head_block),
++ so either matches the single-stream kernels' 16 (tests/cuda/test_glm_attn_segments.py checks both)."""
++ return HB_WIDE if R >= SEG_WIDE_ROWS else HB
++
++
++def seg_attention(qa: torch.Tensor, cache: torch.Tensor, rows, tokens: torch.Tensor | None,
++ counts: torch.Tensor | None, s: LatentScratch, *, scale: float, out: torch.Tensor,
++ hb: int | None = None) -> torch.Tensor:
++ """Attention of a segmented window's rows qa [R, H, 512] -> out [R, H, 512]: dense rows over their stream's
++ keys 0 .. pos, sparse rows over their selected tokens (``segments.seg_select``: tokens relative to the stream,
++ counts), each in its own extent of the arena. One chunk pass and one merge for both kinds; a row gets the bits
++ of ``attention`` (dense) or ``sparse_attention`` (sparse) run on its segment alone."""
++ R, H, LW = qa.shape
++ nch = seg_chunks()
++ if nch > s.nch or R > s.rows or LW != s.lw:
++ raise ValueError(f"segmented attention: {R} rows, {nch} chunks, width {LW} past the scratch's "
++ f"{s.rows}, {s.nch}, {s.lw}")
++ if tokens is None: # a window without sparse rows (no index): nothing reads the lists
++ tokens, counts, W = s.dummy, s.dummy, 1
++ else:
++ W = tokens.shape[1]
++ n = nch * R * H
++ hb = seg_head_block(R) if hb is None else hb
++ if hb not in (HB, HB_WIDE):
++ raise ValueError(f"segmented attention: {hb} heads a tile, not {HB} or {HB_WIDE}")
++ _seg_chunks[(R, triton.cdiv(H, hb), nch)](qa, cache, rows.pos, rows.base, rows.sparse, tokens, counts,
++ s.po[:n * LW], s.pm[:n], s.pl[:n], R, W=W, H=H, LW=LW, CH=CHUNK,
++ SCALE=scale, HBT=hb, KTT=KT, num_warps=8, num_stages=chunk_stages())
++ _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
+diff --git tensorfold/families/glm5_next/cuda/segments.py tensorfold/families/glm5_next/cuda/segments.py
+new file mode 100644
+index 0000000..91b3d06
+--- /dev/null
++++ tensorfold/families/glm5_next/cuda/segments.py
+@@ -0,0 +1,99 @@
++"""Multi-stream decode windows: several streams' rows back to back ([s1: rows][s2: rows]...), each stream's per-token
++DSA state in its own extent of shared arenas (latents [P, 512], index keys and gates [P, 128], pooled keys
++[P / 4 + 2, 128]; extents aligned to EXTENT tokens). ``SegRows`` holds the per-row and per-segment device tables the
++segmented kernels read (latent.seg_*, sparse.seg_*); ``SelectScratch`` the token selection's buffers. Static
++buffers, so one CUDA graph per window size covers every mix of positions and context lengths."""
++
++from __future__ import annotations
++
++from typing import Sequence
++
++import torch
++
++from .sparse import POOL, SPARSE_FROM, TOKENS, split_scratch
++
++MAX_SEGS = 4 # streams a window holds
++EXTENT = 2048 # a stream's extent starts at a multiple of this many tokens (its pooled keys at base / 4)
++
++
++class SegRows:
++ """Device tables of a window of up to ``rows`` rows in up to ``max_segs`` segments, one int32 tensor:
++
++ per row: ``pos`` (the row's position in its stream), ``base`` (its stream's first arena row), ``seg`` (segment
++ index), ``sparse`` (1: past the dense limit, attends to its selected tokens; 0: dense over keys 0 .. pos);
++ per segment: ``seg_start`` (first row), ``seg_rows`` (0: unused), ``seg_pbase`` (pooled-key base, base / 4),
++ ``seg_pools`` (pools its last row sees when it has sparse rows, else 0: what the selection scores)."""
++
++ def __init__(self, rows: int, device, max_segs: int = MAX_SEGS) -> None:
++ self.rows, self.max_segs = rows, max_segs
++ n = 4 * rows + 4 * max_segs
++ pin = torch.cuda.is_available() and torch.device(device).type == "cuda"
++ self.host = torch.zeros((n,), dtype=torch.int32, pin_memory=pin)
++ self.dev = torch.zeros((n,), dtype=torch.int32, device=device)
++ self.pos, self.base, self.seg, self.sparse = (self.dev[i * rows:(i + 1) * rows] for i in range(4))
++ o = 4 * rows
++ self.seg_start, self.seg_rows, self.seg_pbase, self.seg_pools = (
++ self.dev[o + i * max_segs:o + (i + 1) * max_segs] for i in range(4))
++ self.staged = torch.cuda.Event() if pin else None
++ self.R = 0
++ self.segments: list[tuple[int, int, int]] = []
++
++ def fill(self, segments: Sequence[tuple[int, int, int]], *, sparse_from: int | None = SPARSE_FROM):
++ """The host tables for ``segments`` [(base, pos, rows)] in window order (numpy int32, the device layout).
++ ``sparse_from``: the first position that attends sparsely (None: no index, every row dense)."""
++
++ if not 1 <= len(segments) <= self.max_segs:
++ raise ValueError(f"a window of {len(segments)} segments, at most {self.max_segs}")
++ R = sum(n for _, _, n in segments)
++ if R > self.rows:
++ raise ValueError(f"a window of {R} rows, the tables hold {self.rows}")
++ rows, S = self.rows, self.max_segs
++ t = torch.zeros((4 * rows + 4 * S,), dtype=torch.int32).numpy()
++ r = 0
++ for s, (base, pos, n) in enumerate(segments):
++ if n < 1 or pos < 0 or base < 0 or base % EXTENT:
++ raise ValueError(f"segment {s}: base {base} (a multiple of {EXTENT}), position {pos}, {n} rows")
++ for i in range(n):
++ q = pos + i
++ t[r + i] = q
++ t[rows + r + i] = base
++ t[2 * rows + r + i] = s
++ t[3 * rows + r + i] = int(sparse_from is not None and q >= sparse_from)
++ last = pos + n - 1
++ t[4 * rows + s] = r
++ t[4 * rows + S + s] = n
++ t[4 * rows + 2 * S + s] = base // POOL
++ t[4 * rows + 3 * S + s] = (last + 1) // POOL if sparse_from is not None and last >= sparse_from else 0
++ r += n
++ return t, R
++
++ def set(self, segments: Sequence[tuple[int, int, int]], *, sparse_from: int | None = SPARSE_FROM) -> int:
++ """Stage ``segments`` [(base, pos, rows)] into the device tables (a pinned copy, ordered on the current
++ stream like forward.stage's token ids); returns the window's rows."""
++
++ t, R = self.fill(segments, sparse_from=sparse_from)
++ if self.staged is not None:
++ self.staged.synchronize() # the previous copy has left the pinned buffer
++ self.host.numpy()[:] = t
++ self.dev.copy_(self.host, non_blocking=True)
++ if self.staged is not None:
++ self.staged.record()
++ self.R, self.segments = R, list(segments)
++ return R
++
++ def any_sparse(self) -> bool:
++ """Host view of the last ``set``: does any row attend sparsely."""
++ return bool(self.host[3 * self.rows:3 * self.rows + self.R].any())
++
++
++class SelectScratch:
++ """The segmented selection's buffers: fp32 scores [rows, pools] (a stream's pools at most: its largest context
++ / 4), tokens [rows, 2051] int32, counts [rows] int32, the split selection's scratch."""
++
++ def __init__(self, rows: int, max_context: int, device) -> None:
++ self.rows = rows
++ pools = max(1, -(-max_context // POOL))
++ self.scores = torch.empty((rows, pools), dtype=torch.float32, device=device)
++ self.tokens = torch.full((rows, TOKENS), -1, dtype=torch.int32, device=device)
++ 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
+--- tensorfold/families/glm5_next/cuda/sparse.py
++++ tensorfold/families/glm5_next/cuda/sparse.py
+@@ -11,6 +11,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
++TOKENS = TOPK_POOLS * POOL + POOL - 1 # a sparse row's attended tokens: its 512 pools', then its incomplete pool's
+
+
+ @triton.jit
+@@ -152,12 +153,17 @@ def _select_rows(S, OUT, NP, K: tl.constexpr, BLOCK: tl.constexpr):
+
+
+ def top_pools(scores: torch.Tensor, k: int) -> 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."""
+ R, NP = scores.shape
+ if NP < k or not scores.is_contiguous():
+ return _top_pools(scores, k)
++ if R < SPLIT_ROWS and NP >= SPLIT_FROM: # decode rows at long context: each row across chunk programs
++ return select_split(scores, k)
++ # 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)
+ return out
+
+
+@@ -370,3 +376,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)
++
++
++# ------------------------------------------------------------------------------------- multi-stream windows ---
++# Segmented windows (latent.py's section of the same name): each stream's index keys and gates in its own extent of
++# shared arenas [P, 128] (token t of the stream at base + t) and its pooled keys at base / 4 + p of [P / 4 + 2, 128];
++# per-row device tables (``segments.SegRows``) give each row its position, base and kind. A row keeps its
++# single-stream arithmetic. Reads and writes of the index caches go through the helpers below.
++
++def _ix_put(IX, row, d, x, D: tl.constexpr):
++ """Index key or gate row ``row`` (int64) <- x [D] as bf16."""
++ tl.store(IX + row * D + d, x.to(tl.bfloat16))
++
++
++def _ix_get(IX, row, d, D: tl.constexpr):
++ """Index key or gate row ``row`` (int64) as fp32 [D]."""
++ return tl.load(IX + row * D + d).to(tl.float32)
++
++
++def _pk_put(PK, row, d, x, D: tl.constexpr):
++ """Pooled key row ``row`` (int64) <- x [D] (fp32) as bf16."""
++ tl.store(PK + row * D + d, x.to(tl.bfloat16))
++
++
++def _pk_get(PK, rows, ok, d, D: tl.constexpr):
++ """Pooled key rows ``rows`` (int64 [n]) as a bf16 tile [n, D]; rows with ok false are zeros."""
++ return tl.load(PK + rows[:, None] * D + d[None, :], mask=ok[:, None], other=0.0).to(tl.bfloat16)
++
++
++def _seg_index_write(KR, k_stride, GR, LNW, LNB, IK, IG, POS, BASE, eps, D: tl.constexpr):
++ """_index_write for row r at its stream's row base[r] + pos[r]."""
++
++ r = tl.program_id(0)
++ row = tl.load(BASE + r).to(tl.int64) + tl.load(POS + r).to(tl.int64)
++ d = tl.arange(0, D)
++ x = tl.load(KR + r * k_stride + d).to(tl.float32)
++ mean = tl.sum(x, axis=0) / D
++ 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)
++ _ix_put(IK, row, d, y, D)
++ _ix_put(IG, row, d, tl.load(GR + r * D + d), D)
++
++
++def _seg_pool_keys(IK, IG, APE, PK, POS, BASE, D: tl.constexpr):
++ """Program r: the pool row r completes (pos[r] % 4 == 3), pool p = pos[r] // 4 of its stream, from tokens
++ base + 4p .. base + 4p + 3 into pooled row base / 4 + p: _pool_keys' arithmetic (the pools a single-stream
++ window completes are exactly those its rows end)."""
++
++ r = tl.program_id(0)
++ q = tl.load(POS + r).to(tl.int64)
++ if q % 4 != 3:
++ return
++ B = tl.load(BASE + r).to(tl.int64)
++ t = B + (q // 4) * 4
++ d = tl.arange(0, D)
++ l0 = _ix_get(IG, t + 0, d, D) + tl.load(APE + 0 * D + d).to(tl.float32)
++ l1 = _ix_get(IG, t + 1, d, D) + tl.load(APE + 1 * D + d).to(tl.float32)
++ l2 = _ix_get(IG, t + 2, d, D) + tl.load(APE + 2 * D + d).to(tl.float32)
++ l3 = _ix_get(IG, t + 3, d, D) + tl.load(APE + 3 * D + d).to(tl.float32)
++ m = tl.maximum(tl.maximum(l0, l1), tl.maximum(l2, l3))
++ e0 = tl.exp(l0 - m)
++ e1 = tl.exp(l1 - m)
++ e2 = tl.exp(l2 - m)
++ e3 = tl.exp(l3 - m)
++ s = ((e0 + e1) + e2) + e3
++ k0 = _ix_get(IK, t + 0, d, D)
++ k1 = _ix_get(IK, t + 1, d, D)
++ k2 = _ix_get(IK, t + 2, d, D)
++ k3 = _ix_get(IK, t + 3, d, D)
++ t0 = ((e0 / s).to(tl.bfloat16).to(tl.float32) * k0).to(tl.bfloat16).to(tl.float32)
++ t1 = ((e1 / s).to(tl.bfloat16).to(tl.float32) * k1).to(tl.bfloat16).to(tl.float32)
++ t2 = ((e2 / s).to(tl.bfloat16).to(tl.float32) * k2).to(tl.bfloat16).to(tl.float32)
++ t3 = ((e3 / s).to(tl.bfloat16).to(tl.float32) * k3).to(tl.bfloat16).to(tl.float32)
++ _pk_put(PK, B // 4 + q // 4, d, ((t0 + t1) + t2) + t3, D)
++
++
++def seg_index_update(k_raw: torch.Tensor, gate: torch.Tensor, ln_w: torch.Tensor, ln_b: torch.Tensor,
++ ape: torch.Tensor, ik: torch.Tensor, ig: torch.Tensor, pk: torch.Tensor, rows) -> None:
++ """index_update for a segmented window: each row's index key and gate at its stream's base + pos, then every
++ pool a row completes (``rows``: segments.SegRows)."""
++
++ R = k_raw.shape[0]
++ _seg_index_write[(R,)](k_raw, k_raw.stride(0), gate, ln_w, ln_b, ik, ig, rows.pos, rows.base, 1e-6, D=128,
++ num_warps=1)
++ _seg_pool_keys[(R,)](ik, ig, ape, pk, rows.pos, rows.base, D=128, num_warps=1)
++
++
++def _seg_scores(QI, W, w_stride, PK, OUT, o_stride, POS, SPR, SEG_START, SEG_ROWS, SEG_PBASE, SEG_POOLS, scale,
++ wscale, H: tl.constexpr, HP: tl.constexpr, D: tl.constexpr, BP: tl.constexpr, G: tl.constexpr):
++ """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
++ visible pools only (the ones the selection reads)."""
++
++ s = tl.program_id(0)
++ g = tl.program_id(1)
++ npm = tl.load(SEG_POOLS + s)
++ nr = tl.load(SEG_ROWS + s)
++ r0 = tl.load(SEG_START + s)
++ pbase = tl.load(SEG_PBASE + s).to(tl.int64)
++ d = tl.arange(0, D)
++ hh = tl.arange(0, HP)
++ hok = hh < H
++ for pb in range(g, (npm + BP - 1) // BP, G):
++ p = pb * BP + tl.arange(0, BP)
++ k = _pk_get(PK, pbase + p, p < npm, d, D) # [BP, D]
++ for i in range(nr):
++ r = r0 + i
++ if tl.load(SPR + r) != 0:
++ npool = (tl.load(POS + r) + 1) // 4
++ 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
++ 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)
++
++
++def _seg_select(S, s_stride, POS, SPR, TOK, CNT, W: tl.constexpr, K: tl.constexpr, PL: tl.constexpr,
++ BLOCK: tl.constexpr):
++ """Program r (a sparse row): _select_rows over the row's visible pools, its K pools' tokens written as they are
++ taken (ascending), then _tokens' tail and count; a dense row gets count 0. Every single-stream path scores more
++ columns, but those lie past the row's visible pools, score -inf and have the highest indices: they rank below
++ every visible pool (ties go to the lower pool), so a row with more than K visible pools selects the same ones
++ (sparse._select_prompt)."""
++
++ r = tl.program_id(0).to(tl.int64)
++ if tl.load(SPR + r) == 0:
++ tl.store(CNT + r, 0)
++ return
++ qpos = tl.load(POS + r).to(tl.int64)
++ NP = (qpos + 1) // PL
++ row = S + r * s_stride
++ bins = tl.arange(0, 256)
++ prefix = tl.zeros((), dtype=tl.uint32)
++ fixed = tl.zeros((), dtype=tl.uint32)
++ need = K
++ for p in tl.static_range(4):
++ hist = tl.zeros((256,), dtype=tl.int32)
++ for c in range(0, NP, BLOCK):
++ i = c + tl.arange(0, BLOCK)
++ 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)
++ at_or_above = tl.sum(hist, 0) - tl.cumsum(hist, 0) + hist
++ digit = tl.max(tl.where(at_or_above >= need, bins, 0), 0)
++ need -= tl.sum(tl.where(bins > digit, hist, 0), 0)
++ prefix = prefix | (digit.to(tl.uint32) << (24 - 8 * p))
++ fixed = fixed | (tl.full((), 0xFF, tl.uint32) << (24 - 8 * p))
++ written = 0
++ equal_seen = 0
++ j = tl.arange(0, PL)
++ for c in range(0, NP, BLOCK):
++ i = c + tl.arange(0, BLOCK)
++ 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))
++ t = take.to(tl.int32)
++ slot = (written + tl.cumsum(t, 0) - t).to(tl.int64)
++ tl.store(TOK + r * W + slot[:, None] * PL + j[None, :], (i.to(tl.int64)[:, None] * PL + j[None, :]).to(tl.int32),
++ mask=take[:, None])
++ written += tl.sum(t, 0)
++ equal_seen += tl.sum(eq, 0)
++ jt = tl.arange(0, 4)
++ jok = jt < PL - 1
++ tail = NP * PL + jt
++ tok = jok & (tail <= qpos)
++ tl.store(TOK + r * W + K * PL + jt, tl.where(tok, tail, -1).to(tl.int32), mask=jok)
++ n = K * PL + tl.sum(tok.to(tl.int64), 0)
++ tl.store(CNT + r, tl.where(NP > K, n, 0).to(tl.int32))
++
++
++SEG_SCORE_GRID = 256 # _seg_scores programs a segment (grid stride over its pool blocks): speed only
++SEG_SPLIT = True # seg_select_tokens: the split selection (select_split), else one program a row (_seg_select)
++SEG_SELECT = (4096, 8) # _seg_select's scores a step and warps: speed only (the selection is exact integer logic)
++
++
++def seg_select_tokens(qi: torch.Tensor, wts: torch.Tensor, pk: torch.Tensor, rows, scratch) -> tuple[torch.Tensor,
++ 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
++ count, so one CUDA graph per window size serves every context length (``scratch``: segments.SelectScratch)."""
++
++ if qi.stride(0) != qi.shape[1] or wts.stride(1) != 1:
++ raise ValueError("seg_select_tokens: index queries must be contiguous rows, weights unit-stride columns")
++ R = qi.shape[0]
++ if R > scratch.rows:
++ raise ValueError(f"seg_select_tokens: {R} rows, the scratch holds {scratch.rows}")
++ H = wts.shape[1]
++ D = qi.shape[1] // H
++ 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))
++ _seg_scores[(rows.max_segs, grid)](qi, wts, wts.stride(0), pk, scores, scores.stride(0), rows.pos, rows.sparse,
++ rows.seg_start, rows.seg_rows, rows.seg_pbase, rows.seg_pools, D ** -0.5,
++ wscale, H=H, HP=max(16, triton.next_power_of_2(H)), D=D, BP=64, G=grid,
++ num_warps=4)
++ tokens, counts = scratch.tokens[:R], scratch.counts[:R]
++ if SEG_SPLIT:
++ select_split(scores[:R], TOPK_POOLS, scratch=scratch.split, rows=rows, tokens=tokens, counts=counts)
++ return tokens, counts
++ _seg_select[(R,)](scores, scores.stride(0), rows.pos, rows.sparse, tokens, counts, W=TOKENS, K=TOPK_POOLS,
++ PL=POOL, BLOCK=SEG_SELECT[0], num_warps=SEG_SELECT[1])
++ return tokens, counts
++
++
++# ----------------------------------------------------------------------------------- split top-k selection ---
++# _select_rows' radix select with each row's scores split into CHS-score chunks, one program a (row, chunk), in five
++# launches. Passes 0..3: every program takes the digits so far from the row's total histograms (TOT, integer
++# atomic sums: exact in any order), keeps its chunk's count of scores above them (GT, first differing at an earlier
++# byte) and its chunk's histogram of the next byte (HIST), adding it into the row's total. Step 4 writes the chunk's
++# pools at the offset the earlier chunks' counts give (GT and their last histograms, which step 4 only reads):
++# scores above the K-th best, then ties in pool order. The same K-th best, ties and ascending output as
++# _select_rows: integers only, no floating-point sum order to keep.
++
++def _split_digits(TOT, r, STEPS: tl.constexpr, K: tl.constexpr):
++ """(prefix, fixed, need, last digit) after the first STEPS passes, from the row's total histograms."""
++ bins = tl.arange(0, 256)
++ prefix = tl.zeros((), dtype=tl.uint32)
++ fixed = tl.zeros((), dtype=tl.uint32)
++ need = tl.full((), K, tl.int32)
++ digit = tl.full((), 0, tl.int32)
++ for p in tl.static_range(STEPS):
++ hist = tl.load(TOT + (r * 4 + p) * 256 + bins)
++ at_or_above = tl.sum(hist, 0) - tl.cumsum(hist, 0) + hist
++ digit = tl.max(tl.where(at_or_above >= need, bins, 0), 0)
++ need -= tl.sum(tl.where(bins > digit, hist, 0), 0)
++ prefix = prefix | (digit.to(tl.uint32) << (24 - 8 * p))
++ fixed = fixed | (tl.full((), 0xFF, tl.uint32) << (24 - 8 * p))
++ return prefix, fixed, need, digit
++
++
++def _select_split(S, s_stride, NPC, POS, SPR, TOT, HIST, GT, OUT, TOK, CNT, W: tl.constexpr, K: tl.constexpr,
++ PL: tl.constexpr, CHS: tl.constexpr, CP: tl.constexpr, STEP: tl.constexpr, SEG: tl.constexpr):
++ """Program (row, chunk), STEP 0..3: pass STEP over the chunk; STEP 4: its selected pools, as pool ids OUT[r, :K]
++ (SEG False: NPC scores a row) or (SEG: the row's visible pools, dense rows skipped) as _seg_select's tokens,
++ tail and count. TOT [R, 4, 256] zeroed before step 0; HIST [R, CP, 256], GT [R, CP] int32."""
++
++ r = tl.program_id(0).to(tl.int64)
++ c = tl.program_id(1)
++ if SEG:
++ if tl.load(SPR + r) == 0:
++ if STEP == 4:
++ if c == 0:
++ tl.store(CNT + r, 0)
++ return
++ qpos = tl.load(POS + r).to(tl.int64)
++ NP = (qpos + 1) // PL
++ else:
++ qpos = 0
++ NP = NPC
++ nch = (NP + CHS - 1) // CHS
++ if c >= nch:
++ return
++ bins = tl.arange(0, 256)
++ i = c * CHS + tl.arange(0, CHS)
++ ok = i < NP
++ u = _order_key(tl.load(S + r * s_stride + i, mask=ok, other=0.0))
++ prefix, fixed, need, d = _split_digits(TOT, r, STEP, K)
++ own = HIST + (r * CP + c) * 256
++ if STEP > 0 and STEP < 4: # the chunk's scores above the prefix first at the byte just fixed
++ above = tl.sum(tl.where(bins > d, tl.load(own + bins), 0), 0)
++ if STEP > 1:
++ above += tl.load(GT + r * CP + c)
++ tl.store(GT + r * CP + c, above)
++ if STEP < 4:
++ match = ok & ((u & fixed) == prefix)
++ hist = tl.histogram(((u >> (24 - 8 * STEP)) & 0xFF).to(tl.int32), 256, mask=match)
++ tl.store(own + bins, hist)
++ tl.atomic_add(TOT + (r * 4 + STEP) * 256 + bins, hist)
++ else:
++ ci = tl.arange(0, CP)
++ before = ci < c
++ # earlier chunks: scores above the prefix at bytes 0..2 (GT), at byte 3 and equal to it (their last histograms)
++ last = tl.load(HIST + (r * CP + ci[:, None]) * 256 + bins[None, :], mask=before[:, None], other=0)
++ gt = tl.load(GT + r * CP + ci, mask=before, other=0) + tl.sum(tl.where(bins[None, :] > d, last, 0), 1)
++ equal_seen = tl.sum(tl.sum(tl.where(bins[None, :] == d, last, 0), 1), 0)
++ written = tl.sum(gt, 0) + tl.minimum(equal_seen, need)
++ e = (ok & (u == prefix)).to(tl.int32)
++ 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)
++ if SEG:
++ j = tl.arange(0, PL)
++ tl.store(TOK + r * W + slot[:, None] * PL + j[None, :],
++ (i.to(tl.int64)[:, None] * PL + j[None, :]).to(tl.int32), mask=take[:, None])
++ if c == 0:
++ jt = tl.arange(0, 4)
++ jok = jt < PL - 1
++ tail = NP * PL + jt
++ tok = jok & (tail <= qpos)
++ tl.store(TOK + r * W + K * PL + jt, tl.where(tok, tail, -1).to(tl.int32), mask=jok)
++ n = K * PL + tl.sum(tok.to(tl.int64), 0)
++ tl.store(CNT + r, tl.where(NP > K, n, 0).to(tl.int32))
++ else:
++ tl.store(OUT + r * K + slot, i.to(tl.int64), mask=take)
++
++
++SPLIT_FROM = 8192 # decode windows split rows of at least this many scores (fewer: one program a row)
++SPLIT_ROWS = 64 # ... windows of fewer rows (prompt chunks' hundreds of rows fill the GPU as they are)
++SPLIT_WARPS = 4
++
++
++def split_chunk(np_: int) -> int:
++ """Scores a chunk program takes (speed only): 2,048 up to 16,384 a row, else 4,096."""
++ return 2048 if np_ <= 16384 else 4096
++
++
++def split_chunks(np_: int) -> int:
++ """Chunk programs a row of np_ scores takes (a power of two, the chunk tables' row stride)."""
++ return triton.next_power_of_2(triton.cdiv(np_, split_chunk(np_)))
++
++
++def split_scratch(rows: int, np_: int, device) -> torch.Tensor:
++ """select_split's int32 scratch for rows of np_ scores: totals [rows, 4, 256], then chunk histograms and counts."""
++ return torch.empty((rows * (1024 + split_chunks(np_) * 257),), dtype=torch.int32, device=device)
++
++
++def select_split(scores: torch.Tensor, k: int, *, scratch: torch.Tensor | None = None, rows=None,
++ tokens: torch.Tensor | None = None, counts: torch.Tensor | None = None) -> torch.Tensor | None:
++ """The split selection: top_pools' pools [R, k] (``rows`` None), or with ``rows`` (segments.SegRows) and
++ 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)."""
++
++ R, NP = scores.shape
++ chs, warps = split_chunk(NP), SPLIT_WARPS
++ cp = split_chunks(NP)
++ if scratch is None or scratch.numel() < R * (1024 + cp * 257):
++ scratch = split_scratch(R, NP, scores.device)
++ tot = scratch[:R * 1024]
++ hist = scratch[R * 1024:R * (1024 + cp * 256)]
++ gt = scratch[R * (1024 + cp * 256):R * (1024 + cp * 257)]
++ tot.zero_()
++ seg = rows is not None
++ out = None if seg else torch.empty((R, k), dtype=torch.int64, device=scores.device)
++ dummy = scratch
++ for step in range(5):
++ _select_split[(R, cp)](scores, scores.stride(0), NP, rows.pos if seg else dummy, rows.sparse if seg else dummy,
++ tot, hist, gt, out if out is not None else dummy, tokens if seg else dummy,
++ counts if seg else dummy, W=TOKENS, K=k, PL=POOL, CHS=chs, CP=cp, STEP=step, SEG=seg,
++ num_warps=warps)
++ return out
diff --git a/patches/0033-glm-multi-stream-engine.patch b/patches/0033-glm-multi-stream-engine.patch
new file mode 100644
index 0000000..ff50c42
--- /dev/null
+++ b/patches/0033-glm-multi-stream-engine.patch
@@ -0,0 +1,2280 @@
+diff --git tensorfold/cuda/health.py tensorfold/cuda/health.py
+index 47b7270..5902ad3 100644
+--- tensorfold/cuda/health.py
++++ tensorfold/cuda/health.py
+@@ -64,6 +64,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}
++ more = getattr(decoder, "health", None) # a decoder's own counts (GLM: paused streams, its pool)
++ if callable(more):
++ try:
++ extra = dict(more())
++ except Exception: # noqa: BLE001 (a table changing under the read)
++ extra = {}
++ body["streams"].update(extra.pop("streams", {}))
++ body.update(extra)
+ window = getattr(app, "effective_context_window", None)
+ 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
+--- 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:
+ 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)),
+- vision_urls=bool(options.get("vision_urls", False)))
++ vision_urls=bool(options.get("vision_urls", False)), parallel=int(options.get("parallel", 1)))
+
+
+ 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
+--- tensorfold/families/glm5_next/cuda/decode.py
++++ tensorfold/families/glm5_next/cuda/decode.py
+@@ -84,11 +84,15 @@ class Engine:
+
+ def __init__(self, w: Weights, *, capacity: int = 2560, max_rows: int = 8, prefill_rows: int = PREFILL_ROWS,
+ graphs: bool = False, graph_rows: tuple[int, ...] = (1, 2, 3, 4), long_context: bool = False,
+- taps: tuple[int, ...] = (), grid: int = 0, split=None, mtp_rows: int | None = None) -> None:
++ taps: tuple[int, ...] = (), grid: int = 0, split=None, mtp_rows: int | None = None,
++ streams: int = 1, pool_rows: int | None = None) -> None:
+ """``grid``: prompt chunks start on multiples of it (TF_GLM_PROMPT_GRID; 0: anywhere); ``split``: a
+ ``hcsplit.SplitSettings`` (TF_GLM_HC_SPLIT, TF_GLM_PREFILL_OVERLAP) for prompt chunks, None or off: unsplit;
+ ``mtp_rows``: rows of an MTP step (its absorb chunks; default ``max_rows``): draft chains take one row a step,
+- so the MTP buffers need not be as wide as the verify windows."""
++ so the MTP buffers need not be as wide as the verify windows; ``streams``: stream slots (``forward.Slots``)
++ and ``pool_rows``: tokens of the shared cache pool (``forward.Caches``, default ``capacity``) for concurrent
++ streams (``multi``). ``st`` is the state the single-stream paths run on: ``home`` (slot 0, the pool's first
++ ``capacity`` tokens), the one the CUDA graphs were captured on, unless ``use`` points it at another."""
+
+ if grid and prefill_rows % grid:
+ raise ValueError(f"prompt chunks of {prefill_rows} rows do not tile a {grid}-row grid")
+@@ -110,7 +114,11 @@ class Engine:
+
+ self.pbuf.split = HcSplit(w, self.pbuf, split)
+ self.mbuf = Buffers(w, min(mtp_rows or max_rows, max_rows), capacity) if w.mtp is not None else None
+- self.st = State(w, capacity, max_rows)
++ from .forward import Caches, Slots
++
++ self.caches = Caches(w, pool_rows or capacity)
++ 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
+ self.constraint = self.window = None # a request's grammar, and the next sample's rows under it
+ self.draft_n = w.head.n
+@@ -126,13 +134,29 @@ class Engine:
+ def reset(self) -> None:
+ self.st.reset()
+
++ def use(self, st: State) -> State:
++ """Run the single-stream paths (prefill, forward, commit, snapshots) on ``st``; returns the previous state."""
++
++ prev, self.st = self.st, st
++ return prev
++
++ def graphed(self, st: State | None = None) -> bool:
++ """Whether the captured graphs run ``st`` (default the current state): the same slot and extent base as the
++ state they were captured on (and the pool's views, not a clone's)."""
++
++ st = self.st if st is None else st
++ return (self.graphs is not None and st.caches is self.caches and st.slots is self.slots
++ and st.graph_key == self.home.graph_key)
++
+ def forward(self, tokens: Sequence[int]) -> torch.Tensor:
+- """A step's forward (a CUDA graph when one was captured for its shape): logits [R, V/world]."""
++ """A step's forward (a CUDA graph when one was captured for its shape and state): logits [R, V/world]."""
+
+ R = stage(self.w, self.st, self.buf, tokens)
+ dense = self.st.pos + R <= self.w.cfg.dense_limit
+ g, kind = None, "main"
+- if self.graphs is not None and dense:
++ if not self.graphed():
++ pass
++ elif self.graphs is not None and dense:
+ g = self.graphs.main.get((R, self.st.parity))
+ elif self.graphs is not None and self.st.pos >= self.w.cfg.dense_limit and self.st.index is not None:
+ # every row past the dense limit: the sparse graph for this pool bucket (same kernels as eager)
+@@ -151,7 +175,9 @@ class Engine:
+ n = mtp_stage(self.w, self.st, self.mbuf, next_tokens, hidden)
+ dense = self.st.mtp_len + n <= self.w.cfg.dense_limit
+ g, kind = None, "mtp"
+- if self.graphs is not None and not self.mbuf.zero_first and dense:
++ if not self.graphed():
++ pass
++ elif self.graphs is not None and not self.mbuf.zero_first and dense:
+ 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:
+ 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)
+- inject = feed.chunk(start, R) if feed is not None else None
+- 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 drafter is not None:
+- drafter.add_taps(e.tap_rows(R, b))
+- if use_mtp:
+- nxt = list(prompt[start + 1:start + R + 1])
+- if nxt:
+- with prof.timed("mtp absorb"):
+- _absorb_rows(e, b.fnormed[:len(nxt)], nxt)
+- with prof.timed("commit"):
+- commit(w, st, b, R, R)
++ last = prefill_chunk(e, prompt, start, min(e.prefill_rows, len(prompt) - start), drafter=drafter, feed=feed,
++ mtp=use_mtp, head=sample)
+ 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:
+ return first
+
+
++def prefill_chunk(e: Engine, prompt: Sequence[int], start: int, R: int, *, drafter=None, feed=None,
++ mtp: bool = False, head: bool = True) -> torch.Tensor | None:
++ """Commit prompt rows start .. start + R (at e.st.pos == start): the chunk's forward, DFlash2's taps, the MTP
++ head's rows (``mtp``: the next tokens are the prompt's), the commit; a copy of the head's logits of its last
++ row, taken before anything else reuses the buffers, with ``head``, else None. ``prefill`` runs a prompt as these;
++ so do concurrent streams' prompt steps (``multi``), one chunk at a time."""
++
++ w, st, b = e.w, e.st, e.pbuf
++ chunk = list(prompt[start:start + R])
++ inject = feed.chunk(start, R) if feed is not None else None
++ out = compute(w, st, b, stage(w, st, b, chunk), nch=chunks_for(st, R), host_pos=st.pos, inject=inject,
++ head=head)
++ out = out.clone() if head else None
++ e.last_hidden = b.fnormed[R - 1:R].clone()
++ if drafter is not None:
++ drafter.add_taps(e.tap_rows(R, b))
++ if mtp:
++ nxt = list(prompt[start + 1:start + R + 1])
++ if nxt:
++ with prof.timed("mtp absorb"):
++ _absorb_rows(e, b.fnormed[:len(nxt)], nxt)
++ with prof.timed("commit"):
++ commit(w, st, b, R, R)
++ return out
++
++
+ def _absorb_rows(e: Engine, hidden: torch.Tensor, next_tokens: Sequence[int]) -> None:
+ """A prompt's rows into the MTP cache through the prefill buffers (the prefill arithmetic, like the prompt)."""
+
+diff --git tensorfold/families/glm5_next/cuda/engine.py tensorfold/families/glm5_next/cuda/engine.py
+index 37051b4..9bc5550 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, ...]:
+ return tuple(v + costs["block"] + 0.0 + costs["taps_row"] * 1 for v in costs["verify"])
+
+
++PARALLEL_MOST = 4 # --parallel: concurrent requests at most (the segmented kernels' streams)
++MULTI_WINDOW = 32 # --parallel: rows of every stream's verify windows together (multi.MAX_WINDOW)
++
++
++def slot_bytes(t: dict, world: int = 2, rows: int = MAX_ROWS) -> int:
++ """What one more stream slot (``forward.Slots``) takes on each rank, from the text config: every KDA layer's
++ recurrent states (two parities), conv window, a decode window's projections and replay scratch."""
++
++ from tensorfold.cuda.geometry import layer_counts
++
++ linear, _ = layer_counts(t)
++ lin = t.get("linear_attn_config") or {}
++ lh = int(lin.get("num_heads", t.get("linear_num_heads", 64))) // world
++ ld = int(lin.get("head_dim", t.get("linear_head_dim", 128)))
++ conv = int(lin.get("short_conv_kernel_size", t.get("linear_conv_kernel_dim", 4)))
++ width = 3 * lh * ld + 2 * ld + lh # the KDA input projection's rows (q, k, v, f_a, g_a, beta)
++ scratch = rows * lh * (ld * 2 + ld * 4 + ld * 2 + ld * 4 + 4)
++ return linear * (2 * lh * ld * ld * 4 + (conv - 1) * 3 * lh * ld * 2 + rows * width * 2 + scratch)
++
++
++def multi_draft_bytes(t: dict, streams: int, world: int = 2, *, ring: bool, capacity: int,
++ tap_rows: int = MAX_ROWS) -> int:
++ """``dflash2_multi.MultiDrafter``'s context pool on each rank: ``streams`` rings (or flat contexts of capacity +
++ block rows) and the padded context updates' trash rows, keys and values per draft layer."""
++
++ from tensorfold.cuda.geometry import draft_ring_rows
++
++ 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))
++ ring_rows = draft_ring_rows(window - 1, block) if ring and window > 0 else 0
++ cap = ring_rows if 0 < ring_rows < capacity + block else capacity + block
++ trash = -(-max(64, streams * tap_rows) // block) * block
++ return 2 * layers * heads * hd * (streams * cap + trash) * 2
++
++
+ def _f64_ints(x: float) -> list[int]:
+ return list(struct.unpack("<2i", struct.pack("<d", float(x))))
+
+@@ -287,14 +325,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
++ parallel = 1 # --parallel N: requests decoded together (``multi``); 1 serves one at a time
++ concurrent = False # the server hands every request straight to ``generate`` (the scheduler orders them)
++ multi = None # --parallel > 1: the ``multi.MultiDecoder`` (both ranks)
++ scheduler = None # ... and rank 0's ``multi.GlmScheduler``
+
+ def __init__(self, model_dir: Path, *, rank: int, master: str, port: int, policy: str = DEFAULT_POLICY,
+ drafter: Path | None = None, context: int | None = None, context_explicit: bool | None = None, serial_only: bool = False, comm=None,
+ prefill_rows: int | None = None, vision: bool = False, vision_urls: bool = False,
+- split=None) -> None:
++ split=None, parallel: int = 1) -> None:
+ """``comm``: a communicator with ``all_gather`` and ``barrier`` instead of NCCL between two machines (tests);
+ ``vision``: rank 0 runs the image tower (rank 1 only takes its rows); ``split``: a ``hcsplit.SplitSettings``
+- instead of TF_GLM_HC_SPLIT / TF_GLM_PREFILL_OVERLAP (tests)."""
++ instead of TF_GLM_HC_SPLIT / TF_GLM_PREFILL_OVERLAP (tests); ``parallel``: requests decoded together
++ (``multi``: their caches share one pool, each stream up to the context window; DFlash2 drafts only)."""
+
+ import torch
+
+@@ -322,6 +365,10 @@ class GlmEngine:
+ torch.cuda.set_device(0)
+ self.torch = torch
+ self.rank = rank
++ parallel = int(parallel)
++ if not 1 <= parallel <= PARALLEL_MOST:
++ raise ValueError(f"--parallel: 1 to {PARALLEL_MOST} requests at once for GLM-5.3-Flash, not {parallel}")
++ self.parallel = parallel
+ self.policy = "0" if serial_only else policy
+ self.serial_only = serial_only
+ self.comm = comm if comm is not None else NCCL(rank, 2, master, port)
+@@ -352,7 +399,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
+- 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:
+ 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")
+- return Geometry(lambda slots: g.bytes_at(slots) + workspace, g.reserve, g.minimum_slots) if workspace else g
++ # --parallel: every stream slot past the first (KDA states, conv windows, window scratch); the batched
++ # verify window's buffers fit the decode rows the estimate sizes (MLA_DECODE_ROWS), its token selection's
++ # fp32 scores (MAX_WINDOW rows x a pool of 4 tokens) grow with the pool
++ extra = workspace + (parallel - 1) * slot_bytes(text)
++ per = 4 * MULTI_WINDOW // 4 if parallel > 1 else 0
++ if not extra and not per:
++ return g
++ return Geometry(lambda slots: g.bytes_at(slots) + extra + per * slots, g.reserve, g.minimum_slots)
++
++ def draft_geometry(text):
++ from tensorfold.cuda.capacity import Geometry
++
++ g = dflash2_geometry(text, 2, MAX_ROWS, ring=DRAFT_RING)
++ if parallel == 1:
++ return g
++ # --parallel: the multi-stream drafter's own pool of contexts beside the solo drafter's
++ return Geometry(lambda slots: g.bytes_at(slots) + multi_draft_bytes(text, parallel, ring=DRAFT_RING,
++ capacity=slots), g.reserve)
+ self.capacity_plan = admit(model_dir, context if explicit else cfg.dense_limit, explicit, torch,
+ geometry,
+ weights_estimate, rank=rank, world=2, gather=self._gather_ints,
+ draft_dir=drafter, draft_weights=lambda d: dflash2_weights(d, 2),
+- draft_geometry=lambda text: dflash2_geometry(text, 2, MAX_ROWS, ring=DRAFT_RING))
++ draft_geometry=draft_geometry)
+ 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:
+ from .draft_dump import dump_dir
+ from .qmm import DRAFT_QUANTS, draft_quant
+
+- self.dump = dump_dir() if drafter is not None and not serial_only else None
++ 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())
++ verify_code = 0
++ if parallel > 1: # serial and batched verify windows make different collectives
++ from .multi import verify_kind
++
++ 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),
+ 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(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:
+ 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_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 "
+ "(or pass --drafter none to both) and give both the same flags")
+ self.cache_bytes = min(both[0][-1], both[1][-1]) << 20
+ plan["kept_bytes"] = self.cache_bytes
+ for key in ("serving_peak_bytes_estimate", "total_bytes_estimate"):
+ plan[key] = plan[key] + self.cache_bytes
+- if rank == 0 and self.cache_bytes < wanted:
++ # --parallel: one pool of per-token caches for every stream and kept prompt: the window's slots, plus what
++ # TF_GLM_CACHE_GIB gives kept prompts (their rows in the pool, their KDA states and DFlash2 windows beside it),
++ # whole 2,048-token extents; each stream holds up to the window (pool.py, multi.py)
++ pool_rows = None
++ if parallel > 1:
++ from tensorfold.cuda.capacity import config as read_config
++
++ from .pool import ALIGN
++
++ text = read_config(model_dir)
++ g = geometry(text)
++ per_token = max(1, -(-(g.bytes_at(capacity + 65536) - g.bytes_at(capacity)) // 65536))
++ states = int(os.environ.get("TF_GLM_CACHE_ENTRIES", "8")) * (slot_bytes(text, rows=0) // 2 + (22 << 20))
++ pool_rows = (capacity + max(0, self.cache_bytes - states) // per_token) // ALIGN * ALIGN
++ if pool_rows < ALIGN:
++ raise ValueError(f"--parallel {parallel}: a pool of {pool_rows} tokens is less than one {ALIGN}-token "
++ f"extent; free memory or lower --context")
++ self.limit = min(self.limit, pool_rows - MAX_ROWS)
++ self.cache_bytes = 0 # kept prompts live in the pool
++ plan["pool_tokens"] = pool_rows
++ if rank == 0 and self.cache_bytes < wanted and parallel == 1:
+ 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:
+ if drafter is not None:
+ from .dflash2 import Drafter
+
+- 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,
++ 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,
+ 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, mtp_rows=MTP_ROWS)
++ split=self.split, mtp_rows=MTP_ROWS, streams=parallel, pool_rows=pool_rows)
+ 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:
+ self.cache: list = []
+ self.live: list[int] = []
+ self.cache_entries = int(os.environ.get("TF_GLM_CACHE_ENTRIES", "8"))
++ if parallel > 1:
++ from .multi import GlmScheduler, MultiDecoder
++
++ self.multi = MultiDecoder(self, parallel)
++ self.multi.model_dir = self.model_dir
++ if rank == 0:
++ self.scheduler = GlmScheduler(self.multi, max_streams=parallel)
++ self.concurrent = True
++ 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 "
++ f"{self.multi.share:g})", flush=True)
+
+ 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:
+ return stats
+
+ def generate(self, prompt: list[int], max_tokens: int, sampling, on_tokens, draft: bool = True,
+- constraint=None, *, vision=None) -> dict[str, Any]:
+- """Mirror one rank-0 request on rank 1; draft=False uses serial decoding and fresh prefill as the reference drafted replies must equal; ``vision``: an image prompt's prepared pictures (``GlmPrepared``)."""
++ constraint=None, *, vision=None, background: bool = False) -> dict[str, Any]:
++ """Mirror one rank-0 request on rank 1; draft=False uses serial decoding and fresh prefill as the reference drafted replies must equal; ``vision``: an image prompt's prepared pictures (``GlmPrepared``); ``background``: under --parallel, after the other requests and yielding to them."""
+
+ 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:
+ spec = getattr(self.request, "policy", None) or self.policy
+ code = self._effective(encode_policy(spec))
+ stop_eos = bool(getattr(self.request, "stop_eos", True))
++ if self.scheduler is not None: # --parallel: the scheduler's worker runs it with the others
++ if vision is not None and self.vision is None:
++ raise ValueError("image inputs require starting this server with --vision")
++ stats = self.scheduler.submit(list(prompt), max_tokens, sampling, bool(draft) and not self.serial_only,
++ on_tokens, stop_eos=stop_eos, vision=vision, constraint=constraint,
++ background=background, glm={"code": code, "spec": spec})
++ stats.update(policy=spec, drafts=draft)
++ return stats
+ 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:
+ def follow(self) -> None:
+ """Rank 1: mirror every request rank 0 serves, forever."""
+
++ if self.multi is not None:
++ self.multi.follow()
++ return
+ while True:
+ self.follow_one()
+
+diff --git tensorfold/families/glm5_next/cuda/forward.py tensorfold/families/glm5_next/cuda/forward.py
+index 1a8894f..42f2929 100644
+--- tensorfold/families/glm5_next/cuda/forward.py
++++ tensorfold/families/glm5_next/cuda/forward.py
+@@ -160,52 +160,137 @@ class Buffers:
+ return p
+
+
+-class State:
+- """Committed caches of one sequence (and of the MTP head's attention layer)."""
++class Caches:
++ """Every per-token cache of the model over ``rows`` tokens of a shared pool (``pool.Arena``): per DSA layer its
++ latents (or keys and values without the latent cache); the MTP layer's; and with long contexts per indexed layer
++ (the DSA layers, then the MTP layer) its index keys, gates and pooled keys (a row a pool of 4 tokens, 2 rows of
++ pad). Element types and layouts are decided here; a ``State`` views them over its extent (``bind``)."""
++
++ def __init__(self, w: Weights, rows: int) -> None:
++ from .pool import Arena, Plane
+
+- def __init__(self, w: Weights, capacity: int, rows: int) -> None:
+ c = w.cfg
+ dev = w.device
+ HL = c.heads // w.world
++ dsa = len([l for l in w.layers if l.kind == "dsa"])
++ self.latent = latent.ENABLED
++ planes: list[Plane] = []
++
++ def add(shape, div: int = 1, pad: int = 0) -> int:
++ planes.append(Plane(torch.zeros((rows // div + pad, *shape), dtype=torch.bfloat16, device=dev), div, pad))
++ return len(planes) - 1
++
++ def attention_planes() -> tuple[int, int | None]:
++ if self.latent: # one 512-wide latent a token and layer (kc), no separate values (vc)
++ return add((c.kv_lora,)), None
++ return add((HL, c.qk_dim)), add((HL, c.v_dim))
++
++ self.kc, self.vc = [], []
++ for _ in range(dsa):
++ k, v = attention_planes()
++ self.kc.append(k)
++ self.vc.append(v)
++ self.mtp = attention_planes() if w.mtp is not None else None
++ # DSA indexer caches (long contexts only): per layer (and the MTP layer, last) keys, gates, pool keys
++ self.index = None
++ if w.meta.get("long_context"):
++ n_idx = dsa + (1 if w.mtp is not None else 0)
++ self.index = [(add((c.index_dim,)), add((c.index_dim,)), add((c.index_dim,), 4, 2)) for _ in range(n_idx)]
++ self.arena = Arena(rows, planes)
++ self.rows = rows
++
++ def bind(self, st: "State", base: int, size: int) -> None:
++ """Point ``st``'s caches at tokens [base, base + size) of the pool."""
++
++ view = lambda i: None if i is None else self.arena.view(i, base, size) # noqa: E731
++ st.kc = [view(i) for i in self.kc]
++ 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])
++ st.index = None if self.index is None else [tuple(view(i) for i in trio) for trio in self.index]
++
++
++class Slots:
++ """What each of ``count`` concurrent streams holds whatever its length: KDA recurrent states [count, 2, layers,
++ H, 128, 128] (two parities) and conv windows [count, layers, 3, C], the decode window's KDA projections and replay
++ scratch (so a window's commit can come after another stream's forward), and the device positions a captured graph
++ reads. A ``State`` in slot s views slot s."""
++
++ def __init__(self, w: Weights, count: int, rows: int) -> None:
++ c = w.cfg
++ dev = w.device
+ LL = c.lin_heads // w.world
+- self.capacity = capacity
+- self.pos = 0
+- self.pos_dev = torch.zeros((1,), dtype=torch.int32, device=dev)
+- self.mtp_pos_dev = torch.zeros((1,), dtype=torch.int32, device=dev)
++ kda_layers = [l for l in w.layers if l.kind == "kda"]
++ n = len(kda_layers)
++ width = kda_layers[0].kda.proj.n if kda_layers else 0
++ self.count, self.rows, self.layers = count, rows, n
++ self.conv = torch.zeros((count, n, c.conv - 1, 3 * LL * 128), dtype=torch.bfloat16, device=dev)
++ self.rec = torch.zeros((count, 2, n, LL, 128, 128), dtype=torch.float32, device=dev)
++ self.proj = torch.zeros((count, n, rows, width), dtype=torch.bfloat16, device=dev)
++ self.scratch = [kda_mod.KDAScratchSet(n, rows, LL, dev) if n else None for _ in range(count)]
++ self.pos_dev = torch.zeros((count, 1), dtype=torch.int32, device=dev)
++ self.mtp_pos_dev = torch.zeros((count, 1), dtype=torch.int32, device=dev)
++
++ def nbytes(self) -> int:
++ t = [self.conv, self.rec, self.proj, self.pos_dev, self.mtp_pos_dev]
++ s = [x for set_ in self.scratch if set_ is not None for x in (set_.out, set_.k, set_.v, set_.g, set_.b)]
++ return sum(x.numel() * x.element_size() for x in t + s)
++
++
++def slot_bytes(w: Weights, rows: int) -> int:
++ """Device bytes one more stream slot takes (``Slots``), without allocating it."""
++
++ c = w.cfg
++ LL = c.lin_heads // w.world
++ kda_layers = [l for l in w.layers if l.kind == "kda"]
++ n = len(kda_layers)
++ width = kda_layers[0].kda.proj.n if kda_layers else 0
++ DK = DV = 128
++ scratch = rows * LL * DV * 2 + rows * LL * DK * 4 + rows * LL * DV * 2 + rows * LL * DK * 4 + rows * LL * 4
++ return (n * (c.conv - 1) * 3 * LL * 128 * 2 + 2 * n * LL * 128 * 128 * 4 + n * rows * width * 2 + n * scratch
++ + 16)
++
++
++class State:
++ """Committed caches of one sequence (and of the MTP head's attention layer): views of its extent [base, base +
++ capacity) of the pool's ``Caches`` and of its stream slot (``Slots``). Without ``caches`` / ``slots`` it makes its
++ 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,
++ slots: Slots | None = None, slot: int = 0) -> None:
++ self.caches = caches if caches is not None else Caches(w, capacity)
++ 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"]
+ dsa_layers = [l for l in w.layers if l.kind == "dsa"]
+ self.kda_index = {l.index: i for i, l in enumerate(kda_layers)}
+ self.dsa_index = {l.index: i for i, l in enumerate(dsa_layers)}
+ n = len(kda_layers)
+- width = kda_layers[0].kda.proj.n if kda_layers else 0
+- self.conv = torch.zeros((n, c.conv - 1, 3 * LL * 128), dtype=torch.bfloat16, device=dev)
+- self.rec = torch.zeros((2, n, LL, 128, 128), dtype=torch.float32, device=dev)
++ sl = self.slots
++ self.pos = 0
++ self.pos_dev = sl.pos_dev[slot]
++ self.mtp_pos_dev = sl.mtp_pos_dev[slot]
++ self.conv = sl.conv[slot]
++ self.rec = sl.rec[slot]
+ self.cur = [0] * n
+- self.proj = torch.zeros((n, rows, width), dtype=torch.bfloat16, device=dev)
+- self.scratch_set = kda_mod.KDAScratchSet(n, rows, LL, dev) if n else None
++ self.proj = sl.proj[slot]
++ self.scratch_set = sl.scratch[slot]
+ self.scratch = self.scratch_set.views if n else []
+ self.latent = latent.ENABLED
+- if self.latent: # one 512-wide latent a token and layer (kc), no separate values (vc)
+- self.kc = [torch.zeros((capacity, c.kv_lora), dtype=torch.bfloat16, device=dev) for _ in dsa_layers]
+- self.vc = [None for _ in dsa_layers]
+- else:
+- self.kc = [torch.zeros((capacity, HL, c.qk_dim), dtype=torch.bfloat16, device=dev) for _ in dsa_layers]
+- self.vc = [torch.zeros((capacity, HL, c.v_dim), dtype=torch.bfloat16, device=dev) for _ in dsa_layers]
+ self.mtp_len = 0
+ self.mtp_drafted = 0
+- if w.mtp is not None:
+- if self.latent:
+- self.mtp_kc = torch.zeros((capacity, c.kv_lora), dtype=torch.bfloat16, device=dev)
+- self.mtp_vc = None
+- else:
+- self.mtp_kc = torch.zeros((capacity, HL, c.qk_dim), dtype=torch.bfloat16, device=dev)
+- self.mtp_vc = torch.zeros((capacity, HL, c.v_dim), dtype=torch.bfloat16, device=dev)
+- # DSA indexer caches (long contexts only): per layer (and the MTP layer, last) keys, gates, pool keys
+- self.index = None
+- if w.meta.get("long_context"):
+- n_idx = len(dsa_layers) + (1 if w.mtp is not None else 0)
+- mk = lambda n: torch.zeros((n, c.index_dim), dtype=torch.bfloat16, device=dev) # noqa: E731
+- self.index = [(mk(capacity), mk(capacity), mk(capacity // 4 + 2)) for _ in range(n_idx)]
++ self.bind(base, capacity)
++
++ def bind(self, base: int, capacity: int) -> None:
++ """View the pool's tokens [base, base + capacity) (a new extent, grown or moved: the rows are the caller's)."""
++
++ self.base, self.capacity = int(base), int(capacity)
++ self.caches.bind(self, self.base, self.capacity)
++
++ @property
++ def graph_key(self) -> tuple[int, int]:
++ """What a captured graph baked in besides the shared buffers: the slot and the extent's base."""
++ return self.slot, self.base
+
+ def reset(self) -> None:
+ self.conv.zero_()
+@@ -228,9 +313,11 @@ class State:
+ return self.cur[0] if self.cur else 0
+
+ def clone(self) -> "State":
++ """A copy with tensors of its own (no longer the pool's or the slot's views; not for captured graphs)."""
+ import copy
+
+ other = copy.copy(self)
++ other.proj = self.proj.clone()
+ 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
+ return out_proj(w, b, out, k.o, None if pre else qmm.group_sums(out, b.kxs[:R]), R)
+
+
++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
++ row at once (``proj`` [layers, rows, width]: the window's, which the commit's conv shift reads), the chain per
++ segment from its slot's state (``kda.chain_segments``: each segment's bits alone; always the wide path, as
++ decode windows run by default), ``scratch``: the window's replay scratch (a KDAScratchSet)."""
++
++ c = w.cfg
++ k = layer.kda
++ p = proj[li, :R]
++ with prof.timed("kda: projections"):
++ mm(b, b.normed[:R], k.proj, b.xs[:R], p)
++ fa = p[:, k.fa_off:k.fa_off + 128]
++ 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])
++ with prof.timed("kda: recurrence"):
++ out = kda_mod.chain_segments(seg, p, k.b_off, b.ka[:R], b.kg[:R], slots.conv[:, li], k.conv,
++ slots.rec[:, :, li], k.a_log, k.dt_bias, k.norm, c.eps, c.lower, R,
++ scratch.views[li])
++ with prof.timed("kda: out + all-gather"):
++ return out_proj(w, b, out, k.o, qmm.group_sums(out, b.kxs[:R]), R)
++
++
+ 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:
+
+
+ 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) -> None:
++ host_pos: int | None = None, sparse_np: int | None = None, mixer=None) -> None:
++ """``mixer``: the layer's KDA / DSA block as ``mixer(layer)`` instead of on ``st`` (a multi-stream window's
++ segmented blocks, ``verify.BatchedVerify``); everything else is the same calls."""
++
+ c = w.cfg
+ 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],
+ b.hcpart[:R], c.eps, c.hc_eps, c.hc_iters, prompt=b.prefill)
+- g = _mixer(layer, w, st, b, R, nch, host_pos, sparse_np)
++ g = mixer(layer) if mixer is not None else _mixer(layer, w, st, b, R, nch, host_pos, sparse_np)
+ 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:
+
+
+ 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, head: bool = True):
++ 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)."""
+
+ c = w.cfg
+@@ -613,11 +727,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))
+- if b.prefill and b.split is not None and sparse_np is None and b.split.applies(R):
++ if b.prefill and b.split is not None and sparse_np is None and mixer is None and b.split.applies(R):
+ split_layers(w, st, b, R, nch, host_pos) # also leaves the taps and b.hidden[:R]
+ else:
+ 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, mixer)
+ 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])
+diff --git tensorfold/families/glm5_next/cuda/multi.py tensorfold/families/glm5_next/cuda/multi.py
+new file mode 100644
+index 0000000..f62a69d
+--- /dev/null
++++ tensorfold/families/glm5_next/cuda/multi.py
+@@ -0,0 +1,1117 @@
++"""GLM-5.3-Flash's concurrent requests (--parallel N) on two ranks: every stream commits exactly its own rows, so each
++reply is the one its request gets served alone with ``"draft": false``.
++
++Layout: the per-token caches are one pool (``pool.py``, ``forward.Caches``); a stream, or a kept prompt, owns an
++extent of it aligned to 2,048 tokens, and the single-stream code (prompt chunks, verify windows, commits, snapshots)
++runs on a ``forward.State`` viewing that extent and the stream's slot (``forward.Slots``: KDA states, conv windows,
++window scratch; a DFlash2 context, ``dflash2_multi.DraftContext``; host side its copy-draft index, sampler and grammar).
++
++Iterations (``GlmScheduler``, one worker thread on rank 0): admissions, then either one prompt chunk of the oldest
++filling stream (FIFO, at most TF_GLM_FILL_ROWS rows while others decode, the engine's prompt chunk alone) or one
++decode round, alternating by TF_GLM_FILL_SHARE; a prompt chunk never shares a forward with decode rows. A round: each
++decoding stream (admission order) proposes drafts under its own DFlash2 policy (copy drafts first), the combined
++window is capped at ``MAX_WINDOW`` rows (the longest tails trimmed), one verify over every stream's rows
++(``forward_streams``: ``verify.BatchedVerify``, one forward over every stream's rows through the segmented KDA and
++DSA kernels, or ``verify.SerialVerify``, the reference running each window as its own forward; TF_GLM_MULTI_VERIFY),
++one packed all-gather for the samplers, each stream accepts and commits its own.
++
++Rank 0 decides everything that depends on time, clients or placement; rank 1 applies it. Each iteration rank 0 sends
++ONE message (``GlmEngine._share``): ops ADMIT, EVICT, MOVE, GROW, FILL, ROUND, FINISH, IDLE, which both ranks apply
++in order through the same code (rank 0 as it decides them). Rank 1 derives drafts itself and checks the depths rank 0
++sent. An idle rank 1 waits on the doorbell (``GlmEngine._await_bell``), not in an all-gather. After an error the two
++ranks cannot be trusted to agree: ``broken`` latches and every later call fails until both restart.
++
++Multi-stream mode drafts with DFlash2 only: MTP policies are remapped to DFlash2 ones (drafts never change a reply)."""
++
++from __future__ import annotations
++
++import hashlib
++import json
++import os
++import queue
++import time
++from dataclasses import dataclass, field
++from typing import Any, Callable, Sequence
++
++import numpy as np
++import torch
++
++from tensorfold.cuda.scheduler import Scheduler
++from tensorfold.cuda.streams import Stream, next_fill
++
++from .pool import ALIGN, Pool, align_up
++from .verify import BatchedVerify, Segment, SerialVerify, Verified
++
++ADMIT, EVICT, MOVE, GROW, FILL, ROUND, FINISH, IDLE = range(1, 9)
++OPS = {ADMIT: "ADMIT", EVICT: "EVICT", MOVE: "MOVE", GROW: "GROW", FILL: "FILL", ROUND: "ROUND", FINISH: "FINISH",
++ IDLE: "IDLE"}
++DONE, CANCELLED, REQUEUED = 0, 1, 2 # FINISH reasons
++MAX_WINDOW = 32 # rows of every stream's windows together in one round
++SHARED_SLOTS = 2 # shared-prefix points an ADMIT carries (engine.SHARED_MOST)
++
++
++# -- settings ------------------------------------------------------------------------------------------------------
++def fill_rows(prefill_rows: int, grid: int = 0, value: str | None = None) -> int:
++ """TF_GLM_FILL_ROWS: rows of a prompt chunk while other streams decode (default 1,024 or the engine's prompt
++ chunk if smaller): a multiple of 64 and of the prompt grid, at most the prompt chunk (TF_GLM_PREFILL_ROWS)."""
++
++ value = os.environ.get("TF_GLM_FILL_ROWS", "") if value is None else value
++ value = value.strip()
++ rows = min(1024, prefill_rows) if value == "" else int(value) if value.isdecimal() else -1
++ if rows < 64 or rows % 64 or rows > prefill_rows or (grid and rows % grid):
++ raise ValueError(f"TF_GLM_FILL_ROWS: a multiple of 64{f' and of the {grid}-token prompt grid' if grid else ''}"
++ f" up to the {prefill_rows}-row prompt chunk, not {value!r}")
++ return rows
++
++
++def fill_share(value: str | None = None) -> float:
++ """TF_GLM_FILL_SHARE: the share of iterations prompt chunks take while other streams decode (default 0.5: a
++ chunk, a round, a chunk, ...); 1 fills every prompt before decoding on."""
++
++ value = os.environ.get("TF_GLM_FILL_SHARE", "") if value is None else value
++ try:
++ share = 0.5 if value.strip() == "" else float(value)
++ except ValueError:
++ share = -1.0
++ if not 0 < share <= 1:
++ raise ValueError(f"TF_GLM_FILL_SHARE: a share above 0 and at most 1, not {value!r}")
++ return share
++
++
++def multi_code(code: list[int], dflash: bool, dflash_policy: list[int]) -> list[int]:
++ """A request's policy code under --parallel: serial stays serial; auto becomes TF_GLM_DFLASH_POLICY; an MTP
++ policy its DFlash2 twin; without a draft model, serial."""
++
++ kind = code[0]
++ if kind == 0 or not dflash:
++ return [0, 0, 0, 0]
++ if kind in (4, 5):
++ return list(dflash_policy)
++ return [kind + 10] + list(code[1:]) if kind < 10 else list(code)
++
++
++def trim(drafts: list[list[int]], cap: int = MAX_WINDOW) -> list[list[int]]:
++ """Cut drafts until every window (a pending token and its drafts) fits ``cap`` rows together: one draft at a
++ time off the longest window (the latest of equals)."""
++
++ drafts = [list(d) for d in drafts]
++ total = sum(1 + len(d) for d in drafts)
++ while total > cap:
++ k = max(range(len(drafts)), key=lambda i: (len(drafts[i]), i))
++ if not drafts[k]:
++ break
++ drafts[k].pop()
++ total -= 1
++ return drafts
++
++
++def _f64(x: float) -> list[int]:
++ import struct
++
++ return list(struct.unpack("<2i", struct.pack("<d", float(x))))
++
++
++def _unf64(lo: int, hi: int) -> float:
++ import struct
++
++ return struct.unpack("<d", struct.pack("<2i", lo, hi))[0]
++
++
++def pack_sampling(sampling) -> list[int]:
++ """10 int32 words: the seed (3 words of 31, 31 and 2 bits), temperature, top_k, top_p, min_p."""
++
++ seed = (sampling.seed if sampling else 0) & 0xFFFFFFFFFFFFFFFF
++ return [seed & 0x7FFFFFFF, (seed >> 31) & 0x7FFFFFFF, seed >> 62,
++ *_f64(sampling.temperature if sampling else 0.0), int(sampling.top_k) if sampling else 0,
++ *_f64(sampling.top_p if sampling else 1.0), *_f64(sampling.min_p if sampling else 0.0)]
++
++
++def unpack_sampling(w: Sequence[int]):
++ from tensorfold.engine.exact_sampling import Sampling
++
++ s_lo, s_hi, s_top, t_lo, t_hi, top_k, p_lo, p_hi, m_lo, m_hi = w
++ temperature = _unf64(t_lo, t_hi)
++ if temperature <= 0:
++ return None
++ return Sampling((s_top << 62) | (s_hi << 31) | s_lo, temperature, top_k, _unf64(p_lo, p_hi), _unf64(m_lo, m_hi))
++
++
++# -- DFlash2 contexts per slot ---------------------------------------------------------------------------------------
++def draft_window(ctx, n: int) -> list[torch.Tensor]:
++ """A copy of a stream's DFlash2 window rows before n (``dflash2_multi.DraftContext``, or a solo ``Drafter``):
++ what a later block pass at n or past it reads. A ring's are copied by ``take_snapshot`` already."""
++
++ from .decode import _drafter_views, _ring_window
++
++ return _ring_window(ctx, n) if getattr(ctx, "ring", 0) else [v.clone() for v in _drafter_views(ctx, n)]
++
++
++def put_draft_window(ctx, n: int, rows: list[torch.Tensor]) -> None:
++ """Put a kept prompt's DFlash2 window back and end the context at n."""
++
++ from .decode import _drafter_views, _put_ring_window
++
++ if getattr(ctx, "ring", 0):
++ _put_ring_window(ctx, n, rows)
++ else:
++ views = _drafter_views(ctx, n)
++ if len(views) != len(rows):
++ raise ValueError("a kept state's DFlash2 window does not match the drafter's context")
++ for dst, src in zip(views, rows):
++ dst.copy_(src)
++ ctx.context_end = n
++ ctx.pos_dev.fill_(n)
++
++
++# -- the verify seam -------------------------------------------------------------------------------------------------
++def verify_kind(value: str | None = None) -> str:
++ """TF_GLM_MULTI_VERIFY: how a round's windows are verified: batched (the default: one forward over every stream's
++ rows, the segmented kernels) or serial (the reference: each stream's window as its own forward)."""
++
++ value = (os.environ.get("TF_GLM_MULTI_VERIFY", "") if value is None else value).strip().lower() or "batched"
++ if value not in ("batched", "serial"):
++ raise ValueError(f"TF_GLM_MULTI_VERIFY: batched or serial, not {value!r}")
++ return value
++
++
++def forward_streams(verify, segments: Sequence[Segment]) -> Verified:
++ """The seam: every segment's logits (and taps) of one round, by ``verify`` (``verify.SerialVerify`` or
++ ``verify.BatchedVerify``, the same two calls)."""
++
++ return verify.forward(segments)
++
++
++def sample_streams(w, parts: Sequence[tuple]) -> list[list[int]]:
++ """parts [(logits [R, V/world], positions, sampling)] -> each part's tokens, as ``decode.sample_rows`` samples
++ each alone: every top-k (and greedy) part's candidates in ONE all-gather, a nucleus part (top_k off) through the
++ shared nucleus rule (its own gathers), in part order on every rank."""
++
++ from tensorfold.cuda.sampling import comm_gather, nucleus_rows, one_rank
++ from tensorfold.engine.exact_sampling import MARGIN, choose_rows
++
++ out: list[list[int] | None] = [None] * len(parts)
++ packed, layout = [], []
++ for k, (logits, positions, sampling) in enumerate(parts):
++ greedy = sampling is None or sampling.temperature <= 0
++ if not greedy and not sampling.top_k:
++ continue
++ n = 1 if greedy else min(logits.shape[1], int(sampling.top_k) + MARGIN)
++ vals, ids = torch.topk(logits.float(), n, dim=-1)
++ ids = (ids + w.vocab_offset).to(torch.int32)
++ packed.append(torch.cat([vals, ids.view(torch.float32)], dim=1).reshape(-1))
++ layout.append((k, logits.shape[0], n))
++ if packed:
++ flat = torch.cat(packed) if len(packed) > 1 else packed[0]
++ if w.comm is None:
++ host = flat.view(1, -1).cpu()
++ else:
++ got = torch.empty((w.world * flat.numel(),), dtype=torch.float32, device=flat.device)
++ w.comm.all_gather(flat.contiguous(), got)
++ host = got.view(w.world, -1).cpu()
++ at = 0
++ for k, R, n in layout:
++ g = host[:, at:at + R * 2 * n].reshape(host.shape[0], R, 2 * n)
++ at += R * 2 * n
++ values = torch.cat([g[r, :, :n] for r in range(g.shape[0])], dim=1).numpy().astype(np.float32)
++ tokens = torch.cat([g[r, :, n:].contiguous().view(torch.int32) for r in range(g.shape[0])],
++ dim=1).numpy().astype(np.int64)
++ _, positions, sampling = parts[k]
++ if sampling is None or sampling.temperature <= 0:
++ order = np.lexsort((tokens, -values), axis=-1)
++ out[k] = [int(tokens[i, order[i, 0]]) for i in range(R)]
++ else:
++ out[k] = choose_rows(values, tokens, positions, sampling)
++ for k, (logits, positions, sampling) in enumerate(parts):
++ if out[k] is None:
++ out[k] = nucleus_rows(logits, positions, sampling, offset=w.vocab_offset,
++ gather=one_rank if w.comm is None else comm_gather(w.comm))
++ return out
++
++
++# -- streams -------------------------------------------------------------------------------------------------------------
++@dataclass(eq=False)
++class Lane:
++ """An admitted stream: its request (``Stream``), slot, extent, state views and decoding state (both ranks)."""
++
++ s: Stream
++ sid: int
++ slot: int
++ extent: Any
++ st: Any
++ order: int
++ code: list[int]
++ spec: str = ""
++ policy: Any = None # decode.DepthPolicy (DFlash2), None: one row a round
++ dflash: bool = False # the stream drafts with DFlash2 (its slot's context holds its taps)
++ depth: int = 0
++ copies: Any = None
++ feed: Any = None
++ constraint: Any = None
++ window: Any = None # the grammar's window of this round's rows
++ stops: list[int] = field(default_factory=list) # prompt positions whose states are kept (before the end)
++ point: int | None = None # where the prompt's own state is kept (engine.grid_point), or None
++ shared: list[int] = field(default_factory=list)
++ decoding: bool = False
++ paused: bool = False
++ t0: float = 0.0
++ copy_rounds: int = 0
++ copy_drafted: int = 0
++ copy_accepted: int = 0
++
++
++class NoRoom(RuntimeError):
++ """The pool cannot place a stream now (it waits for others to finish)."""
++
++
++class MultiDecoder:
++ """The ``GlmScheduler``'s decoder, on rank 0 (deciding) and rank 1 (``follow``, applying)."""
++
++ def __init__(self, engine, streams: int, *, verify=None, drafts=None, draft_graphs: bool | None = None) -> None:
++ """``drafts``: the multi-stream drafter (``dflash2_multi.MultiDrafter``; default one over the engine's
++ drafter, its graphs captured unless TF_GLM_MULTI_DRAFT_GRAPHS=0); ``verify``: the verify seam (default
++ ``SerialVerify``)."""
++ from .engine import DFLASH_POLICY, encode_policy
++
++ self.g = engine
++ self.e = e = engine.e
++ self.w = e.w
++ self.rank = engine.rank
++ self.count = streams
++ if e.slots.count < streams:
++ raise ValueError(f"the engine holds {e.slots.count} stream slots, not {streams}")
++ self.rows_max = e.rows # a stream's window (decode.MAX_ROWS)
++ self.pool = Pool(e.caches.rows)
++ self.arena = e.caches.arena
++ self.grid = engine.grid
++ self.fill_rows = fill_rows(e.prefill_rows, self.grid)
++ self.share = fill_share()
++ self.credit = 0.0
++ self.drafts = drafts
++ if self.drafts is None and engine.drafter is not None:
++ from .dflash2_multi import MultiDrafter
++
++ self.drafts = MultiDrafter(engine.drafter, streams=streams)
++ graphs = os.environ.get("TF_GLM_MULTI_DRAFT_GRAPHS", "1") != "0" if draft_graphs is None else draft_graphs
++ if graphs and torch.cuda.is_available():
++ self.drafts.capture()
++ if verify is None:
++ if verify_kind() == "batched":
++ taps = engine.drafter.tap_layers if engine.drafter is not None else ()
++ verify = BatchedVerify(e, taps=taps, rows=MAX_WINDOW)
++ # TF_GLM_MULTI_GRAPHS=0: eager windows (the same bits); by default a graph a window size
++ if os.environ.get("TF_GLM_MULTI_GRAPHS", "1") != "0" and torch.cuda.is_available():
++ verify.capture()
++ else:
++ verify = SerialVerify(e, taps=self.drafts is not None)
++ self.verify = verify
++ self.lanes: dict[int, Lane] = {} # by sid, in admission order
++ self.kept: list = [] # kept prompts (decode.Snapshot + kid, extent), oldest first
++ self.next_sid = self.next_kid = self.next_order = 0
++ self.outbox: list[int] = []
++ self.idle = True
++ self.broken: Exception | None = None
++ self.requeue: list[Stream] = [] # rank 0: streams given back to the scheduler's queue
++ self.eos = tuple(self.w.cfg.eos)
++ self.dflash_code = encode_policy(DFLASH_POLICY)
++
++ # -- the scheduler's view ----------------------------------------------------------------------------------------
++ @property
++ def streams(self) -> dict[int, Stream]:
++ """Decoding streams (``Scheduler._yield`` and /health read it)."""
++ return {sid: lane.s for sid, lane in self.lanes.items() if lane.decoding}
++
++ @property
++ def filling(self) -> list[Stream]:
++ return [lane.s for lane in self.lanes.values() if not lane.decoding]
++
++ def live(self) -> int:
++ return len(self.lanes)
++
++ def health(self) -> dict:
++ lanes = list(self.lanes.values())
++ return {"streams": {"decoding": sum(l.decoding and not l.paused for l in lanes),
++ "filling": sum(not l.decoding for l in lanes),
++ "paused": sum(l.decoding and l.paused for l in lanes)},
++ "pool_tokens": self.pool.rows, "pool_free_tokens": self.pool.free_rows(),
++ "kept_prompts": len(self.kept)}
++
++ def _check(self) -> None:
++ if self.broken is not None:
++ raise RuntimeError("the two ranks are out of step after an error; restart both") from self.broken
++
++ # -- messages --------------------------------------------------------------------------------------------------------
++ def _emit(self, op: int, payload: Sequence[int]) -> list[int]:
++ payload = [int(v) for v in payload]
++ self.outbox += [op, len(payload), *payload]
++ return payload
++
++ def _flush(self) -> None:
++ """Rank 0: this iteration's ops to rank 1, one message (after the doorbell when rank 1 idles)."""
++
++ if self.idle:
++ self.g._ring()
++ self.idle = False
++ msg, self.outbox = self.outbox, []
++ self.g._share(msg)
++
++ @staticmethod
++ def parse(msg: Sequence[int]) -> list[tuple[int, list[int]]]:
++ ops, i = [], 0
++ while i < len(msg):
++ op, n = int(msg[i]), int(msg[i + 1])
++ ops.append((op, [int(v) for v in msg[i + 2:i + 2 + n]]))
++ i += 2 + n
++ return ops
++
++ # -- admission (rank 0 decides) ---------------------------------------------------------------------------------------
++ def _need(self, prompt: int) -> int:
++ return align_up(prompt + self.rows_max)
++
++ def fits(self, s: Stream) -> bool:
++ """Whether ``s`` can be placed now (else it waits, in order, for streams to finish): the free rows and the
++ kept-only extents cover its prompt, with a block of headroom for each decoding stream to grow into."""
++
++ if not self.lanes:
++ return True # everything can be evicted; a prompt past the pool fails in ``admit``
++ need = self._need(len(s.prompt))
++ room = self.pool.free_rows() + sum(x.size for x in self.pool.extents if x.owner is None)
++ return room >= need + ALIGN * sum(l.decoding for l in self.lanes.values())
++
++ def admit(self, s: Stream) -> None:
++ """Rank 0: place a request (slot, extent; resumed from the longest kept prefix of its prompt when it drafts)
++ and queue its ADMIT; its prompt is prefilled chunk by chunk in later iterations."""
++
++ from .engine import grid_point, shared_points
++ from .engine import VisionFeed
++
++ self._check()
++ g = self.g
++ prompt = [int(t) for t in s.prompt]
++ if not prompt:
++ raise ValueError("a request needs at least one prompt token")
++ if len(prompt) >= g.limit:
++ raise ValueError(f"prompt of {len(prompt)} tokens: this engine serves contexts up to {g.limit}")
++ s.count = max(1, min(int(s.count), g.limit - len(prompt)))
++ if self._need(len(prompt)) > self.pool.rows:
++ raise ValueError(f"a prompt of {len(prompt)} tokens does not fit the {self.pool.rows}-token pool")
++ info = getattr(s, "glm", None) or {}
++ draft = bool(s.draft) and not g.serial_only
++ code = multi_code(info.get("code") or [0, 0, 0, 0], self.drafts is not None and draft,
++ self.dflash_code) if draft else [0, 0, 0, 0]
++ positions: list[int] = []
++ feed = None
++ if s.vision is not None: # encoded before anything is decided or sent: a failure stops here
++ if g.vision is None:
++ raise ValueError("image inputs require starting this server with --vision")
++ positions = [int(p) for p in s.vision.positions]
++ if positions and (positions[-1] >= len(prompt) or positions != sorted(set(positions))):
++ raise ValueError("image rows must sit at increasing positions inside the prompt")
++ t = time.perf_counter()
++ torch.cuda.empty_cache()
++ rows = g.vision.features(s.vision)
++ torch.cuda.empty_cache()
++ if rows.shape[0] != len(positions):
++ raise ValueError(f"the tower gave {rows.shape[0]} rows for {len(positions)} image positions")
++ feed = VisionFeed(g, positions, rows)
++ feed.encode_s = time.perf_counter() - t
++ slot = next((k for k in range(self.count) if k not in {l.slot for l in self.lanes.values()}), None)
++ if slot is None:
++ raise NoRoom(f"every one of the {self.count} stream slots is taken")
++ hit = self._resume(prompt) if draft and feed is None else None
++ need = self._need(len(prompt))
++ # placement: take a kept extent over in place, or copy its rows into a new one while a stream writes in it
++ copy = 0
++ base = None
++ if hit is not None and hit.extent.owner is None:
++ x = hit.extent
++ for c in list(x.kept): # kept prompts the stream would overwrite: gone
++ if len(c.ids) > len(hit.ids) and prompt[:len(c.ids)] != c.ids:
++ self._evict(c)
++ if self._grow(x, need, protect=[x]):
++ base = x.base
++ else:
++ hit = None
++ if base is None:
++ base = self._room(need, [hit.extent] if hit is not None else [])
++ if base is None and hit is not None: # no room beside the kept rows: start fresh
++ hit = None
++ base = self._room(need)
++ if base is None:
++ raise NoRoom(f"no room for a {need}-token extent in the {self.pool.rows}-token pool now")
++ copy = int(hit is not None)
++ cut = len(hit.ids) if hit is not None else 0
++ shared: list[int] = []
++ if draft and feed is None and g.shared:
++ known = [np.asarray(c.ids, dtype=np.int64) for c in self.kept]
++ shared = shared_points(prompt, cut, grid_point(len(prompt), cut, self.grid), self.grid, g.shared, known,
++ g.opener)
++ sid = self.next_sid
++ payload = [sid, slot, base, need, hit.kid if hit is not None else -1, copy, s.count, int(s.stop_eos),
++ int(draft), *pack_sampling(s.sampling), *(shared + [0] * SHARED_SLOTS)[:SHARED_SLOTS], *code,
++ len(prompt), *prompt]
++ from tensorfold.engine.grammar import pack
++
++ packed = pack(s.constraint)
++ payload += [len(packed), *packed, len(positions), *positions]
++ self._emit(ADMIT, payload)
++ try:
++ self._admitted(self._parse_admit(payload), s, feed, s.constraint, info.get("spec", ""))
++ except Exception as exc: # rank 1 applies the same ADMIT: the ranks may no longer agree
++ self.broken = exc
++ raise
++
++ @staticmethod
++ def _parse_admit(p: list[int]) -> dict:
++ (sid, slot, base, size, kid, copy, count, stop_eos, draft) = p[:9]
++ sampling = unpack_sampling(p[9:19])
++ shared = [v for v in p[19:19 + SHARED_SLOTS] if v]
++ i = 19 + SHARED_SLOTS
++ code = p[i:i + 4]
++ i += 4
++ n = p[i]
++ prompt = p[i + 1:i + 1 + n]
++ i += 1 + n
++ n = p[i]
++ packed = p[i + 1:i + 1 + n]
++ i += 1 + n
++ n = p[i]
++ positions = p[i + 1:i + 1 + n]
++ return dict(sid=sid, slot=slot, base=base, size=size, kid=kid, copy=copy, count=count, stop_eos=bool(stop_eos),
++ draft=bool(draft), sampling=sampling, shared=shared, code=code, prompt=prompt, packed=packed,
++ positions=positions)
++
++ def _admitted(self, a: dict, s: Stream, feed, constraint, spec: str = "") -> None:
++ """Both ranks: an ADMIT's stream in its slot and extent, resumed from its kept prompt if it names one."""
++
++ from .engine import decode_policy, grid_point
++ from .forward import State
++
++ g, e = self.g, self.e
++ hit = self._kept_by_id(a["kid"]) if a["kid"] >= 0 else None
++ prompt = a["prompt"]
++ s.prompt = list(prompt)
++ cut = len(hit.ids) if hit is not None else 0
++ if hit is not None and hit.ids != prompt[:cut]:
++ raise RuntimeError(f"the kept prompt {a['kid']} is not a prefix of stream {a['sid']}'s prompt")
++ if hit is not None and not a["copy"]:
++ x = hit.extent
++ if (x.base, x.size) != (a["base"], a["size"]) or x.owner is not None:
++ raise RuntimeError(f"stream {a['sid']} takes over extent {x.eid} at [{x.base}, {x.end}), "
++ f"rank 0 said [{a['base']}, {a['base'] + a['size']})")
++ else:
++ x = self.pool.add(a["base"], a["size"])
++ if hit is not None:
++ self.arena.copy(hit.extent.base, x.base, cut)
++ x.owner = a["sid"]
++ st = State(self.w, x.size, e.rows, caches=e.caches, base=x.base, slots=e.slots, slot=a["slot"])
++ code = a["code"]
++ dflash = code[0] >= 10 and self.drafts is not None
++ policy = decode_policy(code, g.costs) if code[0] else None
++ lane = Lane(s, a["sid"], a["slot"], x, st, self.next_order, code, spec, policy, dflash, feed=feed,
++ constraint=constraint)
++ self.next_sid = max(self.next_sid, a["sid"] + 1)
++ self.next_order += 1
++ s.sid, s.cached = a["sid"], cut
++ # the slot's state: the kept prompt's, or fresh
++ st.reset()
++ if self.drafts is not None:
++ self._ctx(lane).reset()
++ if hit is not None:
++ st.rec[st.cur[0]].copy_(hit.rec)
++ st.conv.copy_(hit.conv)
++ st.set_pos(cut)
++ if dflash:
++ if hit.drafter_end != cut or hit.drafter_rows is None:
++ raise RuntimeError("a kept prompt without DFlash2's window was chosen for a DFlash2 stream")
++ put_draft_window(self._ctx(lane), cut, hit.drafter_rows)
++ self._touch(hit)
++ # where its prompt states are kept: the grid point (or the end) and rank 0's shared-prefix points
++ if a["draft"] and feed is None:
++ lane.point = grid_point(len(prompt), cut, self.grid)
++ lane.shared = sorted(p for p in set(a["shared"]) if lane.point is not None and cut < p < lane.point)
++ lane.stops = list(lane.shared) + ([lane.point] if lane.point is not None and lane.point < len(prompt)
++ else [])
++ s.started = time.perf_counter()
++ lane.t0 = s.started
++ self.lanes[lane.sid] = lane
++
++ def _ctx(self, lane: Lane):
++ """The lane's slot's DFlash2 context."""
++ return self.drafts.contexts[lane.slot]
++
++ # -- kept prompts ------------------------------------------------------------------------------------------------------
++ def _kept_by_id(self, kid: int):
++ for c in self.kept:
++ if c.kid == kid:
++ return c
++ raise RuntimeError(f"rank {self.rank} holds no kept prompt {kid}")
++
++ def _resume(self, prompt: list[int]):
++ best = None
++ for c in self.kept:
++ n = len(c.ids)
++ fits = c.drafter_end == n and c.drafter_rows is not None or self.drafts is None
++ fits = fits and not (self.grid and n % self.grid)
++ if fits and n < len(prompt) and prompt[:n] == c.ids and (best is None or n > len(best.ids)):
++ best = c
++ return best
++
++ def _touch(self, c) -> None:
++ self.kept = [k for k in self.kept if k is not c] + [c]
++
++ def _keep(self, lane: Lane, n: int) -> None:
++ """Both ranks: the lane's state at prompt position n (== its pos) becomes a kept prompt in its extent."""
++
++ from .decode import take_snapshot
++
++ prev = self.e.use(lane.st)
++ try:
++ snap = take_snapshot(self.e, lane.s.prompt[:n], None, mtp=False, drafter=None)
++ finally:
++ self.e.use(prev)
++ snap.drafter_end = -1
++ if lane.dflash:
++ snap.drafter_end = n
++ snap.drafter_rows = draft_window(self._ctx(lane), n)
++ snap.kid = self.next_kid
++ self.next_kid += 1
++ snap.extent = lane.extent
++ for c in [c for c in self.kept if c.ids == snap.ids]:
++ self._drop(c)
++ lane.extent.kept.append(snap)
++ self.kept.append(snap)
++ while len(self.kept) > max(1, self.g.cache_entries):
++ self._drop(self.kept[0])
++
++ def _drop(self, c) -> None:
++ """Forget a kept prompt; its extent goes when nothing else holds it, else shrinks to what is kept."""
++
++ self.kept = [k for k in self.kept if k is not c]
++ x = c.extent
++ x.kept = [k for k in x.kept if k is not c]
++ c.rec = c.conv = None
++ c.drafter_rows = None
++ self._settle(x)
++
++ def _settle(self, x) -> None:
++ if x.owner is not None:
++ return
++ if not x.kept:
++ self.pool.remove(x)
++ return
++ size = align_up(max(len(k.ids) for k in x.kept))
++ if size < x.size:
++ self.pool.resize(x, size)
++
++ def _evict(self, c) -> None:
++ """Rank 0: drop a kept prompt on both ranks."""
++
++ self._emit(EVICT, [c.kid])
++ self._drop(c)
++
++ # -- room --------------------------------------------------------------------------------------------------------------
++ def _used(self, x) -> int:
++ used = max([len(k.ids) for k in x.kept], default=0)
++ if x.owner is not None:
++ used = max(used, self.lanes[x.owner].st.pos)
++ return used
++
++ def _move(self, x, base: int, size: int) -> None:
++ """Both ranks: relocate extent x (its used rows copied) to [base, base + size)."""
++
++ used = self._used(x)
++ old = self.pool.move(x, base, size)
++ self.arena.copy(old, base, used)
++ if x.owner is not None:
++ self.lanes[x.owner].st.bind(x.base, x.size)
++
++ def _resize(self, x, size: int) -> None:
++ self.pool.resize(x, size)
++ if x.owner is not None:
++ self.lanes[x.owner].st.bind(x.base, x.size)
++
++ def _victims(self, protect) -> list:
++ keep = set(id(x) for x in protect)
++ return [c for c in self.kept if c.extent.owner is None and id(c.extent) not in keep]
++
++ def _compact(self) -> None:
++ """Rank 0: slide every extent down to the lowest free rows (MOVEs), so the free rows are one range."""
++
++ at = 0
++ for x in list(self.pool.extents):
++ if x.base != at:
++ self._emit(MOVE, [x.eid, at, x.size])
++ self._move(x, at, x.size)
++ at += x.size
++
++ def _room(self, need: int, protect=()) -> int | None:
++ """Rank 0: a base with ``need`` free rows, evicting kept prompts (least recently used first, never
++ ``protect``'s extents) and compacting as needed; None if even that leaves too little."""
++
++ base = self.pool.place(need)
++ while base is None:
++ victims = self._victims(protect)
++ if not victims:
++ break
++ self._evict(victims[0])
++ base = self.pool.place(need)
++ if base is None and self.pool.free_rows() >= need:
++ self._compact()
++ base = self.pool.place(need)
++ return base
++
++ def _grow(self, x, size: int, protect=()) -> bool:
++ """Rank 0: extent x to at least ``size`` rows, in place or moved (evicting and compacting as needed)."""
++
++ size = align_up(size)
++ if size <= x.size:
++ return True
++ protect = list(protect) + [x]
++ while True:
++ if self.pool.room_after(x) >= size - x.size:
++ self._emit(GROW, [x.eid, size])
++ self._resize(x, size)
++ return True
++ base = self.pool.place(size, ignore=[x])
++ if base is not None:
++ self._emit(MOVE, [x.eid, base, size])
++ self._move(x, base, size)
++ return True
++ victims = self._victims(protect)
++ if not victims:
++ break
++ self._evict(victims[0])
++ if self.pool.free_rows() + x.size >= size:
++ self._compact()
++ if self.pool.room_after(x) >= size - x.size:
++ self._emit(GROW, [x.eid, size])
++ self._resize(x, size)
++ return True
++ base = self.pool.place(size, ignore=[x])
++ if base is not None:
++ self._emit(MOVE, [x.eid, base, size])
++ self._move(x, base, size)
++ return True
++ return False
++
++ # -- iterations ---------------------------------------------------------------------------------------------------------
++ @torch.no_grad()
++ def round(self) -> list[Stream]:
++ """Rank 0: one prompt chunk or one decode round; returns the streams that finished."""
++
++ self._check()
++ try:
++ return self._iterate()
++ except Exception as exc:
++ self.broken = exc
++ raise
++
++ def _fill_turn(self) -> Lane | None:
++ filling = [l for l in self.lanes.values() if not l.decoding]
++ if not filling:
++ return None
++ decoding = [l for l in self.lanes.values() if l.decoding and not l.paused and not l.s.done]
++ if decoding:
++ self.credit += self.share
++ if self.credit < 1:
++ return None
++ self.credit -= 1
++ s = next_fill([l.s for l in filling])
++ return self.lanes[s.sid]
++
++ def _iterate(self) -> list[Stream]:
++ lane = self._fill_turn()
++ if lane is not None:
++ stop = self._stop(lane)
++ self._emit(FILL, [lane.sid, stop])
++ self._flush()
++ first = self._fill(lane, stop)
++ if first is not None:
++ lane.s.take([first], self._ends(lane))
++ return [lane.s] if lane.s.done else []
++ lanes = [l for l in self.lanes.values() if l.decoding and not l.s.done]
++ for l in lanes: # room for this round's widest window, else paused
++ l.paused = not self._grow(l.extent, l.st.pos + self.rows_max, protect=[l.extent])
++ active = [l for l in lanes if not l.paused]
++ if not active:
++ done = []
++ if lanes and not any(not l.decoding for l in self.lanes.values()):
++ done = self._give_back() # every stream waits for room: the youngest goes back to the queue
++ if self.outbox: # what was decided (evictions, moves, a stream given back) goes now
++ self._flush()
++ return done
++ plan = [(l.sid, l.depth) for l in active]
++ self._emit(ROUND, [len(plan), *[v for p in plan for v in p]])
++ self._flush()
++ self._round(active)
++ return [l.s for l in active if l.s.done]
++
++ def _stop(self, lane: Lane) -> int:
++ pos, n = lane.st.pos, len(lane.s.prompt)
++ stop = next((p for p in lane.stops if p > pos), n)
++ busy = any(l.decoding and not l.s.done for l in self.lanes.values())
++ rows = self.fill_rows if busy or lane.s.background else self.e.prefill_rows
++ return min(stop, pos + rows)
++
++ def _ends(self, lane: Lane) -> tuple[int, ...]:
++ return self.eos if lane.s.stop_eos else ()
++
++ @torch.no_grad()
++ def _fill(self, lane: Lane, stop: int) -> int | None:
++ """Both ranks: the lane's prompt rows pos .. stop in one chunk; its kept states; at the prompt's end its first
++ token (the stream then decodes)."""
++
++ from .copy_drafts import CopyDrafts
++ from .decode import prefill_chunk
++
++ e = self.e
++ s = lane.s
++ prompt = s.prompt
++ n = len(prompt)
++ start = lane.st.pos
++ if not start < stop <= n or stop - start > e.prefill_rows:
++ raise RuntimeError(f"stream {lane.sid}: a prompt chunk {start} .. {stop} of {n}")
++ t = time.perf_counter()
++ prev = e.use(lane.st)
++ try:
++ out = prefill_chunk(e, prompt, start, stop - start, drafter=self._ctx(lane) if lane.dflash else None,
++ feed=lane.feed, mtp=False, head=stop == n)
++ if stop < n:
++ if stop in lane.stops:
++ self._keep(lane, stop)
++ return None
++ if lane.point == n:
++ self._keep(lane, n)
++ logits = out[:1]
++ if lane.constraint is not None: # the first token's row, under the reply's grammar
++ lane.constraint.mask(logits, lane.constraint.window([0], [-1]), self.w.vocab_offset)
++ first = sample_streams(self.w, [(logits, [n], s.sampling)])[0][0]
++ if lane.constraint is not None:
++ lane.constraint.advance([first])
++ finally:
++ e.use(prev)
++ s.prefill_s += time.perf_counter() - t
++ lane.decoding = True
++ s.started = time.perf_counter()
++ if lane.policy is not None and self.g.copy is not None:
++ lane.copies = CopyDrafts(list(prompt) + [first], self.g.copy.match, self.g.copy.most)
++ if lane.policy is not None:
++ lane.depth = min(lane.policy.next(0, 0), s.count - 1)
++ return first
++
++ @torch.no_grad()
++ def _round(self, lanes: list[Lane], depths: list[int] | None = None) -> None:
++ """Both ranks: one decode round over ``lanes`` (``depths``: rank 0's, checked on rank 1)."""
++
++ from .decode import copy_room
++ from .dflash2_multi import DraftRequest
++
++ if depths is not None and [l.depth for l in lanes] != depths:
++ raise RuntimeError(f"rank {self.rank}'s draft depths {[l.depth for l in lanes]} are not rank 0's {depths}")
++ drafts: list[list[int]] = []
++ copied: list[bool] = []
++ asks = []
++ for l in lanes:
++ c = l.copies.propose(copy_room(l.copies, l.s.count, l.s.out)) if l.copies is not None else []
++ copied.append(bool(c))
++ drafts.append(list(c))
++ if not c and l.dflash and l.depth > 0:
++ asks.append((len(drafts) - 1, DraftRequest(self._ctx(l), l.s.out[-1], l.depth, l.s.sampling,
++ l.policy.confidence, **l.policy.chain_rule)))
++ if asks:
++ got = self.drafts.propose([a for _, a in asks])
++ for (k, _), d in zip(asks, got):
++ drafts[k] = list(d)
++ drafts = trim(drafts, MAX_WINDOW)
++ segments = []
++ for l, d in zip(lanes, drafts):
++ tokens = [l.s.out[-1]] + d
++ l.window = None
++ if l.constraint is not None: # the chain cut at its first draft the grammar rejects
++ l.window = l.constraint.window(tokens, list(range(-1, len(tokens) - 1)))
++ tokens = list(l.window.tokens)
++ segments.append(Segment(l.st, tokens))
++ v = forward_streams(self.verify, segments)
++ parts = []
++ for l, seg, logits in zip(lanes, segments, v.logits):
++ if l.window is not None:
++ l.constraint.mask(logits, l.window, self.w.vocab_offset)
++ parts.append((logits, [l.st.pos + 1 + r for r in range(len(seg.tokens))], l.s.sampling))
++ sampled = sample_streams(self.w, parts)
++ keeps = []
++ for l, seg, rows in zip(lanes, segments, sampled):
++ keep = 1
++ for i, d in enumerate(seg.tokens[1:]):
++ if rows[i] != d or (l.s.stop_eos and rows[i] in self.eos):
++ break
++ keep += 1
++ keeps.append(keep)
++ self.verify.commit(segments, keeps)
++ if self.drafts is not None:
++ items = [(self._ctx(l), v.taps[k][:keep]) for k, (l, keep) in enumerate(zip(lanes, keeps)) if l.dflash]
++ if items:
++ self.drafts.commit(items)
++ for l, seg, rows, keep, was_copy in zip(lanes, segments, sampled, keeps, copied):
++ s = l.s
++ new = rows[:keep]
++ if l.constraint is not None:
++ l.constraint.advance(new)
++ if l.copies is not None:
++ l.copies.extend(new)
++ ndrafts = len(seg.tokens) - 1
++ s.counted(len(seg.tokens)) # Stream.take counts the accepted drafts
++ if was_copy:
++ l.copy_rounds += 1
++ l.copy_drafted += ndrafts
++ l.copy_accepted += keep - 1
++ room = s.count - len(s.out)
++ s.take(new[:max(0, room)], self._ends(l))
++ if l.policy is not None:
++ l.depth = min(l.policy.next(*((0, 0) if was_copy else (ndrafts, keep - 1))),
++ max(0, s.count - len(s.out)))
++
++ # -- ends ----------------------------------------------------------------------------------------------------------------
++ def finish(self, done: list[Stream]) -> None:
++ """Rank 0: finished (or cancelled) streams leave on both ranks; an idle rank 1 is told to wait for the bell."""
++
++ for s in done:
++ lane = self.lanes.get(s.sid)
++ if lane is None or lane.s is not s:
++ continue
++ reason = CANCELLED if s.error is None and len(s.out) < s.count and not (
++ s.out and s.out[-1] in self._ends(lane)) else DONE
++ self._emit(FINISH, [lane.sid, reason])
++ self._finish(lane.sid)
++ if not self.lanes and not self.idle and self.broken is None:
++ self._emit(IDLE, [])
++ self._flush()
++ self.idle = True
++
++ def _finish(self, sid: int) -> None:
++ """Both ranks: the stream's slot frees; its extent stays for its kept prompts (shrunk to them) or goes."""
++
++ lane = self.lanes.pop(sid)
++ x = lane.extent
++ x.owner = None
++ self._settle(x)
++ lane.s.finished = lane.s.finished or time.perf_counter()
++
++ def _give_back(self) -> list[Stream]:
++ """Rank 0: the youngest stream (one without a grammar or images, which cannot replay) leaves its slot and
++ extent and returns to the queue; it replays later, its sent tokens owed, not sent again. If every stream has
++ a grammar or images, the youngest fails instead (returned, to be finished)."""
++
++ lanes = sorted(self.lanes.values(), key=lambda l: l.order, reverse=True)
++ lane = next((l for l in lanes if l.constraint is None and l.feed is None), None)
++ if lane is None:
++ lane = lanes[0]
++ lane.s.error = NoRoom("the pool is full: every stream waits for room, and the youngest cannot replay "
++ "(a grammar or images)")
++ lane.s.done = True
++ return [lane.s]
++ for c in list(lane.extent.kept):
++ self._evict(c)
++ self._emit(FINISH, [lane.sid, REQUEUED])
++ self._finish(lane.sid)
++ self.requeue.append(lane.s)
++ return []
++
++ def drop(self) -> list[Stream]:
++ """After an error in an iteration: forget every stream (the ranks can no longer be trusted to agree)."""
++
++ live = [l.s for l in self.lanes.values()]
++ self.lanes = {}
++ if self.broken is None:
++ self.broken = RuntimeError("an iteration failed")
++ return live
++
++ def stats(self, s: Stream) -> dict:
++ """A finished request's stats (as ``GlmEngine.generate`` reports them)."""
++
++ out = s.stats()
++ out["decode_s"] = round(max((s.finished or time.perf_counter()) - s.started, 0.0), 4)
++ tokens = list(s.out[:s.count])
++ out.update(sha256=hashlib.sha256(json.dumps(tokens).encode()).hexdigest()[:16],
++ tokens_per_round=round((len(tokens) - 1) / max(s.rounds, 1), 3), parallel=self.count)
++ lane_info = getattr(s, "glm_lane", None)
++ if lane_info:
++ out.update(lane_info)
++ return out
++
++ # -- rank 1 --------------------------------------------------------------------------------------------------------------
++ @torch.no_grad()
++ def follow(self, once: bool = False) -> None:
++ """Rank 1: apply rank 0's messages forever (``once``: one message)."""
++
++ while True:
++ if self.idle:
++ self.g._await_bell()
++ self.idle = False
++ self.apply(self.g._share(None))
++ if once:
++ return
++
++ def apply(self, msg: Sequence[int]) -> None:
++ """Rank 1: one iteration's ops, in order."""
++
++ from tensorfold.engine.exact_sampling import Sampling # noqa: F401
++
++ for op, p in self.parse(msg):
++ if op == ADMIT:
++ a = self._parse_admit(p)
++ s = Stream(list(a["prompt"]), a["count"], a["sampling"], draft=a["draft"], stop_eos=a["stop_eos"],
++ sid=a["sid"])
++ constraint = None
++ if a["packed"]:
++ from tensorfold.engine import grammar
++
++ constraint = grammar.compiler(self.g, self.g.model_dir, self.g.eos).follow(a["packed"])
++ s.constraint = constraint
++ feed = None
++ if a["positions"]:
++ from .engine import VisionFeed
++
++ feed = VisionFeed(self.g, list(a["positions"]), None)
++ s.vision = feed
++ self._admitted(a, s, feed, constraint)
++ elif op == EVICT:
++ self._drop(self._kept_by_id(p[0]))
++ elif op == MOVE:
++ self._move(self.pool.get(p[0]), p[1], p[2])
++ elif op == GROW:
++ self._resize(self.pool.get(p[0]), p[1])
++ elif op == FILL:
++ lane = self.lanes[p[0]]
++ if p[1] != self._stop_bound(lane, p[1]):
++ raise RuntimeError(f"rank 1: stream {p[0]}'s prompt chunk to {p[1]} passes a kept point")
++ first = self._fill(lane, p[1])
++ if first is not None:
++ lane.s.take([first], self._ends(lane))
++ elif op == ROUND:
++ n = p[0]
++ sids, depths = p[1:1 + 2 * n:2], p[2:2 + 2 * n:2]
++ self._round([self.lanes[sid] for sid in sids], depths)
++ elif op == FINISH:
++ self._finish(p[0])
++ elif op == IDLE:
++ if self.lanes:
++ raise RuntimeError(f"rank 1 holds {len(self.lanes)} streams rank 0 has finished")
++ self.idle = True
++ else:
++ raise RuntimeError(f"rank 1: unknown op {op}")
++
++ def _stop_bound(self, lane: Lane, stop: int) -> int:
++ """The stop rank 0 sent, if it passes no kept point (else where it should have stopped)."""
++
++ nxt = next((q for q in lane.stops if q > lane.st.pos), len(lane.s.prompt))
++ return min(stop, nxt)
++
++
++# -- the scheduler ----------------------------------------------------------------------------------------------------
++class GlmScheduler(Scheduler):
++ """``cuda.scheduler.Scheduler`` for the GLM decoder: a request's GLM settings ride on its stream (``glm``); a
++ request the pool cannot place yet waits at the head of the queue (``MultiDecoder.fits``); streams the decoder gives
++ back (every stream waiting for room) return to the queue to replay."""
++
++ def __init__(self, decoder: MultiDecoder, *, max_streams: int) -> None:
++ self.held = None
++ super().__init__(decoder, max_streams=max_streams)
++
++ def submit(self, prompt: list[int], count: int, sampling: Any, draft: bool,
++ emit: Callable[[list[int]], bool | None], stop_eos: bool = True, *, vision: Any = None,
++ constraint: Any = None, background: bool = False, glm: dict | None = None) -> dict:
++ box: queue.Queue = queue.Queue()
++ stream = Stream(list(prompt), max(1, count), sampling, draft=draft, stop_eos=stop_eos, vision=vision,
++ constraint=constraint, background=background)
++ stream.glm = dict(glm or {})
++ cancel = [False]
++ stream.emit = lambda new: (box.put(("tokens", new)), cancel[0])[1]
++ self.waiting.put((stream, box))
++ while True:
++ kind, value = box.get()
++ if kind == "tokens":
++ if not cancel[0] and emit(value):
++ cancel[0] = True # the client left or a stop string: the stream ends next round
++ elif kind == "error":
++ raise value
++ else:
++ return value
++
++ def _admit(self, first=None) -> list[Stream]:
++ done: list[Stream] = []
++ while self.decoder.live() < self.max_streams:
++ if first is not None:
++ item, first = first, None
++ elif self.held is not None:
++ item, self.held = self.held, None
++ else:
++ try:
++ item = self.waiting.get_nowait()
++ except queue.Empty:
++ break
++ stream, box = item
++ if not self.decoder.fits(stream):
++ self.held = item # waits, first in line, for room
++ break
++ self.boxes[id(stream)] = box
++ try:
++ self.decoder.admit(stream)
++ except NoRoom:
++ self.boxes.pop(id(stream))
++ self.held = item
++ break
++ except Exception as exc: # noqa: BLE001 (this request fails, the others go on)
++ self.boxes.pop(id(stream)).put(("error", exc))
++ continue
++ if stream.done:
++ done.append(stream)
++ return done
++
++ def _yield(self) -> None:
++ """``Scheduler._yield``, the stream's GLM settings carried to its replay."""
++
++ if self.decoder.live() < self.max_streams or not self.waiting.foreground():
++ return
++ live = list(self.decoder.streams.values())
++ stream = next((s for s in reversed(live) if s.background and not s.done and s.constraint is None
++ and s.vision is None and len(s.out) < s.count), None)
++ if stream is None:
++ return
++ box = self.boxes.pop(id(stream))
++ self.decoder.finish([stream])
++ self.yields += 1
++ again = stream.continued()
++ again.glm = getattr(stream, "glm", {})
++ self.waiting.put((again, box))
++
++ def _requeue(self) -> None:
++ for stream in self.decoder.requeue:
++ box = self.boxes.pop(id(stream), None)
++ if box is None:
++ continue
++ again = stream.continued()
++ again.glm = getattr(stream, "glm", {})
++ self.yields += 1
++ self.waiting.put((again, box))
++ self.decoder.requeue = []
++
++ def _loop(self) -> None:
++ while True:
++ self._yield()
++ idle = not self.decoder.live() and self.held is None
++ done = self._admit(self.waiting.get() if idle else None) # idle: wait for a request
++ try:
++ done += self.decoder.round()
++ except Exception as exc: # noqa: BLE001 (the live requests fail)
++ for s in self.decoder.drop():
++ self._reply(s, "error", exc)
++ self._requeue()
++ try:
++ self.decoder.finish(done)
++ except Exception as exc: # noqa: BLE001
++ for s in self.decoder.drop():
++ self._reply(s, "error", exc)
++ for s in done:
++ self._reply(s, *(("error", s.error) if s.error is not None else ("done", self.decoder.stats(s))))
++ if self.held is not None and not self.decoder.live():
++ time.sleep(0) # the held request retries next iteration (now alone)
+diff --git tensorfold/families/glm5_next/cuda/pool.py tensorfold/families/glm5_next/cuda/pool.py
+new file mode 100644
+index 0000000..1313652
+--- /dev/null
++++ tensorfold/families/glm5_next/cuda/pool.py
+@@ -0,0 +1,223 @@
++"""GLM-5.3-Flash's per-token state as one shared pool: arenas of rows every stream draws from, and the extents that cut
++them up.
++
++An ``Arena`` holds planes of device rows (per DSA layer its latents; per indexed layer its index keys, gates and
++pooled keys; the MTP layer's), each ``rows // div + pad`` rows: latents div 1, pooled keys (a pool of 4 tokens) div 4
++with 2 rows of pad (the token selection reads up to 2 pools past a window). What a plane holds and in which element
++type (bf16, FP8 with scales, a ring) is the cache module's business (``forward.Caches``); the arena only views,
++copies and places rows.
++
++An extent [base, base + size), both multiples of ``ALIGN``, views every plane at [base // div, (base + size) // div +
++pad): the single-stream code (prefill, decode windows, snapshots) runs on those views exactly as on tensors of its
++own. The pad rows of one extent's pooled keys are the next extent's first rows: they are only ever read (and masked),
++never written (``sparse._pool_keys`` writes complete pools, all inside the extent).
++
++``Pool`` is the host-side bookkeeping of the extents (no device work): lowest-base first fit, growth in place,
++placement for relocations. Both ranks apply the same operations in the same order (rank 0 decides, rank 1 applies
++what it is sent), so their pools stay equal."""
++
++from __future__ import annotations
++
++from dataclasses import dataclass, field
++from typing import Iterable
++
++ALIGN = 2048 # extents start and end on multiples of this many tokens (the pooled keys at base / 4)
++
++
++def align_up(n: int, align: int = ALIGN) -> int:
++ return -(-int(n) // align) * align
++
++
++class Plane:
++ """One cache tensor over the arena's rows: row r of token t at t // div (``div`` tokens a row), ``pad`` rows
++ past the last token's."""
++
++ def __init__(self, tensor, div: int = 1, pad: int = 0) -> None:
++ self.tensor, self.div, self.pad = tensor, int(div), int(pad)
++
++ def rows_for(self, tokens: int) -> int:
++ return tokens // self.div
++
++ def view(self, base: int, size: int):
++ return self.tensor[base // self.div:(base + size) // self.div + self.pad]
++
++
++class Arena:
++ """Planes over ``rows`` tokens (a multiple of ``ALIGN`` when shared by several extents)."""
++
++ def __init__(self, rows: int, planes: list[Plane]) -> None:
++ self.rows = int(rows)
++ self.planes = planes
++ for p in planes:
++ want = self.rows // p.div + p.pad
++ if p.tensor.shape[0] != want:
++ raise ValueError(f"a plane of {p.tensor.shape[0]} rows over {self.rows} tokens (div {p.div}, pad "
++ f"{p.pad}): want {want}")
++
++ def view(self, i: int, base: int, size: int):
++ if base < 0 or base + size > self.rows:
++ raise ValueError(f"extent [{base}, {base + size}) outside the arena's {self.rows} tokens")
++ return self.planes[i].view(base, size)
++
++ def nbytes(self) -> int:
++ return sum(p.tensor.numel() * p.tensor.element_size() for p in self.planes)
++
++ def token_bytes(self) -> float:
++ """Device bytes a token of every plane takes (the pad aside)."""
++ return sum(p.tensor[0].numel() * p.tensor.element_size() / p.div for p in self.planes)
++
++ def copy(self, src: int, dst: int, n: int) -> None:
++ """Tokens [src, src + n) of every plane to [dst, dst + n): a whole last row of a plane whose rows hold
++ several tokens (``div``) goes too (its tokens past n are the source's, which nothing reads). Overlapping
++ ranges copy in pieces that never read a row already written."""
++
++ if n <= 0 or src == dst:
++ return
++ if min(src, dst) < 0 or max(src, dst) + n > self.rows:
++ raise ValueError(f"a copy of {n} tokens from {src} to {dst} reaches outside the arena's {self.rows}")
++ for p in self.planes:
++ a, b = src // p.div, dst // p.div
++ m = -(-n // p.div)
++ m = min(m, p.tensor.shape[0] - max(a, b))
++ _move(p.tensor, a, b, m)
++
++
++def _move(t, a: int, b: int, m: int) -> None:
++ """t[b:b + m] = t[a:a + m] (rows), safe when they overlap."""
++
++ gap = abs(a - b)
++ if gap >= m:
++ t[b:b + m].copy_(t[a:a + m])
++ return
++ step = gap
++ starts = range(0, m, step) if b < a else reversed(range(0, m, step))
++ for s in starts: # down: front to back; up: back to front
++ k = min(step, m - s)
++ t[b + s:b + s + k].copy_(t[a + s:a + s + k])
++
++
++@dataclass(eq=False)
++class Extent:
++ """Pool rows [base, base + size). ``owner``: the live stream writing into it (its sid), or None; ``kept``: the
++ kept prompts whose rows it holds (each a prefix of the rows)."""
++
++ base: int
++ size: int
++ eid: int = 0
++ owner: int | None = None
++ kept: list = field(default_factory=list)
++
++ @property
++ def end(self) -> int:
++ return self.base + self.size
++
++ def free(self) -> bool:
++ return self.owner is None and not self.kept
++
++
++class Pool:
++ """Extents over ``rows`` pool rows, host side only. Placement is lowest base first; every call is deterministic
++ in the calls before it, so two ranks making the same calls hold the same extents."""
++
++ def __init__(self, rows: int, align: int = ALIGN) -> None:
++ if rows <= 0 or rows % align:
++ raise ValueError(f"a pool of {rows} rows: a positive multiple of {align}")
++ self.rows, self.align = int(rows), int(align)
++ self.extents: list[Extent] = [] # by base
++ self.next_id = 0
++
++ # -- queries -------------------------------------------------------------------------------------------------
++ def gaps(self, ignore: Iterable[Extent] = ()) -> list[tuple[int, int]]:
++ """Free (base, size) ranges by base, the extents in ``ignore`` counted as free."""
++
++ skip = set(id(x) for x in ignore)
++ out, at = [], 0
++ for x in self.extents:
++ if id(x) in skip:
++ continue
++ if x.base > at:
++ out.append((at, x.base - at))
++ at = max(at, x.end)
++ if at < self.rows:
++ out.append((at, self.rows - at))
++ return _merge(out)
++
++ def free_rows(self) -> int:
++ return self.rows - sum(x.size for x in self.extents)
++
++ def place(self, size: int, ignore: Iterable[Extent] = ()) -> int | None:
++ """The lowest base with ``size`` free rows (``ignore``'s rows free), or None."""
++
++ size = align_up(size, self.align)
++ for base, n in self.gaps(ignore):
++ if n >= size:
++ return base
++ return None
++
++ def room_after(self, x: Extent) -> int:
++ """Free rows right after x (before the next extent or the pool's end)."""
++
++ nxt = min((y.base for y in self.extents if y.base >= x.end and y is not x), default=self.rows)
++ return nxt - x.end
++
++ def get(self, eid: int) -> Extent:
++ for x in self.extents:
++ if x.eid == eid:
++ return x
++ raise KeyError(f"no extent {eid}")
++
++ # -- changes -------------------------------------------------------------------------------------------------
++ def add(self, base: int, size: int) -> Extent:
++ """A new extent at exactly [base, base + size) (rank 0's placement, applied on both ranks)."""
++
++ size = align_up(size, self.align)
++ if base % self.align or base < 0 or base + size > self.rows:
++ raise ValueError(f"extent [{base}, {base + size}) is not an aligned range of the {self.rows}-row pool")
++ if any(x.base < base + size and base < x.end for x in self.extents):
++ raise ValueError(f"extent [{base}, {base + size}) overlaps another")
++ x = Extent(base, size, self.next_id)
++ self.next_id += 1
++ self.extents.append(x)
++ self.extents.sort(key=lambda y: y.base)
++ return x
++
++ def alloc(self, size: int) -> Extent | None:
++ base = self.place(size)
++ return None if base is None else self.add(base, size)
++
++ def resize(self, x: Extent, size: int) -> None:
++ """Grow in place (the rows after it free) or shrink (from its end)."""
++
++ size = align_up(size, self.align)
++ if size > x.size and size - x.size > self.room_after(x):
++ raise ValueError(f"extent {x.eid} cannot grow to {size} rows in place")
++ if size <= 0:
++ raise ValueError("an extent keeps at least one aligned block")
++ x.size = size
++
++ def move(self, x: Extent, base: int, size: int | None = None) -> int:
++ """Place x at ``base`` (with ``size`` rows): the bookkeeping only (the caller copies the rows). Returns the old
++ base."""
++
++ size = x.size if size is None else align_up(size, self.align)
++ if base % self.align or base < 0 or base + size > self.rows:
++ raise ValueError(f"extent [{base}, {base + size}) is not an aligned range of the pool")
++ if any(y is not x and y.base < base + size and base < y.end for y in self.extents):
++ raise ValueError(f"extent {x.eid} cannot move to [{base}, {base + size}): taken")
++ old = x.base
++ x.base, x.size = base, size
++ self.extents.sort(key=lambda y: y.base)
++ return old
++
++ def remove(self, x: Extent) -> None:
++ self.extents = [y for y in self.extents if y is not x]
++
++
++def _merge(ranges: list[tuple[int, int]]) -> list[tuple[int, int]]:
++ out: list[tuple[int, int]] = []
++ for base, n in ranges:
++ if out and out[-1][0] + out[-1][1] == base:
++ out[-1] = (out[-1][0], out[-1][1] + n)
++ elif n > 0:
++ out.append((base, n))
++ return out
+diff --git tensorfold/families/glm5_next/cuda/verify.py tensorfold/families/glm5_next/cuda/verify.py
+new file mode 100644
+index 0000000..2d13572
+--- /dev/null
++++ tensorfold/families/glm5_next/cuda/verify.py
+@@ -0,0 +1,244 @@
++"""The verify seam of GLM-5.3-Flash's concurrent streams (``multi.forward_streams``): a round's windows, one per
++stream (its state: extent and slot views; its tokens: the pending token, then its drafts), in, each window's logits
++and DFlash2 taps out, then each stream's commit of the rows it keeps. Two implementations of the same two calls:
++
++- ``SerialVerify``: each window as its own forward on its own state (the solo kernels: exact by construction; a CUDA
++ graph where the state is the one they were captured on);
++- ``BatchedVerify``: ONE forward over every stream's rows back to back: the row-independent parts (embeddings,
++ hyper-connection glue, projections, MLP / MoE, head) on the whole window, KDA layers through the segmented chain
++ (``kda.chain_segments``: each segment from its slot's state, into its slot's other parity), DSA layers through the
++ segmented latent / sparse attention over the streams' extents (``forward.dsa_segments``, ``segments.SegRows``);
++ the commit replays each segment's kept rows (``kda.replay_layers_segments``) and shifts its conv window
++ (``forward.conv_shift_segments``). Every segment's rows get the bits of that stream's window alone.
++
++The scheduler (``multi.MultiDecoder``) only sees ``forward`` / ``commit``."""
++
++from __future__ import annotations
++
++from dataclasses import dataclass
++from typing import Any, Sequence
++
++import torch
++
++
++@dataclass
++class Segment:
++ """One stream's rows of a round's verify window: its state (extent and slot views) and tokens (the pending
++ token, then its drafts)."""
++
++ st: Any
++ tokens: list[int]
++
++
++@dataclass
++class Verified:
++ logits: list[torch.Tensor] # per segment [rows, V / world] (this rank's vocabulary columns)
++ taps: list[torch.Tensor | None] # per segment [rows, taps * D] (DFlash2's inputs), or None
++
++
++class SerialVerify:
++ """The reference: each segment's window as its own forward on its own state. Logits and taps are copied out
++ before the next segment's forward reuses the buffers; each slot keeps its own KDA window scratch, so the commits
++ can come after every forward."""
++
++ def __init__(self, e, *, taps: bool) -> None:
++ self.e, self.taps = e, taps
++
++ def forward(self, segments: Sequence[Segment]) -> Verified:
++ e = self.e
++ logits, taps = [], []
++ for seg in segments:
++ prev = e.use(seg.st)
++ try:
++ R = len(seg.tokens)
++ logits.append(e.forward(seg.tokens)[:R].clone())
++ taps.append(e.tap_rows(R).clone() if self.taps else None)
++ finally:
++ e.use(prev)
++ return Verified(logits, taps)
++
++ def commit(self, segments: Sequence[Segment], keeps: Sequence[int]) -> None:
++ from .forward import commit
++
++ e = self.e
++ for seg, keep in zip(segments, keeps):
++ commit(e.w, seg.st, e.buf, len(seg.tokens), keep)
++
++
++class BatchedVerify:
++ """One forward over every segment's rows (``rows`` at most, ``segments.MAX_SEGS`` streams), on buffers of its
++ own; see the module docstring. ``taps``: the drafter's tap layers (DFlash2's inputs), or ()."""
++
++ def __init__(self, e, *, taps: Sequence[int] = (), rows: int = 32) -> None:
++ from . import kda as kda_mod
++ from . import latent
++ from .forward import Buffers
++ from .segments import MAX_SEGS, SegRows, SelectScratch
++
++ if not latent.ENABLED:
++ raise ValueError("batched verify windows need the latent cache (TF_GLM_LATENT=1)")
++ w = e.w
++ c = w.cfg
++ self.e, self.w, self.rows_max = e, w, rows
++ dev = w.device
++ self.b = Buffers(w, rows, e.caches.rows)
++ if taps:
++ self.b.set_taps(tuple(taps), c.hidden)
++ self.taps = bool(taps)
++ self.seg_rows = SegRows(rows, dev, max_segs=MAX_SEGS)
++ self.sel = SelectScratch(rows, e.caches.rows, dev) if e.caches.index is not None else None
++ kda_layers = [l for l in w.layers if l.kind == "kda"]
++ n = len(kda_layers)
++ LL = c.lin_heads // w.world
++ width = kda_layers[0].kda.proj.n if kda_layers else 0
++ self.kda_index = {l.index: i for i, l in enumerate(kda_layers)}
++ self.dsa_index = {l.index: i for i, l in enumerate(l for l in w.layers if l.kind == "dsa")}
++ self.proj = torch.zeros((n, rows, width), dtype=torch.bfloat16, device=dev)
++ self.scratch = kda_mod.KDAScratchSet(n, rows, LL, dev) if n else None
++ self.kseg = torch.zeros((MAX_SEGS, kda_mod.SEG_COLS), dtype=torch.int32, device=dev)
++ self.kseg_host = torch.zeros((MAX_SEGS, kda_mod.SEG_COLS), dtype=torch.int32,
++ pin_memory=torch.cuda.is_available())
++ self.staged = torch.cuda.Event() if torch.cuda.is_available() else None
++ self.segments: list[Segment] = []
++ self.R = 0
++ self.graphs: dict[int, torch.cuda.CUDAGraph] = {}
++ self.replays = {"graph": 0, "eager": 0}
++
++ @torch.no_grad()
++ def capture(self, rows: Sequence[int] | None = None) -> None:
++ """CUDA graphs of the window for each row count (default 1 .. its rows), both ranks together: positions,
++ extents, slots and parities live in the device tables, so one graph a row count covers every mix. Captured on
++ a window of slot 0 at the pool's first rows (the warm-up runs write there; slot 0's states are cleared after,
++ so capture before any stream is admitted). With the indexer the graphs always run the token selection (its
++ dense rows ignore it: the same bits as a window that skips it)."""
++
++ from .forward import compute
++ from .sparse import SPARSE_FROM
++
++ e, w, b = self.e, self.w, self.b
++ index = e.caches.index is not None
++ pool = torch.cuda.graph_pool_handle()
++ for R in rows or range(1, self.rows_max + 1):
++ self._stage([0] * R)
++ self.seg_rows.set([(0, 0, R)], sparse_from=SPARSE_FROM if index else None)
++ self._write_table([(R, 0, 0, 0, R)])
++ run = lambda: compute(w, None, b, R, mixer=lambda layer: self._mixer(layer, R, index)) # noqa: E731
++ for _ in range(2):
++ run()
++ torch.cuda.synchronize()
++ g = torch.cuda.CUDAGraph()
++ with torch.cuda.graph(g, pool=pool):
++ run()
++ self.graphs[R] = g
++ torch.cuda.synchronize()
++ e.slots.rec[0].zero_()
++ e.slots.conv[0].zero_()
++
++ # -- the window's tables -------------------------------------------------------------------------------------------
++ def _tables(self, segments: Sequence[Segment], keeps: Sequence[int] | None = None) -> None:
++ """The KDA segment table (row0, rows, slot, parity, conv slot, keep) into the device copy, in place (a captured
++ graph reads the same tensor); unused segments have 0 rows."""
++
++ self._write_table([(len(s.tokens), s.st.slot, s.st.cur[0] if s.st.cur else 0, s.st.slot,
++ len(s.tokens) if keeps is None else keeps[k]) for k, s in enumerate(segments)])
++
++ def _write_table(self, rows) -> None:
++ from . import kda as kda_mod
++
++ table = kda_mod.segment_table(rows, "cpu", out=torch.zeros_like(self.kseg_host))
++ if self.staged is not None:
++ self.staged.synchronize()
++ self.kseg_host.copy_(table)
++ self.kseg.copy_(self.kseg_host, non_blocking=True)
++ if self.staged is not None:
++ self.staged.record()
++
++ def _stage(self, tokens: list[int]) -> None:
++ b = self.b
++ R = len(tokens)
++ if R > b.rows:
++ raise ValueError(f"a window of {R} rows, the batched buffers hold {b.rows}")
++ b.staged.synchronize()
++ b.ids_host[:R].numpy()[:] = tokens
++ b.ids[:R].copy_(b.ids_host[:R], non_blocking=True)
++ b.staged.record()
++
++ # -- the seam --------------------------------------------------------------------------------------------------------
++ @torch.no_grad()
++ def forward(self, segments: Sequence[Segment]) -> Verified:
++ from .forward import check_room, compute
++ from .sparse import SPARSE_FROM
++
++ w, b = self.w, self.b
++ index = self.e.caches.index is not None
++ spans = []
++ for seg in segments:
++ check_room(w, seg.st, len(seg.tokens))
++ spans.append((seg.st.base, seg.st.pos, len(seg.tokens)))
++ tokens = [t for seg in segments for t in seg.tokens]
++ R = len(tokens)
++ self._stage(tokens)
++ self.seg_rows.set(spans, sparse_from=SPARSE_FROM if index else None)
++ self._tables(segments)
++ self.segments, self.R = list(segments), R
++ g = self.graphs.get(R)
++ if g is not None:
++ self.replays["graph"] += 1
++ g.replay()
++ logits = b.logits[:R]
++ else:
++ self.replays["eager"] += 1
++ select = index and self.seg_rows.any_sparse()
++ logits = compute(w, None, b, R, mixer=lambda layer: self._mixer(layer, R, select))
++ out, taps, at = [], [], 0
++ for seg in segments:
++ n = len(seg.tokens)
++ out.append(logits[at:at + n])
++ taps.append(torch.cat([t[at:at + n] for t in b.taps], dim=1) if self.taps else None)
++ at += n
++ return Verified(out, taps)
++
++ def _mixer(self, layer, R: int, select: bool):
++ """A layer's KDA or DSA block over the whole window, each segment on its own stream's state."""
++
++ from . import prof
++ from .forward import dsa_segments, kda_segments
++
++ e = self.e
++ if layer.kind == "kda":
++ with prof.timed("kda"):
++ return kda_segments(layer, self.w, self.b, R, self.kseg, e.slots, self.proj, self.scratch,
++ self.kda_index[layer.index])
++ caches = e.caches
++ di = self.dsa_index[layer.index]
++ planes = caches.arena.planes
++ lc = planes[caches.kc[di]].tensor
++ index = None if caches.index is None else tuple(planes[i].tensor for i in caches.index[di])
++ with prof.timed("dsa (total)"):
++ return dsa_segments(layer, self.w, lc, self.b, R, self.seg_rows, self.sel, index, select=select)
++
++ @torch.no_grad()
++ def commit(self, segments: Sequence[Segment], keeps: Sequence[int]) -> None:
++ """Each segment keeps its first ``keeps[k]`` rows: its KDA states replayed to them (when it keeps fewer than
++ its rows), its conv window shifted, its parity flipped, its position advanced."""
++
++ from . import kda as kda_mod
++ from .forward import conv_shift_segments
++
++ if [id(s) for s in segments] != [id(s) for s in self.segments]:
++ raise ValueError("commit takes the segments of the last forward")
++ for seg, keep in zip(segments, keeps):
++ if not 1 <= keep <= len(seg.tokens):
++ raise ValueError("keep must be in 1..rows")
++ e = self.e
++ if self.scratch is not None:
++ self._tables(segments, keeps)
++ if any(k < len(s.tokens) for s, k in zip(segments, keeps)):
++ kda_mod.replay_layers_segments(self.kseg, e.slots.rec, self.scratch)
++ conv_shift_segments(e.slots.conv, self.proj, self.kseg)
++ for seg, keep in zip(segments, keeps):
++ st = seg.st
++ if st.cur:
++ st.cur = [1 - st.cur[0]] * len(st.cur)
++ st.set_pos(st.pos + keep)
++ self.segments = []
diff --git a/patches/0034-glm-decode-index-regs.patch b/patches/0034-glm-decode-index-regs.patch
new file mode 100644
index 0000000..e60799c
--- /dev/null
+++ b/patches/0034-glm-decode-index-regs.patch
@@ -0,0 +1,80 @@
+diff --git tensorfold/families/glm5_next/cuda/sparse.py tensorfold/families/glm5_next/cuda/sparse.py
+index dcd849f..59c274b 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
+ tl.store(OUT + r * NP + p, sc, mask=p < NP)
+
+
++def _scores_rows(QI, W, w_stride, PK, 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):
++ """Decode rows, program (row, g): the row's index queries and head weights loaded once, then pool blocks g,
++ g + G, .. each through _scores' arithmetic for that row (the same key mask, dot tile, warps and head sum, so
++ RB = 1's bits). SEG False: NP columns a row from one position (POS[0] + r; pools past the row's -inf); SEG: a
++ segmented window's row r (skipped when dense) over its own visible pools, keys at its stream's base / 4."""
++
++ r = tl.program_id(0)
++ g = tl.program_id(1)
++ if SEG:
++ if tl.load(SPR + r) == 0:
++ return
++ npool = (tl.load(POS + r) + 1) // 4
++ pk = PK + (tl.load(BASE + r).to(tl.int64) // 4) * D
++ nb = (npool + BP - 1) // BP
++ else:
++ npool = (tl.load(POS) + r + 1) // 4
++ pk = PK
++ nb = (NP + BP - 1) // BP
++ if g >= nb:
++ return
++ d = tl.arange(0, D)
++ hh = tl.arange(0, HP)
++ hok = hh < H
++ q = tl.load(QI + (r * H + hh[:, None]) * D + d[None, :], mask=hok[:, None], other=0.0).to(tl.bfloat16)
++ 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)
++ k = tl.load(pk + p[:, None] * D + d[None, :], mask=(p < npool)[:, 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
++ 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)
++ else:
++ sc = tl.where(p < npool, sc, float("-inf"))
++ tl.store(OUT + r * o_stride + p, sc, mask=p < NP)
++
++
++# decode rows' scoring (_scores_rows): the tile (BP pools, 4 warps) is _scores', which sets the bits (8 warps or
++# 32-pool blocks give others); G, the programs a row, is speed only
++ROW_SCORE_G = 128
++
++
+ 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
+ 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)
++ 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
+ 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
+ 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
+- count, so one CUDA graph per window size serves every context length (``scratch``: segments.SelectScratch)."""
++ count (_seg_scores: a pool block's keys loaded once for all the segment's rows; _scores_rows' row-major loop
++ measured no faster here, and slower on dense windows), so one CUDA graph per window size serves every context
++ length (``scratch``: segments.SelectScratch)."""
+
+ if qi.stride(0) != qi.shape[1] or wts.stride(1) != 1:
+ raise ValueError("seg_select_tokens: index queries must be contiguous rows, weights unit-stride columns")
diff --git a/patches/0035-glm-code-copy-drafts.patch b/patches/0035-glm-code-copy-drafts.patch
new file mode 100644
index 0000000..c384f52
--- /dev/null
+++ b/patches/0035-glm-code-copy-drafts.patch
@@ -0,0 +1,301 @@
+diff --git tensorfold/families/glm5_next/cuda/copy_drafts.py tensorfold/families/glm5_next/cuda/copy_drafts.py
+index 3aa3b25..10860da 100644
+--- tensorfold/families/glm5_next/cuda/copy_drafts.py
++++ tensorfold/families/glm5_next/cuda/copy_drafts.py
+@@ -4,6 +4,17 @@ A reply that quotes or edits its prompt (or repeats itself) is cheap to draft: i
+ pending token included) are searched in the prompt and the reply so far, and the tokens after the latest earlier
+ occurrence become the drafts. They only propose; verification keeps the serial sample, so replies stay exact.
+
++Three refinements, off by default (they only change what is proposed, never what is kept):
++- ``reply_match`` (TF_GLM_COPY_REPLY_MATCH): an occurrence that starts inside the reply must match the context's last
++ ``reply_match`` tokens, not ``match``. Code replies repeat short boilerplate (`` def __init__(self``, ``}); ``)
++ whose continuations differ: over 39 live code replies (2026-09-30) reply-sourced copies kept 23% of their drafts,
++ prompt-sourced ones 74%, and a missed copy round costs a wide window and the DFlash2 round it displaced.
++- ``miss_most`` (TF_GLM_COPY_MISS_MAX): after a copied round whose drafts were not all kept, the next copied round
++ proposes at most this many (a narrow window), until a copied round keeps all of its drafts again.
++- ``pad`` (the engine's TF_GLM_WIDE_GRAPHS widths): a proposal whose window (pending token + drafts) falls between 8
++ rows and a captured width is padded to that width by repeating its last draft, so the window replays a CUDA graph
++ instead of running eagerly. Padded drafts are drafts like any other: kept only where they equal the sample.
++
+ Both ranks hold the same prompt and sample the same tokens, so each computes the same proposals with no exchange.
+ Pure numpy (no torch), so it is testable anywhere."""
+
+@@ -19,14 +30,22 @@ MATCH = 8 # the context's last this many tokens must have occurred before
+ MOST = 5 # drafts a round (TF_GLM_COPY_MAX, up to 15): graphs cover windows of 8 rows, wider ones run eagerly
+
+
++GRAPHED = 8 # verify windows up to this many rows always replay CUDA graphs (engine.GRAPH_ROWS)
++
++
+ @dataclass(frozen=True)
+ class CopySettings:
+ match: int = MATCH
+ most: int = MOST
++ reply_match: int = 0 # 0: occurrences in the reply need ``match`` tokens like the prompt's
++ pad: tuple[int, ...] = () # window widths past GRAPHED rows that replay CUDA graphs (TF_GLM_WIDE_GRAPHS)
++ miss_most: int = 0 # 0: off; else drafts a copied round after one that missed
+
+ @classmethod
+- def from_env(cls, max_drafts: int, env=None) -> CopySettings | None:
+- """TF_GLM_COPY_DRAFTS=1 turns copy drafts on (off by default); TF_GLM_COPY_MATCH and TF_GLM_COPY_MAX tune."""
++ def from_env(cls, max_drafts: int, env=None, pad: Sequence[int] = ()) -> CopySettings | None:
++ """TF_GLM_COPY_DRAFTS=1 turns copy drafts on (off by default); TF_GLM_COPY_MATCH, TF_GLM_COPY_MAX and
++ TF_GLM_COPY_REPLY_MATCH (0 or more than the match, up to 64) and TF_GLM_COPY_MISS_MAX (0: off, or 1 up to
++ TF_GLM_COPY_MAX) tune; ``pad``: the engine's wide graph widths."""
+
+ env = os.environ if env is None else env
+ on = env.get("TF_GLM_COPY_DRAFTS", "0").strip()
+@@ -43,22 +62,46 @@ class CopySettings:
+ raise ValueError(f"{name}: {low} to {high}, not {text!r}")
+ return int(text)
+
+- return cls(number("TF_GLM_COPY_MATCH", MATCH, 2, 64),
+- number("TF_GLM_COPY_MAX", min(MOST, max_drafts), 1, max_drafts))
++ match = number("TF_GLM_COPY_MATCH", MATCH, 2, 64)
++ reply = number("TF_GLM_COPY_REPLY_MATCH", 0, 0, 64)
++ if reply and reply <= match:
++ raise ValueError(f"TF_GLM_COPY_REPLY_MATCH: 0 (off) or more than TF_GLM_COPY_MATCH ({match}), not {reply}")
++ widths = tuple(sorted(int(r) for r in pad if GRAPHED < int(r) <= max_drafts + 1))
++ most = number("TF_GLM_COPY_MAX", min(MOST, max_drafts), 1, max_drafts)
++ return cls(match, most, reply, widths, number("TF_GLM_COPY_MISS_MAX", 0, 0, most))
+
+ def code(self) -> list[int]:
+- """The settings as ints both ranks compare at startup (zeros: off)."""
++ """The settings as ints both ranks compare at startup (zeros: off; the pad widths are the engine's
++ TF_GLM_WIDE_GRAPHS, compared on their own)."""
+
+- return [self.match, self.most]
++ return [self.match, self.most, self.reply_match, self.miss_most]
++
++ def drafts(self, context: Sequence[int]) -> CopyDrafts:
++ """A request's index: ``context`` is its prompt and pending token (the reply's first token)."""
++
++ return CopyDrafts(context, self.match, self.most, prompt=max(len(context) - 1, 0),
++ reply_match=self.reply_match, pad=self.pad, miss_most=self.miss_most)
+
+
+ class CopyDrafts:
+ """One sequence's context (prompt, then committed reply tokens and the pending one) and its copy proposals."""
+
+- def __init__(self, context: Sequence[int], match: int = MATCH, most: int = MOST) -> None:
++ def __init__(self, context: Sequence[int], match: int = MATCH, most: int = MOST, *, prompt: int = 0,
++ reply_match: int = 0, pad: Sequence[int] = (), miss_most: int = 0) -> None:
++ """``prompt``: how many leading context tokens are the prompt (occurrences starting at or past it are the
++ reply's, which need ``reply_match`` tokens when that is more than ``match``); ``pad``: window widths past
++ GRAPHED rows to pad a proposal's window up to (``propose``); ``miss_most``: drafts a copied round after one
++ that missed (0: ``most`` always)."""
++
+ if match < 1 or most < 1:
+ raise ValueError("match and most must be positive")
+ self.match, self.most = int(match), int(most)
++ self.prompt = int(prompt)
++ self.reply_match = int(reply_match) if int(reply_match) > self.match else 0
++ self.pad = tuple(sorted(int(r) for r in pad if int(r) > GRAPHED))
++ self.miss_most = int(miss_most)
++ self.proposed = 0 # drafts of the last proposal not yet settled by ``extend``
++ self.missed = False # the last settled copied round kept fewer than all of its drafts
+ n = len(context)
+ self.buf = np.empty((max(1024, 2 * n),), dtype=np.int32)
+ self.buf[:n] = np.asarray(context, dtype=np.int32) if n else 0
+@@ -71,11 +114,15 @@ class CopyDrafts:
+ return self.buf[:self.length].tolist()
+
+ def extend(self, tokens: Sequence[int]) -> None:
+- """Committed tokens (the last one is the next round's pending token) join the context."""
++ """Committed tokens (the last one is the next round's pending token) join the context; after a proposal,
++ they settle whether its round kept all of its copied drafts (they then number at least those plus one)."""
+
+ k = len(tokens)
+ if not k:
+ return
++ if self.proposed:
++ self.missed = k <= self.proposed
++ self.proposed = 0
+ if self.length + k > self.buf.shape[0]:
+ grown = np.empty((2 * (self.length + k),), dtype=np.int32)
+ grown[:self.length] = self.buf[:self.length]
+@@ -97,13 +144,28 @@ class CopyDrafts:
+ if not hits.size:
+ break
+ hits = hits[ctx[hits + k] == q[k]]
++ extra = self.reply_match - n if self.reply_match else 0
++ if extra and hits.size:
++ # an occurrence starting inside the reply: the extra tokens before it must match too
++ inside = hits >= self.prompt
++ ok = ~inside | ((hits >= extra) & (L - n - extra >= 0))
++ for k in range(1, extra + 1):
++ sel = inside & ok
++ if not sel.any():
++ break
++ ok[sel] = ctx[hits[sel] - k] == ctx[L - n - k]
++ hits = hits[ok]
+ return hits
+
+ def propose(self, room: int | None = None) -> list[int]:
+ """Up to ``min(most, room)`` drafts: what followed the latest earlier occurrence that has that many tokens
+- after it, else the most after any occurrence (the earliest); [] when the suffix never occurred before."""
++ after it, else the most after any occurrence (the earliest); [] when the suffix never occurred before. With
++ ``pad``, a window of more than GRAPHED rows short of a padded width is filled up to it (``room`` allowing)
++ by repeating the last draft."""
+
+- k = self.most if room is None else min(self.most, int(room))
++ most = min(self.most, self.miss_most) if self.missed and self.miss_most else self.most
++ k = most if room is None else min(most, int(room))
++ self.proposed = 0
+ if k < 1:
+ return []
+ hits = self.starts()
+@@ -112,4 +174,18 @@ class CopyDrafts:
+ L, n = self.length, self.match
+ full = hits[hits <= L - n - k]
+ s = int(full[-1]) if full.size else int(hits[0])
+- return self.buf[s + n:min(s + n + k, L)].tolist()
++ out = self.buf[s + n:min(s + n + k, L)].tolist()
++ self.proposed = len(out) # the copied drafts (a pad's repeats may miss without counting)
++ return self.padded(out, room)
++
++ def padded(self, drafts: list[int], room: int | None = None) -> list[int]:
++ """``drafts`` filled up to the next ``pad`` width's window by repeating the last one, when their window is
++ wider than GRAPHED rows, narrower than that width, and ``room`` (default ``most``) leaves space for it."""
++
++ rows = 1 + len(drafts)
++ if not self.pad or not drafts or rows <= GRAPHED:
++ return drafts
++ width = next((w for w in self.pad if w >= rows), 0)
++ if width <= rows or width - 1 > (self.most if room is None else int(room)):
++ 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
+--- tensorfold/families/glm5_next/cuda/engine.py
++++ tensorfold/families/glm5_next/cuda/engine.py
+@@ -17,7 +17,48 @@ DEFAULT_POLICY = "auto"
+ 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)
++
++
++def max_rows(value: str | None = None) -> int:
++ """TF_GLM_MAX_ROWS: the widest verify window, 16 (default) to 64 in steps of 8 (``geometry.MLA_DECODE_ROWS``,
++ which the startup estimate sizes decode buffers for). Wider windows serve copy drafts only (TF_GLM_COPY_MAX up to
++ this minus one); past 16 rows a window's all-gathers exceed TF_ROCE_MAX_KB's default 256 KiB (16 KiB a row) and
++ go through NCCL unless it is raised (TF_ROCE_MAX_KB=512 for 32 rows)."""
++
++ from tensorfold.cuda.geometry import MLA_DECODE_ROWS
++
++ value = (os.environ.get("TF_GLM_MAX_ROWS", "") if value is None else value).strip()
++ if value == "":
++ return 16
++ if not value.isdecimal() or not 16 <= int(value) <= MLA_DECODE_ROWS or int(value) % 8:
++ raise ValueError(f"TF_GLM_MAX_ROWS: 16 to {MLA_DECODE_ROWS} in steps of 8, not {value!r}")
++ return int(value)
++
++
++MAX_ROWS = max_rows() # the widest verify window (a pending token and up to 15 drafts: copy drafts)
++
++
++def wide_graphs(value: str | None = None, most: int | None = None) -> tuple[int, ...]:
++ """TF_GLM_WIDE_GRAPHS: verify-window widths past GRAPH_ROWS (9 to TF_GLM_MAX_ROWS) that also replay CUDA graphs,
++ comma separated (e.g. ``16`` or ``16,32``; off by default: wider windows run eagerly). Copy drafts pad a window
++ that falls short of a captured width up to it (``copy_drafts.CopySettings.pad``). Each width costs a graph a KDA
++ parity, and one more a pool bucket past the dense limit, at startup."""
++
++ most = MAX_ROWS if most is None else most
++ value = (os.environ.get("TF_GLM_WIDE_GRAPHS", "") if value is None else value).strip()
++ if value in ("", "0"):
++ return ()
++ out = set()
++ for part in value.split(","):
++ part = part.strip()
++ if not part.isdecimal() or not max(GRAPH_ROWS) < int(part) <= most:
++ raise ValueError(f"TF_GLM_WIDE_GRAPHS: widths from {max(GRAPH_ROWS) + 1} to {most} (TF_GLM_MAX_ROWS), "
++ f"comma separated, not {value!r}")
++ out.add(int(part))
++ return tuple(sorted(out))
++
++
++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:
+
+ # 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)
++ self.copy = None if serial_only else CopySettings.from_env(MAX_ROWS - 1, pad=WIDE_GRAPHS)
+ 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:
+ 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),
+- prefill_rows, self.grid, KVB_KINDS.index(kvb)] + (self.copy.code() if self.copy is not None else [0, 0]) + \
++ 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]
++ parallel, verify_code, MAX_ROWS, len(WIDE_GRAPHS), sum(WIDE_GRAPHS),
++ max(WIDE_GRAPHS, default=0)]
+ # 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:
+ "TF_GLM_LATENT, TF_GLM_PREFILL_ROWS, TF_GLM_PROMPT_GRID, TF_GLM_KVB, TF_GLM_COPY_*, "
+ "TF_GLM_HC_SPLIT*, TF_GLM_PREFILL_OVERLAP, TF_GLM_OVERLAP_PIECES, TF_GLM_DRAFT_DUMP, "
+ "TF_GLM_DRAFT_QUANT, TF_GLM_SHARED_PREFIX, TF_GLM_DRAFT_RING, TF_GLM_MTP, --parallel, "
+- "TF_GLM_MULTI_VERIFY): "
++ "TF_GLM_MULTI_VERIFY, TF_GLM_MAX_ROWS, TF_GLM_WIDE_GRAPHS): "
+ 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:
+
+ 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,
+- graph_rows=GRAPH_ROWS, long_context=long_context,
++ graph_rows=GRAPH_ROWS + WIDE_GRAPHS, long_context=long_context,
+ taps=self.drafter.tap_layers if self.drafter is not None else (), grid=self.grid,
+ split=self.split, mtp_rows=MTP_ROWS, streams=parallel, pool_rows=pool_rows)
+ if self.e.pbuf.split is not None:
+ self.e.pbuf.split.warm() # both ranks: open the send/receive connection now
+ if rank == 0:
+ print(f"[tensorfold] {self.split.describe()}", flush=True)
++ c = self.copy
++ if rank == 0 and (WIDE_GRAPHS or MAX_ROWS != 16 or (c is not None and (c.reply_match or c.miss_most))):
++ print(f"[tensorfold] verify windows up to {MAX_ROWS} rows, CUDA graphs for "
++ f"{', '.join(map(str, GRAPH_ROWS + WIDE_GRAPHS))} rows (TF_GLM_MAX_ROWS, TF_GLM_WIDE_GRAPHS)"
++ + (f"; copies from the reply match {c.reply_match} tokens (TF_GLM_COPY_REPLY_MATCH)"
++ if c is not None and c.reply_match else "")
++ + (f"; {c.miss_most} copied drafts after a copied round that missed (TF_GLM_COPY_MISS_MAX)"
++ if c is not None and c.miss_most else ""), flush=True)
+ 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:
+ 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
+- from .copy_drafts import CopyDrafts
+-
+- copies = CopyDrafts(list(prompt) + [first], self.copy.match, self.copy.most)
++ copies = self.copy.drafts(list(prompt) + [first])
+ if policy is None:
+ res = serial_decode(self.e, first, max_tokens, sampling, stop_eos=stop_eos, on_tokens=on_tokens)
+ elif self.dump is not None and drafter is not None: # serial's reply, the drafter's view recorded
+diff --git tensorfold/families/glm5_next/cuda/multi.py tensorfold/families/glm5_next/cuda/multi.py
+index f62a69d..bf316fd 100644
+--- tensorfold/families/glm5_next/cuda/multi.py
++++ tensorfold/families/glm5_next/cuda/multi.py
+@@ -794,7 +794,9 @@ class MultiDecoder:
+ lane.decoding = True
+ s.started = time.perf_counter()
+ if lane.policy is not None and self.g.copy is not None:
+- lane.copies = CopyDrafts(list(prompt) + [first], self.g.copy.match, self.g.copy.most)
++ c = self.g.copy # no pads: batched windows are not the single-stream widths
++ lane.copies = CopyDrafts(list(prompt) + [first], c.match, c.most, prompt=n, reply_match=c.reply_match,
++ miss_most=c.miss_most)
+ if lane.policy is not None:
+ lane.depth = min(lane.policy.next(0, 0), s.count - 1)
+ return first
diff --git a/patches/0036-glm-prefill-overlap2.patch b/patches/0036-glm-prefill-overlap2.patch
new file mode 100644
index 0000000..9f77a4d
--- /dev/null
+++ b/patches/0036-glm-prefill-overlap2.patch
@@ -0,0 +1,327 @@
+diff --git tensorfold/families/glm5_next/cuda/forward.py tensorfold/families/glm5_next/cuda/forward.py
+index 42f2929..ef785e7 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
+ return partials(w, b, R, fill)
+
+
+-def kda_block(layer: LayerW, w: Weights, st: State, b: Buffers, R: int) -> torch.Tensor:
++def undone(R: int, done: tuple[int, int] | None) -> list[tuple[int, int]]:
++ """The row ranges of [0, R) outside ``done`` (a block's front already run on those rows, TF_GLM_PREFILL_OVERLAP=2),
++ in row order; every row when ``done`` is None."""
++
++ if done is None:
++ return [(0, R)]
++ lo, hi = done
++ return [(a, z) for a, z in ((0, min(lo, R)), (max(hi, 0), R)) if z > a]
++
++
++def kda_front(layer: LayerW, b: Buffers, lo: int, hi: int) -> None:
++ """A prompt chunk's KDA input projections of rows lo .. hi (row-independent: the prompt matmul's bits for any
++ row range; BF16 / FP8 projections of an EXL3 checkpoint keep rows apart too)."""
++
++ k = layer.kda
++ p = b.kproj[0, lo:hi]
++ mm(b, b.normed[lo:hi], k.proj, b.xs[lo:hi], p)
++ mm(b, p[:, k.fa_off:k.fa_off + 128], k.fb, None, b.ka[lo:hi])
++ mm(b, p[:, k.ga_off:k.ga_off + 128], k.gb, None, b.kg[lo:hi])
++
++
++def kda_block(layer: LayerW, w: Weights, st: State, b: Buffers, R: int, done: tuple[int, int] | None = None
++ ) -> torch.Tensor:
++ """``done``: rows whose projections ``kda_front`` already wrote (a prompt chunk, TF_GLM_PREFILL_OVERLAP=2)."""
++
+ c = w.cfg
+ k = layer.kda
+ li = st.kda_index[layer.index]
+ p = b.kproj[0, :R] if b.prefill else st.proj[li, :R]
+ pre = b.prefill
+ with prof.timed("kda: projections"):
+- mm(b, b.normed[:R], k.proj, b.xs[:R], p)
+- fa = p[:, k.fa_off:k.fa_off + 128]
+- ga = p[:, k.ga_off:k.ga_off + 128]
+- 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])
++ if pre:
++ for lo, hi in undone(R, done):
++ kda_front(layer, b, lo, hi)
++ else:
++ mm(b, b.normed[:R], k.proj, b.xs[:R], p)
++ fa = p[:, k.fa_off:k.fa_off + 128]
++ 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])
+ 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
+ return out_proj(w, b, out, k.o, qmm.group_sums(out, b.kxs[:R]), R)
+
+
++def dsa_front(layer: LayerW, w: Weights, b: Buffers, lo: int, hi: int) -> None:
++ """DSA's projection, query / latent norms and query expansion of rows lo .. hi (row-independent kernels)."""
++
++ c = w.cfg
++ a = layer.dsa
++ mm(b, b.normed[lo:hi], a.proj, b.xs[lo:hi], b.dp[lo:hi])
++ glue.rmsnorm(b.dp[lo:hi, :c.q_lora], a.q_norm, c.eps, b.qr[lo:hi], b.xs_qr[lo:hi])
++ glue.rmsnorm(b.dp[lo:hi, c.q_lora:], a.kv_norm, c.eps, b.lat[lo:hi], b.xs_lat[lo:hi])
++ mm(b, b.qr[lo:hi], a.q_b, b.xs_qr[lo:hi], b.q[lo:hi].view(hi - lo, a.heads * c.qk_dim))
++
++
+ 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:
+- """Write every index key and pool; rows past the dense limit attend to their top-512 pools (host_pos eager, or sparse_np in a captured graph)."""
++ sparse_np: int | None = None, done: tuple[int, int] | None = None) -> torch.Tensor:
++ """Write every index key and pool; rows past the dense limit attend to their top-512 pools (host_pos eager, or sparse_np in a captured graph). ``done``: rows ``dsa_front`` already ran on (TF_GLM_PREFILL_OVERLAP=2)."""
+
+ c = w.cfg
+ a = layer.dsa
+- mm(b, b.normed[:R], a.proj, b.xs[:R], b.dp[:R])
+- glue.rmsnorm(b.dp[:R, :c.q_lora], a.q_norm, c.eps, b.qr[:R], b.xs_qr[:R])
+- glue.rmsnorm(b.dp[:R, c.q_lora:], a.kv_norm, c.eps, b.lat[:R], b.xs_lat[:R])
++ for lo, hi in undone(R, done):
++ dsa_front(layer, w, b, lo, hi)
+ HL = a.heads
+- mm(b, b.qr[:R], a.q_b, b.xs_qr[:R], b.q[:R].view(R, HL * c.qk_dim))
+ 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
+ return out_proj(w, b, o, a.o, qmm.group_sums(o, b.xs_ao[:R]), R)
+
+
+-def mlp_block(layer: LayerW, w: Weights, b: Buffers, R: int) -> torch.Tensor:
++def mlp_front(layer: LayerW, w: Weights, b: Buffers, lo: int, hi: int) -> None:
+ m = layer.mlp
+- mm(b, b.normed[:R], m.gu, b.xs[:R], b.gu[:R])
+- glue.swiglu(b.gu[:R], b.act[:R], b.xs_act[:R], w.cfg.limit)
++ mm(b, b.normed[lo:hi], m.gu, b.xs[lo:hi], b.gu[lo:hi])
++ glue.swiglu(b.gu[lo:hi], b.act[lo:hi], b.xs_act[lo:hi], w.cfg.limit)
++
++
++def mlp_block(layer: LayerW, w: Weights, b: Buffers, R: int, done: tuple[int, int] | None = None) -> torch.Tensor:
++ m = layer.mlp
++ for lo, hi in undone(R, done):
++ mlp_front(layer, w, b, lo, hi)
+ return out_proj(w, b, b.act[:R], m.down, b.xs_act[:R], R)
+
+
+-def moe_block(layer: LayerW, w: Weights, b: Buffers, R: int) -> torch.Tensor:
++def shared_front(layer: LayerW, w: Weights, b: Buffers, lo: int, hi: int) -> None:
++ """The MoE's shared expert (an EXL3 checkpoint's, BF16 / FP8 / 4-bit matmuls) on rows lo .. hi: b.sy."""
++
++ s, c = layer.moe.shared, w.cfg
++ with prof.timed("moe: shared expert"):
++ mm(b, b.normed[lo:hi], s.gu, b.xs[lo:hi], b.sgu[lo:hi])
++ 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)
++
++
++def moe_block(layer: LayerW, w: Weights, b: Buffers, R: int, done: tuple[int, int] | None = None) -> torch.Tensor:
++ """``done``: rows whose shared expert ``shared_front`` already ran (TF_GLM_PREFILL_OVERLAP=2)."""
++
+ 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:
+
+ 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
+
+ def fill(lo: int, hi: int) -> None:
+- with prof.timed("moe: shared expert"):
+- mm(b, b.normed[lo:hi], s.gu, b.xs[lo:hi], b.sgu[lo:hi])
+- 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)
++ for a, z in undone(hi, done): # rows lo .. hi the front has not run on
++ if max(a, lo) < z:
++ shared_front(layer, w, b, max(a, lo), z)
+ 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:
+
+
+ def _mixer(layer: LayerW, w: Weights, st: State, b: Buffers, R: int, nch: int | None, host_pos: int | None,
+- sparse_np: int | None) -> torch.Tensor | None:
++ sparse_np: int | None, done: tuple[int, int] | None = None) -> torch.Tensor | None:
+ """The layer's KDA or DSA block on b.normed: every rank's partials, or None row-split (``partials``)."""
+
+ if layer.kind == "kda":
+ with prof.timed("kda"):
+- return kda_block(layer, w, st, b, R)
++ return kda_block(layer, w, st, b, R, done)
+ di = st.dsa_index[layer.index]
+ with prof.timed("dsa (total)"):
+ return dsa_block(layer, w, st.kc[di], st.vc[di], st.pos_dev, b, R, nch,
+- st.index[di] if st.index is not None else None, host_pos, sparse_np)
++ st.index[di] if st.index is not None else None, host_pos, sparse_np, done)
+
+
+-def _ffn(layer: LayerW, w: Weights, b: Buffers, R: int) -> torch.Tensor | None:
++def _ffn(layer: LayerW, w: Weights, b: Buffers, R: int, done: tuple[int, int] | None = None) -> torch.Tensor | None:
+ with prof.timed("moe (total)" if layer.mlp is None else "mlp"):
+- return mlp_block(layer, w, b, R) if layer.mlp is not None else moe_block(layer, w, b, R)
++ return mlp_block(layer, w, b, R, done) if layer.mlp is not None else moe_block(layer, w, b, R, done)
++
++
++def mixer_front(layer: LayerW, w: Weights, b: Buffers):
++ """A prompt chunk's KDA / DSA front as ``front(lo, hi)`` (``hcsplit.HcSplit.glue``)."""
++
++ if layer.kind == "kda":
++ return lambda lo, hi: kda_front(layer, b, lo, hi)
++ return lambda lo, hi: dsa_front(layer, w, b, lo, hi)
++
++
++def ffn_front(layer: LayerW, w: Weights, b: Buffers):
++ """The dense MLP's gate/up or the MoE's shared expert as ``front(lo, hi)``; None for a MoE without a separate
++ shared expert (an MLX checkpoint's routes it with the others)."""
++
++ if layer.mlp is not None:
++ return lambda lo, hi: mlp_front(layer, w, b, lo, hi)
++ if layer.moe.shared is not None:
++ return lambda lo, hi: shared_front(layer, w, b, lo, hi)
++ return None
+
+
+ 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
+ sp = b.split
+ layers = w.layers
+ sp.begin(R)
++ fronts = sp.settings.fronts
+ try:
+ Rp = sp.Rp # R, or R + 1 with a zero pad row for an odd chunk
+ first, h = layers[0], layers[0].attn_hc
+ glue.hc_pre(b.x[:Rp], h.fn, h.base, h.scale, first.in_norm, b.normed[:Rp], b.xs[:Rp], b.post[:Rp],
+ 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):
+- _mixer(layer, w, st, b, R, nch, host_pos, None)
++ _mixer(layer, w, st, b, R, nch, host_pos, None, done)
++ front = ffn_front(layer, w, b) if fronts else None
+ with prof.timed("hc"):
+- sp.glue(layer.ffn_hc, layer.post_norm)
+- _ffn(layer, w, b, R)
++ sp.glue(layer.ffn_hc, layer.post_norm, front=front)
++ _ffn(layer, w, b, R, sp.own() if front is not None else None)
+ nxt = layers[i + 1] if i + 1 < len(layers) else None
++ front = mixer_front(nxt, w, b) if fronts and nxt is not None else None
+ with prof.timed("hc (layer end)"):
+ sp.glue(nxt.attn_hc if nxt is not None else None, nxt.in_norm if nxt is not None else None,
+- taps=tuple(b.tap_at.get(layer.index, ())), final=nxt is None)
++ taps=tuple(b.tap_at.get(layer.index, ())), final=nxt is None, front=front)
++ done = sp.own() if front is not None else None
+ finally:
+ sp.finish()
+
+diff --git tensorfold/families/glm5_next/cuda/hcsplit.py tensorfold/families/glm5_next/cuda/hcsplit.py
+index 17acbf9..5426bb7 100644
+--- tensorfold/families/glm5_next/cuda/hcsplit.py
++++ tensorfold/families/glm5_next/cuda/hcsplit.py
+@@ -18,6 +18,13 @@ peer's rows of its partial first, piece by piece, each piece's swap starting as
+ the glue piece by piece, each piece waiting only for its own partial rows and its normed rows swapped while the next
+ piece's glue runs. Events order the two streams; the arithmetic is the same kernels on the same rows.
+
++TF_GLM_PREFILL_OVERLAP=2 also runs the next block's row-independent front (``glue``'s ``front``: KDA's input
++projections, DSA's projections, norms and query expansion, the dense MLP's gate/up, the shared expert of the MoE) on
++this rank's rows of each piece right after that piece's glue, while its normed rows (and the later pieces' partials)
++are still on the wire; the block then runs its front on the peer's rows once they have arrived, and the rest as
++before. Without it the main stream waited for the last piece's swap with nothing to do. The fronts are row-independent
++kernels (the prompt matmul gives every row range the same bits), so every bit is still the unsplit path's.
++
+ TF_GLM_HC_EXCHANGE: ``p2p`` (the default) swaps rows with ncclSend/ncclRecv; ``gather`` uses the NCCL all-gather
+ instead (whole halves, one piece: the partial halves out of place into the unused all-gather buffer, the bf16 rows in
+ place), the same bytes on the wire, for when NCCL's point-to-point path is slower or misbehaves on a fabric."""
+@@ -58,19 +65,28 @@ class SplitSettings:
+ pieces: int = 2 # TF_GLM_OVERLAP_PIECES: row pieces a site's swaps run in (overlap, p2p only)
+ min_rows: int = 64 # TF_GLM_HC_SPLIT_MIN_ROWS: shorter chunks (a prompt's tail) run unsplit
+ exchange: str = "p2p" # TF_GLM_HC_EXCHANGE: p2p (ncclSend/ncclRecv) or gather (the all-gather)
++ fronts: bool = False # TF_GLM_PREFILL_OVERLAP=2: the next block's front on own rows during the swaps
++
++ def __post_init__(self) -> None:
++ if self.fronts and not self.overlap:
++ raise ValueError("the blocks' fronts run during the overlapped swaps: they need the overlap")
+
+ @classmethod
+ def from_env(cls, env=None) -> "SplitSettings":
+ env = os.environ if env is None else env
+ split = _flag(env, "TF_GLM_HC_SPLIT")
+- overlap = _flag(env, "TF_GLM_PREFILL_OVERLAP")
++ level = str(env.get("TF_GLM_PREFILL_OVERLAP", "") or "0").strip()
++ if level not in ("0", "1", "2"):
++ raise ValueError(f"TF_GLM_PREFILL_OVERLAP: 0, 1 or 2, not {level!r}")
++ overlap = level != "0"
+ if overlap and not split:
+- raise ValueError("TF_GLM_PREFILL_OVERLAP=1 overlaps the row-split exchanges: it needs TF_GLM_HC_SPLIT=1")
++ raise ValueError(f"TF_GLM_PREFILL_OVERLAP={level} overlaps the row-split exchanges: it needs "
++ "TF_GLM_HC_SPLIT=1")
+ exchange = str(env.get("TF_GLM_HC_EXCHANGE", "") or "p2p").strip()
+ if exchange not in EXCHANGES:
+ raise ValueError(f"TF_GLM_HC_EXCHANGE: {' or '.join(EXCHANGES)}, not {exchange!r}")
+ return cls(split, overlap, _int(env, "TF_GLM_OVERLAP_PIECES", 2, 1, 8),
+- _int(env, "TF_GLM_HC_SPLIT_MIN_ROWS", 64, 2, 16384), exchange)
++ _int(env, "TF_GLM_HC_SPLIT_MIN_ROWS", 64, 2, 16384), exchange, fronts=level == "2")
+
+ def piece_count(self) -> int:
+ return self.pieces if self.overlap and self.exchange == "p2p" else 1
+@@ -78,7 +94,8 @@ class SplitSettings:
+ def code(self) -> list[int]:
+ if not self.split:
+ return [0, 0, 0, 0, 0]
+- return [1, int(self.overlap), self.piece_count(), self.min_rows, EXCHANGES.index(self.exchange)]
++ return [1, int(self.overlap) + int(self.fronts), self.piece_count(), self.min_rows,
++ EXCHANGES.index(self.exchange)]
+
+ def describe(self) -> str:
+ what = "rows split between the ranks"
+@@ -86,6 +103,8 @@ class SplitSettings:
+ if self.overlap:
+ n = self.piece_count()
+ what += f" on a second stream{f' in {n} pieces' if n > 1 else ''}"
++ if self.fronts:
++ what += ", the next block's front on own rows meanwhile"
+ return f"prompt chunks' hyper-connections: {what} (chunks of {self.min_rows}+ rows)"
+
+
+@@ -214,9 +233,18 @@ class HcSplit:
+ self.ev_part[j].record(self.stream)
+ self._fill(fill, mine, mine + self.H)
+
+- def glue(self, hc=None, norm=None, taps: tuple[int, ...] = (), final: bool = False) -> None:
++ def own(self) -> tuple[int, int]:
++ """This rank's rows of the chunk, [lo, hi) (the pad row left out)."""
++
++ return self.mine(), min(self.mine() + self.H, self.R)
++
++ def glue(self, hc=None, norm=None, taps: tuple[int, ...] = (), final: bool = False,
++ front: Callable[[int, int], None] | None = None) -> None:
+ """hc_post of this rank's rows, then (in order) the layer's DFlash2 taps, the final stream mean (``final``)
+- and the next hc_pre (``hc``, ``norm``); their rows swapped with the peer's."""
++ and the next hc_pre (``hc``, ``norm``); their rows swapped with the peer's. ``front(lo, hi)``
++ (TF_GLM_PREFILL_OVERLAP=2): the next block's row-independent start on this rank's rows of each piece, on the
++ main stream right after the piece's glue, while its swap (and the later pieces' partials) are on the wire;
++ the caller runs it on the peer's rows (``own`` is what was done) after this returns."""
+
+ b, c = self.b, self.w.cfg
+ mine = self.mine()
+@@ -239,11 +267,15 @@ class HcSplit:
+ b.comb[lo:hi], b.hcpart[lo:hi], c.eps, c.hc_eps, c.hc_iters, prompt=True)
+ if self.stream is None:
+ self._swap_rows(j, outs)
++ if front is not None:
++ self._fill(front, lo, hi)
+ continue
+ self.ev_glue[j].record(main)
+ with torch.cuda.stream(self.stream):
+ self.stream.wait_event(self.ev_glue[j])
+ self._swap_rows(j, outs)
++ if front is not None:
++ self._fill(front, lo, hi)
+ if self.stream is not None:
+ self.ev_done.record(self.stream)
+ main.wait_event(self.ev_done)
diff --git a/patches/0037-cuda-nucleus-union.patch b/patches/0037-cuda-nucleus-union.patch
new file mode 100644
index 0000000..6af2cf3
--- /dev/null
+++ b/patches/0037-cuda-nucleus-union.patch
@@ -0,0 +1,75 @@
+diff --git tensorfold/cuda/sampling.py tensorfold/cuda/sampling.py
+index fd435f8..5bc101e 100644
+--- tensorfold/cuda/sampling.py
++++ tensorfold/cuda/sampling.py
+@@ -5,6 +5,7 @@ from __future__ import annotations
+ from collections.abc import Callable, Sequence
+ from fractions import Fraction
+ import math
++import os
+
+ import numpy as np
+ import torch
+@@ -123,6 +124,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)
++ if drawn is None and union_cover() and int(got[4].max()) > WIDER: # wider candidates first (the same draw)
++ drawn = _draw(_shares(gather, scaled, mass, WIDER, offset, id_map), positions, sampling)
+ 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):
+ both[:, :, 2 * count:3 * count], both[:, :, 3 * count], both[:, :, 3 * count + 1])
+
+
++def union_cover() -> bool:
++ """TENSORFOLD_NUCLEUS_UNION=1: ``_draw``'s top_p coverage test on every rank's candidates together (the same
++ draws, fewer whole-shard reads on several ranks); every rank must be given the same setting."""
++
++ return os.environ.get("TENSORFOLD_NUCLEUS_UNION", "0") == "1"
++
++
++def _union_covers(vals, ids, mass, widths, r: int, need: int) -> bool:
++ """Whether row r's top_p nucleus lies inside the ranks' candidates taken together: walking them merged (value
++ down, then id) to the cumulative mass ``need`` stops at a value v* above the last candidate of every rank that
++ did not send its whole shard. A token no rank sent is at or below its rank's last candidate, below v*, so the
++ merged walk is the whole vocabulary's up to v*: the same nucleus, the same draw as from whole shards."""
++
++ partial = [k for k in range(vals.shape[0]) if int((ids[k, r] >= 0).sum()) != widths[k, r]]
++ if not partial: # every rank sent its whole shard
++ return True
++ v, i, m = vals[:, r].reshape(-1), ids[:, r].reshape(-1), mass[:, r].reshape(-1)
++ order = np.lexsort((i, -v))
++ order = order[i[order] >= 0]
++ at = np.nonzero(np.cumsum(m[order]) >= need)[0]
++ if not len(at):
++ return False
++ top = v[order][int(at[0])]
++ for k in partial:
++ if not top > vals[k, r][ids[k, r] >= 0].min():
++ return False
++ return True
++
++
++WIDER = 16 * NUCLEUS # TENSORFOLD_NUCLEUS_UNION: candidates a rank reads when a row's nucleus runs past NUCLEUS
++
++
+ def _draw(got, positions, s: Sampling) -> list[tuple[int, float]] | None:
+ """Each row's (token, its share of the mass) from every rank's candidates; None if a row needs whole shards."""
+
+ vals, ids, mass, sums, widths = got
+ cut = 0.0 < s.top_p < 1.0
++ union = cut and union_cover()
+ drawn = []
+ for r, position in enumerate(positions):
+ total = int(sums[:, r].sum())
+ need = math.ceil(Fraction(s.top_p) * total) if cut else None
+ floor = vals[:, r, :].max() + s.min_log # the min_p cut (-inf when off)
+- for k in range(vals.shape[0]): # a rank's share must end inside its candidates
++ if union and not _union_covers(vals, ids, mass, widths, r, need):
++ return None
++ for k in range(0 if not union else vals.shape[0], vals.shape[0]): # a rank's share inside its candidates
+ real = int((ids[k, r] >= 0).sum())
+ if real == widths[k, r]: # its whole shard
+ continue
diff --git a/patches/0038-glm-multi-rounds.patch b/patches/0038-glm-multi-rounds.patch
new file mode 100644
index 0000000..1381dbb
--- /dev/null
+++ b/patches/0038-glm-multi-rounds.patch
@@ -0,0 +1,833 @@
+diff --git tensorfold/families/glm5_next/cuda/decode.py tensorfold/families/glm5_next/cuda/decode.py
+index febb0eb..6732311 100644
+--- tensorfold/families/glm5_next/cuda/decode.py
++++ tensorfold/families/glm5_next/cuda/decode.py
+@@ -160,7 +160,9 @@ class Engine:
+ g = self.graphs.main.get((R, self.st.parity))
+ elif self.graphs is not None and self.st.pos >= self.w.cfg.dense_limit and self.st.index is not None:
+ # every row past the dense limit: the sparse graph for this pool bucket (same kernels as eager)
+- bucket = pool_bucket(self.st.pos, R, self.st.index[0][2].shape[0] - 2)
++ # the pool buckets the graphs were captured for: the home view's (a stream at home with a smaller
++ # extent scores pools past its own too, all past its visible ones: -inf, the same selection)
++ bucket = pool_bucket(self.st.pos, R, self.home.index[0][2].shape[0] - 2)
+ g, kind = self.graphs.sparse.get((R, self.st.parity, bucket)), "sparse"
+ if g is not None:
+ self.replays[kind] += 1
+@@ -181,7 +183,7 @@ class Engine:
+ 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):
+- bucket = pool_bucket(self.st.mtp_len, n, self.st.index[-1][2].shape[0] - 2)
++ bucket = pool_bucket(self.st.mtp_len, n, self.home.index[-1][2].shape[0] - 2)
+ g, kind = self.graphs.sparse_mtp.get((n, bucket)), "sparse_mtp"
+ 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
+--- tensorfold/families/glm5_next/cuda/dflash2.py
++++ tensorfold/families/glm5_next/cuda/dflash2.py
+@@ -508,11 +508,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,
+- round_ms: tuple[float, ...] | None = None) -> list[int]:
++ round_ms: tuple[float, ...] | None = None, confs: list | None = None) -> list[int]:
+ """Choose candidates with selector edges and target keyed noise; stop below cumulative confidence, always
+ keeping the first draft. ``beta`` > 0: the confidences are noise-aware (``noisy_confidence``); with
+ ``round_ms`` (ms of a round of k drafts, k = 0..) the chain is walked whole and cut at ``best_depth`` of
+- them instead (``confidence`` unused). Only where the chain stops changes: the picks are the same."""
++ them instead (``confidence`` unused). Only where the chain stops changes: the picks are the same. ``confs``
++ (a list): the chain is walked whole and each pick's confidence (noise-aware with ``beta``, else the
++ softmax share of its score) appended to it, for a caller that cuts the chains itself (``multi``'s joint
++ allocation)."""
+
+ depth = tokens.shape[0]
+ sampled = sampling is not None and sampling.temperature > 0
+@@ -529,7 +532,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))
+- if noisy:
++ if confs is not None:
++ if noisy:
++ confs.append(noisy_confidence(score, noise[d] if noise is not None else None, j, beta))
++ else:
++ p = np.exp(score - score.max())
++ confs.append(float(p[j] / p.sum()))
++ elif noisy:
+ 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:
+ break
+ prev = int(tokens[d, j])
+ out.append(prev)
+- if noisy and round_ms is not None:
++ if noisy and round_ms is not None and confs is None:
+ out = out[:best_depth(conf, round_ms)]
+ return out
+
+diff --git tensorfold/families/glm5_next/cuda/engine.py tensorfold/families/glm5_next/cuda/engine.py
+index 109dbf0..8154dc6 100644
+--- tensorfold/families/glm5_next/cuda/engine.py
++++ tensorfold/families/glm5_next/cuda/engine.py
+@@ -506,17 +506,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())
++ from tensorfold.cuda.sampling import union_cover
++
+ verify_code = 0
+ if parallel > 1: # serial and batched verify windows make different collectives
+ from .multi import verify_kind
+
+ verify_code = 1 + ("batched", "serial").index(verify_kind())
++ from .multi_tune import MultiSettings
++
++ verify_code = [verify_code] + MultiSettings.from_env().code()
++ else:
++ verify_code = [verify_code]
+ # 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, 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, MAX_ROWS, len(WIDE_GRAPHS), sum(WIDE_GRAPHS),
+- max(WIDE_GRAPHS, default=0)]
++ parallel, *verify_code, int(union_cover()), MAX_ROWS, len(WIDE_GRAPHS),
++ sum(WIDE_GRAPHS), max(WIDE_GRAPHS, default=0)]
+ # 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:
+ "TF_GLM_LATENT, TF_GLM_PREFILL_ROWS, TF_GLM_PROMPT_GRID, TF_GLM_KVB, TF_GLM_COPY_*, "
+ "TF_GLM_HC_SPLIT*, TF_GLM_PREFILL_OVERLAP, TF_GLM_OVERLAP_PIECES, TF_GLM_DRAFT_DUMP, "
+ "TF_GLM_DRAFT_QUANT, TF_GLM_SHARED_PREFIX, TF_GLM_DRAFT_RING, TF_GLM_MTP, --parallel, "
+- "TF_GLM_MULTI_VERIFY, TF_GLM_MAX_ROWS, TF_GLM_WIDE_GRAPHS): "
++ "TF_GLM_MULTI_VERIFY, TF_GLM_MULTI_SAMPLER / _DEPTH / _OVERHEAD_MS / _ASYNC / _LONE, "
++ "TENSORFOLD_NUCLEUS_UNION, TF_GLM_MAX_ROWS, TF_GLM_WIDE_GRAPHS): "
+ 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:
+ 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 "
+- f"{self.multi.share:g})", flush=True)
++ f"{self.multi.share:g}); {self.multi.tune.describe()}", flush=True)
++ if self.multi.row_ms is not None:
++ print("[tensorfold] --parallel batched window ms by rows: " +
++ " ".join(f"{i + 1}:{ms:.1f}" for i, ms in enumerate(self.multi.row_ms)), flush=True)
+
+ def _calibrate(self) -> dict:
+ """Per-piece ms for ``drafter_choice.DrafterChoice``: fastest of interleaved passes, equal on both ranks."""
+diff --git tensorfold/families/glm5_next/cuda/multi.py tensorfold/families/glm5_next/cuda/multi.py
+index bf316fd..d1ed1f4 100644
+--- tensorfold/families/glm5_next/cuda/multi.py
++++ tensorfold/families/glm5_next/cuda/multi.py
+@@ -39,12 +39,14 @@ import torch
+ from tensorfold.cuda.scheduler import Scheduler
+ from tensorfold.cuda.streams import Stream, next_fill
+
++from .multi_tune import MultiSettings, RoundProfile, allocate, reach_of, sample_packed, scaled_confidence
+ from .pool import ALIGN, Pool, align_up
+ from .verify import BatchedVerify, Segment, SerialVerify, Verified
+
+-ADMIT, EVICT, MOVE, GROW, FILL, ROUND, FINISH, IDLE = range(1, 9)
++ADMIT, EVICT, MOVE, GROW, FILL, ROUND, FINISH, IDLE, SLOT = range(1, 10)
+ OPS = {ADMIT: "ADMIT", EVICT: "EVICT", MOVE: "MOVE", GROW: "GROW", FILL: "FILL", ROUND: "ROUND", FINISH: "FINISH",
+- IDLE: "IDLE"}
++ IDLE: "IDLE", SLOT: "SLOT"}
++LONE_LEFT = 16 # a lone stream moves home only with at least this many tokens still to go
+ DONE, CANCELLED, REQUEUED = 0, 1, 2 # FINISH reasons
+ MAX_WINDOW = 32 # rows of every stream's windows together in one round
+ SHARED_SLOTS = 2 # shared-prefix points an ADMIT carries (engine.SHARED_MOST)
+@@ -266,7 +268,8 @@ class NoRoom(RuntimeError):
+ class MultiDecoder:
+ """The ``GlmScheduler``'s decoder, on rank 0 (deciding) and rank 1 (``follow``, applying)."""
+
+- def __init__(self, engine, streams: int, *, verify=None, drafts=None, draft_graphs: bool | None = None) -> None:
++ def __init__(self, engine, streams: int, *, verify=None, drafts=None, draft_graphs: bool | None = None,
++ tune: MultiSettings | None = None, row_ms: Sequence[float] | None = None) -> None:
+ """``drafts``: the multi-stream drafter (``dflash2_multi.MultiDrafter``; default one over the engine's
+ drafter, its graphs captured unless TF_GLM_MULTI_DRAFT_GRAPHS=0); ``verify``: the verify seam (default
+ ``SerialVerify``)."""
+@@ -304,6 +307,22 @@ class MultiDecoder:
+ else:
+ verify = SerialVerify(e, taps=self.drafts is not None)
+ self.verify = verify
++ # speed settings (multi_tune): the sampler's gathers, the drafts' depth, async messages, the profile
++ self.tune = tune if tune is not None else MultiSettings.from_env()
++ self.profiles = None
++ if self.tune.profile and self.rank == 0:
++ self.profiles = {False: RoundProfile(self.tune.profile, label="batched"),
++ True: RoundProfile(self.tune.profile, label="lone stream, one-stream graphs")}
++ self.profile = None # the current round's (``profiles``), or None
++ self.solo_verify = SerialVerify(e, taps=self.drafts is not None)
++ graphs = getattr(e, "graphs", None)
++ self.lone_rows = max((r for r, _ in getattr(graphs, "main", {})), default=0)
++ self.row_ms = list(row_ms) if row_ms is not None else None
++ if self.tune.depth == "joint" and self.row_ms is None:
++ self.row_ms = self._time_rows()
++ if self.profiles is not None and isinstance(self.verify, BatchedVerify) and self.verify.graphs:
++ self._compare_paths()
++ self.msg = None # TF_GLM_MULTI_ASYNC: rank 0's pinned message staging
+ self.lanes: dict[int, Lane] = {} # by sid, in admission order
+ self.kept: list = [] # kept prompts (decode.Snapshot + kid, extent), oldest first
+ self.next_sid = self.next_kid = self.next_order = 0
+@@ -352,7 +371,82 @@ class MultiDecoder:
+ self.g._ring()
+ self.idle = False
+ msg, self.outbox = self.outbox, []
+- self.g._share(msg)
++ if self.tune.async_msg:
++ self._send(msg)
++ else:
++ self.g._share(msg)
++
++ def _send(self, values: list[int]) -> None:
++ """Rank 0, TF_GLM_MULTI_ASYNC: ``GlmEngine._share``'s two all-gathers (the length, then the values) without
++ reading anything back: the values go through a pinned staging buffer (reused once its last copy has left),
++ so the host does not wait for the GPU. Rank 1 receives them with its ``_share`` as ever."""
++
++ n = len(values)
++ dev = self.w.device
++ if self.msg is None or self.msg[0].numel() < n + 1:
++ if self.msg is not None:
++ self.msg[2].synchronize()
++ size = max(4096, 2 * (n + 1))
++ pinned = torch.cuda.is_available()
++ self.msg = (torch.zeros((size,), dtype=torch.int32, pin_memory=pinned),
++ torch.zeros((size,), dtype=torch.int32, device=dev),
++ torch.cuda.Event() if pinned else None)
++ host, buf, ready = self.msg
++ if ready is not None:
++ ready.synchronize() # the last message's copy has left the staging buffer
++ host[0] = n
++ if n:
++ host[1:1 + n].numpy()[:] = values
++ buf[:1 + n].copy_(host[:1 + n], non_blocking=True)
++ if ready is not None:
++ ready.record()
++ comm = self.g.comm
++ got = torch.empty((2,), dtype=torch.int32, device=dev)
++ comm.all_gather(buf[:1], got)
++ allv = torch.empty((2 * n,), dtype=torch.int32, device=dev)
++ comm.all_gather(buf[1:1 + n], allv)
++
++ def _time_rows(self, reps: int = 5) -> list[float]:
++ """TF_GLM_MULTI_DEPTH=joint: the batched window's ms for 1 .. MAX_WINDOW rows (its graphs, fastest of
++ ``reps``), the larger of both ranks' (so both allocate alike)."""
++
++ v = self.verify
++ if not isinstance(v, BatchedVerify) or not v.graphs:
++ raise ValueError("TF_GLM_MULTI_DEPTH=joint needs the batched verify window's graphs "
++ "(TF_GLM_MULTI_VERIFY=batched, TF_GLM_MULTI_GRAPHS=1)")
++ mine = torch.tensor(v.time_rows(reps), dtype=torch.float32, device=self.w.device)
++ got = torch.empty((2 * mine.numel(),), dtype=torch.float32, device=self.w.device)
++ self.g.comm.all_gather(mine, got)
++ return [float(x) for x in got.view(2, -1).max(dim=0).values.tolist()]
++
++ def _compare_paths(self, reps: int = 5) -> None:
++ """TF_GLM_MULTI_PROFILE (rank 0, at startup): a lone stream's verify window on the one-stream graphs and on
++ the batched graphs, ms by rows (fastest of ``reps``; slot 0's states cleared after)."""
++
++ e, v = self.e, self.verify
++ start, stop = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
++ solo = v.time_rows(reps)
++ out = []
++ for R in range(1, self.lone_rows + 1):
++ g = e.graphs.main.get((R, e.home.parity))
++ if g is None:
++ continue
++ best = float("inf")
++ for _ in range(reps + 1):
++ start.record()
++ g.replay()
++ stop.record()
++ stop.synchronize()
++ best = min(best, start.elapsed_time(stop))
++ out.append(f"{R}: {best:.2f} vs {solo[R - 1]:.2f}")
++ e.slots.rec[0].zero_()
++ e.slots.conv[0].zero_()
++ print("[tensorfold] multi profile: a lone stream's verify window ms, one-stream graphs vs batched graphs, by "
++ "rows: " + ", ".join(out), flush=True)
++
++ def _row_cost(self, rows: int) -> float:
++ ms = self.row_ms
++ return ms[min(max(rows, 1), len(ms)) - 1] + max(0, rows - len(ms)) * (ms[-1] - ms[-2] if len(ms) > 1 else 0)
+
+ @staticmethod
+ def parse(msg: Sequence[int]) -> list[tuple[int, list[int]]]:
+@@ -720,16 +814,21 @@ class MultiDecoder:
+ return self.lanes[s.sid]
+
+ def _iterate(self) -> list[Stream]:
++ prof = self.profiles[False] if self.profiles is not None else None # prompt chunks count there
+ lane = self._fill_turn()
+ if lane is not None:
++ t = time.perf_counter()
+ stop = self._stop(lane)
+ self._emit(FILL, [lane.sid, stop])
+ self._flush()
+ first = self._fill(lane, stop)
+ if first is not None:
+ lane.s.take([first], self._ends(lane))
++ if prof is not None:
++ prof.fill(time.perf_counter() - t)
+ return [lane.s] if lane.s.done else []
+ lanes = [l for l in self.lanes.values() if l.decoding and not l.s.done]
++ t_begin = time.perf_counter()
+ for l in lanes: # room for this round's widest window, else paused
+ l.paused = not self._grow(l.extent, l.st.pos + self.rows_max, protect=[l.extent])
+ active = [l for l in lanes if not l.paused]
+@@ -740,12 +839,65 @@ class MultiDecoder:
+ if self.outbox: # what was decided (evictions, moves, a stream given back) goes now
+ self._flush()
+ return done
++ lone = False
++ if (self.tune.lone and len(active) == 1 and len(self.lanes) == 1 and self.lone_rows
++ and active[0].s.count - len(active[0].s.out) >= LONE_LEFT):
++ lone = self._home(active[0])
++ prof = self.profile = self.profiles[lone] if self.profiles is not None else None
++ if prof is not None:
++ prof.begin(t_begin)
+ plan = [(l.sid, l.depth) for l in active]
+- self._emit(ROUND, [len(plan), *[v for p in plan for v in p]])
++ self._emit(ROUND, [len(plan), *[v for p in plan for v in p], int(lone)])
++ if prof is not None:
++ prof.mark("plan")
+ self._flush()
+- self._round(active)
++ if prof is not None:
++ prof.mark("message")
++ self._round(active, lone=lone)
+ return [l.s for l in active if l.s.done]
+
++ def _home(self, lane: Lane) -> bool:
++ """Rank 0: a lone stream into the one-stream graphs' home, slot 0 at the pool's first rows (SLOT, then
++ kept prompts in the way evicted and its extent MOVEd); True once it is there."""
++
++ if self.e.graphed(lane.st):
++ return True
++ if lane.slot != 0:
++ self._emit(SLOT, [lane.sid, 0])
++ self._reslot(lane, 0)
++ x = lane.extent
++ if x.base != 0:
++ for c in list(self.kept): # kept prompts in [0, x.size) make way
++ y = c.extent
++ if y is not x and y.base < x.size and c in self.kept:
++ self._evict(c)
++ if any(y is not x and y.base < x.size for y in self.pool.extents):
++ return False # something else holds the home rows (cannot happen alone)
++ self._emit(MOVE, [x.eid, 0, x.size])
++ self._move(x, 0, x.size)
++ return self.e.graphed(lane.st)
++
++ def _reslot(self, lane: Lane, slot: int) -> None:
++ """Both ranks: the lane's slot state (KDA states, conv windows, DFlash2 context) copied into ``slot``."""
++
++ from .forward import State
++
++ e, old = self.e, lane.slot
++ if any(l.slot == slot for l in self.lanes.values() if l is not lane):
++ raise RuntimeError(f"stream {lane.sid} cannot take slot {slot}: another stream holds it")
++ e.slots.rec[slot].copy_(e.slots.rec[old])
++ e.slots.conv[slot].copy_(e.slots.conv[old])
++ if self.drafts is not None:
++ a, b = self.drafts.contexts[old], self.drafts.contexts[slot]
++ for dst, src in zip(list(b.kc) + list(b.vc), list(a.kc) + list(a.vc)):
++ dst.copy_(src)
++ b.context_end = a.context_end
++ b.pos_dev.copy_(a.pos_dev)
++ st = State(self.w, lane.extent.size, e.rows, caches=e.caches, base=lane.extent.base, slots=e.slots, slot=slot)
++ st.set_pos(lane.st.pos)
++ st.cur = list(lane.st.cur)
++ lane.st, lane.slot = st, slot
++
+ def _stop(self, lane: Lane) -> int:
+ pos, n = lane.st.pos, len(lane.s.prompt)
+ stop = next((p for p in lane.stops if p > pos), n)
+@@ -802,14 +954,17 @@ class MultiDecoder:
+ return first
+
+ @torch.no_grad()
+- def _round(self, lanes: list[Lane], depths: list[int] | None = None) -> None:
+- """Both ranks: one decode round over ``lanes`` (``depths``: rank 0's, checked on rank 1)."""
++ def _round(self, lanes: list[Lane], depths: list[int] | None = None, lone: bool = False) -> None:
++ """Both ranks: one decode round over ``lanes`` (``depths``: rank 0's, checked on rank 1); ``lone``: one
++ stream at home, verified through the one-stream graphs when its window fits them."""
+
+ from .decode import copy_room
+ from .dflash2_multi import DraftRequest
+
+ if depths is not None and [l.depth for l in lanes] != depths:
+ raise RuntimeError(f"rank {self.rank}'s draft depths {[l.depth for l in lanes]} are not rank 0's {depths}")
++ prof = self.profile
++ tune = self.tune
+ drafts: list[list[int]] = []
+ copied: list[bool] = []
+ asks = []
+@@ -818,13 +973,20 @@ class MultiDecoder:
+ copied.append(bool(c))
+ drafts.append(list(c))
+ if not c and l.dflash and l.depth > 0:
++ conf = l.policy.confidence
++ if tune.depth == "scale":
++ conf = scaled_confidence(conf, len(lanes), tune.alpha)
+ asks.append((len(drafts) - 1, DraftRequest(self._ctx(l), l.s.out[-1], l.depth, l.s.sampling,
+- l.policy.confidence, **l.policy.chain_rule)))
+- if asks:
++ conf, **l.policy.chain_rule)))
++ if asks and tune.depth == "joint":
++ self._joint(lanes, drafts, asks)
++ elif asks:
+ got = self.drafts.propose([a for _, a in asks])
+ for (k, _), d in zip(asks, got):
+ drafts[k] = list(d)
+ drafts = trim(drafts, MAX_WINDOW)
++ if prof is not None:
++ prof.mark("propose")
+ segments = []
+ for l, d in zip(lanes, drafts):
+ tokens = [l.s.out[-1]] + d
+@@ -833,13 +995,26 @@ class MultiDecoder:
+ l.window = l.constraint.window(tokens, list(range(-1, len(tokens) - 1)))
+ tokens = list(l.window.tokens)
+ segments.append(Segment(l.st, tokens))
+- v = forward_streams(self.verify, segments)
++ verify = self.verify
++ if lone:
++ if not self.e.graphed(lanes[0].st):
++ raise RuntimeError(f"rank {self.rank}: a lone round's stream is not at the graphs' home")
++ if len(segments[0].tokens) <= self.lone_rows:
++ verify = self.solo_verify
++ if prof is not None:
++ prof.gpu_start()
++ v = forward_streams(verify, segments)
++ if prof is not None:
++ prof.gpu_stop()
++ prof.mark("verify")
+ parts = []
+ for l, seg, logits in zip(lanes, segments, v.logits):
+ if l.window is not None:
+ l.constraint.mask(logits, l.window, self.w.vocab_offset)
+ parts.append((logits, [l.st.pos + 1 + r for r in range(len(seg.tokens))], l.s.sampling))
+- sampled = sample_streams(self.w, parts)
++ sampled = sample_packed(self.w, parts) if tune.sampler == "packed" else sample_streams(self.w, parts)
++ if prof is not None:
++ prof.mark("sample")
+ keeps = []
+ for l, seg, rows in zip(lanes, segments, sampled):
+ keep = 1
+@@ -848,11 +1023,17 @@ class MultiDecoder:
+ break
+ keep += 1
+ keeps.append(keep)
+- self.verify.commit(segments, keeps)
++ if prof is not None:
++ prof.mark("accept")
++ verify.commit(segments, keeps)
++ if prof is not None:
++ prof.mark("commit")
+ if self.drafts is not None:
+ items = [(self._ctx(l), v.taps[k][:keep]) for k, (l, keep) in enumerate(zip(lanes, keeps)) if l.dflash]
+ if items:
+ self.drafts.commit(items)
++ if prof is not None:
++ prof.mark("taps")
+ for l, seg, rows, keep, was_copy in zip(lanes, segments, sampled, keeps, copied):
+ s = l.s
+ new = rows[:keep]
+@@ -871,6 +1052,32 @@ class MultiDecoder:
+ if l.policy is not None:
+ l.depth = min(l.policy.next(*((0, 0) if was_copy else (ndrafts, keep - 1))),
+ max(0, s.count - len(s.out)))
++ if prof is not None:
++ prof.mark("emit")
++ prof.end(len(lanes), sum(len(g.tokens) for g in segments), sum(keeps),
++ sum(len(g.tokens) - 1 for g in segments))
++
++ def _joint(self, lanes: list[Lane], drafts: list[list[int]], asks: list) -> None:
++ """TF_GLM_MULTI_DEPTH=joint: every asking stream's chain walked to its depth in one block pass, then the
++ round's rows allocated across them by expected tokens per ms (``multi_tune.allocate``). The picks are each
++ policy's; only where each chain stops differs (drafts never change a reply)."""
++
++ md = self.drafts
++ live = [(k, r) for k, r in asks if min(r.depth, md.block - 1) >= 1 and r.ctx.context_end > 0]
++ if not live:
++ return
++ got = md.candidates([(r.ctx, r.pending, min(r.depth, md.block - 1)) for _, r in live])
++ reach = []
++ for (k, r), (tokens, values, proj) in zip(live, got):
++ confs: list[float] = []
++ drafts[k] = md.d.chain(tokens, values, proj, r.pending, r.ctx.context_end + 1, r.sampling, 0.0,
++ beta=r.beta, confs=confs)
++ reach.append(reach_of(confs))
++ asked = {k for k, _ in live}
++ fixed = sum(1 + (0 if k in asked else len(d)) for k, d in enumerate(drafts))
++ take = allocate(reach, fixed, self._row_cost, self.tune.overhead_ms, MAX_WINDOW)
++ for (k, _), n in zip(live, take):
++ drafts[k] = drafts[k][:n]
+
+ # -- ends ----------------------------------------------------------------------------------------------------------------
+ def finish(self, done: list[Stream]) -> None:
+@@ -992,7 +1199,10 @@ class MultiDecoder:
+ elif op == ROUND:
+ n = p[0]
+ sids, depths = p[1:1 + 2 * n:2], p[2:2 + 2 * n:2]
+- self._round([self.lanes[sid] for sid in sids], depths)
++ lone = bool(p[1 + 2 * n]) if len(p) > 1 + 2 * n else False
++ self._round([self.lanes[sid] for sid in sids], depths, lone=lone)
++ elif op == SLOT:
++ self._reslot(self.lanes[p[0]], p[1])
+ elif op == FINISH:
+ self._finish(p[0])
+ elif op == IDLE:
+diff --git tensorfold/families/glm5_next/cuda/multi_tune.py tensorfold/families/glm5_next/cuda/multi_tune.py
+new file mode 100644
+index 0000000..4020b91
+--- /dev/null
++++ tensorfold/families/glm5_next/cuda/multi_tune.py
+@@ -0,0 +1,303 @@
++"""Speed settings of GLM-5.3-Flash's concurrent rounds (``multi``), none of which changes a reply's bits:
++
++- TF_GLM_MULTI_SAMPLER=streams|packed: ``streams`` (the default) samples as ``multi.sample_streams`` did: every
++ top-k stream's candidates in one all-gather, each nucleus (top_k off) stream through ``nucleus_rows``' own two
++ gathers and host syncs. ``packed``: every stream's rows in two all-gathers whatever the samplings: the top-k
++ candidates and the nucleus rows' maxima together, then every nucleus row's candidates and shard masses together
++ (``sample_packed``: row for row the arithmetic ``nucleus_rows`` does; a stream whose nucleus runs past the
++ candidates falls back to whole shards on its own, as it does alone).
++- TF_GLM_MULTI_DEPTH=policy|joint|scale:A: how many drafts each stream verifies. ``policy`` (the default): each its
++ own DFlash2 policy, as alone. ``joint``: every drafting stream's chain walked to its policy's most, then the rows
++ of the round allocated across the streams by expected tokens per ms (``allocate``) on the startup-timed curve of
++ the batched window's ms by rows plus TF_GLM_MULTI_OVERHEAD_MS (default 12) for the rest of a round.
++ ``scale:A``: each stream's chain stop threshold raised to min(0.95, p * S**A) with S streams in the round.
++- TF_GLM_MULTI_ASYNC=1: rank 0 sends each iteration's message without waiting for the GPU (a pinned staging copy;
++ the same two all-gathers rank 1 reads), so its host runs ahead into the next round's host work.
++- TF_GLM_MULTI_LONE=1 (the default; 0: off): a stream decoding alone (no other stream decoding or filling) moves
++ once into the one-stream CUDA graphs' home (slot 0 at the pool's first rows) and verifies its windows through them
++ (``verify.SerialVerify``, the single-stream forward) while they fit the graphs; a second stream joins it on the
++ batched path at the next round boundary.
++- TF_GLM_MULTI_PROFILE=N: rank 0 logs a round's time breakdown every N decode rounds, lone-stream rounds (one-stream
++ graphs) and batched ones apart (``RoundProfile``), and at startup both paths' window ms for one stream.
++
++All but the profile change the collectives or the drafts, so both ranks must agree: ``MultiSettings.code`` joins the
++engine's two-rank settings comparison."""
++
++from __future__ import annotations
++
++import math
++import os
++import time
++from dataclasses import dataclass
++from typing import Callable, Sequence
++
++import numpy as np
++import torch
++
++
++@dataclass
++class MultiSettings:
++ sampler: str = "streams"
++ depth: str = "policy"
++ alpha: float = 0.0
++ overhead_ms: float = 12.0
++ async_msg: bool = False
++ profile: int = 0
++ lone: bool = True
++
++ @classmethod
++ def from_env(cls, env=None) -> "MultiSettings":
++ env = os.environ if env is None else env
++ s = cls()
++ s.sampler = (env.get("TF_GLM_MULTI_SAMPLER", "") or "streams").strip().lower()
++ if s.sampler not in ("streams", "packed"):
++ raise ValueError(f"TF_GLM_MULTI_SAMPLER: streams or packed, not {s.sampler!r}")
++ depth = (env.get("TF_GLM_MULTI_DEPTH", "") or "policy").strip().lower()
++ if depth.startswith("scale:"):
++ try:
++ s.alpha = float(depth[6:])
++ except ValueError:
++ s.alpha = -1.0
++ if not 0 < s.alpha <= 4:
++ raise ValueError(f"TF_GLM_MULTI_DEPTH=scale:A: A above 0 and at most 4, not {depth[6:]!r}")
++ depth = "scale"
++ if depth not in ("policy", "joint", "scale"):
++ raise ValueError(f"TF_GLM_MULTI_DEPTH: policy, joint or scale:A, not {depth!r}")
++ s.depth = depth
++ try:
++ s.overhead_ms = float(env.get("TF_GLM_MULTI_OVERHEAD_MS", "") or 12.0)
++ except ValueError:
++ s.overhead_ms = -1.0
++ if not 0 <= s.overhead_ms <= 1000:
++ raise ValueError("TF_GLM_MULTI_OVERHEAD_MS: 0 to 1,000 ms")
++ a = (env.get("TF_GLM_MULTI_ASYNC", "") or "0").strip()
++ if a not in ("0", "1"):
++ raise ValueError(f"TF_GLM_MULTI_ASYNC: 0 or 1, not {a!r}")
++ s.async_msg = a == "1"
++ lone = (env.get("TF_GLM_MULTI_LONE", "") or "1").strip()
++ if lone not in ("0", "1"):
++ raise ValueError(f"TF_GLM_MULTI_LONE: 0 or 1, not {lone!r}")
++ s.lone = lone == "1"
++ p = (env.get("TF_GLM_MULTI_PROFILE", "") or "0").strip()
++ if not p.isdecimal():
++ raise ValueError(f"TF_GLM_MULTI_PROFILE: 0 (off) or the rounds between reports, not {p!r}")
++ s.profile = int(p)
++ return s
++
++ def code(self) -> list[int]:
++ """What both ranks must agree on (the profile is rank 0's alone)."""
++
++ return [("streams", "packed").index(self.sampler), ("policy", "joint", "scale").index(self.depth),
++ int(round(self.alpha * 1000)), int(round(self.overhead_ms * 1000)), int(self.async_msg),
++ int(self.lone)]
++
++ def describe(self) -> str:
++ depth = f"scale:{self.alpha:g}" if self.depth == "scale" else self.depth
++ return (f"sampler {self.sampler}, depth {depth}"
++ f"{f' (overhead {self.overhead_ms:g} ms)' if self.depth == 'joint' else ''}, async messages "
++ f"{'on' if self.async_msg else 'off'}, lone stream on the one-stream graphs "
++ f"{'on' if self.lone else 'off'}{f', profile every {self.profile} rounds' if self.profile else ''}")
++
++
++def scaled_confidence(p: float, streams: int, alpha: float) -> float:
++ """TF_GLM_MULTI_DEPTH=scale:A: a stream's chain stop threshold with ``streams`` streams in the round."""
++
++ if p <= 0 or alpha <= 0 or streams <= 1:
++ return p
++ return min(0.95, p * streams ** alpha)
++
++
++def allocate(reach: Sequence[Sequence[float]], fixed: int, cost: Callable[[int], float], overhead: float,
++ cap: int) -> list[int]:
++ """TF_GLM_MULTI_DEPTH=joint: drafts to verify per stream. ``reach[s][k]``: the chance stream s's draft k is kept
++ (the product of its chain's confidences up to k), non-increasing in k; ``fixed``: the round's rows that are
++ decided (every pending token, copied drafts); ``cost(rows)``: the verify window's ms. Rows are added best reach
++ first while the expected tokens per ms (``fixed`` streams' pending tokens count 1 each, a draft its reach) grows,
++ at most ``cap`` rows in all. Deterministic in its inputs, so both ranks allocate alike."""
++
++ take = [0] * len(reach)
++ rows = fixed
++ tokens = float(len(reach))
++ best = tokens / (cost(rows) + overhead)
++ while rows < cap:
++ k = max(range(len(reach)), key=lambda s: (reach[s][take[s]] if take[s] < len(reach[s]) else -1.0, -s),
++ default=None)
++ if k is None or take[k] >= len(reach[k]):
++ break
++ gain = reach[k][take[k]]
++ rate = (tokens + gain) / (cost(rows + 1) + overhead)
++ if rate <= best:
++ break
++ take[k] += 1
++ rows += 1
++ tokens += gain
++ best = rate
++ return take
++
++
++def reach_of(confs: Sequence[float]) -> list[float]:
++ return [float(x) for x in np.cumprod(np.asarray(confs, dtype=np.float64))] if len(confs) else []
++
++
++# -- sampling --------------------------------------------------------------------------------------------------------
++def sample_packed(w, parts: Sequence[tuple]) -> list[list[int]]:
++ """parts [(logits [R, V/world], positions, sampling)] -> each part's tokens, bit for bit what ``decode.sample_rows``
++ gives each part alone, in two all-gathers for every part: (1) every top-k / greedy part's top candidates (values,
++ ids as fp32 bits) and every nucleus part's row maxima (fp64 as two fp32 words), (2) every nucleus row's
++ ``NUCLEUS`` best (value, id, mass), its shard's mass and width. Row by row the arithmetic is ``nucleus_rows``' and
++ ``sample_rows``'; a nucleus part some row of which runs past the candidates reads whole shards on its own."""
++
++ from tensorfold.cuda.sampling import MASS, NUCLEUS, WIDER, _draw, _shares, comm_gather, one_rank, union_cover
++ from tensorfold.engine.exact_sampling import MARGIN, choose_rows
++
++ gather = one_rank if w.comm is None else comm_gather(w.comm)
++ world = 1 if w.comm is None else w.world
++ out: list[list[int] | None] = [None] * len(parts)
++ words, topk, nucl = [], [], []
++ at = 0 # each part's first word in the first gather
++ for k, (logits, positions, sampling) in enumerate(parts):
++ greedy = sampling is None or sampling.temperature <= 0
++ if greedy or sampling.top_k:
++ n = 1 if greedy else min(logits.shape[1], int(sampling.top_k) + MARGIN)
++ vals, ids = torch.topk(logits.float(), n, dim=-1)
++ ids = (ids + w.vocab_offset).to(torch.int32)
++ words.append(torch.cat([vals, ids.view(torch.float32)], dim=1).reshape(-1))
++ topk.append((k, logits.shape[0], n, at))
++ at += logits.shape[0] * 2 * n
++ else:
++ scaled = logits.float().double() / max(float(sampling.temperature), 1e-6)
++ words.append(scaled.max(dim=-1).values.contiguous().view(torch.float32).view(-1))
++ nucl.append((k, scaled, at))
++ at += 2 * logits.shape[0]
++ if not words:
++ return []
++ flat = torch.cat(words) if len(words) > 1 else words[0]
++ got1 = gather(flat.contiguous()) # [world, words]
++ host2 = None
++ if nucl:
++ # every rank's maxima of each nucleus row, then the rows' masses and candidates (nucleus_rows' arithmetic)
++ scaled_all, tops = [], []
++ for k, scaled, off in nucl:
++ R = scaled.shape[0]
++ m = got1[:, off:off + 2 * R].contiguous().view(torch.float64) # [world, R]
++ tops.append(m.reshape(world, R).max(dim=0).values)
++ scaled_all.append(scaled)
++ scaled = torch.cat(scaled_all) if len(scaled_all) > 1 else scaled_all[0]
++ top = torch.cat(tops) if len(tops) > 1 else tops[0]
++ mass = torch.floor(torch.exp(scaled - top[:, None]) * MASS).to(torch.int64)
++ rows, width = scaled.shape
++ count = NUCLEUS
++ vals, cols = torch.topk(scaled, min(count, width), dim=-1)
++ ids = cols + int(w.vocab_offset)
++ pad = count - vals.shape[1]
++ if pad:
++ vals = torch.cat([vals, vals.new_full((rows, pad), float("-inf"))], dim=1)
++ ids = torch.cat([ids, ids.new_full((rows, pad), -1)], dim=1)
++ kept = mass.gather(1, cols)
++ kept = torch.cat([kept, kept.new_zeros((rows, pad))], dim=1) if pad else kept
++ shard = torch.tensor([[width]], dtype=torch.int64, device=scaled.device).expand(rows, 1)
++ packed = torch.cat([vals.view(torch.int64), ids, kept, mass.sum(dim=-1, keepdim=True), shard], dim=1)
++ words2 = packed.contiguous().view(torch.float32).view(-1)
++ host2 = gather(words2).reshape(-1, words2.numel()).view(torch.int64).reshape(-1, rows, 3 * count + 2)
++ host2 = host2.cpu().numpy()
++ host1 = got1.cpu()
++ for k, R, n, at in topk:
++ g = host1[:, at:at + R * 2 * n].reshape(host1.shape[0], R, 2 * n)
++ values = torch.cat([g[r, :, :n] for r in range(g.shape[0])], dim=1).numpy().astype(np.float32)
++ tokens = torch.cat([g[r, :, n:].contiguous().view(torch.int32) for r in range(g.shape[0])],
++ dim=1).numpy().astype(np.int64)
++ _, positions, sampling = parts[k]
++ if sampling is None or sampling.temperature <= 0:
++ order = np.lexsort((tokens, -values), axis=-1)
++ out[k] = [int(tokens[i, order[i, 0]]) for i in range(R)]
++ else:
++ out[k] = choose_rows(values, tokens, positions, sampling)
++ if nucl:
++ r0 = 0
++ for k, scaled_k, _ in nucl:
++ R = scaled_k.shape[0]
++ both = host2[:, r0:r0 + R]
++ got = (np.ascontiguousarray(both[:, :, :count]).view(np.float64), both[:, :, count:2 * count],
++ both[:, :, 2 * count:3 * count], both[:, :, 3 * count], both[:, :, 3 * count + 1])
++ _, positions, sampling = parts[k]
++ drawn = _draw(got, positions, sampling)
++ m_k = mass[r0:r0 + R]
++ if drawn is None and union_cover() and int(got[4].max()) > WIDER: # as nucleus_rows: wider first
++ drawn = _draw(_shares(gather, scaled_k, m_k, WIDER, int(w.vocab_offset), None), positions, sampling)
++ if drawn is None: # a row's nucleus runs past the candidates: this part reads whole shards
++ drawn = _draw(_shares(gather, scaled_k, m_k, int(got[4].max()), int(w.vocab_offset), None),
++ positions, sampling)
++ out[k] = [token for token, _ in drawn]
++ r0 += R
++ return out
++
++
++# -- the profile -------------------------------------------------------------------------------------------------------
++class RoundProfile:
++ """TF_GLM_MULTI_PROFILE=N (rank 0): where a decode round's wall time goes, averaged over the last N rounds, and
++ the prompt chunks' share of the wall time between reports. Stages are host wall time between marks; ``verify``
++ also has the window's GPU time from CUDA events, read after the sampler has waited for it anyway."""
++
++ STAGES = ("plan", "message", "propose", "verify", "sample", "accept", "commit", "taps", "emit")
++
++ def __init__(self, every: int, log=print, label: str = "") -> None:
++ self.every, self.log, self.label = every, log, label
++ self.cuda = torch.cuda.is_available()
++ self.ev = [torch.cuda.Event(enable_timing=True) for _ in range(2)] if self.cuda else None
++ self._reset()
++ self.t_report = time.perf_counter()
++
++ def _reset(self) -> None:
++ self.rounds = 0
++ self.sums = dict.fromkeys(self.STAGES + ("wall", "gpu"), 0.0)
++ self.rows = self.streams = self.tokens = self.drafted = 0
++ self.fill_s = 0.0
++ self.fills = 0
++
++ def begin(self, t0: float | None = None) -> None:
++ self.t0 = time.perf_counter() if t0 is None else t0
++ self.t = self.t0
++
++ def mark(self, stage: str) -> None:
++ now = time.perf_counter()
++ self.sums[stage] += now - self.t
++ self.t = now
++
++ def gpu_start(self) -> None:
++ if self.cuda:
++ self.ev[0].record()
++
++ def gpu_stop(self) -> None:
++ if self.cuda:
++ self.ev[1].record()
++
++ def fill(self, seconds: float) -> None:
++ self.fills += 1
++ self.fill_s += seconds
++
++ def end(self, streams: int, rows: int, tokens: int, drafted: int) -> None:
++ self.sums["wall"] += time.perf_counter() - self.t0
++ if self.cuda:
++ self.sums["gpu"] += self.ev[0].elapsed_time(self.ev[1]) / 1e3
++ self.rounds += 1
++ self.streams += streams
++ self.rows += rows
++ self.tokens += tokens
++ self.drafted += drafted
++ if self.rounds >= self.every:
++ self.report()
++
++ def report(self) -> None:
++ n = max(self.rounds, 1)
++ ms = {k: 1e3 * v / n for k, v in self.sums.items()}
++ staged = sum(ms[k] for k in self.STAGES)
++ span = time.perf_counter() - self.t_report
++ self.log(f"[tensorfold] multi profile{' (' + self.label + ')' if self.label else ''}, {self.rounds} rounds: {self.streams / n:.2f} streams, "
++ f"{self.rows / n:.1f} rows ({self.drafted / n:.1f} drafted), {self.tokens / n:.2f} tokens a round; "
++ f"ms a round: wall {ms['wall']:.1f} = " +
++ " + ".join(f"{k} {ms[k]:.1f}" for k in self.STAGES) +
++ f" + other {ms['wall'] - staged:.1f}; verify GPU {ms['gpu']:.1f}; "
++ f"{self.tokens / max(self.sums['wall'], 1e-9):.1f} tok/s in rounds; prompt chunks {self.fills} "
++ f"({1e3 * self.fill_s:.0f} ms, {100 * self.fill_s / max(span, 1e-9):.1f}% of {span:.1f} s)")
++ self._reset()
++ self.t_report = time.perf_counter()
+diff --git tensorfold/families/glm5_next/cuda/verify.py tensorfold/families/glm5_next/cuda/verify.py
+index 2d13572..676a151 100644
+--- tensorfold/families/glm5_next/cuda/verify.py
++++ tensorfold/families/glm5_next/cuda/verify.py
+@@ -135,6 +135,33 @@ class BatchedVerify:
+ e.slots.conv[0].zero_()
+
+ # -- the window's tables -------------------------------------------------------------------------------------------
++ @torch.no_grad()
++ def time_rows(self, reps: int = 5) -> list[float]:
++ """ms of the captured window of each size (1 .. its rows): the fastest of ``reps`` replays, on the capture's
++ own tables (slot 0 at the pool's first rows; its states cleared after), before any stream is admitted."""
++
++ from .sparse import SPARSE_FROM
++
++ index = self.e.caches.index is not None
++ out = []
++ start, stop = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
++ for R in range(1, self.rows_max + 1):
++ g = self.graphs[R]
++ self._stage([0] * R)
++ self.seg_rows.set([(0, 0, R)], sparse_from=SPARSE_FROM if index else None)
++ self._write_table([(R, 0, 0, 0, R)])
++ best = float("inf")
++ for _ in range(reps + 1):
++ start.record()
++ g.replay()
++ stop.record()
++ stop.synchronize()
++ best = min(best, start.elapsed_time(stop))
++ out.append(best)
++ self.e.slots.rec[0].zero_()
++ self.e.slots.conv[0].zero_()
++ return out
++
+ def _tables(self, segments: Sequence[Segment], keeps: Sequence[int] | None = None) -> None:
+ """The KDA segment table (row0, rows, slot, parity, conv slot, keep) into the device copy, in place (a captured
+ graph reads the same tensor); unused segments have 0 rows."""
diff --git a/patches/0039-glm-tool-calls.patch b/patches/0039-glm-tool-calls.patch
new file mode 100644
index 0000000..86af561
--- /dev/null
+++ b/patches/0039-glm-tool-calls.patch
@@ -0,0 +1,834 @@
+diff --git tensorfold/cuda/http.py tensorfold/cuda/http.py
+index f314446..c3d7cca 100644
+--- tensorfold/cuda/http.py
++++ tensorfold/cuda/http.py
+@@ -143,8 +143,12 @@ def make_handler(app: App):
+ return self._stream_error({"message": _error_message(exc), "type": "server_error"})
+ if result["final"]:
+ emit(result["final"])
++ for delta in result.get("call_deltas") or (): # the end of calls streamed as they were written
++ 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"]}}]})
+diff --git tensorfold/cuda/reply_text.py tensorfold/cuda/reply_text.py
+index 6fa1026..c073b19 100644
+--- tensorfold/cuda/reply_text.py
++++ tensorfold/cuda/reply_text.py
+@@ -1,4 +1,8 @@
+-"""The CUDA server's reply text: streamed decoding, think blocks and tool-call parsing (the Mac lane server's rules)."""
++"""The CUDA server's reply text: streamed decoding, think blocks and tool-call parsing (the Mac lane server's rules).
++
++Parts adapted from jayleaton/glm53-tensorfold-spark patch 0620 (Apache-2.0): the rule that calls written inside the
++think block are the reply's calls when they end it (its ``trailing_calls``), in ``ThinkSplit``.
++"""
+
+ from __future__ import annotations
+
+@@ -8,8 +12,8 @@ import uuid
+ from typing import Any
+
+ from tensorfold.server.stopping import StopPolicy
+-from tensorfold.server.tools import parse_glm_tool_call_block
+-from tensorfold.tool_parameters import decode_parameter, parameter_schemas
++from tensorfold.server.tools import _GLM_NAME_RE as _GLM_NAME, parse_glm_tool_call_block
++from tensorfold.tool_parameters import decode_parameter, nullable_text, parameter_schemas, typed_parameter
+
+ _CALL_OPEN, _CALL_CLOSE = "<tool_call>", "</tool_call>"
+ _TOOL_CALL_BLOCK_RE = re.compile(r"<tool_call>\s*(.*?)\s*</tool_call>", re.IGNORECASE | re.DOTALL)
+@@ -155,4 +159,212 @@ def parse_tool_calls(text: str, tools: list[dict[str, Any]], *, max_calls: int |
+ return "".join(residue).strip(), calls or None
+
+
++_THINK_CLOSE = "</think>"
++_CALL_BLOCK = re.compile(r"<tool_call>.*?</tool_call>", re.DOTALL)
++THINK_CALL_HOLD = 1024 # characters of a call written inside the think block held before it streams as a call
++
++
++def _call_run(text: str, start: int, finished: bool) -> tuple[int, str]:
++ """(where the run of complete ``<tool_call>`` blocks from ``start`` ends, what it is): ``"calls"`` when the reply
++ ended on it (nothing after it but whitespace and a closing ``</think>``), ``"pending"`` while that may still
++ come true, ``"reasoning"`` once text follows it (more reasoning, or an answer after the think block)."""
++
++ end = pos = start
++ while (block := _CALL_BLOCK.match(text, pos)) is not None:
++ end = block.end()
++ pos = len(text) - len(text[end:].lstrip())
++ after = text[end:].lstrip()
++ if after.startswith(_THINK_CLOSE) and not after[len(_THINK_CLOSE):].strip():
++ after = ""
++ if not after:
++ return end, "calls" if finished and end > start else "pending"
++ if not finished and (after.startswith(_CALL_OPEN) or _CALL_OPEN.startswith(after)
++ or _THINK_CLOSE.startswith(after)):
++ return end, "pending" # a block, or the think block's close, being written
++ return end, "reasoning"
++
++
++class ThinkSplit:
++ """(reasoning, answer) of a thinking GLM reply with tools, streamed or whole: the think block ends at its
++ ``</think>``, and calls the model wrote inside it are its calls only when they end the reply (nothing after them
++ but whitespace and the block's close; theirs is the D5 rule of jayleaton/glm53-tensorfold-spark patch 0620, and
++ upstream's split read any call in an unclosed block as the answer). A call in the think block is held: its text
++ stays out of the reasoning until the reply ends on it (a call) or text follows it (reasoning after all). With
++ ``hold``, a held call longer than ``hold`` characters is taken as a call at once (``committed``) so a long file
++ write streams while it is written; nothing after it can make it reasoning again.
++
++ ``stream_from`` is where the text a call streamer reads begins once known (the answer, or a committed call); a
++ reply whose calls it never reaches has them from the end parser."""
++
++ def __init__(self, hold: int | None = None) -> None:
++ self.hold = hold
++ self.floor = 0 # calls before this are reasoning
++ self.committed: int | None = None
++ self.stream_from: int | None = None
++
++ def __call__(self, text: str, finished: bool) -> tuple[str, str]:
++ if self.committed is not None:
++ at = self.committed
++ return text[:at], text[at:].replace(_THINK_CLOSE, "", 1).lstrip()
++ close = text.find(_THINK_CLOSE)
++ while True:
++ call = text.find(_CALL_OPEN, self.floor)
++ if close >= 0 and (call < 0 or close < call):
++ self.stream_from = close + len(_THINK_CLOSE)
++ return text[:close], text[self.stream_from:].lstrip("\n")
++ if call < 0:
++ held = 0 if finished else max(_partial_tag(text, tag) for tag in (_THINK_CLOSE, _CALL_OPEN))
++ return text[:len(text) - held], ""
++ end, kind = _call_run(text, call, finished)
++ if kind == "calls":
++ return text[:call], text[call:end]
++ if kind == "reasoning":
++ self.floor = max(end, call + len(_CALL_OPEN))
++ continue
++ if self.hold is not None and len(text) - call > self.hold and close < 0:
++ self.committed = self.stream_from = call
++ return self(text, finished)
++ return text[:call], ""
++
++
++_KEY, _KEY_END, _VALUE, _VALUE_END = "<arg_key>", "</arg_key>", "<arg_value>", "</arg_value>"
++_VALUE_OPENS = re.compile(r"\s*<arg_value>")
++
++
++def _json(value: Any) -> str:
++ return json.dumps(value, ensure_ascii=False, separators=(",", ":"))
++
++
++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.
++
++ ``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."""
++
++ def __init__(self, tools: list[dict[str, Any]]) -> None:
++ self.known = {_tool_name(t).lower(): _tool_name(t) for t in tools}
++ self.schemas = parameter_schemas(tools)
++ self.calls: list[dict[str, Any]] = [] # every call whose header was sent, its arguments as sent
++ self.skipped: list[str] = [] # whole blocks it did not follow, for the end parser
++ self.pos, self.state, self.start = 0, "outside", 0
++ self.open = False # the last call's header went out, its </tool_call> has not
++ 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
++
++ def _args(self, out: list[dict[str, Any]], piece: str) -> None:
++ index = len(self.calls) - 1
++ self.calls[index]["function"]["arguments"] += piece
++ last = out[-1]["tool_calls"][0] if out else None
++ if last is not None and last["index"] == index and "id" not in last: # one delta a call a feed
++ last["function"]["arguments"] += piece
++ else:
++ out.append({"tool_calls": [{"index": index, "function": {"arguments": piece}}]})
++
++ def feed(self, text: str) -> list[dict[str, Any]]:
++ out: list[dict[str, Any]] = []
++ while True:
++ rest = text[self.pos:]
++ if self.state == "outside":
++ at = rest.find(_CALL_OPEN)
++ if at < 0:
++ return out
++ self.start = self.pos + at
++ self.pos, self.state = self.start + len(_CALL_OPEN), "name"
++ elif self.state == "name": # the end parser's name: the text before <arg_key> or the end
++ ends = [at for at in (rest.find(_KEY), rest.find(_CALL_CLOSE)) if at >= 0]
++ if not ends:
++ if len(rest) > 256:
++ self.state = "skip"
++ continue
++ return out
++ name = rest[:min(ends)].strip()
++ if not self._callable(name):
++ self.state = "skip"
++ continue
++ name, id_ = self.known[name.lower()], f"call_{uuid.uuid4().hex[:24]}"
++ self.calls.append({"id": id_, "type": "function", "function": {"name": name, "arguments": ""}})
++ self.open = True
++ out.append({"tool_calls": [{"index": len(self.calls) - 1, "id": id_, "type": "function",
++ "function": {"name": name, "arguments": ""}}]})
++ self.schema = self.schemas.get(name.lower(), {})
++ self.pos, self.state = self.pos + min(ends), "arguments"
++ elif self.state == "skip": # a block the end parser decides: to its end
++ at = rest.find(_CALL_CLOSE)
++ if at < 0:
++ return out
++ self.pos, self.state = self.pos + at + len(_CALL_CLOSE), "outside"
++ self.skipped.append(text[self.start:self.pos])
++ elif self.state == "arguments": # text between arguments is ignored, as the end parser does
++ key, close = rest.find(_KEY), rest.find(_CALL_CLOSE)
++ if close >= 0 and (key < 0 or close < key):
++ self._args(out, "}" if self.calls[-1]["function"]["arguments"] else "{}")
++ self.pos, self.state, self.open = self.pos + close + len(_CALL_CLOSE), "outside", False
++ elif key >= 0:
++ self.pos, self.state = self.pos + key + len(_KEY), "key"
++ else:
++ return out
++ elif self.state == "key":
++ end = rest.find(_KEY_END)
++ opens = _VALUE_OPENS.match(rest, end + len(_KEY_END)) if end >= 0 else None
++ if opens is None:
++ after = rest[end + len(_KEY_END):] if end >= 0 else ""
++ cut = _CALL_CLOSE in (rest if end < 0 else after)
++ if not cut and (end < 0 or not after.strip() or _VALUE.startswith(after.lstrip())):
++ return out # the key or its value's opener is still being written
++ self.state = "arguments" # not an argument the end parser reads the same way
++ continue
++ key = rest[:end].strip()
++ schema = self.schema.get(key, {})
++ self.value_schema = schema if typed_parameter(schema) else None
++ self.maybe_null = self.value_schema is None and nullable_text(schema)
++ opened = "{" if not self.calls[-1]["function"]["arguments"] else ","
++ quote = "" if self.value_schema is not None or self.maybe_null else '"'
++ self._args(out, opened + _json(key) + ":" + quote)
++ self.pos, self.state = self.pos + opens.end(), "value"
++ elif self.state == "value":
++ end = rest.find(_VALUE_END)
++ 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)))
++ 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":
++ self._args(out, "null")
++ elif end < 0 and "null".startswith(written):
++ return out
++ else:
++ self._args(out, '"')
++ self.maybe_null = False
++ continue
++ else: # text: as it arrives, less a tail that may begin the closer
++ written = rest[:end] if end >= 0 else rest[:len(rest) - _partial_tag(rest, _VALUE_END)]
++ piece = _json(written)[1:-1] + ('"' if end >= 0 else "")
++ if piece:
++ self._args(out, piece)
++ if end < 0:
++ self.pos += len(written)
++ return out
++ self.pos, self.state = self.pos + end + len(_VALUE_END), "arguments"
++
++ def _callable(self, name: str) -> bool:
++ """Whether the end parser reads a block beginning ``name`` as a GLM call to an offered tool."""
++
++ if _GLM_NAME.fullmatch(name) is None or name.lower() not in self.known:
++ return False
++ try:
++ json.loads(name) # a name that is JSON (``true``, ``1``) is read as JSON
++ except ValueError:
++ return True
++ return False
++
++ def rest(self, tools: list[dict[str, Any]]) -> list[dict[str, Any]]:
++ """The calls the end parser reads in the blocks this streamer skipped (JSON or Qwen markup): sent at the end."""
++
++ return [call for block in self.skipped for call in parse_tool_calls(block, tools)[1] or []]
++
++
+ # -- chat template -------------------------------------------------------------------------
+diff --git tensorfold/cuda/server.py tensorfold/cuda/server.py
+index 31e0268..4ab6484 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
+
+ from tensorfold.cuda import health
+ from tensorfold.cuda.chat_template import ChatTemplate
+-from tensorfold.cuda.reply_text import StopStrings, StreamDecoder, hide_tool_calls, parse_tool_calls
++from tensorfold.cuda.reply_text import (THINK_CALL_HOLD, GlmCallStreamer, StopStrings, StreamDecoder, ThinkSplit,
++ hide_tool_calls, parse_tool_calls)
+ from tensorfold.cuda.turns import Turns, Yield
+ from tensorfold.server.text import is_title_request, reasoning_count, split_thinking
+
+@@ -273,19 +274,35 @@ class App:
+ stopped = {"client": False, "stop": False}
+ failed: list[Exception] = []
+ stream = StreamDecoder(self.tok, ends)
+-
+- def visible(finished: bool) -> tuple[str, str]:
++ # 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
++ # 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 split(raw: str, finished: bool) -> tuple[str, str]:
++ if not (chat and thinking):
++ return "", raw
++ return think(raw, finished) if think is not None else split_thinking(raw, finished=finished)
++
++ def call_text(raw: str) -> str:
++ """The text the call streamer reads: the answer, or a long call taken from the think block; "" before."""
++
++ if think is None:
++ return raw
++ return raw[think.stream_from:] if think.stream_from is not None else ""
++
++ def visible(finished: bool) -> tuple[str, str, str]:
+ raw = stream.final() if finished else stream.text
+ # stop strings match the generated text, reasoning included, before it is split (as on the Mac)
+ raw = stops.visible(raw, partial=not finished) if stops.strings else raw
+- if chat and thinking:
+- reasoning, answer = split_thinking(raw, finished=finished)
+- else:
+- reasoning, answer = "", raw
++ reasoning, answer = split(raw, finished)
+ 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:
+ else:
+ out.extend(new)
+ stream.add(new)
+- reasoning, answer = visible(False)
++ reasoning, answer, raw = visible(False)
+ delta: dict[str, Any] = {}
+ if len(reasoning) > sent["reasoning"]:
+ delta["reasoning_content"] = reasoning[sent["reasoning"]:]
+@@ -312,7 +329,10 @@ class App:
+ if len(answer) > sent["content"]:
+ delta["content"] = answer[sent["content"]:]
+ sent["content"] = len(answer)
+- if delta and not emit(delta):
++ parts = [delta] if delta else []
++ if calls_stream is not None:
++ 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 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)}
+- reasoning, answer = visible(True)
++ reasoning, answer, raw = visible(True)
+ final: dict[str, Any] = {}
+ if len(reasoning) > sent["reasoning"]:
+ final["reasoning_content"] = reasoning[sent["reasoning"]:]
+ text = stops.visible(self.tok.decode([t for t in out if t not in ends], skip_special_tokens=False))
+- raw_answer = split_thinking(text, finished=True)[1] if chat and thinking else text
++ raw_answer = split(text, True)[1]
+ content, calls = parse_tool_calls(raw_answer, tools, max_calls=policy.max_calls) if tools else (answer, None)
+ content = policy.content(content) if tools else content
++ call_deltas, streamed = [], 0
++ # the calls streamed as sent, then any the streamer did not follow; calls held in the think block to the end
++ # (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
++ content = answer.strip()
+ tail = content[sent["content"]:] if content.startswith(answer[:sent["content"]]) else ""
+ if tail:
+ final["content"] = tail
+- finish = "tool_calls" if calls else ("stop" if stopped["stop"] or (out and out[-1] in ends) else "length")
++ finish = "tool_calls" if calls and not cut else ("stop" if stopped["stop"] or (out and out[-1] in ends)
++ 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]}
+- return {"final": final, "calls": calls, "finish": finish, "content": content, "reasoning": reasoning,
++ return {"final": final, "calls": calls, "call_deltas": call_deltas, "calls_streamed": streamed,
++ "finish": finish, "content": content, "reasoning": reasoning,
+ "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:
+ close += self.tok.encode("\n\n", add_special_tokens=False).ids
+ return ThinkBudget(prepared.think_budget, close, think_end)
+
++ def _glm_calls(self) -> bool:
++ """Whether this model writes GLM's ``<arg_key>``/``<arg_value>`` calls (streamed while they are written): its
++ tokenizer has those marks as tokens."""
++
++ lookup = getattr(self.tok, "token_to_id", None)
++ return lookup is not None and all(lookup(mark) is not None for mark in ("<tool_call>", "<arg_key>",
++ "</arg_value>"))
++
+ def _call_gate(self, prompt: list[int], tools: list[dict[str, Any]]) -> CallGate:
+ """The gate a required tool call needs, from this template's call markup and the rendered prompt."""
+
+diff --git tensorfold/engine/tool_draft.py tensorfold/engine/tool_draft.py
+index bd64ae6..83497ba 100644
+--- tensorfold/engine/tool_draft.py
++++ tensorfold/engine/tool_draft.py
+@@ -5,7 +5,7 @@ from __future__ import annotations
+ import re
+ from typing import Any, Sequence
+
+-from tensorfold.tool_parameters import decode_parameter, parameter_schemas, typed_parameter
++from tensorfold.tool_parameters import decode_parameter, nullable_text, parameter_schemas, typed_parameter
+
+ _OPEN = "<tool_call>"
+ _END = "\x00end" # placeholder: after a closed call the draft is the end-of-turn token
+@@ -252,6 +252,7 @@ class ToolCallStreamer:
+ self.schemas = parameter_schemas(tools)
+ self.current_schema = {}
+ self.typed = False
++ self.maybe_null = False # a nullable text value that may still be ``null``: held in value_buffer
+ self.value_buffer = ""
+ self.known = {name.lower(): name for name in tool_schema(tools)}
+ self.pos = 0
+@@ -307,9 +308,10 @@ class ToolCallStreamer:
+ if m is not None:
+ self.value_schema = self.current_schema.get(m.group(1).strip(), {})
+ self.typed = typed_parameter(self.value_schema)
++ self.maybe_null = not self.typed and nullable_text(self.value_schema)
+ self.value_buffer = ""
+- out.append(self._args(("," if self.args_open else "{")
+- + self._esc_key(m.group(1).strip()) + (':' if self.typed else ':"')))
++ out.append(self._args(("," if self.args_open else "{") + self._esc_key(m.group(1).strip())
++ + (':' if self.typed or self.maybe_null else ':"')))
+ self.args_open = True
+ self.pos += m.end()
+ self.state = "value"
+@@ -339,11 +341,16 @@ class ToolCallStreamer:
+ self.held = piece[len(keep):]
+ if self.typed:
+ self.value_buffer += keep
++ elif self.maybe_null:
++ self.value_buffer += keep
++ if not "null".startswith(self.value_buffer): # text after all: the held part first
++ out.append(self._args('"' + self._esc(self.value_buffer)))
++ self.value_buffer, self.maybe_null = "", False
+ elif keep:
+ out.append(self._args(self._esc(keep)))
+ if end < 0:
+ break
+- if self.typed:
++ if self.typed or self.maybe_null:
+ import json
+ 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
+--- tensorfold/families/glm5_next/cuda/app.py
++++ tensorfold/families/glm5_next/cuda/app.py
+@@ -6,19 +6,25 @@ from pathlib import Path
+ from typing import Any, Callable
+
+ from tensorfold.cuda.server import App, PreparedRequest, RequestError
+-from tensorfold.families.glm5_next.prompts import thinking_off
++from tensorfold.families.glm5_next.cuda.kept_reasoning import KeptReasoning
++from tensorfold.families.glm5_next.prompts import agent_history, thinking_off
+
+
+ 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)."""
++ (``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)."""
+
+- def __init__(self, inner) -> None:
++ def __init__(self, inner, kept: KeptReasoning | None = None) -> None:
+ self.inner = inner
+ self.efforts = getattr(inner, "efforts", frozenset())
++ self.kept = kept
+
+ def render(self, messages, *, tools, enable_thinking, extra=None, allow_images: bool = False) -> str:
+- text = self.inner.render(messages, tools=tools, enable_thinking=enable_thinking, extra=extra,
++ if self.kept is not None:
++ messages = self.kept.restore(messages)
++ text = self.inner.render(agent_history(messages), tools=tools, enable_thinking=enable_thinking, extra=extra,
+ allow_images=allow_images)
+ return text if enable_thinking else thinking_off(text)
+
+@@ -49,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))
+- self.template = ThinkingOffTemplate(self.template)
++ self.template = ThinkingOffTemplate(self.template, KeptReasoning.from_env())
+
+ 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):
+ 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))
+- return super().run(body, chat, emit, prepared=prepared, cancelled=cancelled)
++ result = super().run(body, chat, emit, prepared=prepared, cancelled=cancelled)
++ kept = getattr(self.template, "kept", None)
++ if chat and kept is not None and result.get("calls") and result.get("finish") == "tool_calls":
++ # the calls' reasoning, for a client that will not send it back
++ kept.remember(body.get("messages"), result["calls"], result.get("reasoning"))
++ return result
+diff --git tensorfold/families/glm5_next/cuda/kept_reasoning.py tensorfold/families/glm5_next/cuda/kept_reasoning.py
+new file mode 100644
+index 0000000..297326c
+--- /dev/null
++++ tensorfold/families/glm5_next/cuda/kept_reasoning.py
+@@ -0,0 +1,155 @@
++"""The reasoning of GLM's tool-calling replies, put back into later requests whose client dropped it.
++
++Parts adapted from jayleaton/glm53-tensorfold-spark patch 0620 (Apache-2.0): its ``reasoning`` fix (the
++``ReasoningMemory`` LRU, keyed by the server's call ids and by a signature of the calls for clients that renumber
++ids). Here the signature covers the whole conversation before the calls, not only the last user message, so a reply
++is only ever put back into the conversation it was written for.
++
++GLM-5.3's template renders the reasoning of every assistant step after the last user message (interleaved thinking
++inside one tool loop). A client that does not send a step's reasoning back (spark-bench, many agent frameworks) gets
++``<think></think>`` for it: a context the model never wrote, and a prompt that stops matching the previous one at
++that step, so the prefix cache re-reads the rest. With the reasoning kept here, each prompt of a chain continues the
++last one as it was generated. A step that carries its own reasoning (``reasoning_content`` or ``reasoning``, or a
++``<think>`` block in its content) is never changed; an empty one (clients that send ``""`` for every step) is none.
++
++``TF_GLM_KEEP_REASONING``: replies kept (default 1024; 0 turns this off); ``TF_GLM_KEEP_REASONING_MB``: their text
++at most (default 32 MiB); the oldest go first.
++"""
++
++from __future__ import annotations
++
++import hashlib
++import json
++import os
++import re
++import threading
++from collections import OrderedDict
++from typing import Any
++
++_OUR_ID = re.compile(r"^call_[0-9a-f]{24}$") # the ids ``parse_tool_calls`` / ``GlmCallStreamer`` make
++
++
++def _env_int(name: str, default: int) -> int:
++ raw = os.environ.get(name, "").strip()
++ if not raw:
++ return default
++ try:
++ value = int(raw)
++ except ValueError:
++ raise ValueError(f"{name}={raw!r}: expected a whole number") from None
++ if value < 0:
++ raise ValueError(f"{name}={raw!r}: expected 0 or more")
++ return value
++
++
++def _text(content: Any) -> str:
++ if isinstance(content, str):
++ return content
++ if isinstance(content, list):
++ return "".join(p["text"] for p in content if isinstance(p, dict) and isinstance(p.get("text"), str))
++ return ""
++
++
++def _arguments(value: Any) -> Any:
++ if isinstance(value, str):
++ try:
++ return json.loads(value) if value.strip() else {}
++ except ValueError:
++ return value
++ return {} if value is None else value
++
++
++def _calls(calls: Any) -> list[list[Any]]:
++ """Calls as [name, arguments]: ids dropped (clients renumber them), arguments parsed (clients re-serialise)."""
++
++ out = []
++ for call in calls if isinstance(calls, list) else []:
++ fn = call.get("function") if isinstance(call, dict) and isinstance(call.get("function"), dict) else {}
++ out.append([str(fn.get("name") or ""), _arguments(fn.get("arguments"))])
++ return out
++
++
++def signature(history: list[Any], calls: Any) -> str:
++ """The key of ``calls`` written after ``history``: each message's role, text (stripped, as the template renders
++ it) and calls, without ids or reasoning, then the calls."""
++
++ shape = []
++ for m in history:
++ if not isinstance(m, dict):
++ continue
++ entry = [str(m.get("role") or ""), _text(m.get("content")).strip()]
++ if m.get("role") == "assistant" and m.get("tool_calls"):
++ entry.append(_calls(m.get("tool_calls")))
++ shape.append(entry)
++ text = json.dumps([shape, _calls(calls)], ensure_ascii=False, sort_keys=True, separators=(",", ":"), default=str)
++ return "sig:" + hashlib.sha256(text.encode("utf-8", "surrogatepass")).hexdigest()
++
++
++def _keys(history: list[Any], calls: Any) -> list[str]:
++ ids = [c.get("id") for c in calls if isinstance(c, dict)] if isinstance(calls, list) else []
++ return [i for i in ids if isinstance(i, str) and _OUR_ID.match(i)] + [signature(history, calls)]
++
++
++class KeptReasoning:
++ """Recent tool-calling replies' reasoning (LRU, bounded in replies and characters), found by any of its keys."""
++
++ def __init__(self, entries: int = 1024, chars: int = 32 << 20) -> None:
++ self.entries, self.chars = int(entries), int(chars)
++ self.items: OrderedDict[int, tuple[str, tuple[str, ...]]] = OrderedDict()
++ self.by_key: dict[str, int] = {}
++ self.size = self.next = 0
++ self.lock = threading.Lock()
++
++ @classmethod
++ def from_env(cls) -> "KeptReasoning | None":
++ entries = _env_int("TF_GLM_KEEP_REASONING", 1024)
++ return cls(entries, _env_int("TF_GLM_KEEP_REASONING_MB", 32) << 20) if entries else None
++
++ def __len__(self) -> int:
++ return len(self.items)
++
++ def remember(self, messages: Any, calls: Any, reasoning: Any) -> None:
++ """Keep the ``reasoning`` of a reply that made ``calls`` after the request's ``messages``."""
++
++ if not calls or not isinstance(reasoning, str) or not reasoning.strip() or len(reasoning) > self.chars:
++ return
++ keys = tuple(_keys(messages if isinstance(messages, list) else [], calls))
++ with self.lock:
++ n, self.next = self.next, self.next + 1
++ self.items[n] = (reasoning, keys)
++ self.size += len(reasoning)
++ for key in keys: # a key kept again points at the newer reply
++ self.by_key[key] = n
++ while len(self.items) > self.entries or self.size > self.chars:
++ old, (text, old_keys) = self.items.popitem(last=False)
++ self.size -= len(text)
++ for key in old_keys:
++ if self.by_key.get(key) == old:
++ del self.by_key[key]
++
++ def _find(self, keys: list[str]) -> str | None:
++ with self.lock:
++ for key in keys:
++ n = self.by_key.get(key)
++ if n is not None:
++ self.items.move_to_end(n)
++ return self.items[n][0]
++ return None
++
++ def restore(self, messages: Any) -> Any:
++ """``messages`` with the kept reasoning of each assistant step that calls tools and carries none (a copy;
++ the caller's list and messages are left alone)."""
++
++ if not isinstance(messages, list) or not self.items:
++ return messages
++ out = None
++ for i, m in enumerate(messages):
++ if not (isinstance(m, dict) and m.get("role") == "assistant" and m.get("tool_calls")
++ and not _text(m.get("reasoning_content")).strip() and not _text(m.get("reasoning")).strip()
++ and "</think>" not in _text(m.get("content"))):
++ continue
++ kept = self._find(_keys(messages[:i], m["tool_calls"]))
++ if kept is not None:
++ out = out if out is not None else list(messages)
++ 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
+--- 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
+
+ from __future__ import annotations
+
++import json
+ from typing import Any
+
++from tensorfold.server.errors import RequestError
++
+ EFFORT_LINE = "<|system|>Reasoning Effort: Max"
+ OPENED = "<|assistant|><think>"
+
+
++def _call_id(message: Any) -> Any:
++ """The id GLM's template matches a tool result or call by (its ``id_of``)."""
++
++ return message.get("tool_call_id") or message.get("id") if isinstance(message, dict) else None
++
++
++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)."""
++
++ if not isinstance(messages, list):
++ return messages
++ out = list(messages)
++ for i, message in enumerate(out):
++ 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 = []
++ 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 {}
++ if arguments is None or (isinstance(arguments, str) and not arguments.strip()):
++ call = {**call, "function": {**function, "arguments": {}}}
++ elif isinstance(arguments, str):
++ try:
++ parsed = json.loads(arguments)
++ 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}")
++ 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
++ 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")}
++ for result in out[i + 1:end]]
++ return out
++
++
+ 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:
+ return getattr(self._inner, name)
+
+ def apply_chat_template(self, messages: Any, *args: Any, tokenize: bool = True, **kwargs: Any) -> Any:
++ messages = agent_history(messages)
+ if kwargs.get("enable_thinking", True) is not False:
+ return self._inner.apply_chat_template(messages, *args, tokenize=tokenize, **kwargs)
+ text = thinking_off(self._inner.apply_chat_template(messages, *args, tokenize=False, **kwargs))
+diff --git tensorfold/server/messages.py tensorfold/server/messages.py
+index dde2b67..2679969 100644
+--- tensorfold/server/messages.py
++++ tensorfold/server/messages.py
+@@ -73,6 +73,11 @@ def normalize_messages(messages: list[dict[str, Any]], *, late_system: str = "sy
+ elif not isinstance(content, str):
+ raise RequestError("message content must be text or an array of text parts")
+ item = message if content is message.get("content") else {**message, "content": content}
++ if (role == "assistant" and not isinstance(message.get("reasoning_content"), str)
++ and isinstance(message.get("reasoning"), str)):
++ # vLLM's newer replies and OpenRouter's name a step's reasoning ``reasoning``; templates read
++ # ``reasoning_content``, and without it a tool step's reasoning is dropped from the resent history
++ item = {**item, "reasoning_content": message["reasoning"]}
+ if role in ("system", "developer"):
+ if not out:
+ instructions.append(item)
+diff --git tensorfold/tool_parameters.py tensorfold/tool_parameters.py
+index 2ae9146..ea2fae6 100644
+--- tensorfold/tool_parameters.py
++++ tensorfold/tool_parameters.py
+@@ -1,4 +1,9 @@
+-"""Schema-aware decoding of Qwen XML parameter text."""
++"""Schema-aware decoding of Qwen XML parameter text.
++
++Parts adapted from jayleaton/glm53-tensorfold-spark patch 0620 (Apache-2.0): ``const`` schemas, and ``null`` read as
++None for a nullable string (its ``typed_value``), here in 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) are not.
++"""
+
+ from __future__ import annotations
+
+@@ -23,9 +28,39 @@ def parameter_schemas(tools: Sequence[dict[str, Any]] | None) -> dict[str, dict[
+ return result
+
+
+-def typed_parameter(schema: dict[str, Any]) -> bool:
++_TYPED = frozenset({"array", "object", "boolean", "integer", "number", "null"})
++_KINDS = {bool: "boolean", int: "integer", float: "number", str: "string", type(None): "null", list: "array",
++ dict: "object"}
++
++
++def schema_types(schema: dict[str, Any]) -> frozenset[str]:
++ """The JSON types a parameter schema admits: its ``type`` (a name or a list of names), else those of its
++ ``anyOf`` / ``oneOf`` members (none if a member is untyped), else those of its ``enum`` values or ``const``."""
++
+ kind = schema.get("type")
+- return isinstance(kind, str) and kind in {"array", "object", "boolean", "integer", "number", "null"}
++ if isinstance(kind, str):
++ return frozenset({kind})
++ if isinstance(kind, list):
++ return frozenset(k for k in kind if isinstance(k, str))
++ for key in ("anyOf", "oneOf"):
++ members = schema.get(key)
++ if isinstance(members, list) and members:
++ found = [schema_types(m) if isinstance(m, dict) else frozenset() for m in members]
++ return frozenset().union(*found) if all(found) else frozenset()
++ enum = schema.get("enum")
++ if isinstance(enum, list) and enum:
++ return frozenset(_KINDS.get(type(v), "string") for v in enum)
++ if "const" in schema:
++ return frozenset({_KINDS.get(type(schema["const"]), "string")})
++ return frozenset()
++
++
++def typed_parameter(schema: dict[str, Any]) -> bool:
++ """Whether a value is read as JSON: every type the schema admits is a JSON one other than string (a union with
++ string, such as ``["string", "null"]``, keeps the text as written)."""
++
++ kinds = schema_types(schema)
++ return bool(kinds) and kinds <= _TYPED
+
+
+ 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
+
+
++def nullable_text(schema: dict[str, Any]) -> bool:
++ """Whether a text value may also be null (``["string", "null"]``, pydantic's ``Optional[str]``): its value
++ ``null`` is None, as vLLM's GLM and Qwen parsers read it and as the templates render a None argument."""
++
++ kinds = schema_types(schema)
++ return "string" in kinds and "null" in kinds
++
++
+ def decode_parameter(value: str, schema: dict[str, Any]) -> Any:
++ """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)."""
++
+ if not typed_parameter(schema):
+- return value
+- kind = schema["type"]
++ return None if nullable_text(schema) and value == "null" else value
++ kinds = schema_types(schema)
+ # 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
diff --git a/patches/0040-cuda-tokenize.patch b/patches/0040-cuda-tokenize.patch
new file mode 100644
index 0000000..bb994c3
--- /dev/null
+++ b/patches/0040-cuda-tokenize.patch
@@ -0,0 +1,128 @@
+diff --git tensorfold/cuda/http.py tensorfold/cuda/http.py
+index c3d7cca..da26749 100644
+--- tensorfold/cuda/http.py
++++ tensorfold/cuda/http.py
+@@ -18,6 +18,9 @@ if TYPE_CHECKING:
+ from tensorfold.cuda.server import App
+
+
++_TOKENIZER_ROUTES = ("/tokenize", "/v1/tokenize", "/detokenize", "/v1/detokenize")
++
++
+ 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):
+ 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")
+- if not chat and not self.path.rstrip("/").endswith("/completions"):
++ tokenizer = self.path.rstrip("/") in _TOKENIZER_ROUTES
++ if not chat and not tokenizer and not self.path.rstrip("/").endswith("/completions"):
+ 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):
+ 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"}})
++ if tokenizer: # vLLM's /tokenize and /detokenize
++ try:
++ reply = (app.detokenize(body) if self.path.rstrip("/").endswith("/detokenize")
++ else app.tokenize(body))
++ except RequestError as exc:
++ return self._json(400, {"error": {"message": str(exc), "type": "invalid_request_error"}})
++ except Exception as exc:
++ _log_error(exc)
++ return self._json(400, {"error": {"message": _error_message(exc)}})
++ return self._json(200, reply)
+ try:
+ prepared = app.prepare(body, chat)
+ except RequestError as exc:
+diff --git tensorfold/cuda/server.py tensorfold/cuda/server.py
+index 4ab6484..bbcf1a1 100644
+--- tensorfold/cuda/server.py
++++ tensorfold/cuda/server.py
+@@ -190,17 +190,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"])
++ prompt = self.tok.encode(text, add_special_tokens=False).ids
++ elif isinstance(body.get("prompt"), list): # token ids (vLLM's and OpenAI's form): served as given
++ prompt = self.token_ids(body["prompt"])
+ else:
+ text = body.get("prompt")
+ if not isinstance(text, str):
+- raise RequestError("prompt must be a string")
+- prompt = self.tok.encode(text, add_special_tokens=False).ids
++ raise RequestError("prompt must be a string or a list of token ids")
++ prompt = self.tok.encode(text, add_special_tokens=_flag(body, "add_special_tokens", False)).ids
+ if not prompt:
+ raise RequestError("rendered prompt is empty")
+ # sampling is resolved here, so a malformed control is refused before a stream opens
+ return PreparedRequest(prompt, max_tokens, tools, thinking, self.sampling_for(body, prompt),
+ ignore_eos=ignore_eos, stop=stop, grammar=compiled, think_budget=budget)
+
++ def token_ids(self, value: Any, field: str = "prompt") -> list[int]:
++ """Token ids as a request gives them (a list, or a list holding one list); RequestError outside the vocabulary."""
++
++ if isinstance(value, list) and len(value) == 1 and isinstance(value[0], list):
++ value = value[0]
++ if not isinstance(value, list) or any(type(t) is not int for t in value):
++ raise RequestError(f"{field} must be a list of integer token ids (one prompt a request)")
++ size = getattr(self.tok, "get_vocab_size", None)
++ vocab = size(with_added_tokens=True) if size is not None else None
++ if any(t < 0 or (vocab is not None and t >= vocab) for t in value):
++ top = "" if vocab is None else f" to {vocab - 1}"
++ raise RequestError(f"{field} token ids must be in the vocabulary's range 0{top}")
++ return list(value)
++
++ def tokenize(self, body: dict[str, Any]) -> dict[str, Any]:
++ """vLLM's ``/tokenize``: a prompt's ids (``add_special_tokens`` as vLLM, default true), or ``messages``' as the
++ chat route renders them (``add_generation_prompt``, default true)."""
++
++ if not isinstance(body, dict):
++ raise RequestError("the request body must be a JSON object")
++ if "messages" in body:
++ fields = dict(body)
++ if "add_generation_prompt" in body:
++ kwargs = body.get("chat_template_kwargs")
++ kwargs = {} if kwargs is None else kwargs
++ if not isinstance(kwargs, dict):
++ raise RequestError("chat_template_kwargs must be a JSON object or null")
++ fields["chat_template_kwargs"] = {**kwargs,
++ "add_generation_prompt": _flag(body, "add_generation_prompt", True)}
++ ids = self._prepare(fields, True).prompt
++ else:
++ text = body.get("prompt")
++ if not isinstance(text, str):
++ raise RequestError("prompt must be a string (or send messages)")
++ ids = self.tok.encode(text, add_special_tokens=_flag(body, "add_special_tokens", True)).ids
++ limit = self._context_limit()
++ return {"count": len(ids), "max_model_len": limit if limit is not None else self.native_context_window,
++ "tokens": [int(t) for t in ids]}
++
++ def detokenize(self, body: dict[str, Any]) -> dict[str, Any]:
++ """vLLM's ``/detokenize``: the text of ``tokens``, special tokens included."""
++
++ if not isinstance(body, dict):
++ raise RequestError("the request body must be a JSON object")
++ return {"prompt": self.tok.decode(self.token_ids(body.get("tokens"), "tokens"), skip_special_tokens=False)}
++
+ 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:
+ encode=lambda t: list(self.tok.encode(t, add_special_tokens=False).ids))
+
+
++def _flag(body: dict[str, Any], name: str, default: bool) -> bool:
++ value = body.get(name, default)
++ if not isinstance(value, bool):
++ raise RequestError(f"{name} must be a boolean")
++ return value
++
++
+ def token_sha(tokens: list[int]) -> str:
+ """A reply's token ids, hashed as the Mac server does: drafted and ``"draft": false`` replies must match."""
+
diff --git a/patches/0041-glm-kv-fp8.patch b/patches/0041-glm-kv-fp8.patch
new file mode 100644
index 0000000..1df6db5
--- /dev/null
+++ b/patches/0041-glm-kv-fp8.patch
@@ -0,0 +1,1563 @@
+diff --git tensorfold/cuda/geometry.py tensorfold/cuda/geometry.py
+index 49f10d0..afce1d7 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,
+ + 12 * streams + 64)
+
+
++def mla_row_bytes(width: int, kv: str = "bf16") -> int:
++ """A GLM DSA cache row of ``width`` values: bf16, or TF_GLM_KV=fp8's e4m3 codes, fp32 scale and 12 pad bytes
++ (families/glm5_next/cuda/kv8.py)."""
++ if kv not in ("bf16", "fp8"):
++ raise ValueError(f"a GLM DSA cache is bf16 or fp8, not {kv!r}")
++ return width + 16 if kv == "fp8" else 2 * width
++
++
++def mla_index_ring(capacity: int, rows: int) -> int:
++ """Rows of GLM's indexer key and gate rings (forward.index_ring): the widest window and 3, rounded up to 64."""
++ return min(capacity, -(-(rows + 3) // 64) * 64)
++
++
++def mla_ring_bytes(t: dict, rows: int) -> int:
++ """One stream slot's indexer key and gate rings on a rank (forward.Caches): every indexed layer (the DSA layers
++ and the MTP layer), 2 x ``mla_index_ring`` rows of the index width in bf16, at most (a small window's ring is the
++ window)."""
++ _, attention = layer_counts(t)
++ count = attention + int(int(t.get("num_nextn_predict_layers", 0)) > 0)
++ return count * 2 * -(-(rows + 3) // 64) * 64 * int(t.get("index_head_dim", 128)) * 2
++
++
+ 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
+
+ def mla_geometry(t: dict, world: int, reserve: int, *, minimum_slots: int = 2560, latent: bool = False,
+ prefill_rows: int = PREFILL_ROWS, mtp: bool | None = None, onepass: bool = False,
+- exl3_prompt: bool = True, prompt_split_k: bool = True) -> Geometry:
++ exl3_prompt: bool = True, prompt_split_k: bool = True, kv: str = "bf16") -> Geometry:
+ """GLM's engine: ``mtp`` whether it holds the MTP head's caches and decode buffers (None: when the checkpoint has
+ one; GLM's TF_GLM_MTP can leave it out); ``onepass``: prompt chunks' sparse latent attention keeps no partials
+ (TF_GLM_SPARSE_ONEPASS); an EXL3 checkpoint's ``exl3_prompt``: prompt chunks run the prompt expert kernels
+ (TF_GLM_EXL3_PROMPT: no split-K sums), ``prompt_split_k``: the prompt buffers keep split-K partials for BF16 / FP8
+- projections (``forward.Buffers.sk``)."""
++ projections (``forward.Buffers.sk``); ``kv``: the DSA caches' format (TF_GLM_KV: the latent rows and the
++ indexer's pooled keys; the indexer's per-token keys and gates are bf16 rings)."""
+ 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
+ fixed += 8 * prefill_rows * 16384 * 4 if prompt_split_k else 0
+ count = attention + int(mtp)
+ lw = int(t.get("kv_lora_rank", 512))
++ if kv != "bf16" and not latent:
++ raise ValueError("TF_GLM_KV=fp8 needs the latent cache")
+ def bytes_at(capacity: int) -> int:
+ scratch = mla_chunk_scratch(t, world, capacity, latent=latent, prefill_rows=prefill_rows, onepass=onepass)
+ if latent:
+ # latent cache; a prompt chunk's latent partials (its dense pass runs MLA_PROMPT_ATT_ROWS rows at a time)
+ # and absorbed rows (the MTP absorbs through the same buffers)
+- cache = count * capacity * lw * 2
++ cache = count * capacity * mla_row_bytes(lw, kv)
+ dense = min(capacity, minimum_slots) + prefill_rows
+ 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
+- cache += count * (2 * capacity + capacity // 4 + 2) * index * 2
++ # the indexer's pooled keys over the capacity, its per-token keys and gates in rings (forward.Caches)
++ ring = mla_index_ring(capacity, max(prefill_rows, rows))
++ cache += count * (2 * ring * index * 2 + (capacity // 4 + 2) * mla_row_bytes(index, kv))
+ return fixed + cache + scratch
+ 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
+--- tensorfold/families/glm5_next/cuda/decode.py
++++ tensorfold/families/glm5_next/cuda/decode.py
+@@ -85,13 +85,14 @@ class Engine:
+ def __init__(self, w: Weights, *, capacity: int = 2560, max_rows: int = 8, prefill_rows: int = PREFILL_ROWS,
+ graphs: bool = False, graph_rows: tuple[int, ...] = (1, 2, 3, 4), long_context: bool = False,
+ taps: tuple[int, ...] = (), grid: int = 0, split=None, mtp_rows: int | None = None,
+- streams: int = 1, pool_rows: int | None = None) -> None:
+- """``grid``: prompt chunks start on multiples of it (TF_GLM_PROMPT_GRID; 0: anywhere); ``split``: a
+- ``hcsplit.SplitSettings`` (TF_GLM_HC_SPLIT, TF_GLM_PREFILL_OVERLAP) for prompt chunks, None or off: unsplit;
+- ``mtp_rows``: rows of an MTP step (its absorb chunks; default ``max_rows``): draft chains take one row a step,
+- so the MTP buffers need not be as wide as the verify windows; ``streams``: stream slots (``forward.Slots``)
+- and ``pool_rows``: tokens of the shared cache pool (``forward.Caches``, default ``capacity``) for concurrent
+- streams (``multi``). ``st`` is the state the single-stream paths run on: ``home`` (slot 0, the pool's first
++ streams: int = 1, pool_rows: int | None = None, kv: str | None = None) -> None:
++ """``kv``: the DSA caches' format (``kv8``; default TF_GLM_KV, bf16 unless set: fp8 halves the latent cache and
++ the indexer's pooled keys); ``grid``: prompt chunks start on multiples of it (TF_GLM_PROMPT_GRID; 0:
++ anywhere); ``split``: a ``hcsplit.SplitSettings`` (TF_GLM_HC_SPLIT, TF_GLM_PREFILL_OVERLAP) for prompt
++ chunks, None or off: unsplit; ``mtp_rows``: rows of an MTP step (its absorb chunks; default ``max_rows``):
++ draft chains take one row a step, so the MTP buffers need not be as wide as the verify windows; ``streams``:
++ stream slots (``forward.Slots``) and ``pool_rows``: tokens of the shared cache pool (``forward.Caches``,
++ default ``capacity``) for concurrent streams (``multi``). ``st`` is the state the single-stream paths run on: ``home`` (slot 0, the pool's first
+ ``capacity`` tokens), the one the CUDA graphs were captured on, unless ``use`` points it at another."""
+
+ if grid and prefill_rows % grid:
+@@ -114,9 +115,15 @@ class Engine:
+
+ self.pbuf.split = HcSplit(w, self.pbuf, split)
+ self.mbuf = Buffers(w, min(mtp_rows or max_rows, max_rows), capacity) if w.mtp is not None else None
+- from .forward import Caches, Slots
++ from .forward import Caches, Slots, index_ring
+
+- self.caches = Caches(w, pool_rows or capacity)
++ # the indexer's key and gate rings, one a slot, hold the widest window (a prompt chunk, an MTP absorb chunk, a
++ # verify window, a stream's rows of a batched window) and the 3 rows before it
++ from . import kv8
++
++ self.caches = Caches(w, pool_rows or capacity, streams=streams,
++ ring=index_ring(pool_rows or capacity, max(max_rows, prefill_rows)),
++ kv=kv8.kv_kind() if kv is None else kv)
+ 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:
+ 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
++ tail: list | None = None # the indexer rings' rows of the pools still filling at ids' end (``_ring_tail``)
++
++
++def _ring_tail(st, n: int, m: int) -> list[tuple[torch.Tensor, torch.Tensor]]:
++ """(slots, rows) of the indexer's key and gate rings a snapshot of n tokens (m in the MTP head) needs besides the
++ pools: the tokens of each layer's pool still filling (n % 4 of them, the last ones), which later tokens' windows
++ overwrite in the ring (``forward.index_ring``). slots: ring rows (positions mod the ring); rows: [2, k, 128]
++ (keys, gates), cloned."""
++ index, kc = getattr(st, "index", None) or [], getattr(st, "kc", [])
++ out = []
++
++ def take(trio, end):
++ ik, ig, _ = trio
++ slots = torch.arange(end - end % 4, end, device=ik.device) % ik.shape[0]
++ out.append((slots, torch.stack((ik[slots], ig[slots]))))
++
++ for trio in index[:len(kc)]:
++ if n % 4:
++ take(trio, n)
++ if m > 0 and m % 4 and len(index) > len(kc):
++ take(index[-1], m)
++ return out
++
++
++def put_ring_tail(st, snap: Snapshot) -> None:
++ """A kept snapshot's ring tail (``_ring_tail``) into ``st``'s rings (restore, and a multi-stream stream taking
++ over a kept prompt in any slot)."""
++ index, kc = getattr(st, "index", None) or [], getattr(st, "kc", [])
++ idx = list(index[:len(kc)]) if len(snap.ids) % 4 else []
++ if snap.mtp_len > 0 and snap.mtp_len % 4 and len(index) > len(kc):
++ idx.append(index[-1])
++ tail = snap.tail or []
++ if len(tail) != len(idx):
++ raise ValueError("a snapshot's indexer ring rows do not match the caches they go back to")
++ for (ik, ig, _), (slots, rows) in zip(idx, tail):
++ ik.index_copy_(0, slots % ik.shape[0], rows[0])
++ ig.index_copy_(0, slots % ig.shape[0], rows[1])
+
+
+ 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."""
++ """A ring drafter's window rows are copied now (``_ring_window``): its next rows overwrite them in the ring; so
++ are the indexer rings' rows of the pools still filling (``_ring_tail``)."""
+ st = e.st
+ rec = st.rec[st.cur[0]].clone() if st.cur else st.rec[0].clone()
++ mtp_len = st.mtp_len - st.mtp_drafted if mtp and pending is not None else -1
+ 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)
++ mtp_len, drafter.context_end if drafter is not None else -1,
++ tail=_ring_tail(st, len(ids), max(mtp_len, 0)))
+ 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]:
+- """Views of the attention rows a snapshot of n tokens (m in the MTP head) depends on: latents or keys and values, indexer keys, gates and pools."""
++ """Views of the attention rows a snapshot of n tokens (m in the MTP head) depends on: latents or keys and values,
++ and the indexer's pooled keys (its per-token keys and gates live in rings: the snapshot's ``tail``)."""
+ views = [kc[:n] for kc in st.kc] + [vc[:n] for vc in st.vc if vc is not None]
+ idx = st.index or []
+ main_idx = idx[:len(st.kc)]
+- for ik, ig, pk in main_idx:
+- views += [ik[:n], ig[:n], pk[:n // 4 + 1]]
++ for _, _, pk in main_idx:
++ views.append(pk[:n // 4 + 1])
+ if m > 0 and hasattr(st, "mtp_kc"):
+ views.append(st.mtp_kc[:m])
+ if getattr(st, "mtp_vc", None) is not None:
+ views.append(st.mtp_vc[:m])
+ if len(idx) > len(st.kc):
+- ik, ig, pk = idx[-1]
+- views += [ik[:m], ig[:m], pk[:m // 4 + 1]]
++ views.append(idx[-1][2][:m // 4 + 1])
+ return views
+
+
+@@ -374,9 +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."""
++ """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 [])
++ held += [t for pair in (snap.tail or []) for t in pair]
+ 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:
+
+ def restore(e: Engine, snap: Snapshot, drafter=None) -> None:
+ st = e.st
++ put_ring_tail(st, snap)
+ if st.cur:
+ 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
+--- tensorfold/families/glm5_next/cuda/engine.py
++++ tensorfold/families/glm5_next/cuda/engine.py
+@@ -388,7 +388,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,
+- split_weights)
++ mla_ring_bytes, split_weights)
+
+ 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:
+ # 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_KV=fp8: the DSA latent cache and the indexer's pooled keys as e4m3 rows (``kv8``), half the bytes
++ from .kv8 import KINDS as KV_KINDS, kv_kind
++
++ kv = kv_kind()
++ 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
+ 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:
+
+ 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")
++ prompt_split_k=cfg.quant == "exl3" and dense_kind() != "q4", kv=kv)
+ # --parallel: every stream slot past the first (KDA states, conv windows, window scratch); the batched
+ # verify window's buffers fit the decode rows the estimate sizes (MLA_DECODE_ROWS), its token selection's
+ # fp32 scores (MAX_WINDOW rows x a pool of 4 tokens) grow with the pool
+- extra = workspace + (parallel - 1) * slot_bytes(text)
++ extra = workspace + (parallel - 1) * (slot_bytes(text) + mla_ring_bytes(text, prefill_rows))
+ per = 4 * MULTI_WINDOW // 4 if parallel > 1 else 0
+ if not extra and not per:
+ return g
+@@ -523,7 +530,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),
+- sum(WIDE_GRAPHS), max(WIDE_GRAPHS, default=0)]
++ sum(WIDE_GRAPHS), max(WIDE_GRAPHS, default=0),
++ KV_KINDS.index(kv)]
+ # 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:
+ "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, "
+- "TENSORFOLD_NUCLEUS_UNION, TF_GLM_MAX_ROWS, TF_GLM_WIDE_GRAPHS): "
++ "TENSORFOLD_NUCLEUS_UNION, TF_GLM_MAX_ROWS, TF_GLM_WIDE_GRAPHS, TF_GLM_KV): "
+ f"rank 0 {both[0][:-1]}, rank 1 {both[1][:-1]}; pull the draft model on both machines "
+ "(or pass --drafter none to both) and give both the same flags")
+ self.cache_bytes = min(both[0][-1], both[1][-1]) << 20
+@@ -585,7 +593,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,
+- split=self.split, mtp_rows=MTP_ROWS, streams=parallel, pool_rows=pool_rows)
++ split=self.split, mtp_rows=MTP_ROWS, streams=parallel, pool_rows=pool_rows, kv=kv)
+ 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:
+ 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)
++ if rank == 0 and kv != "bf16":
++ print("[tensorfold] TF_GLM_KV=fp8: the DSA latent cache and the indexer's pooled keys as e4m3 rows with a "
++ "power-of-two scale each (lossy; drafted replies still equal serial ones)", flush=True)
+ if rank == 0 and quant_code:
+ 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
+--- 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
+ from tensorfold.cuda.kernels import prefill_attention, qmm as shared
+
+-from . import glue, kda as kda_mod, latent, prof, qmm, sparse
++from . import glue, kda as kda_mod, kv8, latent, prof, qmm, sparse
+ from .attention import AttnScratch, attention, kv_write
+ from .weights import LayerW, Weights
+
+@@ -160,13 +160,28 @@ class Buffers:
+ return p
+
+
++def index_ring(capacity: int, rows: int) -> int:
++ """Rows of the indexer's key and gate rings (``sparse.index_update``) for windows of up to ``rows`` rows: those
++ and the 3 before them, rounded up to 64; the context when that is less (then no row wraps)."""
++ return min(capacity, -(-(rows + 3) // 64) * 64)
++
++
+ class Caches:
+ """Every per-token cache of the model over ``rows`` tokens of a shared pool (``pool.Arena``): per DSA layer its
+ latents (or keys and values without the latent cache); the MTP layer's; and with long contexts per indexed layer
+ (the DSA layers, then the MTP layer) its index keys, gates and pooled keys (a row a pool of 4 tokens, 2 rows of
+- pad). Element types and layouts are decided here; a ``State`` views them over its extent (``bind``)."""
++ pad). Element types and layouts are decided here; a ``State`` views them over its extent (``bind``).
++
++ ``ring``: the index keys and gates (read only by the pool a token falls in, while it fills) are not arena planes
++ but one ring of ``ring`` rows per stream slot (``streams`` of them, ``index_ring``): token t of the stream in slot
++ s at row s x ring + t % ring. They stay with the slot when its extent moves; a kept prompt carries the rows of its
++ pools still filling (``decode.Snapshot.tail``). None: arena planes (token t at its extent's row).
+
+- def __init__(self, w: Weights, rows: int) -> None:
++ ``kv``: the latent planes' and pooled keys' format (TF_GLM_KV, ``kv8``): bf16, or fp8 (a uint8 row a token /
++ pool: e4m3 codes, an fp32 power-of-two scale, pad), with the latent cache only."""
++
++ def __init__(self, w: Weights, rows: int, *, streams: int = 1, ring: int | None = None,
++ kv: str = "bf16") -> None:
+ from .pool import Arena, Plane
+
+ c = w.cfg
+@@ -174,15 +189,21 @@ class Caches:
+ HL = c.heads // w.world
+ dsa = len([l for l in w.layers if l.kind == "dsa"])
+ self.latent = latent.ENABLED
++ if kv not in kv8.KINDS or (kv != "bf16" and not self.latent):
++ raise ValueError(f"TF_GLM_KV={kv}: bf16, or fp8 with the latent cache (TF_GLM_LATENT=1)")
++ self.kv = kv
+ planes: list[Plane] = []
+
+- def add(shape, div: int = 1, pad: int = 0) -> int:
+- planes.append(Plane(torch.zeros((rows // div + pad, *shape), dtype=torch.bfloat16, device=dev), div, pad))
++ def add(shape, div: int = 1, pad: int = 0, fmt: str = "bf16") -> int:
++ n = rows // div + pad
++ t = (kv8.zeros(n, shape[0], fmt, dev) if fmt != "bf16" else
++ torch.zeros((n, *shape), dtype=torch.bfloat16, device=dev))
++ planes.append(Plane(t, div, pad))
+ return len(planes) - 1
+
+ def attention_planes() -> tuple[int, int | None]:
+ if self.latent: # one 512-wide latent a token and layer (kc), no separate values (vc)
+- return add((c.kv_lora,)), None
++ return add((c.kv_lora,), fmt=kv), None
+ return add((HL, c.qk_dim)), add((HL, c.v_dim))
+
+ self.kc, self.vc = [], []
+@@ -191,14 +212,42 @@ class Caches:
+ self.kc.append(k)
+ self.vc.append(v)
+ self.mtp = attention_planes() if w.mtp is not None else None
+- # DSA indexer caches (long contexts only): per layer (and the MTP layer, last) keys, gates, pool keys
++ # DSA indexer caches (long contexts only): per layer (and the MTP layer, last) keys, gates, pool keys; with a
++ # ring, index[i] = (None, None, pool plane) and rings[i] = (keys, gates) [streams x ring, 128]
+ self.index = None
++ self.rings = None
++ self.ring = None if ring is None else int(ring)
++ if self.ring is not None and self.ring < 4:
++ raise ValueError(f"index rings of {self.ring} rows")
+ if w.meta.get("long_context"):
+ n_idx = dsa + (1 if w.mtp is not None else 0)
+- self.index = [(add((c.index_dim,)), add((c.index_dim,)), add((c.index_dim,), 4, 2)) for _ in range(n_idx)]
++ if self.ring is None:
++ self.index = [(add((c.index_dim,)), add((c.index_dim,)), add((c.index_dim,), 4, 2, kv))
++ for _ in range(n_idx)]
++ else:
++ self.index = [(None, None, add((c.index_dim,), 4, 2, kv)) for _ in range(n_idx)]
++ ring_rows = int(streams) * self.ring
++ self.rings = [tuple(torch.zeros((ring_rows, c.index_dim), dtype=torch.bfloat16, device=dev)
++ for _ in range(2)) for _ in range(n_idx)]
+ self.arena = Arena(rows, planes)
+ self.rows = rows
+
++ def index_tensors(self, i: int) -> tuple:
++ """Indexed layer i's (keys, gates, pooled keys) over every stream: the rings (or planes) and the pool plane."""
++
++ planes = self.arena.planes
++ pk = planes[self.index[i][2]].tensor
++ if self.rings is None:
++ return planes[self.index[i][0]].tensor, planes[self.index[i][1]].tensor, pk
++ return self.rings[i][0], self.rings[i][1], pk
++
++ def ring_base(self, slot: int) -> int:
++ """The first ring row of stream slot ``slot`` (index rows at ring_base + t % ring)."""
++ return 0 if self.ring is None else int(slot) * self.ring
++
++ def ring_bytes(self) -> int:
++ return sum(t.numel() * t.element_size() for pair in (self.rings or []) for t in pair)
++
+ 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:
+ 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])
+- st.index = None if self.index is None else [tuple(view(i) for i in trio) for trio in self.index]
++ if self.index is None:
++ st.index = None
++ elif self.rings is None:
++ st.index = [tuple(view(i) for i in trio) for trio in self.index]
++ else: # the slot's rings (index_update's ring: their rows) and the extent's pools
++ r0 = self.ring_base(st.slot)
++ st.index = [(ik[r0:r0 + self.ring], ig[r0:r0 + self.ring], view(trio[2]))
++ for (ik, ig), trio in zip(self.rings, self.index)]
+
+
+ class Slots:
+@@ -257,8 +313,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,
+- slots: Slots | None = None, slot: int = 0) -> None:
+- self.caches = caches if caches is not None else Caches(w, capacity)
++ slots: Slots | None = None, slot: int = 0, kv: str = "bf16") -> None:
++ self.caches = caches if caches is not None else Caches(w, capacity, kv=kv)
+ 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:
+ self.base, self.capacity = int(base), int(capacity)
+ self.caches.bind(self, self.base, self.capacity)
+
++ @property
++ def kv(self) -> str:
++ """The DSA caches' format (TF_GLM_KV): the pool's."""
++ return self.caches.kv
++
+ @property
+ def graph_key(self) -> tuple[int, int]:
+ """What a captured graph baked in besides the shared buffers: the slot and the extent's base."""
+diff --git tensorfold/families/glm5_next/cuda/kv8.py tensorfold/families/glm5_next/cuda/kv8.py
+new file mode 100644
+index 0000000..ed7bf56
+--- /dev/null
++++ tensorfold/families/glm5_next/cuda/kv8.py
+@@ -0,0 +1,137 @@
++"""TF_GLM_KV=fp8: DSA's caches (the 512-wide latent a token and layer, the indexer's pooled keys) as FP8 e4m3 rows
++with a power-of-two scale each, about half the bytes of bf16. Lossy (the owner's call), never inexact: a row's bytes
++are a function of its bf16 row alone (one kernel helper, ``store_row``, quantizes prompt chunks' and decode windows'
++rows), and the readers take the codes to bf16 (exact) and fold each row's scale into their fp32 products (exact for a
++power of two), so a row's attention still depends on its query, its keys and the cache only: drafted == serial and
++resumed == fresh hold as with bf16 (tests/cuda/test_glm_kv8.py). The values are those of the bf16 kernels on the
++dequantized rows up to fp32 summation order (Triton lays converted tiles out for the tensor cores its own way).
++
++A quantized cache is a uint8 tensor [rows, width + PAD]: the row's e4m3 codes, its fp32 scale, 12 zero bytes (rows
++stay 16-byte aligned). One tensor a cache keeps the engine's generic row handling (slices, clones, kept snapshots'
++saved rows, ``row_bytes``) as it is. The scale is 2^(ceil(log2 amax) - SHIFT): the row's largest value quantizes to
++[128, 256], under e4m3's 448, so nothing saturates; a floating-point format's relative precision does not depend on
++the scale, so a per-row power of two loses nothing to a finer or fp32 scale but the values it pushes below e4m3's
++normal range (2^-6), under 2^-14 of the row's largest (DeepSeek-V3.2's indexer keeps FP8 keys with per-token ue8m0
++scales alike). On GLM-5.3-Flash's own kv_a / kv_a_layernorm rows (amax ~3-5x the rms) per-token fp32, per-128-block
++and fixed per-layer scales all land within 0.001 of this one's 2.65% relative error a row. bf16 caches stay as they were (a bf16 tensor [rows, width]); every kernel tells the two by dtype."""
++
++from __future__ import annotations
++
++import os
++
++import torch
++import triton
++import triton.language as tl
++
++KINDS = ("bf16", "fp8")
++PAD = 16 # bytes after an FP8 row's codes: its fp32 scale, then zeros
++SHIFT = 8 # a row's scale: 2^(ceil(log2 amax) - SHIFT), so its codes stay within +-256
++
++
++def kv_kind(env=None) -> str:
++ """TF_GLM_KV: bf16 (the default) or fp8, the DSA latent and indexer key caches' format (lossy: replies differ from
++ bf16's; drafted replies still equal serial ones, resumed prompts fresh ones)."""
++
++ kind = (os.environ if env is None else env).get("TF_GLM_KV", "bf16").strip() or "bf16"
++ if kind not in KINDS:
++ raise ValueError(f"TF_GLM_KV is bf16 or fp8, not {kind!r}")
++ return kind
++
++
++def row_bytes(width: int, kind: str) -> int:
++ """Bytes a cache row of ``width`` values takes."""
++ if kind not in KINDS:
++ raise ValueError(f"a cache is bf16 or fp8, not {kind!r}")
++ return width + PAD if kind == "fp8" else 2 * width
++
++
++def zeros(rows: int, width: int, kind: str, device) -> torch.Tensor:
++ """A zeroed cache of ``rows`` rows of ``width`` values (zero rows dequantize to zeros in either format)."""
++ if kind == "fp8":
++ if width % 4:
++ raise ValueError(f"an FP8 cache row needs a width divisible by 4, not {width}")
++ return torch.zeros((rows, width + PAD), dtype=torch.uint8, device=device)
++ return torch.zeros((rows, row_bytes(width, kind) // 2), dtype=torch.bfloat16, device=device)
++
++
++def quantized(cache: torch.Tensor) -> bool:
++ return cache.dtype == torch.uint8
++
++
++def kind_of(cache: torch.Tensor) -> str:
++ return "fp8" if quantized(cache) else "bf16"
++
++
++def width(cache: torch.Tensor) -> int:
++ """Values a row of ``cache`` holds."""
++ return cache.shape[-1] - PAD if quantized(cache) else cache.shape[-1]
++
++
++def parts(cache: torch.Tensor):
++ """A kernel's view of a cache: (codes or bf16 values, fp32 view for the scales, row stride in elements of the
++ first, FP8). A bf16 cache passes itself as the unused scale argument."""
++ if not quantized(cache):
++ return cache, cache, cache.shape[-1], False
++ if cache.stride(-1) != 1 or cache.shape[-1] % 16:
++ raise ValueError("an FP8 cache: contiguous rows of width + 16 bytes")
++ return cache.view(torch.float8_e4m3fn), cache.view(torch.float32), cache.shape[-1], True
++
++
++# -- the format in torch (tests, and the definition the kernels must equal) -------------------------------------------
++def scales(amax: torch.Tensor) -> torch.Tensor:
++ """fp32 amax -> the fp32 power-of-two scale (the kernels' ``scale_of``, bit for bit)."""
++ bits = amax.float().contiguous().view(torch.int32)
++ e = ((bits >> 23) & 0xFF) + ((bits & 0x7FFFFF) != 0).to(torch.int32)
++ return ((e - SHIFT).clamp(1, 254) << 23).view(torch.float32)
++
++
++def quantize_rows(x: torch.Tensor) -> torch.Tensor:
++ """bf16 (or fp32) rows [n, width] -> an FP8 cache's rows [n, width + PAD], as the write kernels store them."""
++ x = x.float()
++ s = scales(x.abs().amax(dim=1))
++ inv = ((254 - (s.view(torch.int32) >> 23)) << 23).view(torch.float32)
++ out = torch.zeros((x.shape[0], x.shape[1] + PAD), dtype=torch.uint8, device=x.device)
++ out[:, :x.shape[1]] = (x * inv[:, None]).to(torch.float8_e4m3fn).view(torch.uint8)
++ out[:, x.shape[1]:x.shape[1] + 4] = s[:, None].contiguous().view(torch.uint8)
++ return out
++
++
++def dequantize(cache: torch.Tensor) -> torch.Tensor:
++ """A cache's rows as fp32 [n, width] (exact: e4m3 codes times a power of two; bf16 rows as they are)."""
++ if not quantized(cache):
++ return cache.float()
++ w = width(cache)
++ codes = cache[..., :w].contiguous().view(torch.float8_e4m3fn).float()
++ s = cache[..., w:w + 4].contiguous().view(torch.float32)
++ return codes * s
++
++
++# -- the format in kernels ------------------------------------------------------------------------------------------
++def scale_of(amax):
++ """fp32 amax -> 2^(ceil(log2 amax) - SHIFT) and its reciprocal, both exact powers of two (biased exponent held
++ within 1 .. 254: a zero row gets 2^-126 and zeros)."""
++ bits = amax.to(tl.int32, bitcast=True)
++ e = ((bits >> 23) & 0xFF) + ((bits & 0x7FFFFF) != 0).to(tl.int32)
++ e = tl.minimum(tl.maximum(e - 8, 1), 254)
++ return (e << 23).to(tl.float32, bitcast=True), ((254 - e) << 23).to(tl.float32, bitcast=True)
++
++
++def store_row(VALS, SCL, row, x, LW: tl.constexpr, RS: tl.constexpr, FP8: tl.constexpr):
++ """Row ``row`` (int64) of a cache <- x fp32 [LW] as bf16 values, or FP8: the bf16 row's codes and scale."""
++ k = tl.arange(0, LW)
++ xb = x.to(tl.bfloat16)
++ if FP8:
++ xf = xb.to(tl.float32)
++ s, inv = scale_of(tl.max(tl.abs(xf), 0))
++ tl.store(VALS + row * RS + k, (xf * inv).to(tl.float8e4nv))
++ tl.store(SCL + row * (RS // 4) + LW // 4, s)
++ else:
++ tl.store(VALS + row * RS + k, xb)
++
++
++def row_scales(SCL, rows, ok, LW: tl.constexpr, RS: tl.constexpr):
++ """The scales of cache rows ``rows`` (int64 [N]; 1 where not ok)."""
++ return tl.load(SCL + rows * (RS // 4) + LW // 4, mask=ok, other=1.0)
+diff --git tensorfold/families/glm5_next/cuda/latent.py tensorfold/families/glm5_next/cuda/latent.py
+index 1cecc96..16358c9 100644
+--- tensorfold/families/glm5_next/cuda/latent.py
++++ tensorfold/families/glm5_next/cuda/latent.py
+@@ -7,6 +7,8 @@ import triton
+ import triton.language as tl
+
+ from . import LATENT as ENABLED # off (TF_GLM_LATENT=0): per-head keys and values, 0.3.5's path, for A/B
++from . import kv8
++from .kv8 import row_scales
+
+ L = 512 # GLM-5.3-Flash's latent width (kv_lora_rank); the kernels take the width from the tensors
+ CHUNK = 512 # keys per chunk program, merged in absolute order
+@@ -387,54 +389,76 @@ def expand_v(o_lat: torch.Tensor, a, out: torch.Tensor, *, prompt: bool = False)
+ # ------------------------------------------------------------------------------------------------ caches ---
+
+ @triton.jit
+-def _lat_write(LAT, lat_stride, LC, POS, LW: tl.constexpr):
++def _lat_write(LAT, lat_stride, LC, LS, POS, LW: tl.constexpr, RS: tl.constexpr, FP8: tl.constexpr):
++ """Row r -> cache slot pos + r: the bf16 row as it is, or (FP8) its codes and scale (kv8.store_row, a function
++ of the row alone: prompt chunks and decode windows store the same bytes)."""
+ r = tl.program_id(0)
+ P = tl.load(POS).to(tl.int64)
+ k = tl.arange(0, LW)
+- tl.store(LC + (P + r) * LW + k, tl.load(LAT + r * lat_stride + k))
++ kv8.store_row(LC, LS, P + r, tl.load(LAT + r * lat_stride + k).to(tl.float32), LW, RS, FP8)
+
+
+ def latent_write(lat: torch.Tensor, cache: torch.Tensor, pos: torch.Tensor) -> None:
+- """lat [R, latent] bf16 rows into cache slots pos .. pos + R - 1 (pos read on the device)."""
+- _lat_write[(lat.shape[0],)](lat, lat.stride(0), cache, pos, LW=cache.shape[1], num_warps=4)
++ """lat [R, latent] bf16 rows into cache slots pos .. pos + R - 1 (pos read on the device); an FP8 cache
++ (TF_GLM_KV=fp8) takes each row's e4m3 codes and power-of-two scale."""
++ vals, scl, rs, fp8 = kv8.parts(cache)
++ if lat.shape[1] != kv8.width(cache):
++ raise ValueError(f"latent_write: rows of {lat.shape[1]} into a cache of {kv8.width(cache)}")
++ _lat_write[(lat.shape[0],)](lat, lat.stride(0), vals, scl, pos, LW=lat.shape[1], RS=rs, FP8=fp8, num_warps=4)
+
+
+ # --------------------------------------------------------------------------------------------- attention ---
+
+ @triton.jit
+-def _tile(q, kv, m, l, o, valid, SCALE: tl.constexpr):
+- """One key tile for HB heads of one row: kv [KT, 512] is both key and value (the latent)."""
+- scores = tl.dot(q, tl.trans(kv)).to(tl.float32) * SCALE
++def _tile(q, kv, ks, m, l, o, valid, SCALE: tl.constexpr, FP8: tl.constexpr):
++ """One key tile for HB heads of one row: kv [KT, 512] is both key and value (the latent). FP8: kv holds a
++ quantized cache's codes (exact in bf16) and ks [KT] their power-of-two scales, folded into the scores and the
++ probabilities (exactly: scaling by a power of two rounds nothing), so the arithmetic is this tile's on the
++ dequantized rows."""
++ scores = tl.dot(q, tl.trans(kv)).to(tl.float32)
++ if FP8:
++ scores = scores * ks[None, :]
++ scores = scores * SCALE
+ scores = tl.where(valid[None, :], scores, float("-inf"))
+ tile_m = tl.max(scores, 1)
+ active = tile_m != float("-inf")
+ next_m = tl.where(active, tl.maximum(m, tile_m), m)
+ alpha = tl.where(active, tl.where(m == float("-inf"), 0.0, tl.exp(m - next_m)), 1.0)
+ p = tl.where(valid[None, :] & active[:, None], tl.exp(scores - next_m[:, None]), 0.0)
+- o = o * alpha[:, None] + tl.dot(p.to(tl.bfloat16), kv)
++ if FP8:
++ o = o * alpha[:, None] + tl.dot((p * ks[None, :]).to(tl.bfloat16), kv)
++ else:
++ o = o * alpha[:, None] + tl.dot(p.to(tl.bfloat16), kv)
+ l = l * alpha + tl.sum(p, 1)
+ return next_m, l, o
+
+
+ @triton.jit
+-def _tile_v(q, kv, vv, m, l, o, valid, SCALE: tl.constexpr):
++def _tile_v(q, kv, vv, ks, m, l, o, valid, SCALE: tl.constexpr, FP8: tl.constexpr):
+ """_tile with the values a column slice vv [KT, VB] of the keys kv [KT, 512]."""
+- scores = tl.dot(q, tl.trans(kv)).to(tl.float32) * SCALE
++ scores = tl.dot(q, tl.trans(kv)).to(tl.float32)
++ if FP8:
++ scores = scores * ks[None, :]
++ scores = scores * SCALE
+ scores = tl.where(valid[None, :], scores, float("-inf"))
+ tile_m = tl.max(scores, 1)
+ active = tile_m != float("-inf")
+ next_m = tl.where(active, tl.maximum(m, tile_m), m)
+ alpha = tl.where(active, tl.where(m == float("-inf"), 0.0, tl.exp(m - next_m)), 1.0)
+ p = tl.where(valid[None, :] & active[:, None], tl.exp(scores - next_m[:, None]), 0.0)
+- o = o * alpha[:, None] + tl.dot(p.to(tl.bfloat16), vv)
++ if FP8:
++ o = o * alpha[:, None] + tl.dot((p * ks[None, :]).to(tl.bfloat16), vv)
++ else:
++ o = o * alpha[:, None] + tl.dot(p.to(tl.bfloat16), vv)
+ l = l * alpha + tl.sum(p, 1)
+ return next_m, l, o
+
+
+ @triton.jit
+-def _dense_chunks(QA, LC, POS, PO, PM, PL, R, H: tl.constexpr, LW: tl.constexpr, CH: tl.constexpr,
+- SCALE: tl.constexpr, HBT: tl.constexpr, KTT: tl.constexpr):
+- """Program (row, head block, chunk): causal attention of HB heads of row r over keys [c CH, (c + 1) CH)."""
++def _dense_chunks(QA, LC, LS, POS, PO, PM, PL, R, H: tl.constexpr, LW: tl.constexpr, CH: tl.constexpr,
++ SCALE: tl.constexpr, HBT: tl.constexpr, KTT: tl.constexpr, RS: tl.constexpr, FP8: tl.constexpr):
++ """Program (row, head block, chunk): causal attention of HB heads of row r over keys [c CH, (c + 1) CH); cache
++ rows RS elements apart (FP8: codes, their scales through LS)."""
+ r = tl.program_id(0)
+ hb = tl.program_id(1)
+ c = tl.program_id(2)
+@@ -452,8 +476,9 @@ def _dense_chunks(QA, LC, POS, PO, PM, PL, R, H: tl.constexpr, LW: tl.constexpr,
+ for t in range(CH // KTT):
+ ki = start + t * KTT + tl.arange(0, KTT)
+ ok = ki <= limit
+- kv = tl.load(LC + ki[:, None].to(tl.int64) * LW + k[None, :], mask=ok[:, None], other=0).to(tl.bfloat16)
+- m, l, o = _tile(q, kv, m, l, o, ok, SCALE)
++ kv = tl.load(LC + ki[:, None].to(tl.int64) * RS + k[None, :], mask=ok[:, None], other=0.0).to(tl.bfloat16)
++ ks = row_scales(LS, ki.to(tl.int64), ok, LW, RS) if FP8 else None
++ m, l, o = _tile(q, kv, ks, m, l, o, ok, SCALE, FP8)
+ base = (c * R + r) * H + hh
+ tl.store(PO + base[:, None] * LW + k[None, :], o, mask=hok[:, None])
+ tl.store(PM + base, m, mask=hok)
+@@ -461,8 +486,9 @@ def _dense_chunks(QA, LC, POS, PO, PM, PL, R, H: tl.constexpr, LW: tl.constexpr,
+
+
+ @triton.jit
+-def _sparse_chunks(QA, LC, TOK, CNT, PO, PM, PL, R, W: tl.constexpr, H: tl.constexpr, LW: tl.constexpr,
+- CH: tl.constexpr, SCALE: tl.constexpr, HBT: tl.constexpr, KTT: tl.constexpr):
++def _sparse_chunks(QA, LC, LS, TOK, CNT, PO, PM, PL, R, W: tl.constexpr, H: tl.constexpr, LW: tl.constexpr,
++ CH: tl.constexpr, SCALE: tl.constexpr, HBT: tl.constexpr, KTT: tl.constexpr, RS: tl.constexpr,
++ FP8: tl.constexpr):
+ """Program (row, head block, chunk): HB heads of row r over its selected tokens [c CH, (c + 1) CH) in list order."""
+ r = tl.program_id(0)
+ hb = tl.program_id(1)
+@@ -480,8 +506,9 @@ def _sparse_chunks(QA, LC, TOK, CNT, PO, PM, PL, R, W: tl.constexpr, H: tl.const
+ idx = c * CH + t * KTT + tl.arange(0, KTT)
+ ok = idx < n
+ tok = tl.load(TOK + r * W + idx, mask=ok, other=0).to(tl.int64)
+- kv = tl.load(LC + tok[:, None] * LW + k[None, :], mask=ok[:, None], other=0).to(tl.bfloat16)
+- m, l, o = _tile(q, kv, m, l, o, ok, SCALE)
++ kv = tl.load(LC + tok[:, None] * RS + k[None, :], mask=ok[:, None], other=0.0).to(tl.bfloat16)
++ ks = row_scales(LS, tok, ok, LW, RS) if FP8 else None
++ m, l, o = _tile(q, kv, ks, m, l, o, ok, SCALE, FP8)
+ base = (c * R + r) * H + hh
+ tl.store(PO + base[:, None] * LW + k[None, :], o, mask=hok[:, None])
+ tl.store(PM + base, m, mask=hok)
+@@ -496,23 +523,33 @@ def _onepass_ids(row, t0, n, KTT: tl.constexpr):
+
+
+ @triton.jit
+-def _onepass_rows(LC, tok, t0, n, k, LW: tl.constexpr, KTT: tl.constexpr):
+- """Tile t0's latent rows [KTT, LW]; rows past n are not read (zeros)."""
++def _onepass_rows(LC, tok, t0, n, k, RS: tl.constexpr, KTT: tl.constexpr):
++ """Tile t0's latent rows [KTT, LW] (bf16 values or FP8 codes, RS elements apart); rows past n: zeros, unread."""
+ ok = t0 + tl.arange(0, KTT) < n
+- return tl.load(LC + tok[:, None] * LW + k[None, :], mask=ok[:, None], other=0)
++ return tl.load(LC + tok[:, None] * RS + k[None, :], mask=ok[:, None], other=0.0)
+
+
+ @triton.jit
+-def _sparse_onepass(QA, LC, TOK, CNT, OUT, W: tl.constexpr, H: tl.constexpr, LW: tl.constexpr, SCALE: tl.constexpr,
+- HBT: tl.constexpr, KTT: tl.constexpr, SPLIT: tl.constexpr, STAGES: tl.constexpr,
+- PREFETCH: tl.constexpr):
++def _onepass_scales(LS, tok, t0, n, LW: tl.constexpr, RS: tl.constexpr, KTT: tl.constexpr, FP8: tl.constexpr):
++ """Tile t0's row scales [KTT] (FP8; ones, which nothing reads, for a bf16 cache)."""
++ if FP8:
++ return row_scales(LS, tok, t0 + tl.arange(0, KTT) < n, LW, RS)
++ return tl.full((KTT,), 1.0, tl.float32)
++
++
++def _sparse_onepass(QA, LC, LS, TOK, CNT, OUT, W: tl.constexpr, H: tl.constexpr, LW: tl.constexpr,
++ SCALE: tl.constexpr, HBT: tl.constexpr, KTT: tl.constexpr, SPLIT: tl.constexpr,
++ STAGES: tl.constexpr, PREFETCH: tl.constexpr, RS: tl.constexpr, FP8: tl.constexpr):
+ """Prompt rows, program (row, head group, latent slice): HBT heads of row r over all its selected tokens in one
+ online softmax, KTT-key tiles in list order (_tile's math), straight to OUT[r, h] bf16: no partials, no merge.
+ PREFETCH: tile t + 1's gather is issued into registers before tile t's dots (a load blocks only at first use),
+ with Triton's pipeliner off; else the loop is left to Triton's pipeliner at STAGES. SPLIT > 1: the program keeps
+- LW / SPLIT output columns and recomputes the full-width scores. PREFETCH never changes the arithmetic; the tile
+- (HBT, KTT, SPLIT) is fixed (ONEPASS_TILE), so a row's bits depend on its q, its token list and the cache only,
+- never on the other rows or R. Rows with CNT 0 are left alone."""
++ LW / SPLIT output columns and recomputes the full-width scores. PREFETCH never changes the arithmetic on a bf16
++ cache (on FP8 codes Triton may lay the converted tile out otherwise: other bits, the same values); the tile
++ (HBT, KTT, SPLIT) and launch are fixed (ONEPASS_TILE, ONEPASS_LAUNCH), so a row's bits depend on its q, its token
++ list and the cache only, never on the other rows or R. Rows with CNT 0 are left alone. FP8 (TF_GLM_KV=fp8): LC
++ holds e4m3 codes RS bytes apart, LS their scales (kv8), folded into scores and probabilities (_tile)."""
+ r = tl.program_id(0)
+ hb = tl.program_id(1)
+ vs = tl.program_id(2)
+@@ -533,30 +570,34 @@ def _sparse_onepass(QA, LC, TOK, CNT, OUT, W: tl.constexpr, H: tl.constexpr, LW:
+ # ids run two tiles ahead and rows one: tile t + 1's gather is issued (its ids already there) before tile t's
+ # dots, so neither load's latency stalls the in-order warp in front of the tensor-core work
+ tok = _onepass_ids(row, 0, n, KTT)
+- kv = _onepass_rows(LC, tok, 0, n, k, LW, KTT)
++ kv = _onepass_rows(LC, tok, 0, n, k, RS, KTT)
++ ks = _onepass_scales(LS, tok, 0, n, LW, RS, KTT, FP8)
+ tok_next = _onepass_ids(row, KTT, n, KTT)
+ for t0 in range(0, n, KTT):
+ ok = t0 + tl.arange(0, KTT) < n
+- kv_next = _onepass_rows(LC, tok_next, t0 + KTT, n, k, LW, KTT)
++ kv_next = _onepass_rows(LC, tok_next, t0 + KTT, n, k, RS, KTT)
++ ks_next = _onepass_scales(LS, tok_next, t0 + KTT, n, LW, RS, KTT, FP8)
+ tok_after = _onepass_ids(row, t0 + 2 * KTT, n, KTT)
+ if SPLIT == 1:
+- m, l, o = _tile(q, kv.to(tl.bfloat16), m, l, o, ok, SCALE)
++ m, l, o = _tile(q, kv.to(tl.bfloat16), ks, m, l, o, ok, SCALE, FP8)
+ else:
+- vv = tl.load(LC + tok[:, None] * LW + v[None, :], mask=ok[:, None], other=0).to(tl.bfloat16)
+- m, l, o = _tile_v(q, kv.to(tl.bfloat16), vv, m, l, o, ok, SCALE)
++ vv = tl.load(LC + tok[:, None] * RS + v[None, :], mask=ok[:, None], other=0.0).to(tl.bfloat16)
++ m, l, o = _tile_v(q, kv.to(tl.bfloat16), vv, ks, m, l, o, ok, SCALE, FP8)
+ tok = tok_next
+ kv = kv_next
++ ks = ks_next
+ tok_next = tok_after
+ else:
+ for t0 in tl.range(0, n, KTT, num_stages=STAGES):
+ ok = t0 + tl.arange(0, KTT) < n
+ tok = _onepass_ids(row, t0, n, KTT)
+- kv = _onepass_rows(LC, tok, t0, n, k, LW, KTT)
++ kv = _onepass_rows(LC, tok, t0, n, k, RS, KTT)
++ ks = _onepass_scales(LS, tok, t0, n, LW, RS, KTT, FP8)
+ if SPLIT == 1:
+- m, l, o = _tile(q, kv.to(tl.bfloat16), m, l, o, ok, SCALE)
++ m, l, o = _tile(q, kv.to(tl.bfloat16), ks, m, l, o, ok, SCALE, FP8)
+ else:
+- vv = tl.load(LC + tok[:, None] * LW + v[None, :], mask=ok[:, None], other=0).to(tl.bfloat16)
+- m, l, o = _tile_v(q, kv.to(tl.bfloat16), vv, m, l, o, ok, SCALE)
++ vv = tl.load(LC + tok[:, None] * RS + v[None, :], mask=ok[:, None], other=0.0).to(tl.bfloat16)
++ m, l, o = _tile_v(q, kv.to(tl.bfloat16), vv, ks, m, l, o, ok, SCALE, FP8)
+ tl.store(OUT + (r * H + hh[:, None]) * LW + v[None, :], (o / l[:, None]).to(tl.bfloat16), mask=hok[:, None])
+
+
+@@ -587,6 +628,13 @@ def _merge(PO, PM, PL, OUT, CNT, R, H: tl.constexpr, LW: tl.constexpr, NCH: tl.c
+ tl.store(OUT + (r * H + h) * LW + k, (o / l).to(tl.bfloat16))
+
+
++def _cache_parts(cache: torch.Tensor, lw: int):
++ """kv8.parts of a latent cache whose rows hold ``lw`` values."""
++ if kv8.width(cache) != lw or cache.stride(-1) != 1 or cache.stride(0) != cache.shape[1]:
++ raise ValueError(f"latent attention: a cache of contiguous {kv8.width(cache)}-wide rows, queries {lw} wide")
++ return kv8.parts(cache)
++
++
+ def chunk_stages() -> int:
+ """TF_GLM_LATENT_STAGES (default 3): Triton pipeline depth of the dense / sparse chunk programs' key tiles: the
+ loads only, the same bits (1: none, as before; 4 does not fit in shared memory)."""
+@@ -623,8 +671,9 @@ def attention(qa: torch.Tensor, cache: torch.Tensor, pos: torch.Tensor, s: Laten
+ 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 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,
++ vals, scl, rs, fp8 = _cache_parts(cache, LW)
++ _dense_chunks[(R, triton.cdiv(H, hb), nch)](qa, vals, scl, pos, s.po[:n * LW], s.pm[:n], s.pl[:n], R, H=H, LW=LW,
++ CH=CHUNK, SCALE=scale, HBT=hb, KTT=KT, RS=rs, FP8=fp8, num_warps=8,
+ num_stages=chunk_stages())
+ _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
+@@ -641,8 +690,9 @@ def sparse_attention(qa: torch.Tensor, cache: torch.Tensor, tokens: torch.Tensor
+ pm = torch.empty((n,), dtype=torch.float32, device=qa.device)
+ 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,
+- CH=CHUNK, SCALE=scale, HBT=hb, KTT=KT, num_warps=8,
++ vals, scl, rs, fp8 = _cache_parts(cache, LW)
++ _sparse_chunks[(R, triton.cdiv(H, hb), nch)](qa, vals, scl, tokens, counts, po, pm, pl, R, W=W, H=H, LW=LW,
++ CH=CHUNK, SCALE=scale, HBT=hb, KTT=KT, RS=rs, FP8=fp8, num_warps=8,
+ num_stages=chunk_stages())
+ _merge[(R, H)](po, pm, pl, out, counts, R, H=H, LW=LW, NCH=nch, SPARSE=True, num_warps=4)
+
+@@ -651,7 +701,9 @@ def sparse_attention(qa: torch.Tensor, cache: torch.Tensor, tokens: torch.Tensor
+ # tile (heads, keys, latent slices) and pipeline depth, so a row's bits never depend on the chunk it sits in.
+ SPARSE_ONEPASS = __import__("os").environ.get("TF_GLM_SPARSE_ONEPASS", "1") != "0"
+ ONEPASS_TILE = (32, 32, 1) # heads per program (a rank's 32), keys per tile, latent slices: sets the bits
+-ONEPASS_LAUNCH = (8, 1, True) # warps, Triton pipeline stages, register prefetch of the next tile: speed only
++# warps, Triton pipeline stages, register prefetch of the next tile: speed only on bf16 caches (on FP8 codes the
++# launch sets the bits too, fixed like the tile)
++ONEPASS_LAUNCH = (8, 1, True)
+
+
+ def sparse_onepass(qa: torch.Tensor, cache: torch.Tensor, tokens: torch.Tensor, counts: torch.Tensor,
+@@ -661,16 +713,17 @@ def sparse_onepass(qa: torch.Tensor, cache: torch.Tensor, tokens: torch.Tensor,
+ than sparse_attention's (one chain instead of merged 512-token chunks), the same for any chunking of the rows.
+ ``tile`` / ``launch`` override ONEPASS_TILE / ONEPASS_LAUNCH (benchmarks)."""
+ R, H, LW = qa.shape
+- if not (qa.is_contiguous() and out.is_contiguous() and tokens.is_contiguous() and cache.stride() == (LW, 1)):
+- raise ValueError("sparse_onepass: expected contiguous queries, output and token lists, cache rows of the width")
++ if not (qa.is_contiguous() and out.is_contiguous() and tokens.is_contiguous() and cache.is_contiguous()):
++ raise ValueError("sparse_onepass: expected contiguous queries, output, token lists and cache")
++ vals, scl, rs, fp8 = _cache_parts(cache, LW)
+ if R == 0:
+ return
+ hbt, kt, split = tile or ONEPASS_TILE
+ warps, stages, prefetch = launch or ONEPASS_LAUNCH
+ hbt = max(16, min(hbt, triton.next_power_of_2(H))) # tensor-core tiles need 16 rows
+- _sparse_onepass[(R, triton.cdiv(H, hbt), split)](qa, cache, tokens, counts, out, W=tokens.shape[1], H=H, LW=LW,
+- SCALE=scale, HBT=hbt, KTT=kt, SPLIT=split, STAGES=stages,
+- PREFETCH=bool(prefetch), num_warps=warps,
++ _sparse_onepass[(R, triton.cdiv(H, hbt), split)](qa, vals, scl, tokens, counts, out, W=tokens.shape[1], H=H,
++ LW=LW, SCALE=scale, HBT=hbt, KTT=kt, SPLIT=split, STAGES=stages,
++ PREFETCH=bool(prefetch), RS=rs, FP8=fp8, num_warps=warps,
+ num_stages=1 if prefetch else stages)
+
+
+@@ -683,37 +736,46 @@ def chunks_for(length: int) -> int:
+ # of a shared arena [P, LW]: per-row device tables (``segments.SegRows``: position, extent base, dense or sparse)
+ # drive the kernels below. Every row keeps the arithmetic, tiles and head blocks of today's single-stream kernels,
+ # so a segment's rows get the bits of that segment run alone on its extent (tests/cuda/test_glm_attn_segments.py).
+-# Cache reads and writes go through _lat_get / _lat_put (the one place a quantized cache plugs in).
++# Cache reads and writes go through _lat_get / _lat_put: bf16 rows, or TF_GLM_KV=fp8's (kv8: codes, then scales in
++# LS, rows RS elements apart), as the single-stream kernels read and write them.
+
+ @triton.jit
+-def _lat_get(LC, rows, ok, k, RS: tl.constexpr):
+- """Cache rows ``rows`` (int64 [n]) as a bf16 tile [n, LW]; rows with ok false are not read (zeros)."""
+- return tl.load(LC + rows[:, None] * RS + k[None, :], mask=ok[:, None], other=0).to(tl.bfloat16)
++def _lat_get(LC, LS, rows, ok, k, LW: tl.constexpr, RS: tl.constexpr, FP8: tl.constexpr):
++ """Cache rows ``rows`` (int64 [n]) as a bf16 tile [n, LW] (FP8: the codes, exact) and their scales [n] (FP8;
++ ones for bf16, unread); rows with ok false are not read (zeros)."""
++ kv = tl.load(LC + rows[:, None] * RS + k[None, :], mask=ok[:, None], other=0.0).to(tl.bfloat16)
++ if FP8:
++ return kv, row_scales(LS, rows, ok, LW, RS)
++ return kv, tl.full(rows.shape, 1.0, tl.float32)
+
+
+ @triton.jit
+-def _lat_put(LC, row, k, x, RS: tl.constexpr):
+- """Cache row ``row`` (int64) <- x [LW] (bf16)."""
+- tl.store(LC + row * RS + k, x)
++def _lat_put(LC, LS, row, x, LW: tl.constexpr, RS: tl.constexpr, FP8: tl.constexpr):
++ """Cache row ``row`` (int64) <- x [LW] (fp32 of a bf16 row), through kv8.store_row as latent_write stores it."""
++ kv8.store_row(LC, LS, row, x, LW, RS, FP8)
+
+
+ @triton.jit
+-def _seg_lat_write(LAT, lat_stride, LC, POS, BASE, LW: tl.constexpr):
++def _seg_lat_write(LAT, lat_stride, LC, LS, POS, BASE, LW: tl.constexpr, RS: tl.constexpr, FP8: tl.constexpr):
+ """Row r -> arena row base[r] + pos[r]."""
+ r = tl.program_id(0)
+ row = tl.load(BASE + r).to(tl.int64) + tl.load(POS + r).to(tl.int64)
+ k = tl.arange(0, LW)
+- _lat_put(LC, row, k, tl.load(LAT + r * lat_stride + k), LW)
++ _lat_put(LC, LS, row, tl.load(LAT + r * lat_stride + k).to(tl.float32), LW, RS, FP8)
+
+
+ def seg_latent_write(lat: torch.Tensor, cache: torch.Tensor, rows) -> None:
+- """lat [R, latent] bf16 rows into the arena at each row's base + pos (``rows``: segments.SegRows)."""
+- _seg_lat_write[(lat.shape[0],)](lat, lat.stride(0), cache, rows.pos, rows.base, LW=cache.shape[1], num_warps=4)
++ """lat [R, latent] bf16 rows into the arena at each row's base + pos (``rows``: segments.SegRows); an FP8 arena
++ (TF_GLM_KV=fp8) takes latent_write's bytes."""
++ vals, scl, rs, fp8 = _cache_parts(cache, lat.shape[1])
++ _seg_lat_write[(lat.shape[0],)](lat, lat.stride(0), vals, scl, rows.pos, rows.base, LW=lat.shape[1], RS=rs,
++ FP8=fp8, num_warps=4)
+
+
+ @triton.jit
+-def _seg_chunks(QA, LC, POS, BASE, SPR, TOK, CNT, PO, PM, PL, R, W: tl.constexpr, H: tl.constexpr,
+- LW: tl.constexpr, CH: tl.constexpr, SCALE: tl.constexpr, HBT: tl.constexpr, KTT: tl.constexpr):
++def _seg_chunks(QA, LC, LS, POS, BASE, SPR, TOK, CNT, PO, PM, PL, R, W: tl.constexpr, H: tl.constexpr,
++ LW: tl.constexpr, CH: tl.constexpr, SCALE: tl.constexpr, HBT: tl.constexpr, KTT: tl.constexpr,
++ RS: tl.constexpr, FP8: tl.constexpr):
+ """Program (row, head block, chunk): _dense_chunks for a dense row (keys base + 0 .. base + pos[r], its own
+ limit), _sparse_chunks for a sparse one (keys base + its selected tokens, list order): the same tiles, masks and
+ _tile math either way, so a row's partials are those of its single-stream kernel."""
+@@ -736,8 +798,8 @@ def _seg_chunks(QA, LC, POS, BASE, SPR, TOK, CNT, PO, PM, PL, R, W: tl.constexpr
+ ok = idx < n
+ tok = tl.load(TOK + r * W + idx, mask=ok & sp, other=0).to(tl.int64)
+ tok = tl.where(sp, tok, idx.to(tl.int64))
+- kv = _lat_get(LC, B + tok, ok, k, LW)
+- m, l, o = _tile(q, kv, m, l, o, ok, SCALE)
++ kv, ks = _lat_get(LC, LS, B + tok, ok, k, LW, RS, FP8)
++ m, l, o = _tile(q, kv, ks, m, l, o, ok, SCALE, FP8)
+ base = (c * R + r) * H + hh
+ tl.store(PO + base[:, None] * LW + k[None, :], o, mask=hok[:, None])
+ tl.store(PM + base, m, mask=hok)
+@@ -782,8 +844,10 @@ def seg_attention(qa: torch.Tensor, cache: torch.Tensor, rows, tokens: torch.Ten
+ hb = seg_head_block(R) if hb is None else hb
+ if hb not in (HB, HB_WIDE):
+ raise ValueError(f"segmented attention: {hb} heads a tile, not {HB} or {HB_WIDE}")
+- _seg_chunks[(R, triton.cdiv(H, hb), nch)](qa, cache, rows.pos, rows.base, rows.sparse, tokens, counts,
++ vals, scl, rs, fp8 = _cache_parts(cache, LW)
++ _seg_chunks[(R, triton.cdiv(H, hb), nch)](qa, vals, scl, rows.pos, rows.base, rows.sparse, tokens, counts,
+ s.po[:n * LW], s.pm[:n], s.pl[:n], R, W=W, H=H, LW=LW, CH=CHUNK,
+- SCALE=scale, HBT=hb, KTT=KT, num_warps=8, num_stages=chunk_stages())
++ SCALE=scale, HBT=hb, KTT=KT, RS=rs, FP8=fp8, num_warps=8,
++ num_stages=chunk_stages())
+ _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
+diff --git tensorfold/families/glm5_next/cuda/multi.py tensorfold/families/glm5_next/cuda/multi.py
+index d1ed1f4..1c4af9d 100644
+--- tensorfold/families/glm5_next/cuda/multi.py
++++ tensorfold/families/glm5_next/cuda/multi.py
+@@ -611,8 +611,11 @@ class MultiDecoder:
+ if self.drafts is not None:
+ self._ctx(lane).reset()
+ if hit is not None:
++ from .decode import put_ring_tail
++
+ st.rec[st.cur[0]].copy_(hit.rec)
+ st.conv.copy_(hit.conv)
++ put_ring_tail(st, hit) # the index rows of its pools still filling, into this slot's rings
+ st.set_pos(cut)
+ if dflash:
+ if hit.drafter_end != cut or hit.drafter_rows is None:
+@@ -684,6 +687,7 @@ class MultiDecoder:
+ x = c.extent
+ x.kept = [k for k in x.kept if k is not c]
+ c.rec = c.conv = None
++ c.tail = None
+ c.drafter_rows = None
+ self._settle(x)
+
+diff --git tensorfold/families/glm5_next/cuda/segments.py tensorfold/families/glm5_next/cuda/segments.py
+index 91b3d06..ae8b0d9 100644
+--- tensorfold/families/glm5_next/cuda/segments.py
++++ tensorfold/families/glm5_next/cuda/segments.py
+@@ -1,8 +1,11 @@
+ """Multi-stream decode windows: several streams' rows back to back ([s1: rows][s2: rows]...), each stream's per-token
+-DSA state in its own extent of shared arenas (latents [P, 512], index keys and gates [P, 128], pooled keys
+-[P / 4 + 2, 128]; extents aligned to EXTENT tokens). ``SegRows`` holds the per-row and per-segment device tables the
+-segmented kernels read (latent.seg_*, sparse.seg_*); ``SelectScratch`` the token selection's buffers. Static
+-buffers, so one CUDA graph per window size covers every mix of positions and context lengths."""
++DSA state in its own extent of shared arenas (latents [P, 512], pooled keys [P / 4 + 2, 128], bf16 or TF_GLM_KV=fp8's
++kv8 rows; extents aligned to EXTENT tokens) and its index keys and gates in its own part of [Q, 128] tensors: its
++extent (Q = P, token t at base + t) or, given ``ring``, its stream slot's ring of ``ring`` rows (token t at ring_base
+++ t % ring, as the single-stream rings of forward.index_ring; ``ring`` >= a segment's rows + 3). ``SegRows`` holds
++the per-row and per-segment device tables the segmented kernels read (latent.seg_*, sparse.seg_*); ``SelectScratch``
++the token selection's buffers. Static buffers, so one CUDA graph per window size covers every mix of positions and
++context lengths."""
+
+ from __future__ import annotations
+
+@@ -20,55 +23,78 @@ class SegRows:
+ """Device tables of a window of up to ``rows`` rows in up to ``max_segs`` segments, one int32 tensor:
+
+ per row: ``pos`` (the row's position in its stream), ``base`` (its stream's first arena row), ``seg`` (segment
+- index), ``sparse`` (1: past the dense limit, attends to its selected tokens; 0: dense over keys 0 .. pos);
++ index), ``sparse`` (1: past the dense limit, attends to its selected tokens; 0: dense over keys 0 .. pos),
++ ``ibase`` (its stream's first row in the index key and gate arenas: its ring's, or ``base`` without rings);
+ per segment: ``seg_start`` (first row), ``seg_rows`` (0: unused), ``seg_pbase`` (pooled-key base, base / 4),
+- ``seg_pools`` (pools its last row sees when it has sparse rows, else 0: what the selection scores)."""
++ ``seg_pools`` (pools its last row sees when it has sparse rows, else 0: what the selection scores).
+
+- def __init__(self, rows: int, device, max_segs: int = MAX_SEGS) -> None:
++ ``ring``: rows of each stream's index key and gate ring (None: no rings, token t at base + t); a segment then
++ names its ring's first row (``set``'s fourth field: one ring a stream slot, slot x ring, the same for the
++ stream in every window)."""
++
++ NO_RING = 2 ** 31 - 1 # the kernels' ring size without rings (positions stay below it: base + pos)
++
++ def __init__(self, rows: int, device, max_segs: int = MAX_SEGS, ring: int | None = None) -> None:
++ if ring is not None and ring < 4:
++ raise ValueError(f"an index ring of {ring} rows")
+ self.rows, self.max_segs = rows, max_segs
+- n = 4 * rows + 4 * max_segs
++ self.ring = ring
++ self.ring_rows = ring if ring is not None else self.NO_RING
++ n = 5 * rows + 4 * max_segs
+ pin = torch.cuda.is_available() and torch.device(device).type == "cuda"
+ self.host = torch.zeros((n,), dtype=torch.int32, pin_memory=pin)
+ self.dev = torch.zeros((n,), dtype=torch.int32, device=device)
+- self.pos, self.base, self.seg, self.sparse = (self.dev[i * rows:(i + 1) * rows] for i in range(4))
+- o = 4 * rows
++ self.pos, self.base, self.seg, self.sparse, self.ibase = (self.dev[i * rows:(i + 1) * rows] for i in range(5))
++ o = 5 * rows
+ self.seg_start, self.seg_rows, self.seg_pbase, self.seg_pools = (
+ self.dev[o + i * max_segs:o + (i + 1) * max_segs] for i in range(4))
+ self.staged = torch.cuda.Event() if pin else None
+ self.R = 0
+ self.segments: list[tuple[int, int, int]] = []
+
+- def fill(self, segments: Sequence[tuple[int, int, int]], *, sparse_from: int | None = SPARSE_FROM):
+- """The host tables for ``segments`` [(base, pos, rows)] in window order (numpy int32, the device layout).
++ def fill(self, segments: Sequence[tuple[int, ...]], *, sparse_from: int | None = SPARSE_FROM):
++ """The host tables for ``segments`` [(base, pos, rows[, ring_base])] in window order (numpy int32, the device
++ layout); ring_base (with rings, required): the stream's ring's first row.
+ ``sparse_from``: the first position that attends sparsely (None: no index, every row dense)."""
+
+ if not 1 <= len(segments) <= self.max_segs:
+ raise ValueError(f"a window of {len(segments)} segments, at most {self.max_segs}")
+- R = sum(n for _, _, n in segments)
++ R = sum(seg[2] for seg in segments)
+ if R > self.rows:
+ raise ValueError(f"a window of {R} rows, the tables hold {self.rows}")
+ rows, S = self.rows, self.max_segs
+- t = torch.zeros((4 * rows + 4 * S,), dtype=torch.int32).numpy()
++ t = torch.zeros((5 * rows + 4 * S,), dtype=torch.int32).numpy()
+ r = 0
+- for s, (base, pos, n) in enumerate(segments):
++ for s, seg in enumerate(segments):
++ base, pos, n = seg[:3]
+ if n < 1 or pos < 0 or base < 0 or base % EXTENT:
+ raise ValueError(f"segment {s}: base {base} (a multiple of {EXTENT}), position {pos}, {n} rows")
++ if self.ring is None:
++ ibase = base
++ else:
++ if len(seg) < 4 or seg[3] < 0:
++ raise ValueError(f"segment {s}: index rings need the stream's ring base")
++ ibase = seg[3]
++ if n + 3 > self.ring:
++ raise ValueError(f"segment {s}: {n} rows and the 3 before them past a ring of {self.ring}")
+ for i in range(n):
+ q = pos + i
+ t[r + i] = q
+ t[rows + r + i] = base
+ t[2 * rows + r + i] = s
+ t[3 * rows + r + i] = int(sparse_from is not None and q >= sparse_from)
++ t[4 * rows + r + i] = ibase
+ last = pos + n - 1
+- t[4 * rows + s] = r
+- t[4 * rows + S + s] = n
+- t[4 * rows + 2 * S + s] = base // POOL
+- t[4 * rows + 3 * S + s] = (last + 1) // POOL if sparse_from is not None and last >= sparse_from else 0
++ o = 5 * rows
++ t[o + s] = r
++ t[o + S + s] = n
++ t[o + 2 * S + s] = base // POOL
++ t[o + 3 * S + s] = (last + 1) // POOL if sparse_from is not None and last >= sparse_from else 0
+ r += n
+ return t, R
+
+- def set(self, segments: Sequence[tuple[int, int, int]], *, sparse_from: int | None = SPARSE_FROM) -> int:
+- """Stage ``segments`` [(base, pos, rows)] into the device tables (a pinned copy, ordered on the current
++ def set(self, segments: Sequence[tuple[int, ...]], *, sparse_from: int | None = SPARSE_FROM) -> int:
++ """Stage ``segments`` [(base, pos, rows[, ring_base])] into the device tables (a pinned copy, ordered on the current
+ stream like forward.stage's token ids); returns the window's rows."""
+
+ 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
+--- 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
+
++from . import kv8
++from .kv8 import row_scales
++
+ POOL = 4
+ TOPK_POOLS = 512
+ BR = 16
+@@ -15,8 +18,8 @@ TOKENS = TOPK_POOLS * POOL + POOL - 1 # a sparse row's attended tokens: its
+
+
+ @triton.jit
+-def _index_write(KR, k_stride, GR, LNW, LNB, IK, IG, POS, eps, D: tl.constexpr):
+- """Row r: LayerNorm(k_raw) -> bf16 into IK[pos + r]; the gate row (fp32) -> bf16 into IG[pos + r]."""
++def _index_write(KR, k_stride, GR, LNW, LNB, IK, IG, POS, RING, eps, D: tl.constexpr):
++ """Row r: LayerNorm(k_raw) -> bf16 into IK[(pos + r) % RING]; the gate row (fp32) -> bf16 into IG alike."""
+
+ 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):
+ 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)
+- tl.store(IK + (P + r) * D + d, y.to(tl.bfloat16))
+- tl.store(IG + (P + r) * D + d, tl.load(GR + r * D + d).to(tl.bfloat16))
++ slot = (P + r) % RING
++ tl.store(IK + slot * D + d, y.to(tl.bfloat16))
++ tl.store(IG + slot * D + d, tl.load(GR + r * D + d).to(tl.bfloat16))
+
+
+ @triton.jit
+-def _pool_keys(IK, IG, APE, PK, POS, R, D: tl.constexpr):
+- """Program i: pool p = pos // 4 + i if it is complete within the window (ends at or before pos + R - 1)."""
++def _pool_keys(IK, IG, APE, PK, PKS, POS, R, RING, D: tl.constexpr, RS: tl.constexpr, FP8: tl.constexpr):
++ """Program i: pool p = pos // 4 + i if it is complete within the window (ends at or before pos + R - 1), from its
++ four tokens' keys and gates in the ring (token t at t % RING); a pool's bits depend on those rows only, whichever
++ window completes it. FP8 (TF_GLM_KV=fp8): the pooled key stored as kv8.store_row's codes and scale."""
+
+ 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):
+ if 4 * p + 3 > P + R - 1:
+ return
+ d = tl.arange(0, D)
+- l0 = tl.load(IG + (4 * p + 0) * D + d).to(tl.float32) + tl.load(APE + 0 * D + d).to(tl.float32)
+- l1 = tl.load(IG + (4 * p + 1) * D + d).to(tl.float32) + tl.load(APE + 1 * D + d).to(tl.float32)
+- l2 = tl.load(IG + (4 * p + 2) * D + d).to(tl.float32) + tl.load(APE + 2 * D + d).to(tl.float32)
+- l3 = tl.load(IG + (4 * p + 3) * D + d).to(tl.float32) + tl.load(APE + 3 * D + d).to(tl.float32)
++ s0 = (4 * p + 0) % RING
++ s1 = (4 * p + 1) % RING
++ s2 = (4 * p + 2) % RING
++ s3 = (4 * p + 3) % RING
++ l0 = tl.load(IG + s0 * D + d).to(tl.float32) + tl.load(APE + 0 * D + d).to(tl.float32)
++ l1 = tl.load(IG + s1 * D + d).to(tl.float32) + tl.load(APE + 1 * D + d).to(tl.float32)
++ l2 = tl.load(IG + s2 * D + d).to(tl.float32) + tl.load(APE + 2 * D + d).to(tl.float32)
++ l3 = tl.load(IG + s3 * D + d).to(tl.float32) + tl.load(APE + 3 * D + d).to(tl.float32)
+ m = tl.maximum(tl.maximum(l0, l1), tl.maximum(l2, l3))
+ e0 = tl.exp(l0 - m)
+ e1 = tl.exp(l1 - m)
+ e2 = tl.exp(l2 - m)
+ e3 = tl.exp(l3 - m)
+ s = ((e0 + e1) + e2) + e3
+- k0 = tl.load(IK + (4 * p + 0) * D + d).to(tl.float32)
+- k1 = tl.load(IK + (4 * p + 1) * D + d).to(tl.float32)
+- k2 = tl.load(IK + (4 * p + 2) * D + d).to(tl.float32)
+- k3 = tl.load(IK + (4 * p + 3) * D + d).to(tl.float32)
++ k0 = tl.load(IK + s0 * D + d).to(tl.float32)
++ k1 = tl.load(IK + s1 * D + d).to(tl.float32)
++ k2 = tl.load(IK + s2 * D + d).to(tl.float32)
++ k3 = tl.load(IK + s3 * D + d).to(tl.float32)
+ t0 = ((e0 / s).to(tl.bfloat16).to(tl.float32) * k0).to(tl.bfloat16).to(tl.float32)
+ t1 = ((e1 / s).to(tl.bfloat16).to(tl.float32) * k1).to(tl.bfloat16).to(tl.float32)
+ t2 = ((e2 / s).to(tl.bfloat16).to(tl.float32) * k2).to(tl.bfloat16).to(tl.float32)
+ t3 = ((e3 / s).to(tl.bfloat16).to(tl.float32) * k3).to(tl.bfloat16).to(tl.float32)
+- tl.store(PK + p * D + d, (((t0 + t1) + t2) + t3).to(tl.bfloat16))
++ kv8.store_row(PK, PKS, p, ((t0 + t1) + t2) + t3, D, RS, FP8)
+
+
+ def index_update(k_raw: torch.Tensor, gate: torch.Tensor, ln_w: torch.Tensor, ln_b: torch.Tensor, ape: torch.Tensor,
+ ik: torch.Tensor, ig: torch.Tensor, pk: torch.Tensor, pos: torch.Tensor) -> None:
+- """Window rows' index keys and gates into the caches at pos.., then every pool the window completes."""
++ """Window rows' index keys and gates into their ring (ik, ig: bf16 [ring, 128], token t at row t % ring), then
++ every pool the window completes into pk (bf16, or TF_GLM_KV=fp8's kv8 rows). Only the pool a token belongs to
++ ever reads its key and gate, so the ring needs the window's rows and the 3 before it: ring >= R + 3
++ (forward.index_ring), or at least the context (no row wraps: the full-length caches of before)."""
+
+ R = k_raw.shape[0]
+- _index_write[(R,)](k_raw, k_raw.stride(0), gate, ln_w, ln_b, ik, ig, pos, 1e-6, D=128, num_warps=1)
+- _pool_keys[(R // 4 + 2,)](ik, ig, ape, pk, pos, R, D=128, num_warps=1)
++ ring = ik.shape[0]
++ if ik.dtype != torch.bfloat16 or ig.shape != ik.shape or not ik.is_contiguous() or not ig.is_contiguous():
++ raise ValueError("index_update: bf16 key and gate rings of one shape, contiguous")
++ _index_write[(R,)](k_raw, k_raw.stride(0), gate, ln_w, ln_b, ik, ig, pos, ring, 1e-6, D=128, num_warps=1)
++ if kv8.width(pk) != 128:
++ raise ValueError("index_update: 128-wide pooled keys")
++ pkv, pks, rs, fp8 = kv8.parts(pk)
++ _pool_keys[(R // 4 + 2,)](ik, ig, ape, pkv, pks, pos, R, ring, D=128, RS=rs, FP8=fp8, num_warps=1)
+
+
+ @triton.jit
+-def _scores(QI, W, w_stride, PK, OUT, POS, R, NP, scale, wscale, H: tl.constexpr, HP: tl.constexpr,
+- D: tl.constexpr, BP: tl.constexpr, RB: tl.constexpr):
+- """Program (RB rows, pool block): s_p = sum_h w_h relu(scale * qi_h . pool_p) up to each row's position, heads padded to HP; RB never changes a row's bits."""
++def _scores(QI, W, w_stride, PK, PKS, OUT, POS, R, NP, scale, wscale, H: tl.constexpr, HP: tl.constexpr,
++ D: tl.constexpr, BP: tl.constexpr, RB: tl.constexpr, RS: tl.constexpr, FP8: tl.constexpr):
++ """Program (RB rows, pool block): s_p = sum_h w_h relu(scale * qi_h . pool_p) up to each row's position, heads
++ padded to HP; RB never changes a row's bits. FP8 (TF_GLM_KV=fp8): the pooled keys' e4m3 codes on the tensor
++ cores, each pool's power-of-two scale on its dots."""
+
+ 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
+ d = tl.arange(0, D)
+ hh = tl.arange(0, HP)
+ hok = hh < H
+- k = tl.load(PK + p[:, None] * D + d[None, :], mask=(p < (P + rb * RB + RB) // 4)[:, None],
+- other=0.0).to(tl.bfloat16) # [BP, D]
++ kok = p < (P + rb * RB + RB) // 4
++ k = tl.load(PK + p[:, None].to(tl.int64) * RS + d[None, :], mask=kok[:, None], other=0.0).to(tl.bfloat16) # [BP, D]
++ if FP8:
++ ks = row_scales(PKS, p.to(tl.int64), kok, D, RS)
+ 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
+ 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
++ if FP8:
++ dots = dots * ks[None, :]
+ 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
+
+
+ @triton.jit
+-def _scores_rows(QI, W, w_stride, PK, 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):
++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,
++ RS: tl.constexpr, FP8: tl.constexpr):
+ """Decode rows, program (row, g): the row's index queries and head weights loaded once, then pool blocks g,
+ g + G, .. each through _scores' arithmetic for that row (the same key mask, dot tile, warps and head sum, so
+ RB = 1's bits). SEG False: NP columns a row from one position (POS[0] + r; pools past the row's -inf); SEG: a
+- segmented window's row r (skipped when dense) over its own visible pools, keys at its stream's base / 4."""
++ segmented window's row r (skipped when dense) over its own visible pools, keys at its stream's base / 4. FP8
++ (TF_GLM_KV=fp8): pooled keys as kv8 rows RS bytes apart, each pool's scale on its dots, as in _scores."""
+
+ 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
+ if tl.load(SPR + r) == 0:
+ return
+ npool = (tl.load(POS + r) + 1) // 4
+- pk = PK + (tl.load(BASE + r).to(tl.int64) // 4) * D
++ pbase = tl.load(BASE + r).to(tl.int64) // 4
+ nb = (npool + BP - 1) // BP
+ else:
+ npool = (tl.load(POS) + r + 1) // 4
+- pk = PK
++ pbase = tl.zeros((), tl.int64)
+ 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
+ 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)
+- k = tl.load(pk + p[:, None] * D + d[None, :], mask=(p < npool)[:, None], other=0.0).to(tl.bfloat16)
++ rows = pbase + p
++ k = tl.load(PK + rows[:, None] * RS + d[None, :], mask=(p < npool)[:, 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
++ if FP8:
++ dots = dots * row_scales(PKS, rows, p < npool, D, RS)[None, :]
+ 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
+ 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))
+- _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)
++ 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
+ 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
+ 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)
++ pkv, pks, rs, fp8 = kv8.parts(pk)
+ for a in range(0, R, B):
+ n = min(B, R - a)
+ at = pos_dev if a == 0 else pos_dev + a
+ scores = buf[:n * NP].view(n, NP)
+- _scores[(triton.cdiv(n, rb), triton.cdiv(NP, 64))](qi[a:a + n], wts[a:a + n], wts.stride(0), pk, scores, at, n,
+- NP, D ** -0.5, wscale, H=H,
++ _scores[(triton.cdiv(n, rb), triton.cdiv(NP, 64))](qi[a:a + n], wts[a:a + n], wts.stride(0), pkv, pks, scores,
++ at, n, NP, D ** -0.5, wscale, H=H,
+ HP=max(16, triton.next_power_of_2(H)), D=D, BP=64, RB=rb,
+- num_warps=4)
++ RS=rs, FP8=fp8, num_warps=4)
+ 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
+
+
+ # ------------------------------------------------------------------------------------- multi-stream windows ---
+-# Segmented windows (latent.py's section of the same name): each stream's index keys and gates in its own extent of
+-# shared arenas [P, 128] (token t of the stream at base + t) and its pooled keys at base / 4 + p of [P / 4 + 2, 128];
+-# per-row device tables (``segments.SegRows``) give each row its position, base and kind. A row keeps its
+-# single-stream arithmetic. Reads and writes of the index caches go through the helpers below.
++# Segmented windows (latent.py's section of the same name): each stream's index keys and gates in its own part of
++# shared [Q, 128] tensors (token t of the stream at ibase + t % ring: its slot's ring, or its extent without rings)
++# and its pooled keys at base / 4 + p of [P / 4 + 2, 128]; per-row device tables (``segments.SegRows``) give each row
++# its position, bases and kind; pooled keys bf16 or TF_GLM_KV=fp8's kv8 rows (codes, then scales in PKS, rows RS
++# elements apart). A row keeps its single-stream arithmetic. Reads and writes of the index caches go through the
++# helpers below.
+
+ @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):
+
+
+ @triton.jit
+-def _pk_put(PK, row, d, x, D: tl.constexpr):
+- """Pooled key row ``row`` (int64) <- x [D] (fp32) as bf16."""
+- tl.store(PK + row * D + d, x.to(tl.bfloat16))
++def _pk_put(PK, PKS, row, x, D: tl.constexpr, RS: tl.constexpr, FP8: tl.constexpr):
++ """Pooled key row ``row`` (int64) <- x [D] (fp32) as bf16, or FP8 (kv8.store_row, as _pool_keys stores it)."""
++ kv8.store_row(PK, PKS, row, x, D, RS, FP8)
+
+
+ @triton.jit
+-def _pk_get(PK, rows, ok, d, D: tl.constexpr):
+- """Pooled key rows ``rows`` (int64 [n]) as a bf16 tile [n, D]; rows with ok false are zeros."""
+- return tl.load(PK + rows[:, None] * D + d[None, :], mask=ok[:, None], other=0.0).to(tl.bfloat16)
++def _pk_get(PK, PKS, rows, ok, d, D: tl.constexpr, RS: tl.constexpr, FP8: tl.constexpr):
++ """Pooled key rows ``rows`` (int64 [n]) as a bf16 tile [n, D] (FP8: the codes, exact) and their scales [n]
++ (FP8; ones for bf16, unread); rows with ok false are zeros."""
++ k = tl.load(PK + rows[:, None] * RS + d[None, :], mask=ok[:, None], other=0.0).to(tl.bfloat16)
++ if FP8:
++ return k, row_scales(PKS, rows, ok, D, RS)
++ return k, tl.full(rows.shape, 1.0, tl.float32)
+
+
+ @triton.jit
+-def _seg_index_write(KR, k_stride, GR, LNW, LNB, IK, IG, POS, BASE, eps, D: tl.constexpr):
+- """_index_write for row r at its stream's row base[r] + pos[r]."""
++def _seg_index_write(KR, k_stride, GR, LNW, LNB, IK, IG, POS, IBASE, RING, eps, D: tl.constexpr):
++ """_index_write for row r at its stream's index row ibase[r] + pos[r] % RING."""
+
+ r = tl.program_id(0)
+- row = tl.load(BASE + r).to(tl.int64) + tl.load(POS + r).to(tl.int64)
++ row = tl.load(IBASE + r).to(tl.int64) + tl.load(POS + r).to(tl.int64) % RING
+ 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
+
+
+ @triton.jit
+-def _seg_pool_keys(IK, IG, APE, PK, POS, BASE, D: tl.constexpr):
++def _seg_pool_keys(IK, IG, APE, PK, PKS, POS, BASE, IBASE, RING, D: tl.constexpr, RS: tl.constexpr,
++ FP8: tl.constexpr):
+ """Program r: the pool row r completes (pos[r] % 4 == 3), pool p = pos[r] // 4 of its stream, from tokens
+- base + 4p .. base + 4p + 3 into pooled row base / 4 + p: _pool_keys' arithmetic (the pools a single-stream
+- window completes are exactly those its rows end)."""
++ 4p .. 4p + 3 (index rows ibase + t % RING) into pooled row base / 4 + p: _pool_keys' arithmetic (the pools a
++ single-stream window completes are exactly those its rows end)."""
+
+ r = tl.program_id(0)
+ q = tl.load(POS + r).to(tl.int64)
+ if q % 4 != 3:
+ return
+ B = tl.load(BASE + r).to(tl.int64)
+- t = B + (q // 4) * 4
++ IB = tl.load(IBASE + r).to(tl.int64)
++ t = (q // 4) * 4
++ s0 = IB + (t + 0) % RING
++ s1 = IB + (t + 1) % RING
++ s2 = IB + (t + 2) % RING
++ s3 = IB + (t + 3) % RING
+ d = tl.arange(0, D)
+- l0 = _ix_get(IG, t + 0, d, D) + tl.load(APE + 0 * D + d).to(tl.float32)
+- l1 = _ix_get(IG, t + 1, d, D) + tl.load(APE + 1 * D + d).to(tl.float32)
+- l2 = _ix_get(IG, t + 2, d, D) + tl.load(APE + 2 * D + d).to(tl.float32)
+- l3 = _ix_get(IG, t + 3, d, D) + tl.load(APE + 3 * D + d).to(tl.float32)
++ l0 = _ix_get(IG, s0, d, D) + tl.load(APE + 0 * D + d).to(tl.float32)
++ l1 = _ix_get(IG, s1, d, D) + tl.load(APE + 1 * D + d).to(tl.float32)
++ l2 = _ix_get(IG, s2, d, D) + tl.load(APE + 2 * D + d).to(tl.float32)
++ l3 = _ix_get(IG, s3, d, D) + tl.load(APE + 3 * D + d).to(tl.float32)
+ m = tl.maximum(tl.maximum(l0, l1), tl.maximum(l2, l3))
+ e0 = tl.exp(l0 - m)
+ e1 = tl.exp(l1 - m)
+ e2 = tl.exp(l2 - m)
+ e3 = tl.exp(l3 - m)
+ s = ((e0 + e1) + e2) + e3
+- k0 = _ix_get(IK, t + 0, d, D)
+- k1 = _ix_get(IK, t + 1, d, D)
+- k2 = _ix_get(IK, t + 2, d, D)
+- k3 = _ix_get(IK, t + 3, d, D)
++ k0 = _ix_get(IK, s0, d, D)
++ k1 = _ix_get(IK, s1, d, D)
++ k2 = _ix_get(IK, s2, d, D)
++ k3 = _ix_get(IK, s3, d, D)
+ t0 = ((e0 / s).to(tl.bfloat16).to(tl.float32) * k0).to(tl.bfloat16).to(tl.float32)
+ t1 = ((e1 / s).to(tl.bfloat16).to(tl.float32) * k1).to(tl.bfloat16).to(tl.float32)
+ t2 = ((e2 / s).to(tl.bfloat16).to(tl.float32) * k2).to(tl.bfloat16).to(tl.float32)
+ t3 = ((e3 / s).to(tl.bfloat16).to(tl.float32) * k3).to(tl.bfloat16).to(tl.float32)
+- _pk_put(PK, B // 4 + q // 4, d, ((t0 + t1) + t2) + t3, D)
++ _pk_put(PK, PKS, B // 4 + q // 4, ((t0 + t1) + t2) + t3, D, RS, FP8)
+
+
+ def seg_index_update(k_raw: torch.Tensor, gate: torch.Tensor, ln_w: torch.Tensor, ln_b: torch.Tensor,
+ ape: torch.Tensor, ik: torch.Tensor, ig: torch.Tensor, pk: torch.Tensor, rows) -> None:
+- """index_update for a segmented window: each row's index key and gate at its stream's base + pos, then every
+- pool a row completes (``rows``: segments.SegRows)."""
++ """index_update for a segmented window: each row's index key and gate at its stream's ibase + pos % ring (its
++ slot's ring, or base + pos without rings: ``rows``: segments.SegRows), then every pool a row completes."""
+
+ R = k_raw.shape[0]
+- _seg_index_write[(R,)](k_raw, k_raw.stride(0), gate, ln_w, ln_b, ik, ig, rows.pos, rows.base, 1e-6, D=128,
+- num_warps=1)
+- _seg_pool_keys[(R,)](ik, ig, ape, pk, rows.pos, rows.base, D=128, num_warps=1)
++ _seg_index_write[(R,)](k_raw, k_raw.stride(0), gate, ln_w, ln_b, ik, ig, rows.pos, rows.ibase, rows.ring_rows,
++ 1e-6, D=128, num_warps=1)
++ pkv, pks, rs, fp8 = kv8.parts(pk)
++ _seg_pool_keys[(R,)](ik, ig, ape, pkv, pks, rows.pos, rows.base, rows.ibase, rows.ring_rows, D=128, RS=rs,
++ FP8=fp8, num_warps=1)
+
+
+ @triton.jit
+-def _seg_scores(QI, W, w_stride, PK, OUT, o_stride, POS, SPR, SEG_START, SEG_ROWS, SEG_PBASE, SEG_POOLS, scale,
+- wscale, H: tl.constexpr, HP: tl.constexpr, D: tl.constexpr, BP: tl.constexpr, G: tl.constexpr):
++def _seg_scores(QI, W, w_stride, PK, PKS, OUT, o_stride, POS, SPR, SEG_START, SEG_ROWS, SEG_PBASE, SEG_POOLS, scale,
++ wscale, H: tl.constexpr, HP: tl.constexpr, D: tl.constexpr, BP: tl.constexpr, G: tl.constexpr,
++ RS: tl.constexpr, FP8: tl.constexpr):
+ """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
+ hok = hh < H
+ for pb in range(g, (npm + BP - 1) // BP, G):
+ p = pb * BP + tl.arange(0, BP)
+- k = _pk_get(PK, pbase + p, p < npm, d, D) # [BP, D]
++ k, ks = _pk_get(PK, PKS, pbase + p, p < npm, d, D, RS, FP8) # [BP, D], [BP]
+ 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
+ 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
++ if FP8:
++ dots = dots * ks[None, :]
+ 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
+ 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))
+- _seg_scores[(rows.max_segs, grid)](qi, wts, wts.stride(0), pk, scores, scores.stride(0), rows.pos, rows.sparse,
+- rows.seg_start, rows.seg_rows, rows.seg_pbase, rows.seg_pools, D ** -0.5,
+- wscale, H=H, HP=max(16, triton.next_power_of_2(H)), D=D, BP=64, G=grid,
+- num_warps=4)
++ pkv, pks, rs, fp8 = kv8.parts(pk)
++ _seg_scores[(rows.max_segs, grid)](qi, wts, wts.stride(0), pkv, pks, scores, scores.stride(0), rows.pos,
++ rows.sparse, rows.seg_start, rows.seg_rows, rows.seg_pbase, rows.seg_pools,
++ D ** -0.5, wscale, H=H, HP=max(16, triton.next_power_of_2(H)), D=D, BP=64,
++ G=grid, RS=rs, FP8=fp8, num_warps=4)
+ tokens, counts = scratch.tokens[:R], scratch.counts[:R]
+ if SEG_SPLIT:
+ select_split(scores[:R], TOPK_POOLS, scratch=scratch.split, rows=rows, tokens=tokens, counts=counts)
+diff --git tensorfold/families/glm5_next/cuda/verify.py tensorfold/families/glm5_next/cuda/verify.py
+index 676a151..34205f7 100644
+--- tensorfold/families/glm5_next/cuda/verify.py
++++ tensorfold/families/glm5_next/cuda/verify.py
+@@ -85,7 +85,7 @@ class BatchedVerify:
+ if taps:
+ self.b.set_taps(tuple(taps), c.hidden)
+ self.taps = bool(taps)
+- self.seg_rows = SegRows(rows, dev, max_segs=MAX_SEGS)
++ self.seg_rows = SegRows(rows, dev, max_segs=MAX_SEGS, ring=e.caches.ring if e.caches.rings else None)
+ self.sel = SelectScratch(rows, e.caches.rows, dev) if e.caches.index is not None else None
+ kda_layers = [l for l in w.layers if l.kind == "kda"]
+ n = len(kda_layers)
+@@ -120,7 +120,7 @@ class BatchedVerify:
+ pool = torch.cuda.graph_pool_handle()
+ for R in rows or range(1, self.rows_max + 1):
+ self._stage([0] * R)
+- self.seg_rows.set([(0, 0, R)], sparse_from=SPARSE_FROM if index else None)
++ self.seg_rows.set([self._span(e.home, 0, R)], sparse_from=SPARSE_FROM if index else None)
+ self._write_table([(R, 0, 0, 0, R)])
+ run = lambda: compute(w, None, b, R, mixer=lambda layer: self._mixer(layer, R, index)) # noqa: E731
+ for _ in range(2):
+@@ -169,6 +169,12 @@ class BatchedVerify:
+ self._write_table([(len(s.tokens), s.st.slot, s.st.cur[0] if s.st.cur else 0, s.st.slot,
+ len(s.tokens) if keeps is None else keeps[k]) for k, s in enumerate(segments)])
+
++ def _span(self, st, pos: int, n: int) -> tuple:
++ """SegRows' segment of ``n`` rows of ``st`` from ``pos``: its extent's base, and its slot's ring base."""
++ caches = self.e.caches
++ span = (st.base, pos, n)
++ return span + (caches.ring_base(st.slot),) if caches.rings else span
++
+ def _write_table(self, rows) -> None:
+ from . import kda as kda_mod
+
+@@ -201,7 +207,7 @@ class BatchedVerify:
+ spans = []
+ for seg in segments:
+ check_room(w, seg.st, len(seg.tokens))
+- spans.append((seg.st.base, seg.st.pos, len(seg.tokens)))
++ spans.append(self._span(seg.st, seg.st.pos, len(seg.tokens)))
+ tokens = [t for seg in segments for t in seg.tokens]
+ R = len(tokens)
+ self._stage(tokens)
+@@ -240,7 +246,7 @@ class BatchedVerify:
+ di = self.dsa_index[layer.index]
+ planes = caches.arena.planes
+ lc = planes[caches.kc[di]].tensor
+- index = None if caches.index is None else tuple(planes[i].tensor for i in caches.index[di])
++ index = None if caches.index is None else caches.index_tensors(di)
+ with prof.timed("dsa (total)"):
+ return dsa_segments(layer, self.w, lc, self.b, R, self.seg_rows, self.sel, index, select=select)
+
diff --git a/patches/0042-glm-kda-chunked-kernel.patch b/patches/0042-glm-kda-chunked-kernel.patch
new file mode 100644
index 0000000..37f80f4
--- /dev/null
+++ b/patches/0042-glm-kda-chunked-kernel.patch
@@ -0,0 +1,1552 @@
+diff --git tensorfold/families/glm5_next/cuda/engine.py tensorfold/families/glm5_next/cuda/engine.py
+index b357ce2..64d16d9 100644
+--- tensorfold/families/glm5_next/cuda/engine.py
++++ tensorfold/families/glm5_next/cuda/engine.py
+@@ -86,19 +86,34 @@ def vision_workspace() -> int:
+ GRIDS = (16, 32, 64, 128) # TF_GLM_PROMPT_GRID's values besides 0 (off)
+
+
+-def prompt_grid(prefill_rows: int, value: str | None = None) -> int:
++def kda_chunked_on() -> bool:
++ from .kda import CHUNKED
++
++ return CHUNKED
++
++
++def prompt_grid(prefill_rows: int, value: str | None = None, chunked: bool | None = None) -> int:
+ """TF_GLM_PROMPT_GRID: 0 (off, the default) or G in ``GRIDS``, which ``prefill_rows`` must be a multiple of.
+
+ With G set, every prompt chunk starts on a multiple of G and a kept prompt state sits at the last multiple of G
+- in the prompt (``grid_point``), so prompt kernels whose rows depend on G-row block alignment resume exactly."""
++ in the prompt (``grid_point``), so prompt kernels whose rows depend on G-row block alignment resume exactly.
++ ``chunked`` (default: TF_GLM_KDA_CHUNKED): the chunked KDA prompt path, whose rows depend on the alignment of its
++ 32-row sub-chunks, needs G a multiple of 32; unset or 0 then means 64."""
+
++ if chunked is None:
++ chunked = kda_chunked_on()
+ value = os.environ.get("TF_GLM_PROMPT_GRID", "") if value is None else value
+ value = value.strip()
+ if value in ("", "0"):
+- return 0
++ if not chunked:
++ return 0
++ value = "64"
+ if not value.isdecimal() or int(value) not in GRIDS:
+ raise ValueError(f"TF_GLM_PROMPT_GRID: 0 or one of {', '.join(map(str, GRIDS))}, not {value!r}")
+ grid = int(value)
++ if chunked and grid % 32:
++ raise ValueError(f"TF_GLM_PROMPT_GRID={grid}: TF_GLM_KDA_CHUNKED=1 runs prompt chunks in 32-row sub-chunks at "
++ f"absolute positions, so prompt chunks must start on a grid of 32, 64 or 128 (0: 64)")
+ 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:
+ 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)
++ if rank == 0 and kda_chunked_on():
++ print("[tensorfold] TF_GLM_KDA_CHUNKED=1: KDA prompt chunks in chunked (WY) form, 32-row sub-chunks "
++ "(close to the serial kernel, not its bits; decode keeps the serial kernel)", flush=True)
+ # rank 0: the role token whose first appearance ends a prompt's system block (a shared-prefix point)
+ self.opener = user_opener(model_dir) if self.shared and rank == 0 else None
+ if rank == 0 and self.shared:
+diff --git tensorfold/families/glm5_next/cuda/kda.py tensorfold/families/glm5_next/cuda/kda.py
+index 394dcd0..a1ea49e 100644
+--- tensorfold/families/glm5_next/cuda/kda.py
++++ tensorfold/families/glm5_next/cuda/kda.py
+@@ -60,7 +60,8 @@ def replay_layers(state_in: torch.Tensor, scratch: KDAScratchSet, rows: int, sta
+ # chain_kernel's bits). TF_GLM_KDA_WIDE_ROWS, default 1: every window (decode windows measured 4-36% faster at 1-8
+ # rows on GB10); 64: the one-block chain below 64 rows, as before.
+ WIDE_ROWS = int(os.environ.get("TF_GLM_KDA_WIDE_ROWS", "1"))
+-# prompt chunks in chunked (WY) form, 64-row sub-chunks at absolute positions (kda_chunked.py): close, not the same bits
++# prompt chunks in chunked (WY) form, 32-row sub-chunks at absolute positions (kda_chunked.py, kda_chunk.cu): close to
++# the serial kernels, not their bits; the engine then puts prompt chunks on a 64-token grid (TF_GLM_PROMPT_GRID)
+ CHUNKED = os.environ.get("TF_GLM_KDA_CHUNKED", "0") == "1"
+ _tmp: dict = {}
+ _outgrown: list = []
+diff --git tensorfold/families/glm5_next/cuda/kda_chunk.cpp tensorfold/families/glm5_next/cuda/kda_chunk.cpp
+new file mode 100644
+index 0000000..fcc7da7
+--- /dev/null
++++ tensorfold/families/glm5_next/cuda/kda_chunk.cpp
+@@ -0,0 +1,56 @@
++#include <torch/extension.h>
++#include <c10/cuda/CUDAGuard.h>
++
++void kda_chunk_cuda(const at::Tensor&, int64_t, int64_t, const at::Tensor&, int64_t, const at::Tensor&, int64_t,
++ const at::Tensor&, const at::Tensor&, const at::Tensor&, const at::Tensor&, const at::Tensor&,
++ const at::Tensor&, double, double, int64_t, int64_t, at::Tensor&, at::Tensor&);
++
++static void check(const at::Tensor& x, at::ScalarType t, const char* name) {
++ TORCH_CHECK(x.is_cuda() && x.scalar_type() == t, name, ": expected a CUDA tensor of the right dtype");
++}
++
++// A prompt chunk of ``rows`` rows whose first row sits ``off`` rows into its 32-row sub-chunk (kda_chunk.cu).
++void chain(const at::Tensor& P, int64_t p_stride, int64_t b_off, const at::Tensor& A, int64_t a_stride,
++ const at::Tensor& G, int64_t g_stride, const at::Tensor& cs, const at::Tensor& cw,
++ const at::Tensor& state_in, const at::Tensor& a_log, const at::Tensor& dt_bias, const at::Tensor& norm_w,
++ double eps, double lower, int64_t rows, int64_t off, at::Tensor out, at::Tensor state_out) {
++ check(P, at::kBFloat16, "P");
++ check(A, at::kBFloat16, "A");
++ check(G, at::kBFloat16, "G");
++ check(cs, at::kBFloat16, "conv state");
++ check(cw, at::kBFloat16, "conv weight");
++ check(state_in, at::kFloat, "state");
++ check(state_out, at::kFloat, "state out");
++ check(a_log, at::kFloat, "A_log");
++ check(dt_bias, at::kFloat, "dt_bias");
++ check(norm_w, at::kBFloat16, "norm");
++ check(out, at::kBFloat16, "out");
++ TORCH_CHECK(cs.is_contiguous() && cw.is_contiguous() && state_in.is_contiguous() && state_out.is_contiguous() &&
++ out.is_contiguous() && a_log.is_contiguous() && dt_bias.is_contiguous() && norm_w.is_contiguous(),
++ "conv state, conv weight, states, out and the per-head weights must be contiguous");
++ TORCH_CHECK(P.stride(1) == 1 && A.stride(1) == 1 && G.stride(1) == 1, "rows must be contiguous along channels");
++ const int64_t H = a_log.numel();
++ TORCH_CHECK(dt_bias.numel() == H * 128 && norm_w.numel() == 128, "dt_bias [H*128], norm [128]");
++ TORCH_CHECK(cw.size(0) == 3 * H * 128 && cw.size(1) == 4 && cs.size(0) == 3 && cs.size(1) == 3 * H * 128,
++ "4-tap convolutions of 3 x H x 128 channels");
++ TORCH_CHECK(state_in.numel() == H * 128 * 128 && state_out.numel() == H * 128 * 128, "states [H, 128, 128]");
++ TORCH_CHECK(state_in.data_ptr() != state_out.data_ptr(), "state_out must not alias state_in");
++ TORCH_CHECK(rows >= 1 && P.size(0) >= rows && A.size(0) >= rows && G.size(0) >= rows && out.size(0) >= rows,
++ "rows");
++ TORCH_CHECK(off >= 0 && off < 32, "off");
++ c10::cuda::CUDAGuard guard(P.device());
++ kda_chunk_cuda(P, p_stride, b_off, A, a_stride, G, g_stride, cs, cw, state_in, a_log, dt_bias, norm_w, eps, lower,
++ rows, off, out, state_out);
++}
++
++#ifdef KDA_PROF
++void kda_chunk_prof(at::Tensor&);
++void prof(at::Tensor out) { kda_chunk_prof(out); }
++#endif
++
++PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
++ m.def("chain", &chain);
++#ifdef KDA_PROF
++ m.def("prof", &prof);
++#endif
++}
+diff --git tensorfold/families/glm5_next/cuda/kda_chunk.cu tensorfold/families/glm5_next/cuda/kda_chunk.cu
+new file mode 100644
+index 0000000..6bd6d93
+--- /dev/null
++++ tensorfold/families/glm5_next/cuda/kda_chunk.cu
+@@ -0,0 +1,745 @@
++// GLM-5.3-Flash's KDA prompt chunks in chunked (WY) form: one block of 256 threads per head runs the prompt
++// chunk's 32-row sub-chunks in order (sub-chunks at absolute positions), the 128 x 128 state in registers.
++//
++// Per row the inputs are kda.cu's (this file is built like kda.cu, without FMA contraction, with CUDA's expf and
++// IEEE division): conv + SiLU rounded to bf16, fp32 L2 norms (q times 128^-0.5), beta = bf16(sigmoid(b)), the
++// per-channel decay g = expf(lower * sigmoid(exp(A_log) * (a + dt_bias))). A sub-chunk of rows 0..31 entering state
++// S0 [value, key]:
++//
++// E(t -> s) = g_{t+1} ... g_s per key channel: a running product multiplied in row order, as the serial chain
++// decays its state (empty: 1); E(s) = g_0 ... g_s from the sub-chunk's start;
++// E(s ->) = g_{s+1} ... g_31
++// L[s, t] = beta_s sum_c k_s k_t E(t -> s) t < s
++// M[s, t] = sum_c q_s k_t E(t -> s) t <= s
++// T = (I + L)^-1 forward substitution (16-row blocks)
++// Y = beta (v - (k E(s)) S0^T), V' = T Y the delta rule's corrections ("v_new")
++// O = (q E(s)) S0^T + M V' read-outs, rounded to bf16, then the gated RMSNorm
++// S_end = S0 diag(E(31)) + V'^T (k E(s ->))
++//
++// Every factor is a product of decays <= 1 (no e^(+x), no difference of cumulative log-decays), so a decay carries
++// the serial chain's rounding; all sums run in fp32 with explicit FMAs and shuffle trees in a fixed order: the kernel
++// is deterministic, and a row's bits depend only on its sub-chunk's rows and the state entering it, so they are the
++// same whichever prefill chunk the row came in, as long as prompt chunks start on multiples of 32
++// (TF_GLM_PROMPT_GRID). Rows outside the prompt chunk (a short first or last sub-chunk) are zero rows: decay 1, no
++// key, no value, beta 0.
++//
++// Layout. The state: thread (vg, kp) = (tid / 8, tid % 8) holds value rows 4 vg .. 4 vg + 3 and key quads kp + 8 i
++// (i < 4): an 8-lane group reads 128 contiguous bytes of a key row per load, and products with S reduce over the 8
++// lanes by a transposing shuffle tree (7 shuffles for 8 sums). Read-outs and corrections: thread (vg, kp) finishes
++// value column 4 vg + kp % 4 of the rows of one parity (odd for kp < 4, even otherwise), 16 rows. The next
++// sub-chunk's projection, decay and beta rows are loaded into registers while this one computes, and staged into
++// shared memory that is free at the sub-chunk's start.
++
++#include <ATen/ATen.h>
++#include <ATen/cuda/CUDAContext.h>
++#include <cuda_bf16.h>
++#include <cuda_runtime.h>
++#include <cstdint>
++
++namespace {
++
++constexpr int DK = 128, DV = 128, TAPS = 4;
++constexpr int BT = 32; // rows of a sub-chunk
++constexpr int HALO = TAPS - 1; // conv rows before a sub-chunk
++constexpr int NT = 256, NW = NT / 32; // threads, warps
++constexpr int VPT = 4; // value rows of the state a thread holds
++constexpr int KP = NT * VPT / DV; // threads sharing those value rows (8), each 16 keys
++constexpr int NQ = DK / 4 / KP; // key quads a thread holds (4)
++constexpr int OWN = BT / 2; // rows a thread finishes (16, one parity)
++constexpr int LS = BT + 4; // row stride of L
++constexpr int PCH = 3 * DK; // projection channels of a head (q | k | v)
++constexpr int PF_P = ((BT + HALO) * PCH / 8 + NT - 1) / NT; // 16-byte loads a thread prefetches (7)
++constexpr int PF_A = BT * DK / 8 / NT; // (2)
++static_assert(KP == 8 && NQ == 4 && PF_A * NT * 8 == BT * DK, "layout");
++
++struct Smem {
++ float q[BT][DK]; // q -> q E(s) -> V'
++ float k[BT][DK]; // k -> k E(s) -> (q E) S0^T
++ float g[BT][DK]; // decays -> Y
++ union { // staged projection rows (conv input) -> k E(s ->), L, T, M
++ __nv_bfloat16 raw_p[BT + HALO][PCH];
++ struct {
++ float ke[BT][DK]; // k E(s ->)
++ float L[BT][LS]; // L[s][t]
++ float tt[BT][BT]; // T transposed: tt[t][s] = T[s][t]
++ float mt[BT][BT]; // M transposed: mt[t][s] = M[s][t]
++ } x;
++ } u;
++ __nv_bfloat16 v[BT][DV];
++ __nv_bfloat16 raw_a[BT][DK]; // staged decay rows
++ __nv_bfloat16 cw[PCH][TAPS]; // this head's conv weights
++ float raw_b[BT];
++ float beta[BT];
++ float egl[DK]; // E(31)
++};
++
++__device__ __forceinline__ float bf(float x) { return __bfloat162float(__float2bfloat16_rn(x)); }
++__device__ __forceinline__ float ldb(const __nv_bfloat16* p) { return __bfloat162float(*p); }
++__device__ __forceinline__ float fma_(float a, float b, float c) { return __fmaf_rn(a, b, c); }
++__device__ __forceinline__ float sigmoidf_(float x) { return 1.0f / (1.0f + expf(-x)); }
++
++// a / b with IEEE rounding, branch-free: the fast path of CUDA's division (a refined reciprocal, then one
++// correction), which is the correctly rounded quotient whenever ``div_ok`` holds (checked on 742 M operand pairs
++// against a / b); callers take a / b for the rare operands outside (a huge denominator, a tiny numerator).
++__device__ __forceinline__ float div_rn(float a, float b) {
++ float r;
++ asm("rcp.approx.ftz.f32 %0, %1;" : "=f"(r) : "f"(b));
++ const float e = __fmaf_rn(-b, r, 1.0f);
++ r = __fmaf_rn(e, r, r);
++ const float q = a * r;
++ const float rem = __fmaf_rn(-b, q, a);
++ return __fmaf_rn(rem, r, q);
++}
++
++__device__ __forceinline__ bool div_ok(float a, float b) {
++ return (a == 0.0f || fabsf(a) > 1e-36f) && b >= 1.0f && b < 8e37f;
++}
++
++__device__ __forceinline__ float warp_sum(float x) {
++ for (int o = 16; o; o >>= 1) x += __shfl_xor_sync(0xffffffffu, x, o);
++ return x;
++}
++
++// 8 bf16 from p: one 16-byte load when aligned, else 8 loads.
++__device__ __forceinline__ uint4 ld8(const __nv_bfloat16* p, bool vec) {
++ if (vec) return *reinterpret_cast<const uint4*>(p);
++ const unsigned short* s = reinterpret_cast<const unsigned short*>(p);
++ uint4 r;
++ r.x = s[0] | ((unsigned)s[1] << 16); r.y = s[2] | ((unsigned)s[3] << 16);
++ r.z = s[4] | ((unsigned)s[5] << 16); r.w = s[6] | ((unsigned)s[7] << 16);
++ return r;
++}
++
++// One level of a transposing shuffle tree: this lane keeps the half of a[0..N) its ``hi`` bit selects, adds the
++// partner's (lane ^ mask) copy of that half, and sends the other half.
++template <int N>
++__device__ __forceinline__ void tree_level(float (&a)[N], int mask, bool hi) {
++#pragma unroll
++ for (int j = 0; j < N / 2; ++j) {
++ const float send = hi ? a[j] : a[j + N / 2];
++ const float keep = hi ? a[j + N / 2] : a[j];
++ a[j] = keep + __shfl_xor_sync(0xffffffffu, send, mask);
++ }
++}
++
++// Sums of a[0..8) over the lanes xor 4, 2, 1: lane bits (2, 1, 0) = i gets the sum of a[i].
++__device__ __forceinline__ float tree8(float (&a)[8], int lane) {
++ tree_level<8>(a, 4, lane & 4);
++ float b[4] = {a[0], a[1], a[2], a[3]};
++ tree_level<4>(b, 2, lane & 2);
++ float c[2] = {b[0], b[1]};
++ tree_level<2>(c, 1, lane & 1);
++ return c[0];
++}
++
++// Sums of a[0..16) over the lanes xor m0 > m1 > m2 > m3: the lane whose bits (m0, m1, m2, m3) spell i gets a[i]'s.
++__device__ __forceinline__ float tree16(float (&a)[16], int lane, int m0, int m1, int m2, int m3) {
++ tree_level<16>(a, m0, lane & m0);
++ float b[8];
++#pragma unroll
++ for (int j = 0; j < 8; ++j) b[j] = a[j];
++ tree_level<8>(b, m1, lane & m1);
++ float c[4] = {b[0], b[1], b[2], b[3]};
++ tree_level<4>(c, m2, lane & m2);
++ float d[2] = {c[0], c[1]};
++ tree_level<2>(d, m3, lane & m3);
++ return d[0];
++}
++
++#ifdef KDA_PROF
++__device__ unsigned long long g_prof[16];
++#define MARK(i) \
++ do { if (tid == 0 && h == 0) { const long long t1 = clock64(); g_prof[i] += t1 - t0_; t0_ = t1; } } while (0)
++#else
++#define MARK(i) do {} while (0)
++#endif
++
++__device__ __forceinline__ void prefetch_l2(const void* p) {
++ asm volatile("prefetch.global.L2 [%0];" :: "l"(p));
++}
++
++__device__ __forceinline__ void cp16(void* dst, const void* src) {
++ const unsigned d = (unsigned)__cvta_generic_to_shared(dst);
++ asm volatile("cp.async.cg.shared.global [%0], [%1], 16;" :: "r"(d), "l"(src));
++}
++
++// Warm L2 with the rows of the sub-chunk whose row 0 is prompt-chunk row r0 (projection rows r0 - 3 .. r0 + 31 of
++// this head's q | k | v channels, its decay rows and beta logits; not when ``next`` is false) and the output gate
++// rows from gate_r0.
++__device__ __forceinline__ void warm(int tid, int h, int H, int r0, bool next, int rows, int gate_r0,
++ const __nv_bfloat16* __restrict__ P, int p_stride, int b_off,
++ const __nv_bfloat16* __restrict__ A, int a_stride,
++ const __nv_bfloat16* __restrict__ G, int g_stride) {
++ constexpr int LP = (BT + HALO) * 3 * 2, LA = BT * 2, LB = BT, LG = BT * 2; // 128-byte lines
++ for (int x = next ? tid : tid + LP + LA + LB; x < LP + LA + LB + LG; x += NT) {
++ if (x < LP) {
++ const int row = x / 6, part = (x % 6) / 2, half = x % 2, r = r0 - HALO + row;
++ if (r >= 0 && r < rows) prefetch_l2(P + (size_t)r * p_stride + part * H * DK + h * DK + 64 * half);
++ } else if (x < LP + LA) {
++ const int y = x - LP, r = r0 + y / 2;
++ if (r >= 0 && r < rows) prefetch_l2(A + (size_t)r * a_stride + h * DK + 64 * (y % 2));
++ } else if (x < LP + LA + LB) {
++ const int r = r0 + (x - LP - LA);
++ if (r >= 0 && r < rows) prefetch_l2(P + (size_t)r * p_stride + b_off + h);
++ } else {
++ const int y = x - LP - LA - LB, r = gate_r0 + y / 2;
++ if (r >= 0 && r < rows) prefetch_l2(G + (size_t)r * g_stride + h * DV + 64 * (y % 2));
++ }
++ }
++}
++
++// Stage the rows of the sub-chunk whose row 0 is prompt-chunk row r0 into shared memory: projection rows r0 - 3 ..
++// r0 + 31 (the conv state before row 0, zero rows outside), decay rows and the beta logits. Global to shared
++// directly (cp.async) when the rows are 16-byte aligned; the caller waits (cp.async.wait_all) and syncs.
++__device__ __forceinline__ void stage(Smem& sm, int tid, int h, int H, int r0, int rows,
++ const __nv_bfloat16* __restrict__ P, int p_stride, int b_off,
++ const __nv_bfloat16* __restrict__ A, int a_stride,
++ const __nv_bfloat16* __restrict__ cs, bool vec_p, bool vec_a) {
++ const int C = 3 * H * DK;
++ for (int item = tid; item < (BT + HALO) * PCH / 8; item += NT) {
++ const int row = item / (PCH / 8), q8 = item % (PCH / 8);
++ const int ch = (q8 / (DK / 8)) * H * DK + h * DK + 8 * (q8 % (DK / 8));
++ const int r = r0 - HALO + row;
++ uint4* dst = reinterpret_cast<uint4*>(&sm.u.raw_p[row][0]) + q8;
++ const __nv_bfloat16* src = nullptr;
++ if (r >= 0 && r < rows) src = P + (size_t)r * p_stride + ch;
++ else if (r < 0 && r >= -HALO) src = cs + (size_t)(r + HALO) * C + ch;
++ if (src == nullptr) *dst = make_uint4(0, 0, 0, 0);
++ else if (vec_p) cp16(dst, src);
++ else *dst = ld8(src, false);
++ }
++ for (int item = tid; item < BT * DK / 8; item += NT) {
++ const int row = item / (DK / 8), c8 = item % (DK / 8);
++ const int r = r0 + row;
++ uint4* dst = reinterpret_cast<uint4*>(&sm.raw_a[row][0]) + c8;
++ const __nv_bfloat16* src = A + (size_t)r * a_stride + h * DK + 8 * c8;
++ if (r < 0 || r >= rows) *dst = make_uint4(0, 0, 0, 0);
++ else if (vec_a) cp16(dst, src);
++ else *dst = ld8(src, false);
++ }
++ if (tid < BT) {
++ const int r = r0 + tid;
++ sm.raw_b[tid] = (r >= 0 && r < rows) ? ldb(P + (size_t)r * p_stride + b_off + h) : 0.0f;
++ }
++}
++
++__global__ void __launch_bounds__(NT, 1) chunk_kernel(
++ int H, const __nv_bfloat16* __restrict__ P, int p_stride, int b_off,
++ const __nv_bfloat16* __restrict__ A, int a_stride, const __nv_bfloat16* __restrict__ G, int g_stride,
++ const __nv_bfloat16* __restrict__ cs, const __nv_bfloat16* __restrict__ cw,
++ const float* __restrict__ state_in, const float* __restrict__ a_log, const float* __restrict__ dt_bias,
++ const __nv_bfloat16* __restrict__ norm_w, float eps, float lower, int rows, int off,
++ __nv_bfloat16* __restrict__ out, float* __restrict__ state_out) {
++ extern __shared__ __align__(16) unsigned char smem_raw[];
++ Smem& sm = *reinterpret_cast<Smem*>(smem_raw);
++ const int h = blockIdx.x, tid = threadIdx.x, warp = tid >> 5, lane = tid & 31;
++ const int vg = tid / KP, kp = tid % KP;
++ const int par = kp < 4 ? 1 : 0; // parity of the rows this thread finishes
++ const int ov = VPT * vg + (kp & 3); // their value column
++ const size_t sbase = (size_t)h * DV * DK;
++ const bool vec_p = (p_stride % 8 == 0) && ((uintptr_t)P % 16 == 0) && ((uintptr_t)cs % 16 == 0);
++ const bool vec_a = (a_stride % 8 == 0) && ((uintptr_t)A % 16 == 0);
++
++ float s[VPT][NQ][4];
++#pragma unroll
++ for (int vv = 0; vv < VPT; ++vv)
++#pragma unroll
++ for (int i = 0; i < NQ; ++i) {
++ const float4 x =
++ reinterpret_cast<const float4*>(state_in + sbase + (size_t)(VPT * vg + vv) * DK)[kp + KP * i];
++ s[vv][i][0] = x.x; s[vv][i][1] = x.y; s[vv][i][2] = x.z; s[vv][i][3] = x.w;
++ }
++ const float rate = expf(a_log[h]);
++ const float dtb = dt_bias[h * DK + (tid & (DK - 1))]; // the decay channel this thread computes (tid % 128)
++ float nw[4]; // the norm weights of value columns 4 lane .. 4 lane + 3
++#pragma unroll
++ for (int x = 0; x < 4; ++x) nw[x] = ldb(norm_w + 4 * lane + x);
++ const bool vec_g = (g_stride % 4 == 0) && ((uintptr_t)G % 8 == 0);
++ const bool vec_o = ((H * DV) % 4 == 0) && ((uintptr_t)out % 8 == 0);
++ const int nsub = (rows + off + BT - 1) / BT;
++ for (int x = tid; x < PCH * TAPS; x += NT) {
++ const int ch = x / TAPS;
++ sm.cw[ch][x % TAPS] = cw[(size_t)((ch / DK) * H * DK + h * DK + ch % DK) * TAPS + x % TAPS];
++ }
++#ifdef KDA_PROF
++ long long t0_ = clock64();
++#endif
++
++ for (int c = 0; c < nsub; ++c) {
++ const int r0 = c * BT - off; // the prompt chunk's row at the sub-chunk's row 0
++
++ // 0. stage this sub-chunk's rows (warmed in L2 during the previous one), warm the next one's and this
++ // one's output gates
++ stage(sm, tid, h, H, r0, rows, P, p_stride, b_off, A, a_stride, cs, vec_p, vec_a);
++ asm volatile("cp.async.wait_all;" ::: "memory");
++ __syncthreads(); MARK(0);
++ warm(tid, h, H, r0 + BT, c + 1 < nsub, rows, r0, P, p_stride, b_off, A, a_stride, G, g_stride);
++
++ // 1. conv + SiLU (kda.cu's arithmetic) in 4-row blocks: warp w takes rows 4 w .. 4 w + 3 of q, then of k,
++ // then of v, lane l the channels 4 l .. 4 l + 3 (kda.cu's norm lanes), and the L2 norms of its q and k rows
++ // (kda.cu's sums); then the decays and beta.
++#pragma unroll 1
++ for (int part = 0; part < 3; ++part) {
++ const int rb = 4 * warp, ch = part * DK + 4 * lane;
++ float wt[4][TAPS];
++#pragma unroll
++ for (int x = 0; x < 4; ++x)
++#pragma unroll
++ for (int tap = 0; tap < TAPS; ++tap) wt[x][tap] = __bfloat162float(sm.cw[ch + x][tap]);
++ float xs[4 + HALO][4];
++#pragma unroll
++ for (int j = 0; j < 4 + HALO; ++j) {
++ const uint2 raw = *reinterpret_cast<const uint2*>(&sm.u.raw_p[rb + j][ch]);
++ const __nv_bfloat162 lo = *reinterpret_cast<const __nv_bfloat162*>(&raw.x);
++ const __nv_bfloat162 hi = *reinterpret_cast<const __nv_bfloat162*>(&raw.y);
++ xs[j][0] = __low2float(lo); xs[j][1] = __high2float(lo);
++ xs[j][2] = __low2float(hi); xs[j][3] = __high2float(hi);
++ }
++ float acc[4][4], act[4][4];
++ bool slow = false;
++#pragma unroll
++ for (int i = 0; i < 4; ++i)
++#pragma unroll
++ for (int x = 0; x < 4; ++x) {
++ acc[i][x] = 0.0f;
++#pragma unroll
++ for (int tap = 0; tap < TAPS; ++tap) acc[i][x] = acc[i][x] + wt[x][tap] * xs[i + tap][x];
++ const float den = 1.0f + expf(-acc[i][x]);
++ act[i][x] = div_rn(acc[i][x], den);
++ slow |= !div_ok(acc[i][x], den);
++ }
++ if (slow) { // kda.cu's IEEE division for the rare operands
++#pragma unroll
++ for (int i = 0; i < 4; ++i)
++#pragma unroll
++ for (int x = 0; x < 4; ++x) act[i][x] = acc[i][x] / (1.0f + expf(-acc[i][x]));
++ }
++#pragma unroll
++ for (int i = 0; i < 4; ++i) {
++ const int r = r0 + rb + i;
++#pragma unroll
++ for (int x = 0; x < 4; ++x) act[i][x] = (r >= 0 && r < rows) ? bf(act[i][x]) : 0.0f;
++ }
++ if (part < 2) { // warp-uniform
++ float ss[4];
++#pragma unroll
++ for (int i = 0; i < 4; ++i) {
++ ss[i] = 0.0f;
++#pragma unroll
++ for (int x = 0; x < 4; ++x) ss[i] = ss[i] + act[i][x] * act[i][x];
++ }
++#pragma unroll
++ for (int o = 16; o; o >>= 1) // warp_sum's tree, the rows interleaved
++#pragma unroll
++ for (int i = 0; i < 4; ++i) ss[i] += __shfl_xor_sync(0xffffffffu, ss[i], o);
++ float (*dst)[DK] = part ? sm.k : sm.q;
++#pragma unroll
++ for (int i = 0; i < 4; ++i) {
++ const float inv = 1.0f / sqrtf(ss[i] + 1e-6f);
++ float y[4];
++#pragma unroll
++ for (int x = 0; x < 4; ++x) {
++ y[x] = act[i][x] * inv;
++ if (part == 0) y[x] = y[x] * (1.0f / sqrtf((float)DK));
++ }
++ *reinterpret_cast<float4*>(&dst[rb + i][4 * lane]) = make_float4(y[0], y[1], y[2], y[3]);
++ }
++ } else {
++#pragma unroll
++ for (int i = 0; i < 4; ++i) {
++ __nv_bfloat162 lo = __floats2bfloat162_rn(act[i][0], act[i][1]);
++ __nv_bfloat162 hi = __floats2bfloat162_rn(act[i][2], act[i][3]);
++ uint2 o;
++ o.x = *reinterpret_cast<unsigned*>(&lo); o.y = *reinterpret_cast<unsigned*>(&hi);
++ *reinterpret_cast<uint2*>(&sm.v[rb + i][4 * lane]) = o;
++ }
++ }
++ }
++ {
++ const int cc = tid & (DK - 1);
++#pragma unroll
++ for (int j = tid >> 7; j < BT; j += NT / DK) {
++ const int r = r0 + j;
++ float gv = 1.0f;
++ if (r >= 0 && r < rows) {
++ const float a = __bfloat162float(sm.raw_a[j][cc]) + dtb;
++ const float den = 1.0f + expf(-(rate * a));
++ const float sg = div_ok(1.0f, den) ? div_rn(1.0f, den) : 1.0f / den; // kda.cu's sigmoidf_
++ gv = expf(lower * sg);
++ }
++ sm.g[j][cc] = gv;
++ }
++ if (tid < BT) {
++ const int r = r0 + tid;
++ sm.beta[tid] = (r >= 0 && r < rows) ? bf(sigmoidf_(sm.raw_b[tid])) : 0.0f;
++ }
++ }
++ __syncthreads(); MARK(1);
++
++ // 3. L and M. Group pr = tid / 16 takes column t = pr (rows s > pr), then t = 31 - pr (31 entries in all,
++ // every group alike), in batches of 8; lane cg holds the key quads cg and cg + 16, k_t E(t -> s) multiplied
++ // row after row; a batch's 16 sums reduce over the 16 lanes by a transposing tree.
++ {
++ const int pr = tid >> 4, cg = tid & 15;
++ const int n1 = BT - 1 - pr; // entries of column pr
++ float kt[8], e[8];
++ auto load_t = [&](int tt) {
++#pragma unroll
++ for (int u = 0; u < 2; ++u) {
++ const float4 x = reinterpret_cast<const float4*>(sm.k[tt])[cg + 16 * u];
++ kt[4 * u] = x.x; kt[4 * u + 1] = x.y; kt[4 * u + 2] = x.z; kt[4 * u + 3] = x.w;
++ }
++#pragma unroll
++ for (int i = 0; i < 8; ++i) e[i] = kt[i]; // k_t E(t -> s), multiplied row after row
++ };
++ { // the diagonal of M for both columns
++ float dg[2];
++#pragma unroll
++ for (int hh = 0; hh < 2; ++hh) {
++ const int tt = hh ? BT - 1 - pr : pr;
++ load_t(tt);
++ float a = 0.0f;
++#pragma unroll
++ for (int u = 0; u < 2; ++u) {
++ const float4 x = reinterpret_cast<const float4*>(sm.q[tt])[cg + 16 * u];
++ a = fma_(x.x, kt[4 * u], a); a = fma_(x.y, kt[4 * u + 1], a);
++ a = fma_(x.z, kt[4 * u + 2], a); a = fma_(x.w, kt[4 * u + 3], a);
++ }
++ dg[hh] = a;
++ }
++#pragma unroll
++ for (int o = 8; o; o >>= 1) {
++ dg[0] += __shfl_xor_sync(0xffffffffu, dg[0], o);
++ dg[1] += __shfl_xor_sync(0xffffffffu, dg[1], o);
++ }
++ if (cg == 0) {
++ sm.u.x.mt[pr][pr] = dg[0];
++ sm.u.x.mt[BT - 1 - pr][BT - 1 - pr] = dg[1];
++ }
++ }
++ load_t(pr);
++#pragma unroll
++ for (int b = 0; b < 4; ++b) {
++ float val[16];
++#pragma unroll
++ for (int ii = 0; ii < 8; ++ii) {
++ const int i = 8 * b + ii;
++ if (i == n1 && n1 < BT - 1) load_t(BT - 1 - pr);
++ const int s2 = i < n1 ? pr + 1 + i : BT - pr + (i - n1);
++ float ak = 0.0f, aq = 0.0f;
++ if (i < BT - 1) {
++#pragma unroll
++ for (int u = 0; u < 2; ++u) {
++ const float4 gx = reinterpret_cast<const float4*>(sm.g[s2])[cg + 16 * u];
++ const float4 kx = reinterpret_cast<const float4*>(sm.k[s2])[cg + 16 * u];
++ const float4 qx = reinterpret_cast<const float4*>(sm.q[s2])[cg + 16 * u];
++ const float gg[4] = {gx.x, gx.y, gx.z, gx.w}, kk[4] = {kx.x, kx.y, kx.z, kx.w};
++ const float qq[4] = {qx.x, qx.y, qx.z, qx.w};
++#pragma unroll
++ for (int x = 0; x < 4; ++x) {
++ e[4 * u + x] = e[4 * u + x] * gg[x];
++ ak = fma_(kk[x], e[4 * u + x], ak);
++ aq = fma_(qq[x], e[4 * u + x], aq);
++ }
++ }
++ }
++ val[2 * ii] = ak;
++ val[2 * ii + 1] = aq;
++ }
++ const float sum = tree16(val, lane, 8, 4, 2, 1); // entry cg / 2 of the batch, L (even) or M
++ const int i = 8 * b + (cg >> 1);
++ if (i < BT - 1) {
++ const int tt = i < n1 ? pr : BT - 1 - pr;
++ const int s2 = i < n1 ? pr + 1 + i : BT - pr + (i - n1);
++ if (cg & 1) {
++ sm.u.x.mt[tt][s2] = sum;
++ sm.u.x.mt[s2][tt] = 0.0f; // M[tt][s2], above the diagonal
++ } else {
++ sm.u.x.L[s2][tt] = sm.beta[s2] * sum;
++ }
++ }
++ }
++ }
++ __syncthreads(); MARK(3);
++
++ // 4. T = (I + L)^-1 by warp 0: lane l inverts column l % 16 of diagonal block l / 16 by forward
++ // substitution, then block (1, 0) = -T11 (L10 T00). Warps 1-7 per key channel: k E(s ->), then k E(s) in
++ // place, and E(31) (threads 32-159); q E(s) in place (threads 160-255, then 160-191 for the last 32 channels)
++ if (warp == 0) {
++ const int blk = lane >> 4, j = lane & 15, base = 16 * blk;
++ float col[16];
++#pragma unroll
++ for (int s2 = 0; s2 < 16; ++s2) {
++ float acc = 0.0f;
++#pragma unroll
++ for (int m = 0; m < s2; ++m) acc = fma_(sm.u.x.L[base + s2][base + m], col[m], acc);
++ col[s2] = s2 == j ? 1.0f : (s2 > j ? -acc : 0.0f);
++ }
++#pragma unroll
++ for (int s2 = 0; s2 < 16; ++s2) sm.u.x.tt[base + j][base + s2] = col[s2];
++ if (blk == 1) { // block (0, 1), above the diagonal: zeros
++#pragma unroll
++ for (int s2 = 0; s2 < 16; ++s2) sm.u.x.tt[16 + j][s2] = 0.0f;
++ }
++ __syncwarp();
++ if (blk == 0) {
++ float xr[16]; // (L10 T00)[:, j]
++#pragma unroll
++ for (int s2 = 0; s2 < 16; ++s2) {
++ float acc = 0.0f;
++#pragma unroll
++ for (int m = 0; m < 16; ++m) acc = fma_(sm.u.x.L[16 + s2][m], col[m], acc);
++ xr[s2] = acc;
++ }
++#pragma unroll
++ for (int s2 = 0; s2 < 16; ++s2) {
++ float acc = 0.0f;
++#pragma unroll
++ for (int m = 0; m <= s2; ++m) // T11[s2][m]
++ acc = fma_(sm.u.x.tt[16 + m][16 + s2], xr[m], acc);
++ sm.u.x.tt[j][16 + s2] = -acc;
++ }
++ }
++ } else {
++ const int t2 = tid - 32;
++ if (t2 < DK) {
++ const int cc = t2;
++ float rr = 1.0f;
++#pragma unroll 8
++ for (int j = BT - 1; j >= 0; --j) { sm.u.x.ke[j][cc] = sm.k[j][cc] * rr; rr = rr * sm.g[j][cc]; }
++ float pp = 1.0f;
++#pragma unroll 8
++ for (int j = 0; j < BT; ++j) { pp = pp * sm.g[j][cc]; sm.k[j][cc] = sm.k[j][cc] * pp; }
++ sm.egl[cc] = pp;
++ } else {
++ for (int cc = t2 - DK; cc < DK; cc += NT - 32 - DK) {
++ float pp = 1.0f;
++#pragma unroll 8
++ for (int j = 0; j < BT; ++j) { pp = pp * sm.g[j][cc]; sm.q[j][cc] = sm.q[j][cc] * pp; }
++ }
++ }
++ }
++ __syncthreads(); MARK(4);
++
++ // 5. Every thread: its sums of (k E) S0^T and (q E) S0^T; Y = beta (v - (k E) S0^T) into g, the (q E) S0^T
++ // of the rows it finishes kept in o1.
++ float o1[OWN];
++ {
++ float4 ck[NQ], cq[NQ], nk[NQ], nq[NQ];
++ auto load_row = [&](float4 (&kx)[NQ], float4 (&qx)[NQ], int r) {
++#pragma unroll
++ for (int i = 0; i < NQ; ++i) {
++ kx[i] = reinterpret_cast<const float4*>(sm.k[r])[kp + KP * i];
++ qx[i] = reinterpret_cast<const float4*>(sm.q[r])[kp + KP * i];
++ }
++ };
++ // row r's 8 sums (k sums at ok, q sums at 4 - ok), reduced: entry kp, value column 4 vg + kp % 4
++ auto row_sums = [&](const float4 (&kx)[NQ], const float4 (&qx)[NQ], int ok) {
++ float a[8];
++#pragma unroll
++ for (int x = 0; x < 8; ++x) a[x] = 0.0f;
++ const int oq = 4 - ok;
++#pragma unroll
++ for (int i = 0; i < NQ; ++i)
++#pragma unroll
++ for (int vv = 0; vv < VPT; ++vv) {
++ a[ok + vv] = fma_(kx[i].x, s[vv][i][0], a[ok + vv]);
++ a[ok + vv] = fma_(kx[i].y, s[vv][i][1], a[ok + vv]);
++ a[ok + vv] = fma_(kx[i].z, s[vv][i][2], a[ok + vv]);
++ a[ok + vv] = fma_(kx[i].w, s[vv][i][3], a[ok + vv]);
++ a[oq + vv] = fma_(qx[i].x, s[vv][i][0], a[oq + vv]);
++ a[oq + vv] = fma_(qx[i].y, s[vv][i][1], a[oq + vv]);
++ a[oq + vv] = fma_(qx[i].z, s[vv][i][2], a[oq + vv]);
++ a[oq + vv] = fma_(qx[i].w, s[vv][i][3], a[oq + vv]);
++ }
++ return tree8(a, lane);
++ };
++ load_row(ck, cq, 0);
++#pragma unroll 1
++ for (int rg = 0; rg < BT / 8; ++rg) { // 8 rows: pairs 2 rp (even: k sums first), 2 rp + 1
++#pragma unroll
++ for (int u = 0; u < 4; ++u) {
++ const int r = 8 * rg + 2 * u;
++ load_row(nk, nq, r + 1);
++ const float se = row_sums(ck, cq, 0);
++ load_row(ck, cq, r + 2 < BT ? r + 2 : r); // (the last pair reloads a row: no predicate)
++ const float so = row_sums(nk, nq, 4);
++ // this thread keeps the q sum of its parity's row and writes Y of the other
++ const float qs = par ? so : se, ks = par ? se : so;
++ const int ry = par ? r : r + 1;
++ sm.g[ry][ov] = (__bfloat162float(sm.v[ry][ov]) - ks) * sm.beta[ry];
++ o1[OWN - 4 + u] = qs;
++ }
++ if (rg + 1 < BT / 8) { // after the loop o1[j] is row 2 j + par's
++#pragma unroll
++ for (int j = 0; j + 4 < OWN; ++j) o1[j] = o1[j + 4];
++ }
++ }
++ }
++ __syncthreads(); MARK(5);
++
++ // 6. load this sub-chunk's output gates (warm in L2); (q E) S0^T into k (free now); V' = T Y into q. Tiles:
++ // warp w the rows 4 w' .. 4 w' + 3 with w' = w (w < 4) or 11 - w (the two warps of a scheduler, w and w + 4,
++ // then run 36 steps of t together), lane l the value columns 4 l .. 4 l + 3 (T is zero above its diagonal:
++ // t runs to the tile's last row)
++ const int rq = 4 * (warp < 4 ? warp : 11 - warp), vq = 4 * lane;
++ float gate[4][4];
++#pragma unroll
++ for (int i = 0; i < 4; ++i) {
++ const int r = r0 + rq + i;
++ const bool ok = r >= 0 && r < rows;
++ const __nv_bfloat16* gp = G + (size_t)(ok ? r : 0) * g_stride + h * DV + vq;
++ if (vec_g) {
++ const uint2 x = ok ? *reinterpret_cast<const uint2*>(gp) : make_uint2(0, 0);
++ const __nv_bfloat162 g0 = *reinterpret_cast<const __nv_bfloat162*>(&x.x);
++ const __nv_bfloat162 g1 = *reinterpret_cast<const __nv_bfloat162*>(&x.y);
++ gate[i][0] = __low2float(g0); gate[i][1] = __high2float(g0);
++ gate[i][2] = __low2float(g1); gate[i][3] = __high2float(g1);
++ } else {
++#pragma unroll
++ for (int x = 0; x < 4; ++x) gate[i][x] = ok ? ldb(gp + x) : 0.0f;
++ }
++ }
++#pragma unroll
++ for (int j = 0; j < OWN; ++j) sm.k[2 * j + par][ov] = o1[j];
++ {
++ float acc[4][4];
++#pragma unroll
++ for (int i = 0; i < 4; ++i)
++#pragma unroll
++ for (int x = 0; x < 4; ++x) acc[i][x] = 0.0f;
++#pragma unroll 4
++ for (int t = 0; t < rq + 4; ++t) {
++ const float4 tq = *reinterpret_cast<const float4*>(&sm.u.x.tt[t][rq]);
++ const float4 y = *reinterpret_cast<const float4*>(&sm.g[t][vq]);
++ const float tv[4] = {tq.x, tq.y, tq.z, tq.w}, yv[4] = {y.x, y.y, y.z, y.w};
++#pragma unroll
++ for (int i = 0; i < 4; ++i)
++#pragma unroll
++ for (int x = 0; x < 4; ++x) acc[i][x] = fma_(tv[i], yv[x], acc[i][x]);
++ }
++#pragma unroll
++ for (int i = 0; i < 4; ++i)
++ *reinterpret_cast<float4*>(&sm.q[rq + i][vq]) = make_float4(acc[i][0], acc[i][1], acc[i][2], acc[i][3]);
++ }
++ __syncthreads(); MARK(6);
++
++ // 7. read-outs O = (q E) S0^T + M V' of the same tile, bf16, the gated RMSNorm (kda.cu's formula; a warp
++ // holds its rows' 128 values); the state update
++ {
++ float o[4][4];
++#pragma unroll
++ for (int i = 0; i < 4; ++i) {
++ const float4 x = *reinterpret_cast<const float4*>(&sm.k[rq + i][vq]);
++ o[i][0] = x.x; o[i][1] = x.y; o[i][2] = x.z; o[i][3] = x.w;
++ }
++#pragma unroll 4
++ for (int t = 0; t < rq + 4; ++t) {
++ const float4 mq = *reinterpret_cast<const float4*>(&sm.u.x.mt[t][rq]);
++ const float4 vn = *reinterpret_cast<const float4*>(&sm.q[t][vq]);
++ const float mv[4] = {mq.x, mq.y, mq.z, mq.w}, vv4[4] = {vn.x, vn.y, vn.z, vn.w};
++#pragma unroll
++ for (int i = 0; i < 4; ++i)
++#pragma unroll
++ for (int x = 0; x < 4; ++x) o[i][x] = fma_(mv[i], vv4[x], o[i][x]);
++ }
++ float ss[4];
++#pragma unroll
++ for (int i = 0; i < 4; ++i) {
++ ss[i] = 0.0f;
++#pragma unroll
++ for (int x = 0; x < 4; ++x) { o[i][x] = bf(o[i][x]); ss[i] = ss[i] + o[i][x] * o[i][x]; }
++ }
++#pragma unroll
++ for (int m = 16; m; m >>= 1)
++#pragma unroll
++ for (int i = 0; i < 4; ++i) ss[i] += __shfl_xor_sync(0xffffffffu, ss[i], m);
++#pragma unroll
++ for (int i = 0; i < 4; ++i) {
++ const int r = r0 + rq + i;
++ if (r < 0 || r >= rows) continue;
++ const float rinv = 1.0f / sqrtf(ss[i] / (float)DV + eps);
++ __nv_bfloat16 ob[4];
++#pragma unroll
++ for (int x = 0; x < 4; ++x) {
++ const float yn = o[i][x] * rinv;
++ const float yw = nw[x] * yn;
++ const float den = 1.0f + expf(-gate[i][x]);
++ const float sg = div_ok(1.0f, den) ? div_rn(1.0f, den) : 1.0f / den; // kda.cu's sigmoidf_
++ ob[x] = __float2bfloat16_rn(yw * sg);
++ }
++ __nv_bfloat16* op = out + (size_t)r * H * DV + h * DV + vq;
++ if (vec_o) *reinterpret_cast<uint2*>(op) = *reinterpret_cast<const uint2*>(ob);
++ else {
++#pragma unroll
++ for (int x = 0; x < 4; ++x) op[x] = ob[x];
++ }
++ }
++ }
++#pragma unroll
++ for (int i = 0; i < NQ; ++i) {
++ const float4 ge = reinterpret_cast<const float4*>(sm.egl)[kp + KP * i];
++#pragma unroll
++ for (int vv = 0; vv < VPT; ++vv) {
++ s[vv][i][0] = s[vv][i][0] * ge.x; s[vv][i][1] = s[vv][i][1] * ge.y;
++ s[vv][i][2] = s[vv][i][2] * ge.z; s[vv][i][3] = s[vv][i][3] * ge.w;
++ }
++ }
++#pragma unroll 4
++ for (int t = 0; t < BT; ++t) {
++ const float4 vn = *reinterpret_cast<const float4*>(&sm.q[t][VPT * vg]);
++ const float vs[4] = {vn.x, vn.y, vn.z, vn.w};
++#pragma unroll
++ for (int i = 0; i < NQ; ++i) {
++ const float4 kx = reinterpret_cast<const float4*>(sm.u.x.ke[t])[kp + KP * i];
++#pragma unroll
++ for (int vv = 0; vv < VPT; ++vv) {
++ s[vv][i][0] = fma_(vs[vv], kx.x, s[vv][i][0]); s[vv][i][1] = fma_(vs[vv], kx.y, s[vv][i][1]);
++ s[vv][i][2] = fma_(vs[vv], kx.z, s[vv][i][2]); s[vv][i][3] = fma_(vs[vv], kx.w, s[vv][i][3]);
++ }
++ }
++ }
++ __syncthreads(); MARK(7);
++ }
++#pragma unroll
++ for (int vv = 0; vv < VPT; ++vv)
++#pragma unroll
++ for (int i = 0; i < NQ; ++i)
++ reinterpret_cast<float4*>(state_out + sbase + (size_t)(VPT * vg + vv) * DK)[kp + KP * i] =
++ make_float4(s[vv][i][0], s[vv][i][1], s[vv][i][2], s[vv][i][3]);
++}
++
++} // namespace
++
++#ifdef KDA_PROF
++void kda_chunk_prof(at::Tensor& outp) {
++ cudaMemcpyFromSymbol(outp.data_ptr(), g_prof, sizeof(unsigned long long) * 16);
++ unsigned long long z[16] = {};
++ cudaMemcpyToSymbol(g_prof, z, sizeof(z));
++}
++#endif
++
++template <typename T>
++static T* ptr(const at::Tensor& x) { return x.defined() && x.numel() ? (T*)x.data_ptr() : nullptr; }
++
++void kda_chunk_cuda(const at::Tensor& P, int64_t p_stride, int64_t b_off, const at::Tensor& A, int64_t a_stride,
++ const at::Tensor& G, int64_t g_stride, const at::Tensor& cs, const at::Tensor& cw,
++ const at::Tensor& state_in, const at::Tensor& a_log, const at::Tensor& dt_bias,
++ const at::Tensor& norm_w, double eps, double lower, int64_t rows, int64_t off, at::Tensor& out,
++ at::Tensor& state_out) {
++ auto stream = at::cuda::getCurrentCUDAStream();
++ const int H = (int)a_log.numel();
++ const int smem = (int)sizeof(Smem);
++ static int attr_device = -1;
++ const int device = P.get_device();
++ if (attr_device != device) {
++ C10_CUDA_CHECK(cudaFuncSetAttribute(chunk_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, smem));
++ attr_device = device;
++ }
++ chunk_kernel<<<H, NT, smem, stream>>>(
++ H, ptr<__nv_bfloat16>(P), (int)p_stride, (int)b_off, ptr<__nv_bfloat16>(A), (int)a_stride,
++ ptr<__nv_bfloat16>(G), (int)g_stride, ptr<__nv_bfloat16>(cs), ptr<__nv_bfloat16>(cw), ptr<float>(state_in),
++ ptr<float>(a_log), ptr<float>(dt_bias), ptr<__nv_bfloat16>(norm_w), (float)eps, (float)lower, (int)rows,
++ (int)off, ptr<__nv_bfloat16>(out), ptr<float>(state_out));
++ C10_CUDA_KERNEL_LAUNCH_CHECK();
++}
+diff --git tensorfold/families/glm5_next/cuda/kda_chunked.py tensorfold/families/glm5_next/cuda/kda_chunked.py
+index 09cb28b..6b5e1b9 100644
+--- tensorfold/families/glm5_next/cuda/kda_chunked.py
++++ tensorfold/families/glm5_next/cuda/kda_chunked.py
+@@ -1,64 +1,39 @@
+-"""GLM-5.3-Flash's KDA prompt chunks in chunked (WY) form: sub-chunks of 64 rows at absolute positions, the
+-intra-chunk part as matmuls, the 128 x 128 state carried from sub-chunk to sub-chunk.
+-
+-Per row the definition is kda.cu's (conv + SiLU rounded to bf16, fp32 L2 norms, q times 128^-0.5, beta =
+-bf16(sigmoid(b)), log-decay l = lower * sigmoid(exp(A_log) * (a + dt_bias)) per key channel, the delta rule
+-S <- S diag(e^l); S <- S + beta (v - S k) k^T; o = S q, o rounded to bf16, then the gated RMSNorm). The state S is
+-[value, key] as in kda.cu.
+-
+-Sub-chunk of rows 0..63 (T = 64), entering state S0, G = cumsum(l) within the sub-chunk (per key channel, <= 0 and
+-decreasing: every l is in (lower, 0) = (-5, 0)):
+-
+- L[s, j] = beta_s sum_c k_s[c] k_j[c] e^(G_s[c] - G_j[c]) j < s (strictly lower)
+- M[s, j] = sum_c q_s[c] k_j[c] e^(G_s[c] - G_j[c]) j <= s
+- T = (I + L)^-1 (unit lower triangular)
+- W = T (beta * k * e^G), U = T (beta * v) the WY / UT transform
+- V' = U - W S0^T the corrected values ("v_new")
+- O = (q * e^G) S0^T + M V'
+- S_end = S0 diag(e^G_63) + V'^T (k * e^(G_63 - G))
+-
+-Every exponent above is <= 0 except inside L and M, which are formed as matmuls of row and column factors about a
+-reference row p: e^(G_s - G_j) = e^(G_s - G_p) e^(G_p - G_j). Each exponent is summed outward from its reference
+-(forward from p, backward from p, backward from the sub-chunk's end for k e^(G_63 - G)), never taken as a difference
+-of G's: all l have one sign, so a partial sum's rounding error is a few ulps of the partial sum itself, while G
+-reaches -320 in a sub-chunk and a difference of two G's would carry ulp(320) = 3e-5 into decays near 1 (the first
+-version did: 10x the error of kda.cu's chain). For the rows of 16-row block b against earlier blocks p = the
+-block's first row (both factors <= 1: errors a few ulps of the decay's own exponent); inside the diagonal tile p =
+-the first row of the row's 4-row group (column factors <= e^15 for the rows after p: errors a few ulps of 30). Only
+-blocks j <= b are formed. T is inverted per 16-row diagonal block by forward substitution, then block rows are
+-joined with matmuls (T_bj = -T_bb sum L_bm T_mj). Everything is fp32; the matmuls take tl.dot's
+-``input_precision`` (TF_GLM_KDA_PREC, default tf32x3, about fp32: read-outs ~3e-7 relative against float64 on the
+-tests' inputs, kda.cu's chain ~1e-7; "tf32" is faster and ~5e-4, half a bf16 step).
+-
+-Kernels (``chain``): _kda_lm (sub-chunk, head, block): the conv, norms, beta and decays of its rows, L and M rows,
+-q e^G; _kda_solve (sub-chunk, head): T and the sub-chunk's total log-decay; _kda_wu (sub-chunk, head, block): W, U
+-and the keys decayed to the sub-chunk's end; _kda_state (head, 16 value rows): the only sequential part, sub-chunk
+-after sub-chunk, V' and the state entering each sub-chunk; _kda_out (sub-chunk, head): O, bf16, the gated RMSNorm.
+-q, k, v, G are recomputed from the projection rows where needed rather than kept (registers) or stored (traffic).
+-
+-Sub-chunks start at absolute positions that are multiples of 64 (``pos`` gives the first row's position); a
+-prompt chunk that starts mid-sub-chunk takes a short first sub-chunk (padded rows are zero rows: no decay, no
+-key). A row's output depends only on its sub-chunk's rows and the state entering it, so it is the same whichever
+-prefill chunk it came in, as long as chunk boundaries are multiples of 64 (a short last sub-chunk included).
+-
+-The torch functions (``*_reference``) are the CPU references of the tests; ``chain`` runs the Triton kernels.
++"""GLM-5.3-Flash's KDA prompt chunks in chunked (WY) form (kda_chunk.cu): 32-row sub-chunks at absolute positions,
++one CUDA block per head carrying the 128 x 128 state from sub-chunk to sub-chunk in registers.
++
++Per row the inputs are kda.cu's (conv + SiLU rounded to bf16, fp32 L2 norms, q times 128^-0.5, beta =
++bf16(sigmoid(b)), the per-channel decay g = e^l, l = lower * sigmoid(exp(A_log) * (a + dt_bias))); the delta rule
++S <- S diag(g); S <- S + beta (v - S k) k^T; o = S q, o rounded to bf16, then the gated RMSNorm. S is [value, key].
++
++A sub-chunk of rows 0..31 entering state S0, E(t -> s) = g_{t+1} ... g_s per key channel (empty: 1):
++
++ L[s, t] = beta_s sum_c k_s k_t E(t -> s) t < s M[s, t] = sum_c q_s k_t E(t -> s) t <= s
++ T = (I + L)^-1 Y = beta (v - (k E(0 -> row)) S0^T), V' = T Y
++ O = (q E(0 -> row)) S0^T + M V' S_end = S0 diag(E(0 -> 31)) + V'^T (k E(row -> 31))
++
++Every decay is a running product of per-row decays <= 1, multiplied in row order as the serial chain decays its state
++(no exponent of a difference of cumulative sums: G reaches -160 in a sub-chunk, and ulp(160) = 1.5e-5 would land on
++decays near 1). All products run in fp32 FMAs in a fixed order, so the kernel is deterministic, and a row's bits
++depend only on its sub-chunk's rows and the entering state: the same whichever prefill chunk the row came in, as long
++as prompt chunks start on multiples of the sub-chunk (TF_GLM_PROMPT_GRID, which TF_GLM_KDA_CHUNKED=1 sets to 64).
++Rows outside the prompt chunk (a short first or last sub-chunk) are zero rows: decay 1, no key, no value, beta 0.
++It is not kda.cu's arithmetic (different sums, so bf16 outputs may round the other way and states differ at fp32
++rounding); its error against the float64 delta rule is the serial kernel's order (tests/cuda/test_glm_kda_chunked.py).
++
++The torch functions (``*_reference``) are the CPU references of the tests; ``chain`` runs the CUDA kernel.
+ """
+
+ from __future__ import annotations
+
+ import math
+-import os
++from functools import lru_cache
++from pathlib import Path
+
+ import torch
+-import triton
+-import triton.language as tl
+-from triton.language.extra import libdevice
+
+ DK = DV = 128
+ TAPS = 4
+-CHUNK = 64 # rows of a sub-chunk (the state is carried between sub-chunks)
+-BLOCK = 16 # rows of a block inside a sub-chunk (the tiles of L, M and T)
+-GROUP = 4 # rows about one reference row inside a diagonal tile
++CHUNK = 32 # rows of a sub-chunk (the state is carried between sub-chunks); kda_chunk.cu's BT
+ SCALE = 1.0 / math.sqrt(DK)
+
+
+@@ -114,28 +89,9 @@ def recurrent_reference(q, k, v, lg, beta, state, dtype=torch.float64):
+ return out, S
+
+
+-def tf32(x: torch.Tensor) -> torch.Tensor:
+- """fp32 -> TF32 (10 mantissa bits, round to nearest, ties away: cvt.rna.tf32.f32), as fp32."""
+-
+- i = x.float().contiguous().view(torch.int32)
+- return ((i + 0x1000) & ~0x1FFF).view(torch.float32)
+-
+-
+-def _tri_inverse(Ld: torch.Tensor) -> torch.Tensor:
+- """(I + Ld)^-1 for strictly lower Ld [..., n, n], by forward substitution a row at a time."""
+-
+- n = Ld.shape[-1]
+- T = torch.eye(n, dtype=Ld.dtype, device=Ld.device).expand(Ld.shape).clone()
+- for s in range(1, n):
+- T[..., s, :] = -(Ld[..., s, :, None] * T).sum(-2)
+- T[..., s, s] = 1.0
+- return T
+-
+-
+-def chunked_reference(q, k, v, lg, beta, state, pos: int = 0, dtype=torch.float64, mm_round=None, state_round=...):
+- """The chunked algorithm as the kernels run it (sub-chunks at absolute positions, reference blocks, the block
+- triangular inverse): read-outs [rows, H, 128] and the final state. ``mm_round`` rounds matmul inputs (``tf32``
+- emulates tl.dot's TF32 path), ``state_round`` those of the products with the state (default: ``mm_round``)."""
++def chunked_reference(q, k, v, lg, beta, state, pos: int = 0, dtype=torch.float64):
++ """The chunked algorithm as the kernel runs it (sub-chunks of CHUNK rows at absolute positions, decays as running
++ products, T by forward substitution): read-outs [rows, H, 128] and the final state [H, 128, 128]."""
+
+ rows, H, _ = q.shape
+ dev = q.device
+@@ -143,78 +99,42 @@ def chunked_reference(q, k, v, lg, beta, state, pos: int = 0, dtype=torch.float6
+ nc = -(-(rows + off) // CHUNK)
+ total = nc * CHUNK
+
+- def pad(t):
++ def pad(t, fill=0.0):
+ t = t.to(dtype)
+- z = torch.zeros((total,) + tuple(t.shape[1:]), dtype=dtype, device=dev)
++ z = torch.full((total,) + tuple(t.shape[1:]), fill, dtype=dtype, device=dev)
+ z[off:off + rows] = t
+- return z.view((nc, CHUNK) + tuple(t.shape[1:])).transpose(1, 2) # [nc, H, 64, ...]
+-
+- qc, kc, vc, lc, bc = pad(q), pad(k), pad(v), pad(lg), pad(beta)
+- rnd = mm_round or (lambda x: x)
+- srnd = rnd if state_round is ... else (state_round or (lambda x: x))
+-
+- def mm(x, y):
+- return rnd(x) @ rnd(y)
++ return z.view((nc, CHUNK) + tuple(t.shape[1:])).transpose(1, 2) # [nc, H, CHUNK, ...]
+
+- def mms(x, y):
+- return srnd(x) @ srnd(y)
+-
+- t = torch.arange(CHUNK, device=dev)
+- lower_strict = t[:, None] > t[None, :]
+- lower_incl = t[:, None] >= t[None, :]
+- nb = CHUNK // BLOCK
+- i = torch.arange(BLOCK, device=dev)[None, :, None]
++ qc, kc, vc, bc = pad(q), pad(k), pad(v), pad(beta)
++ gc = pad(torch.exp(lg.to(dtype)), 1.0)
+ S = state.to(dtype).clone() # [H, V, K]
+ out = torch.empty((total, H, DV), dtype=dtype, device=dev)
+-
+- def rcumsum(x):
+- return torch.flip(torch.cumsum(torch.flip(x, [1]), 1), [1])
+-
+ for c in range(nc):
+- qx, kx, vx, lx, bx = qc[c], kc[c], vc[c], lc[c], bc[c] # [H, 64, 128] (beta [H, 64])
+- G = torch.cumsum(lx, dim=1)
+- Akk = torch.zeros((H, CHUNK, CHUNK), dtype=dtype, device=dev)
+- Aqk = torch.zeros_like(Akk)
+- for b in range(nb):
+- rs = slice(b * BLOCK, (b + 1) * BLOCK)
+- lb = lx[:, rs]
+- for g in range(BLOCK // GROUP): # the diagonal tile, about each group's row
+- p = g * GROUP
+- fwd = torch.cumsum(torch.where(i > p, lb, 0.0), 1)
+- back = rcumsum(torch.where(i <= p, lb, 0.0)) - lb
+- rf = torch.where((i >= p) & (i < p + GROUP), torch.exp(fwd), 0.0)
+- cf = torch.where(i < p, torch.exp(back), torch.where(i < p + GROUP, torch.exp(-fwd), 0.0))
+- kt = (kx[:, rs] * cf).transpose(1, 2)
+- Akk[:, rs, rs] += mm(kx[:, rs] * rf, kt)
+- Aqk[:, rs, rs] += mm(qx[:, rs] * rf, kt)
+- rf = torch.exp(torch.cumsum(torch.where(i > 0, lb, 0.0), 1)) # earlier blocks, about the block's row 0
+- carry = lb[:, :1]
+- for j in range(b - 1, -1, -1):
+- cs = slice(j * BLOCK, (j + 1) * BLOCK)
+- rev = rcumsum(lx[:, cs])
+- kt = (kx[:, cs] * torch.exp(carry + (rev - lx[:, cs]))).transpose(1, 2)
+- Akk[:, rs, cs] = mm(kx[:, rs] * rf, kt)
+- Aqk[:, rs, cs] = mm(qx[:, rs] * rf, kt)
+- carry = carry + rev[:, :1]
+- L = torch.where(lower_strict, bx[:, :, None] * Akk, torch.zeros_like(Akk))
+- M = torch.where(lower_incl, Aqk, torch.zeros_like(Aqk))
+- T = torch.zeros_like(L)
+- for b in range(nb):
+- rs = slice(b * BLOCK, (b + 1) * BLOCK)
+- Tbb = _tri_inverse(L[:, rs, rs])
+- X = mm(L[:, rs, :b * BLOCK], T[:, :b * BLOCK, :]) if b else torch.zeros_like(T[:, rs])
+- T[:, rs] = -mm(Tbb, X)
+- T[:, rs, rs] = Tbb
+- eG = torch.exp(G)
+- W = mm(T, bx[:, :, None] * kx * eG)
+- U = mm(T, bx[:, :, None] * vx)
+- gl = G[:, -1:, :]
+- Ke = kx * torch.exp(rcumsum(lx) - lx) # GL - G, summed backward from the end
+- Qt = qx * eG
++ qx, kx, vx, gx, bx = qc[c], kc[c], vc[c], gc[c], bc[c] # [H, T, 128] (beta [H, T])
++ E = torch.zeros((H, CHUNK, CHUNK, DK), dtype=dtype, device=dev) # E[:, s, t] = E(t -> s), t <= s
++ for t in range(CHUNK):
++ e = torch.ones((H, DK), dtype=dtype, device=dev)
++ E[:, t, t] = e
++ for s in range(t + 1, CHUNK):
++ e = e * gx[:, s]
++ E[:, s, t] = e
++ Akk = torch.einsum("hsc,htc,hstc->hst", kx, kx, E)
++ Aqk = torch.einsum("hsc,htc,hstc->hst", qx, kx, E)
++ tri = torch.ones((CHUNK, CHUNK), dtype=torch.bool, device=dev)
++ L = torch.where(torch.tril(tri, -1), bx[:, :, None] * Akk, torch.zeros_like(Akk))
++ M = torch.where(torch.tril(tri), Aqk, torch.zeros_like(Aqk))
++ T = torch.eye(CHUNK, dtype=dtype, device=dev).expand(L.shape).clone()
++ for s in range(1, CHUNK):
++ T[:, s, :] = -(L[:, s, :, None] * T).sum(-2)
++ T[:, s, s] = 1.0
++ fwd = torch.cumprod(gx, dim=1) # E(0 -> row)
++ back = torch.cat([torch.flip(torch.cumprod(torch.flip(gx[:, 1:], [1]), 1), [1]),
++ torch.ones_like(gx[:, :1])], 1)
+ ST = S.transpose(1, 2) # [H, K, V]
+- Vn = U - mms(W, ST)
+- out[c * CHUNK:(c + 1) * CHUNK] = (mms(Qt, ST) + mm(M, Vn)).transpose(0, 1)
+- S = S * torch.exp(gl) + mms(Vn.transpose(1, 2), Ke)
++ Y = bx[:, :, None] * (vx - (kx * fwd) @ ST)
++ Vn = T @ Y
++ out[c * CHUNK:(c + 1) * CHUNK] = ((qx * fwd) @ ST + M @ Vn).transpose(0, 1)
++ S = S * fwd[:, -1:, :] + Vn.transpose(1, 2) @ (kx * back)
+ return out[off:off + rows], S
+
+
+@@ -240,418 +160,37 @@ def chain_reference(p, b_off, a, g, conv_state, conv_w, state_in, a_log, dt_bias
+ return gate_norm_reference(y, g, norm_w, eps), S.float(), y
+
+
+-# -- Triton kernels ---------------------------------------------------------------------------------------------
+-# The per-row values rounded to bf16 (conv + SiLU, beta) must be kda.cu's bits: a value rounded the other way at a
+-# bf16 tie moves a key by 2^-8 in one channel, a beta by 2^-8 of the whole update, far above fp32 noise (and the
+-# read-out of a row whose RMSNorm is eps-dominated carries it into the output). kda.cu is built with --fmad=false and
+-# uses CUDA's expf and IEEE division: the kernels that compute these values launch with enable_fp_fusion=False and
+-# take libdevice's expf (the same algorithm) and div_rn. Triton's interpreter has no libdevice: it takes tl.exp.
+-_PRECISE = tl.constexpr(os.environ.get("TRITON_INTERPRET", "0") != "1")
+-
++def chain_reference(p, b_off, a, g, conv_state, conv_w, state_in, a_log, dt_bias, norm_w, eps, lower, rows, *,
++ pos: int = 0, chunked: bool = True, dtype=torch.float32):
++ """A whole prompt chunk: (out bf16 [rows, H * 128], final state fp32 [H, 128, 128], read-outs y [rows, H, 128])."""
+
+-def _expf(x):
+- """CUDA's expf (libdevice) on the GPU, tl.exp under the interpreter."""
+- if _PRECISE:
+- return libdevice.exp(x)
++ q, k, v, lg, beta = prep_reference(p, b_off, a, conv_state, conv_w, a_log, dt_bias, lower, rows)
++ if chunked:
++ y, S = chunked_reference(q, k, v, lg, beta, state_in, pos, dtype=dtype)
+ else:
+- return tl.exp(x)
++ y, S = recurrent_reference(q, k, v, lg, beta, state_in, dtype=dtype)
++ return gate_norm_reference(y, g, norm_w, eps), S.float(), y
+
+
+-def _sigmoid_f(x):
+- """kda.cu's sigmoidf_: 1 / (1 + expf(-x)), IEEE division."""
+- return tl.math.div_rn(1.0, 1.0 + _expf(-x))
+-
+-
+-def _bf16(x):
+- """fp32 rounded to bf16 (to nearest even), as fp32: bit arithmetic, so Triton's CPU interpreter (which truncates
+- in casts) rounds as the GPU does."""
+- b = x.to(tl.uint32, bitcast=True)
+- b = (b + 0x7FFF + ((b >> 16) & 1)) & 0xFFFF0000
+- return b.to(tl.float32, bitcast=True)
+-
+-
+-def _conv_act(P, p_stride, CS, CW, r, valid, ch, C3, BT: tl.constexpr, DK_: tl.constexpr, TAPS_: tl.constexpr):
+- """Depthwise conv over [conv state; P rows] of channels ch for rows r, SiLU, rounded to bf16: [BT, DK] fp32."""
+-
+- acc = tl.zeros((BT, DK_), dtype=tl.float32)
+- for tap in tl.static_range(TAPS_):
+- at = r + (tap - (TAPS_ - 1)) # P row (negative: conv state row at + TAPS - 1)
+- from_p = valid & (at >= 0)
+- from_s = valid & (at < 0)
+- xp = tl.load(P + at.to(tl.int64)[:, None] * p_stride + ch[None, :], mask=from_p[:, None], other=0.0)
+- xs = tl.load(CS + (at + (TAPS_ - 1)).to(tl.int64)[:, None] * C3 + ch[None, :], mask=from_s[:, None],
+- other=0.0)
+- x = tl.where(from_s[:, None], xs.to(tl.float32), xp.to(tl.float32))
+- wt = tl.load(CW + ch * TAPS_ + tap).to(tl.float32)
+- acc = acc + wt[None, :] * x
+- act = tl.math.div_rn(acc, 1.0 + _expf(-acc))
+- return _bf16(act)
+-
+-
+-def _l2(x):
+- ss = tl.sum(x * x, axis=1)
+- return x * tl.math.div_rn(1.0, tl.sqrt_rn(ss + 1e-6))[:, None]
+-
+-
+-def _row(x, t, s):
+- """Row s of x [n, N] as [N] (a sum with zeros: exact)."""
+- return tl.sum(tl.where((t == s)[:, None], x, 0.0), axis=0)
+-
+-
+-def _tri_inv(Ld, BC: tl.constexpr):
+- """(I + Ld)^-1 of a strictly lower [BC, BC] block by forward substitution."""
+-
+- i = tl.arange(0, BC)
+- T = tl.where(i[:, None] == i[None, :], 1.0, 0.0)
+- for s in range(1, BC):
+- lrow = tl.sum(tl.where((i == s)[:, None], Ld, 0.0), axis=0) # Ld[s, :]
+- trow = -tl.sum(lrow[:, None] * T, axis=0) # -sum_m Ld[s, m] T[m, :]
+- T = tl.where((i == s)[:, None], trow[None, :] + tl.where(i == s, 1.0, 0.0)[None, :], T)
+- return T
+-
+-
+-def _dot_k(a, b, NS: tl.constexpr, PREC: tl.constexpr):
+- """a [M, K] @ b [K, N] as a batched dot over NS slices of K, summed: with M = N = 16 a warp then holds a slice of
+- the operands instead of all of K."""
+- M: tl.constexpr = a.shape[0]
+- K: tl.constexpr = a.shape[1]
+- N: tl.constexpr = b.shape[1]
+- a3 = tl.permute(tl.reshape(a, (M, NS, K // NS)), (1, 0, 2))
+- b3 = tl.reshape(b, (NS, K // NS, N))
+- return tl.sum(tl.dot(a3, b3, input_precision=PREC), axis=0)
+-
+-
+-def _logdecay(A, a_stride, r, valid, hd, ch, rate, dtb, lower):
+- """The log-decays l of rows r [BC, DK] (in (lower, 0)); zero rows outside the chunk."""
+- av = tl.load(A + r.to(tl.int64)[:, None] * a_stride + hd + ch[None, :], mask=valid[:, None], other=0.0)
+- lg = lower * _sigmoid_f(rate * (av.to(tl.float32) + dtb[None, :]))
+- return tl.where(valid[:, None], lg, 0.0)
+-
+-
+-def _gates(A, a_stride, r, valid, hd, ch, rate, dtb, lower, carry):
+- """G for rows r: carry (the running log-decay before them) + their running sum; zero rows outside the chunk."""
+- return carry[None, :] + tl.cumsum(_logdecay(A, a_stride, r, valid, hd, ch, rate, dtb, lower), axis=0)
+-
+-
+-def _beta(P, p_stride, b_off, h, r, valid):
+- braw = tl.load(P + r.to(tl.int64) * p_stride + b_off + h, mask=valid, other=0.0).to(tl.float32)
+- return tl.where(valid, _bf16(_sigmoid_f(braw)), 0.0)
+-
+-
+-def _kda_lm(P, p_stride, b_off, A, a_stride, CS, CW, ALOG, DTB, lower, rows, off, H, QT, L, M,
+- DK_: tl.constexpr, BT: tl.constexpr, BC: tl.constexpr, GR: tl.constexpr, TAPS_: tl.constexpr,
+- KSPLIT: tl.constexpr, PREC: tl.constexpr):
+- """Program (sub-chunk, head, 16-row block b): block b's rows of L (beta k k decays, strictly lower) and M (q k
+- decays, with the diagonal) against blocks j <= b, and its decayed q (QT = q e^G). Rows outside the prompt chunk
+- are zero rows (no decay, no key).
+-
+- A decay e^(G_s - G_j) is formed as e^(G_s - G_p) e^(G_p - G_j) about a reference row p, each exponent summed
+- outward from p (its rounding error a few ulps of its own size, never of G's): p = the block's first row for
+- earlier blocks (both factors <= 1: the error is a few ulps of the decay's own exponent), p = the first row of s's
+- GR-row group inside the diagonal tile (column factors <= e^(5 (GR - 1)), errors a few ulps of 10 (GR - 1))."""
+-
+- c = tl.program_id(0)
+- h = tl.program_id(1)
+- b = tl.program_id(2)
+- i = tl.arange(0, BC)
+- ch = tl.arange(0, DK_)
+- C3 = 3 * H * DK_
+- hd = h * DK_
+- rate = _expf(tl.load(ALOG + h))
+- dtb = tl.load(DTB + hd + ch)
+- r0 = c * BT - off
+- tile = (c.to(tl.int64) * H + h) * BT * BT + (b * BC + i)[:, None] * BT + i[None, :] # + j * BC: tile (b, j)
+-
+- r = r0 + b * BC + i
+- valid = (r >= 0) & (r < rows)
+- lb = _logdecay(A, a_stride, r, valid, hd, ch, rate, dtb, lower)
+- k = _l2(_conv_act(P, p_stride, CS, CW, r, valid, H * DK_ + hd + ch, C3, BC, DK_, TAPS_))
+- q = _l2(_conv_act(P, p_stride, CS, CW, r, valid, hd + ch, C3, BC, DK_, TAPS_)) * 0.08838834764831845
+- beta = _beta(P, p_stride, b_off, h, r, valid)
+-
+- # the diagonal tile in GR-row groups: rows s of group g about p = the group's first row
+- akk = tl.zeros((BC, BC), dtype=tl.float32)
+- aqk = tl.zeros((BC, BC), dtype=tl.float32)
+- for g in tl.static_range(BC // GR):
+- fwd = tl.cumsum(tl.where(i[:, None] > g * GR, lb, 0.0), axis=0) # G_t - G_p, t >= p
+- back = tl.cumsum(tl.where(i[:, None] <= g * GR, lb, 0.0), axis=0, reverse=True) - lb # G_p - G_t, t < p
+- rf = tl.where(((i >= g * GR) & (i < g * GR + GR))[:, None], tl.exp(fwd), 0.0)
+- cf = tl.where((i < g * GR)[:, None], tl.exp(back), tl.where((i < g * GR + GR)[:, None], tl.exp(-fwd), 0.0))
+- col = tl.trans(k * cf)
+- akk += _dot_k(k * rf, col, KSPLIT, PREC)
+- aqk += _dot_k(q * rf, col, KSPLIT, PREC)
+- tl.store(L + tile + b * BC, tl.where(i[:, None] > i[None, :], beta[:, None] * akk, 0.0))
+- tl.store(M + tile + b * BC, tl.where(i[:, None] >= i[None, :], aqk, 0.0))
+-
+- # earlier blocks, nearest first, about p = the block's first row
+- fwd = tl.cumsum(tl.where(i[:, None] > 0, lb, 0.0), axis=0) # G_s - G_p
+- rf = tl.exp(fwd)
+- rk = k * rf
+- rq = q * rf
+- carry = _row(lb, i, 0) # G_p - G_t for t = the previous block's last row
+- for jj in range(0, b):
+- j = b - 1 - jj
+- rj = r0 + j * BC + i
+- vj = (rj >= 0) & (rj < rows)
+- lj = _logdecay(A, a_stride, rj, vj, hd, ch, rate, dtb, lower)
+- rev = tl.cumsum(lj, axis=0, reverse=True)
+- kj = _l2(_conv_act(P, p_stride, CS, CW, rj, vj, H * DK_ + hd + ch, C3, BC, DK_, TAPS_))
+- col = tl.trans(kj * tl.exp(carry[None, :] + (rev - lj))) # e^(G_p - G_t) <= 1, [DK, BC]
+- tl.store(L + tile + j * BC, beta[:, None] * _dot_k(rk, col, KSPLIT, PREC))
+- tl.store(M + tile + j * BC, _dot_k(rq, col, KSPLIT, PREC))
+- carry += _row(rev, i, 0)
+- # carry = G_p, the running log-decay through the block's first row
+- rowbase = (r.to(tl.int64) * H + h) * DK_
+- tl.store(QT + rowbase[:, None] + ch[None, :], q * tl.exp(carry[None, :] + fwd), mask=valid[:, None])
+-
+-
+-def _kda_solve(A, a_stride, ALOG, DTB, lower, rows, off, H, L, T, GL,
+- DK_: tl.constexpr, BT: tl.constexpr, BC: tl.constexpr, PREC: tl.constexpr):
+- """Program (sub-chunk, head): T = (I + L)^-1 in 16-row blocks (T_bb by forward substitution, T_bj = -T_bb
+- sum_{j<=m<b} L_bm T_mj), and the sub-chunk's total log-decay GL."""
+-
+- NB: tl.constexpr = BT // BC
+- c = tl.program_id(0)
+- h = tl.program_id(1)
+- i = tl.arange(0, BC)
+- ch = tl.arange(0, DK_)
+- hd = h * DK_
+- base = (c.to(tl.int64) * H + h) * BT * BT
+- Ts = ()
+- for b in tl.static_range(NB):
+- Lrow = ()
+- for j in tl.static_range(b + 1):
+- Lrow = Lrow + (tl.load(L + base + (b * BC + i)[:, None] * BT + j * BC + i[None, :]),)
+- Tbb = _tri_inv(Lrow[b], BC)
+- Trow = ()
+- for j in tl.static_range(b):
+- X = tl.zeros((BC, BC), dtype=tl.float32)
+- for m in tl.static_range(j, b):
+- X += tl.dot(Lrow[m], Ts[m][j], input_precision=PREC)
+- Trow = Trow + (-tl.dot(Tbb, X, input_precision=PREC),)
+- Trow = Trow + (Tbb,)
+- Ts = Ts + (Trow,)
+- for j in tl.static_range(b + 1):
+- tl.store(T + base + (b * BC + i)[:, None] * BT + j * BC + i[None, :], Trow[j])
+- rate = _expf(tl.load(ALOG + h))
+- dtb = tl.load(DTB + hd + ch)
+- carry = tl.zeros((DK_,), dtype=tl.float32)
+- for b in range(0, NB):
+- r = c * BT - off + b * BC + i
+- carry = _row(_gates(A, a_stride, r, (r >= 0) & (r < rows), hd, ch, rate, dtb, lower, carry), i, BC - 1)
+- tl.store(GL + (c.to(tl.int64) * H + h) * DK_ + ch, carry)
+-
+-
+-def _kda_wu(P, p_stride, b_off, A, a_stride, CS, CW, ALOG, DTB, lower, rows, off, H, T, W, U, KE,
+- DK_: tl.constexpr, BT: tl.constexpr, BC: tl.constexpr, TAPS_: tl.constexpr, PREC: tl.constexpr):
+- """Program (sub-chunk, head, 16-row block b): W_b = sum_{j<=b} T_bj (beta k e^G)_j, U_b = sum_{j<=b} T_bj
+- (beta v)_j (the WY / UT transform), and block b's keys decayed to the sub-chunk's end (KE = k e^(GL - G), the
+- exponent summed backward from the end: a few ulps of its own size)."""
+-
+- NB: tl.constexpr = BT // BC
+- c = tl.program_id(0)
+- h = tl.program_id(1)
+- b = tl.program_id(2)
+- i = tl.arange(0, BC)
+- ch = tl.arange(0, DK_)
+- C3 = 3 * H * DK_
+- hd = h * DK_
+- rate = _expf(tl.load(ALOG + h))
+- dtb = tl.load(DTB + hd + ch)
+- r0 = c * BT - off
+- tbase = (c.to(tl.int64) * H + h) * BT * BT + (b * BC + i)[:, None] * BT + i[None, :]
+- rb = r0 + b * BC + i
+- vb = (rb >= 0) & (rb < rows)
+- rowbase = (rb.to(tl.int64) * H + h) * DK_
+- later = tl.zeros((DK_,), dtype=tl.float32) # log-decay of the blocks after b, last first
+- for jj in range(0, NB - 1 - b):
+- rj = r0 + (NB - 1 - jj) * BC + i
+- later += tl.sum(_logdecay(A, a_stride, rj, (rj >= 0) & (rj < rows), hd, ch, rate, dtb, lower), axis=0)
+- wv = tl.zeros((BC, DK_), dtype=tl.float32)
+- uv = tl.zeros((BC, DK_), dtype=tl.float32)
+- carry = tl.zeros((DK_,), dtype=tl.float32)
+- for j in range(0, b + 1):
+- rj = r0 + j * BC + i
+- vj = (rj >= 0) & (rj < rows)
+- lj = _logdecay(A, a_stride, rj, vj, hd, ch, rate, dtb, lower)
+- Gj = carry[None, :] + tl.cumsum(lj, axis=0)
+- carry = _row(Gj, i, BC - 1)
+- kj = _l2(_conv_act(P, p_stride, CS, CW, rj, vj, H * DK_ + hd + ch, C3, BC, DK_, TAPS_))
+- if j == b:
+- ke = kj * tl.exp(later[None, :] + (tl.cumsum(lj, axis=0, reverse=True) - lj)) # GL - G
+- tl.store(KE + rowbase[:, None] + ch[None, :], ke, mask=vb[:, None])
+- bj = _beta(P, p_stride, b_off, h, rj, vj)
+- vv = _conv_act(P, p_stride, CS, CW, rj, vj, 2 * H * DK_ + hd + ch, C3, BC, DK_, TAPS_)
+- tbj = tl.load(T + tbase + j * BC)
+- wv += tl.dot(tbj, bj[:, None] * kj * tl.exp(Gj), input_precision=PREC)
+- uv += tl.dot(tbj, bj[:, None] * vv, input_precision=PREC)
+- tl.store(W + rowbase[:, None] + ch[None, :], wv, mask=vb[:, None])
+- tl.store(U + rowbase[:, None] + ch[None, :], uv, mask=vb[:, None])
+-
+-
+-def _kda_state(S_IN, S_OUT, W, U, KE, GL, HB, rows, off, NC, H,
+- DK_: tl.constexpr, DV_: tl.constexpr, BT: tl.constexpr, BC: tl.constexpr, BV: tl.constexpr,
+- PREC: tl.constexpr):
+- """Program (head, value tile): the state S [BV value rows, K] from sub-chunk to sub-chunk (the only sequential
+- part), BC rows at a time: V'^T = U^T - S W^T (written over U), S <- S diag(e^GL) + V'^T KE. Saves each
+- sub-chunk's entering state (HB [NC, H, V, K], the state's layout)."""
+-
+- h = tl.program_id(0)
+- v0 = tl.program_id(1) * BV
+- ki = tl.arange(0, DK_)
+- vi = v0 + tl.arange(0, BV)
+- i = tl.arange(0, BC)
+- sbase = h.to(tl.int64) * DV_ * DK_
+- S = tl.load(S_IN + sbase + vi[:, None] * DK_ + ki[None, :]) # [BV, K]
+- for c in range(NC):
+- cb = (c * H + h).to(tl.int64)
+- tl.store(HB + cb * DV_ * DK_ + vi[:, None] * DK_ + ki[None, :], S)
+- nxt = S * tl.exp(tl.load(GL + cb * DK_ + ki))[None, :]
+- for b in tl.static_range(BT // BC):
+- r = c * BT - off + b * BC + i
+- valid = (r >= 0) & (r < rows)
+- rowbase = (r.to(tl.int64) * H + h) * DK_
+- wb = tl.load(W + rowbase[:, None] + ki[None, :], mask=valid[:, None], other=0.0) # [BC, K]
+- ub = tl.load(U + rowbase[:, None] + vi[None, :], mask=valid[:, None], other=0.0) # [BC, BV]
+- vnt = tl.trans(ub) - tl.dot(S, tl.trans(wb), input_precision=PREC) # [BV, BC]
+- tl.store(U + rowbase[:, None] + vi[None, :], tl.trans(vnt), mask=valid[:, None])
+- kb = tl.load(KE + rowbase[:, None] + ki[None, :], mask=valid[:, None], other=0.0) # [BC, K]
+- nxt += tl.dot(vnt, kb, input_precision=PREC)
+- S = nxt
+- tl.store(S_OUT + sbase + vi[:, None] * DK_ + ki[None, :], S)
+-
+-
+-def _kda_out(QT, U, M, HB, G, g_stride, NW, eps, OUT, rows, off, H,
+- DK_: tl.constexpr, DV_: tl.constexpr, BT: tl.constexpr, BC: tl.constexpr, KS: tl.constexpr,
+- PREC: tl.constexpr):
+- """Program (sub-chunk, head): read-outs O = QT S0^T + M V' rounded to bf16, then the gated RMSNorm."""
+-
+- c = tl.program_id(0)
+- h = tl.program_id(1)
+- t = tl.arange(0, BT)
+- i = tl.arange(0, BC)
+- ks = tl.arange(0, KS)
+- vi = tl.arange(0, DV_)
+- r = c * BT - off + t
+- valid = (r >= 0) & (r < rows)
+- rowbase = (r.to(tl.int64) * H + h) * DK_
+- cb = (c * H + h).to(tl.int64)
+- o = tl.zeros((BT, DV_), dtype=tl.float32)
+- for k0 in tl.static_range(0, DK_, KS):
+- qt = tl.load(QT + rowbase[:, None] + k0 + ks[None, :], mask=valid[:, None], other=0.0) # [BT, KS]
+- hs = tl.load(HB + cb * DV_ * DK_ + vi[:, None] * DK_ + k0 + ks[None, :]) # [DV, KS]
+- o += tl.dot(qt, tl.trans(hs), input_precision=PREC)
+- for j in tl.static_range(BT // BC):
+- mq = tl.load(M + cb * BT * BT + t[:, None] * BT + (j * BC + i)[None, :], mask=(t >= j * BC)[:, None],
+- other=0.0) # tiles above the diagonal: 0
+- rj = c * BT - off + j * BC + i
+- vn = tl.load(U + ((rj.to(tl.int64) * H + h) * DK_)[:, None] + vi[None, :],
+- mask=((rj >= 0) & (rj < rows))[:, None], other=0.0)
+- o += tl.dot(mq, vn, input_precision=PREC)
+- y = _bf16(o)
+- rinv = tl.math.div_rn(1.0, tl.sqrt_rn(tl.sum(y * y, axis=1) * (1.0 / DV_) + eps))
+- yw = tl.load(NW + vi).to(tl.float32)[None, :] * (y * rinv[:, None])
+- gate = tl.load(G + r.to(tl.int64)[:, None] * g_stride + h * DV_ + vi[None, :], mask=valid[:, None], other=0.0)
+- res = yw * _sigmoid_f(gate.to(tl.float32))
+- tl.store(OUT + r.to(tl.int64)[:, None] * (H * DV_) + h * DV_ + vi[None, :], _bf16(res).to(tl.bfloat16),
+- mask=valid[:, None])
+-
+-
+-# -- launcher ---------------------------------------------------------------------------------------------------
+-PREC = os.environ.get("TF_GLM_KDA_PREC", "tf32x3") # tl.dot input precision: tf32x3 (~fp32), tf32, ieee
+-BV = int(os.environ.get("TF_GLM_KDA_BV", "16")) # value rows of the state per sequential program
+-STATE_ROWS = int(os.environ.get("TF_GLM_KDA_STATE_ROWS", "32")) # rows per step of the sequential kernel
+-KSPLIT = int(os.environ.get("TF_GLM_KDA_KSPLIT", "4")) # K slices of the 16 x 16 x 128 products (1: one dot)
+-# (num_warps, num_stages) per kernel. One stage everywhere: GB10 (sm_121) gives a block 99 KiB of shared memory
+-# (101,376 B), and pipelined loads of the per-block loops need up to 154 KiB.
+-LAUNCH = {"lm": (8, 1), "solve": (4, 1), "wu": (8, 1), "state": (8, 1), "out": (8, 1)}
+-_EXACT = dict(enable_fp_fusion=False, enable_reflect_ftz=False) # kda.cu's arithmetic (see _PRECISE)
+-_scratch: dict = {}
+-
+-
+-class ChunkScratch:
+- """Intermediates of a prompt chunk of up to ``rows`` rows (one set per head count and device, shared by layers)."""
+-
+- def __init__(self, rows: int, heads: int, device) -> None:
+- f32 = torch.float32
+- nc = -(-(rows + CHUNK - 1) // CHUNK) # room for a short first sub-chunk
+- self.rows, self.nc = rows, nc
+- self.qt = torch.empty((rows, heads, DK), dtype=f32, device=device)
+- self.w = torch.empty((rows, heads, DK), dtype=f32, device=device)
+- self.u = torch.empty((rows, heads, DV), dtype=f32, device=device)
+- self.ke = torch.empty((rows, heads, DK), dtype=f32, device=device)
+- self.m = torch.empty((nc, heads, CHUNK, CHUNK), dtype=f32, device=device)
+- self.l = torch.empty((nc, heads, CHUNK, CHUNK), dtype=f32, device=device)
+- self.t = torch.empty((nc, heads, CHUNK, CHUNK), dtype=f32, device=device)
+- self.gl = torch.empty((nc, heads, DK), dtype=f32, device=device)
+- self.hb = torch.empty((nc, heads, DV, DK), dtype=f32, device=device)
+-
+-
+-def scratch_for(rows: int, heads: int, device) -> ChunkScratch:
+- key = (heads, str(device))
+- s = _scratch.get(key)
+- if s is None or s.rows < rows:
+- s = ChunkScratch(max(rows, CHUNK), heads, device)
+- _scratch[key] = s
+- return s
++# -- the CUDA kernel --------------------------------------------------------------------------------------------
++@lru_cache(maxsize=1)
++def _ext():
++ from tensorfold.cuda.build import load
++
++ here = Path(__file__).parent
++ return load(name="tensorfold_glm_kda_chunk", sources=[str(here / "kda_chunk.cpp"), str(here / "kda_chunk.cu")],
++ extra_cuda_cflags=["-O3", "--fmad=false"], verbose=False)
+
+
+ def chain(p: torch.Tensor, b_off: int, a: torch.Tensor, g: torch.Tensor, conv_state: torch.Tensor,
+ 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, out: torch.Tensor, state_out: torch.Tensor,
+- pos: int = 0, *, prec: str | None = None, bv: int | None = None) -> torch.Tensor:
++ pos: int = 0) -> torch.Tensor:
+ """kda.chain for a prompt chunk in chunked form: projection rows p [q | k | v | ... | b at b_off ...], bf16 gate
+ rows a (decay) and g (output gate), conv state [3, 3 H 128] (read, not shifted), state_in -> state_out
+ [H, 128, 128]; ``pos`` is the first row's absolute position. Writes out[:rows] (bf16 [rows, H * 128])."""
+
+- H = a_log.numel()
+ rows = int(rows)
+- if rows < 1 or p.shape[0] < rows or out.shape[0] < rows:
+- raise ValueError("rows")
+- if conv_w.shape != (3 * H * DK, TAPS) or conv_state.shape[0] != TAPS - 1:
+- raise ValueError("the chunked KDA path is written for 4-tap convolutions of 3 x H x 128 channels")
+- for x in (conv_state, conv_w, state_in, state_out, out, dt_bias, a_log, norm_w):
+- if not x.is_contiguous():
+- raise ValueError("conv state, conv weight, states, out and the per-head weights must be contiguous")
+- if p.stride(1) != 1 or a.stride(1) != 1 or g.stride(1) != 1:
+- raise ValueError("projection and gate rows must be contiguous along the channels")
+- prec = prec or PREC
+- bv = bv or BV
+- off = int(pos) % CHUNK
+- nc = -(-(rows + off) // CHUNK)
+- s = scratch_for(rows, H, p.device)
+- nb = CHUNK // BLOCK
+- _kda_lm[(nc, H, nb)](p, p.stride(0), int(b_off), a, a.stride(0), conv_state, conv_w, a_log, dt_bias, float(lower),
+- rows, off, H, s.qt, s.l, s.m,
+- DK_=DK, BT=CHUNK, BC=BLOCK, GR=GROUP, TAPS_=TAPS, KSPLIT=KSPLIT, PREC=prec,
+- num_warps=LAUNCH["lm"][0], num_stages=LAUNCH["lm"][1], **_EXACT)
+- _kda_solve[(nc, H)](a, a.stride(0), a_log, dt_bias, float(lower), rows, off, H, s.l, s.t, s.gl,
+- DK_=DK, BT=CHUNK, BC=BLOCK, PREC=prec, num_warps=LAUNCH["solve"][0],
+- num_stages=LAUNCH["solve"][1], **_EXACT)
+- _kda_wu[(nc, H, nb)](p, p.stride(0), int(b_off), a, a.stride(0), conv_state, conv_w, a_log, dt_bias, float(lower),
+- rows, off, H, s.t, s.w, s.u, s.ke,
+- DK_=DK, BT=CHUNK, BC=BLOCK, TAPS_=TAPS, PREC=prec, num_warps=LAUNCH["wu"][0],
+- num_stages=LAUNCH["wu"][1], **_EXACT)
+- _kda_state[(H, DV // bv)](state_in, state_out, s.w, s.u, s.ke, s.gl, s.hb, rows, off, nc, H,
+- DK_=DK, DV_=DV, BT=CHUNK, BC=STATE_ROWS, BV=bv, PREC=prec,
+- num_warps=LAUNCH["state"][0], num_stages=LAUNCH["state"][1])
+- _kda_out[(nc, H)](s.qt, s.u, s.m, s.hb, g, g.stride(0), norm_w, float(eps), out, rows, off, H,
+- DK_=DK, DV_=DV, BT=CHUNK, BC=BLOCK, KS=32, PREC=prec, num_warps=LAUNCH["out"][0],
+- num_stages=LAUNCH["out"][1], **_EXACT)
++ _ext().chain(p, p.stride(0), int(b_off), a, a.stride(0), g, g.stride(0), conv_state, conv_w, state_in, a_log,
++ dt_bias, norm_w, float(eps), float(lower), rows, int(pos) % CHUNK, out, state_out)
+ return out[:rows]
diff --git a/patches/0043-glm-parallel-deadlocks.patch b/patches/0043-glm-parallel-deadlocks.patch
new file mode 100644
index 0000000..a81cbba
--- /dev/null
+++ b/patches/0043-glm-parallel-deadlocks.patch
@@ -0,0 +1,305 @@
+diff --git tensorfold/cuda/roce.py tensorfold/cuda/roce.py
+index 52bc376..bba421c 100644
+--- tensorfold/cuda/roce.py
++++ tensorfold/cuda/roce.py
+@@ -142,7 +142,11 @@ class RoceGather:
+
+ def fits(self, send: torch.Tensor) -> bool:
+ n = send.numel() * send.element_size()
+- return 0 < n <= self.max_bytes and n % PACK == 0 and send.data_ptr() % PACK == 0 and send.is_contiguous()
++ return self.fits_bytes(n) and send.data_ptr() % PACK == 0 and send.is_contiguous()
++
++ def fits_bytes(self, n: int) -> bool:
++ """Whether a gather of ``n`` bytes a rank goes over RoCE (the same answer on every rank)."""
++ return 0 < n <= self.max_bytes and n % PACK == 0
+
+ def all_gather(self, send: torch.Tensor, recv: torch.Tensor) -> None:
+ nbytes = send.numel() * send.element_size()
+@@ -183,9 +187,20 @@ class RoceComm:
+ self.small = self.large = 0
+
+ def all_gather(self, send: torch.Tensor, recv: torch.Tensor) -> None:
+- if self.roce.fits(send) and recv.is_contiguous() and recv.data_ptr() % PACK == 0:
++ """RoCE for a gather whose size fits, NCCL otherwise: decided by the byte count alone, which every rank's
++ matching call shares. A send or receive buffer that is not 16-byte aligned or contiguous goes through an
++ aligned copy: choosing by the buffers' addresses let two ranks pick different transports for the same gather
++ (one waiting in RoCE, the other in NCCL, forever)."""
++
++ n = send.numel() * send.element_size()
++ if self.roce.fits_bytes(n):
+ self.small += 1
+- self.roce.all_gather(send, recv)
++ 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)
++ self.roce.all_gather(s, r)
++ if r is not recv:
++ recv.copy_(r)
+ else:
+ 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
+--- tensorfold/families/glm5_next/cuda/engine.py
++++ tensorfold/families/glm5_next/cuda/engine.py
+@@ -557,7 +557,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, "
+- "TF_GLM_MULTI_VERIFY, TF_GLM_MULTI_SAMPLER / _DEPTH / _OVERHEAD_MS / _ASYNC / _LONE, "
++ "TF_GLM_MULTI_VERIFY, TF_GLM_MULTI_SAMPLER / _DEPTH / _OVERHEAD_MS / _ASYNC / _LONE / _PROFILE, "
+ "TENSORFOLD_NUCLEUS_UNION, TF_GLM_MAX_ROWS, TF_GLM_WIDE_GRAPHS, TF_GLM_KV): "
+ f"rank 0 {both[0][:-1]}, rank 1 {both[1][:-1]}; pull the draft model on both machines "
+ "(or pass --drafter none to both) and give both the same flags")
+diff --git tensorfold/families/glm5_next/cuda/multi.py tensorfold/families/glm5_next/cuda/multi.py
+index 1c4af9d..9eafb09 100644
+--- tensorfold/families/glm5_next/cuda/multi.py
++++ tensorfold/families/glm5_next/cuda/multi.py
+@@ -46,6 +46,40 @@ from .verify import BatchedVerify, Segment, SerialVerify, Verified
+ ADMIT, EVICT, MOVE, GROW, FILL, ROUND, FINISH, IDLE, SLOT = range(1, 10)
+ OPS = {ADMIT: "ADMIT", EVICT: "EVICT", MOVE: "MOVE", GROW: "GROW", FILL: "FILL", ROUND: "ROUND", FINISH: "FINISH",
+ IDLE: "IDLE", SLOT: "SLOT"}
++
++
++def watchdog_seconds(value: str | None = None) -> float:
++ """TF_GLM_MULTI_WATCHDOG_S: seconds a rank-0 iteration (or a rank-1 message it is owed) may take before every
++ thread's Python stack is dumped to the log (faulthandler; 0: off; default 300)."""
++
++ value = os.environ.get("TF_GLM_MULTI_WATCHDOG_S", "") if value is None else value
++ try:
++ s = 300.0 if value.strip() == "" else float(value)
++ except ValueError:
++ s = -1.0
++ if s < 0:
++ raise ValueError(f"TF_GLM_MULTI_WATCHDOG_S: seconds (0: off), not {value!r}")
++ return s
++
++
++def _watch(seconds: float, what: str) -> None:
++ if seconds > 0:
++ import faulthandler
++ import sys
++
++ try: # the process's stderr (a test may have swapped sys.stderr)
++ faulthandler.dump_traceback_later(seconds, repeat=True, file=sys.__stderr__, exit=False)
++ except (ValueError, OSError, AttributeError): # no file descriptor to write to: no watchdog
++ pass
++
++
++def _unwatch(seconds: float) -> None:
++ if seconds > 0:
++ import faulthandler
++
++ faulthandler.cancel_dump_traceback_later()
++
++
+ LONE_LEFT = 16 # a lone stream moves home only with at least this many tokens still to go
+ DONE, CANCELLED, REQUEUED = 0, 1, 2 # FINISH reasons
+ MAX_WINDOW = 32 # rows of every stream's windows together in one round
+@@ -320,9 +354,12 @@ class MultiDecoder:
+ self.row_ms = list(row_ms) if row_ms is not None else None
+ if self.tune.depth == "joint" and self.row_ms is None:
+ self.row_ms = self._time_rows()
+- if self.profiles is not None and isinstance(self.verify, BatchedVerify) and self.verify.graphs:
++ # both ranks: the comparison replays graphs whose all-gathers the other rank must join (TF_GLM_MULTI_PROFILE
++ # is in the two-rank settings comparison, so both run it or neither)
++ if self.tune.profile and isinstance(self.verify, BatchedVerify) and self.verify.graphs and self.lone_rows:
+ self._compare_paths()
+ self.msg = None # TF_GLM_MULTI_ASYNC: rank 0's pinned message staging
++ self.watchdog = watchdog_seconds() # stack dumps of a stalled iteration (TF_GLM_MULTI_WATCHDOG_S)
+ self.lanes: dict[int, Lane] = {} # by sid, in admission order
+ self.kept: list = [] # kept prompts (decode.Snapshot + kid, extent), oldest first
+ self.next_sid = self.next_kid = self.next_order = 0
+@@ -379,32 +416,37 @@ class MultiDecoder:
+ def _send(self, values: list[int]) -> None:
+ """Rank 0, TF_GLM_MULTI_ASYNC: ``GlmEngine._share``'s two all-gathers (the length, then the values) without
+ reading anything back: the values go through a pinned staging buffer (reused once its last copy has left),
+- so the host does not wait for the GPU. Rank 1 receives them with its ``_share`` as ever."""
++ so the host does not wait for the GPU. Rank 1 receives them with its ``_share`` as ever. Each gather sends a
++ device buffer of its own from its start, as rank 1's ``_share`` does: a transport may choose by the buffer's
++ address (TF_GLM_COMM=roce did), and a view past an allocation's start once split the ranks' choices."""
+
+ n = len(values)
+ dev = self.w.device
+ if self.msg is None or self.msg[0].numel() < n + 1:
+- if self.msg is not None:
+- self.msg[2].synchronize()
++ if self.msg is not None and self.msg[3] is not None:
++ self.msg[3].synchronize()
+ size = max(4096, 2 * (n + 1))
+ pinned = torch.cuda.is_available()
+ self.msg = (torch.zeros((size,), dtype=torch.int32, pin_memory=pinned),
++ torch.zeros((1,), dtype=torch.int32, device=dev),
+ torch.zeros((size,), dtype=torch.int32, device=dev),
+ torch.cuda.Event() if pinned else None)
+- host, buf, ready = self.msg
++ host, length, vals, ready = self.msg
+ if ready is not None:
+- ready.synchronize() # the last message's copy has left the staging buffer
++ ready.synchronize() # the last message's copies have left the staging buffer
+ host[0] = n
+ if n:
+ host[1:1 + n].numpy()[:] = values
+- buf[:1 + n].copy_(host[:1 + n], non_blocking=True)
++ length.copy_(host[:1], non_blocking=True)
++ if n:
++ vals[:n].copy_(host[1:1 + n], non_blocking=True)
+ if ready is not None:
+ ready.record()
+ comm = self.g.comm
+ got = torch.empty((2,), dtype=torch.int32, device=dev)
+- comm.all_gather(buf[:1], got)
++ comm.all_gather(length, got)
+ allv = torch.empty((2 * n,), dtype=torch.int32, device=dev)
+- comm.all_gather(buf[1:1 + n], allv)
++ comm.all_gather(vals[:n], allv)
+
+ def _time_rows(self, reps: int = 5) -> list[float]:
+ """TF_GLM_MULTI_DEPTH=joint: the batched window's ms for 1 .. MAX_WINDOW rows (its graphs, fastest of
+@@ -420,12 +462,13 @@ class MultiDecoder:
+ return [float(x) for x in got.view(2, -1).max(dim=0).values.tolist()]
+
+ def _compare_paths(self, reps: int = 5) -> None:
+- """TF_GLM_MULTI_PROFILE (rank 0, at startup): a lone stream's verify window on the one-stream graphs and on
+- the batched graphs, ms by rows (fastest of ``reps``; slot 0's states cleared after)."""
++ """TF_GLM_MULTI_PROFILE (at startup, on both ranks: the graphs all-gather; rank 0 prints): a lone stream's
++ verify window on the one-stream graphs and on the batched graphs, ms by rows up to the one-stream graphs'
++ widest (fastest of ``reps``; slot 0's states cleared after)."""
+
+ e, v = self.e, self.verify
+ start, stop = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
+- solo = v.time_rows(reps)
++ solo = v.time_rows(reps, most=self.lone_rows)
+ out = []
+ for R in range(1, self.lone_rows + 1):
+ g = e.graphs.main.get((R, e.home.parity))
+@@ -441,8 +484,9 @@ class MultiDecoder:
+ out.append(f"{R}: {best:.2f} vs {solo[R - 1]:.2f}")
+ e.slots.rec[0].zero_()
+ e.slots.conv[0].zero_()
+- print("[tensorfold] multi profile: a lone stream's verify window ms, one-stream graphs vs batched graphs, by "
+- "rows: " + ", ".join(out), flush=True)
++ if self.rank == 0:
++ print("[tensorfold] multi profile: a lone stream's verify window ms, one-stream graphs vs batched graphs, by "
++ "rows: " + ", ".join(out), flush=True)
+
+ def _row_cost(self, rows: int) -> float:
+ ms = self.row_ms
+@@ -798,6 +842,7 @@ class MultiDecoder:
+ """Rank 0: one prompt chunk or one decode round; returns the streams that finished."""
+
+ self._check()
++ _watch(self.watchdog, "iteration") # cancelled at the end of ``finish``
+ try:
+ return self._iterate()
+ except Exception as exc:
+@@ -1099,6 +1144,7 @@ class MultiDecoder:
+ self._emit(IDLE, [])
+ self._flush()
+ self.idle = True
++ _unwatch(self.watchdog)
+
+ def _finish(self, sid: int) -> None:
+ """Both ranks: the stream's slot frees; its extent stays for its kept prompts (shrunk to them) or goes."""
+@@ -1160,7 +1206,9 @@ class MultiDecoder:
+ if self.idle:
+ self.g._await_bell()
+ self.idle = False
++ _watch(self.watchdog, "rank 1 message") # busy: rank 0's next message is due within a round
+ self.apply(self.g._share(None))
++ _unwatch(self.watchdog)
+ if once:
+ return
+
+@@ -1312,22 +1360,35 @@ class GlmScheduler(Scheduler):
+ self.decoder.requeue = []
+
+ def _loop(self) -> None:
++ import sys
++ import traceback
++
+ while True:
+- self._yield()
+- idle = not self.decoder.live() and self.held is None
+- done = self._admit(self.waiting.get() if idle else None) # idle: wait for a request
+ try:
+- done += self.decoder.round()
+- except Exception as exc: # noqa: BLE001 (the live requests fail)
++ self._iteration()
++ except Exception as exc: # noqa: BLE001 (never a silent dead worker: log, fail, go on)
++ print(f"[tensorfold] --parallel scheduler iteration failed: {exc!r}", file=sys.stderr, flush=True)
++ traceback.print_exc()
+ for s in self.decoder.drop():
+ self._reply(s, "error", exc)
+- self._requeue()
+- try:
+- self.decoder.finish(done)
+- except Exception as exc: # noqa: BLE001
+- for s in self.decoder.drop():
+- self._reply(s, "error", exc)
+- for s in done:
+- self._reply(s, *(("error", s.error) if s.error is not None else ("done", self.decoder.stats(s))))
+- if self.held is not None and not self.decoder.live():
+- time.sleep(0) # the held request retries next iteration (now alone)
++
++ def _iteration(self) -> None:
++ self._yield()
++ idle = not self.decoder.live() and self.held is None
++ done = self._admit(self.waiting.get() if idle else None) # idle: wait for a request
++ try:
++ done += self.decoder.round()
++ except Exception as exc: # noqa: BLE001 (the live requests fail)
++ for s in self.decoder.drop():
++ self._reply(s, "error", exc)
++ self._requeue()
++ try:
++ self.decoder.finish(done)
++ except Exception as exc: # noqa: BLE001
++ for s in self.decoder.drop():
++ self._reply(s, "error", exc)
++ for s in done:
++ self._reply(s, *(("error", s.error) if s.error is not None else ("done", self.decoder.stats(s))))
++ if self.held is not None and not self.decoder.live():
++ time.sleep(0) # the held request retries next iteration (now alone)
++ _unwatch(getattr(self.decoder, "watchdog", 0))
+diff --git tensorfold/families/glm5_next/cuda/multi_tune.py tensorfold/families/glm5_next/cuda/multi_tune.py
+index 4020b91..587d644 100644
+--- tensorfold/families/glm5_next/cuda/multi_tune.py
++++ tensorfold/families/glm5_next/cuda/multi_tune.py
+@@ -85,11 +85,12 @@ class MultiSettings:
+ return s
+
+ def code(self) -> list[int]:
+- """What both ranks must agree on (the profile is rank 0's alone)."""
++ """What both ranks must agree on: every setting that changes collectives or drafts, and whether the profile
++ is on (its startup timing replays graphs on both ranks; only rank 0 logs)."""
+
+ return [("streams", "packed").index(self.sampler), ("policy", "joint", "scale").index(self.depth),
+ int(round(self.alpha * 1000)), int(round(self.overhead_ms * 1000)), int(self.async_msg),
+- int(self.lone)]
++ int(self.lone), int(self.profile > 0)]
+
+ def describe(self) -> str:
+ depth = f"scale:{self.alpha:g}" if self.depth == "scale" else self.depth
+diff --git tensorfold/families/glm5_next/cuda/verify.py tensorfold/families/glm5_next/cuda/verify.py
+index 34205f7..9bf8b95 100644
+--- tensorfold/families/glm5_next/cuda/verify.py
++++ tensorfold/families/glm5_next/cuda/verify.py
+@@ -136,7 +136,7 @@ class BatchedVerify:
+
+ # -- the window's tables -------------------------------------------------------------------------------------------
+ @torch.no_grad()
+- def time_rows(self, reps: int = 5) -> list[float]:
++ def time_rows(self, reps: int = 5, most: int | None = None) -> list[float]:
+ """ms of the captured window of each size (1 .. its rows): the fastest of ``reps`` replays, on the capture's
+ own tables (slot 0 at the pool's first rows; its states cleared after), before any stream is admitted."""
+
+@@ -145,7 +145,7 @@ class BatchedVerify:
+ index = self.e.caches.index is not None
+ out = []
+ start, stop = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
+- for R in range(1, self.rows_max + 1):
++ for R in range(1, min(most or self.rows_max, self.rows_max) + 1):
+ g = self.graphs[R]
+ self._stage([0] * R)
+ self.seg_rows.set([(0, 0, R)], sparse_from=SPARSE_FROM if index else None)
diff --git a/patches/0044-glm-parallel-ring-base.patch b/patches/0044-glm-parallel-ring-base.patch
new file mode 100644
index 0000000..b4b2b3b
--- /dev/null
+++ b/patches/0044-glm-parallel-ring-base.patch
@@ -0,0 +1,13 @@
+diff --git tensorfold/families/glm5_next/cuda/verify.py tensorfold/families/glm5_next/cuda/verify.py
+index 9bf8b95..3858103 100644
+--- tensorfold/families/glm5_next/cuda/verify.py
++++ tensorfold/families/glm5_next/cuda/verify.py
+@@ -148,7 +148,7 @@ class BatchedVerify:
+ for R in range(1, min(most or self.rows_max, self.rows_max) + 1):
+ g = self.graphs[R]
+ self._stage([0] * R)
+- self.seg_rows.set([(0, 0, R)], sparse_from=SPARSE_FROM if index else None)
++ self.seg_rows.set([self._span(self.e.home, 0, R)], sparse_from=SPARSE_FROM if index else None)
+ self._write_table([(R, 0, 0, 0, R)])
+ best = float("inf")
+ for _ in range(reps + 1):
diff --git a/patches/0045-glm-prompt-replay.patch b/patches/0045-glm-prompt-replay.patch
new file mode 100644
index 0000000..e0d1004
--- /dev/null
+++ b/patches/0045-glm-prompt-replay.patch
@@ -0,0 +1,258 @@
+diff --git tensorfold/families/glm5_next/cuda/decode.py tensorfold/families/glm5_next/cuda/decode.py
+index 813f4c0..524eda3 100644
+--- tensorfold/families/glm5_next/cuda/decode.py
++++ tensorfold/families/glm5_next/cuda/decode.py
+@@ -127,6 +127,7 @@ class Engine:
+ 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
++ self.head: torch.Tensor | None = None # the last prompt's end logits row (``prefill``'s keep_head)
+ self.constraint = self.window = None # a request's grammar, and the next sample's rows under it
+ self.draft_n = w.head.n
+ self.graphs = None
+@@ -295,6 +296,10 @@ class Snapshot:
+ nbytes: int = 0
+ drafter_rows: list | None = None # a ring drafter's window rows before drafter_end, copied when taken
+ tail: list | None = None # the indexer rings' rows of the pools still filling at ids' end (``_ring_tail``)
++ # the head's logits row at ids' end (this rank's vocabulary slice, before any grammar mask), kept with a prompt's
++ # own end state: a request of exactly these ids resumes here and samples its first token from it, prefilling
++ # nothing (``prefill``); None for states short of a prompt's end (which no head ran for)
++ head: torch.Tensor | None = None
+
+
+ def _ring_tail(st, n: int, m: int) -> list[tuple[torch.Tensor, torch.Tensor]]:
+@@ -423,6 +428,7 @@ 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,
+ 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 [])
++ held += [snap.head] if snap.head is not None else []
+ held += [t for pair in (snap.tail or []) for t in pair]
+ return sum(t.numel() * t.element_size() for t in held) + (snap.nbytes if snap.rows is not None else 0)
+
+@@ -455,16 +461,28 @@ def restore(e: Engine, snap: Snapshot, drafter=None) -> None:
+
+
+ # -- prefill ----------------------------------------------------------------------------------------------------
++def whole(snap: Snapshot | None, prompt: Sequence[int]) -> bool:
++ """Whether ``snap`` is a state of exactly ``prompt`` that kept its head's logits row (a replay resumes there)."""
++
++ return snap is not None and snap.head is not None and len(snap.ids) == len(prompt)
++
++
+ @torch.no_grad()
+ def prefill(e: Engine, prompt: Sequence[int], sampling: Sampling | None, *, mtp: bool = True, drafter=None,
+- 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."""
++ resume: Snapshot | None = None, feed=None, sample: bool = True, keep_head: bool = False) -> 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.
++
++ ``resume`` may also be a state of the whole prompt that kept its head's logits row (``whole``, a replay): the
++ state goes back and the first token is sampled from that row, nothing prefilled. ``keep_head``: the head's
++ logits row of the prompt's end, as sampled from (before a grammar's mask), is left in ``e.head`` for a snapshot."""
+
+ if not prompt:
+ raise ValueError("prefill requires at least one token")
+ w, st, b = e.w, e.st, e.pbuf
+ use_mtp = mtp and w.mtp is not None
+ begin = 0
++ replay = sample and whole(resume, prompt)
++ e.head = None
+ if resume is None:
+ e.reset()
+ if drafter is not None:
+@@ -473,23 +491,33 @@ def prefill(e: Engine, prompt: Sequence[int], sampling: Sampling | None, *, mtp:
+ begin = len(resume.ids)
+ if e.grid and begin % e.grid:
+ raise ValueError(f"a resumed prefill starts on the {e.grid}-row grid, not at {begin}")
+- 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 (begin >= len(prompt) and not replay) or list(prompt[:begin]) != resume.ids:
++ raise ValueError("a resumed prefill needs a snapshot of a strict prefix of the prompt (or of the whole "
++ "prompt with its head's logits row)")
+ if (use_mtp and resume.mtp_len < 0) or (drafter is not None and resume.drafter_end != begin):
+ raise ValueError("this snapshot's draft caches do not fit the request")
+ restore(e, resume, drafter)
+- if use_mtp:
++ if use_mtp and replay:
++ # the prompt's last hidden row waits for the first token, as a fresh prefill leaves it (the MTP cache
++ # holds every row before it: mtp_len n - 1)
++ e.last_hidden = resume.pending[-1:].clone()
++ elif use_mtp:
+ k = resume.pending.shape[0]
+ _absorb_rows(e, resume.pending, list(prompt[begin - k + 1:begin + 1]))
+ last = None
+- prof.active = True
+- for start in range(begin, len(prompt), e.prefill_rows):
+- last = prefill_chunk(e, prompt, start, min(e.prefill_rows, len(prompt) - start), drafter=drafter, feed=feed,
+- mtp=use_mtp, head=sample)
+- prof.active = False
+- prof.report(len(prompt) - begin)
++ if replay:
++ last = resume.head.clone() # a grammar's mask below writes into the rows it samples
++ else:
++ prof.active = True
++ for start in range(begin, len(prompt), e.prefill_rows):
++ last = prefill_chunk(e, prompt, start, min(e.prefill_rows, len(prompt) - start), drafter=drafter,
++ feed=feed, mtp=use_mtp, head=sample)
++ prof.active = False
++ prof.report(len(prompt) - begin)
+ if not sample:
+ return None
++ if keep_head:
++ e.head = last.clone()
+ if e.constraint is not None: # the first token's row, under the reply's grammar
+ 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
+--- tensorfold/families/glm5_next/cuda/engine.py
++++ tensorfold/families/glm5_next/cuda/engine.py
+@@ -834,14 +834,16 @@ class GlmEngine:
+ return auto, auto or not dflash, dflash
+
+ def _resume(self, prompt: list[int], code: list[int]):
+- """The longest snapshot of a strict prefix of ``prompt`` whose draft caches fit the request's drafters."""
++ """The longest snapshot of a strict prefix of ``prompt`` whose draft caches fit the request's drafters, or of
++ the whole prompt when it kept its head's logits row (a replay of an earlier prompt, ``decode.whole``)."""
+
+ _, mtp, dflash = self._drafters(code)
+ 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)
+ fits = fits and not (self.grid and len(snap.ids) % self.grid) # prompt chunks start on the grid
+- if fits and len(snap.ids) < len(prompt) and prompt[:len(snap.ids)] == snap.ids and (
++ short = len(snap.ids) < len(prompt) or (len(snap.ids) == len(prompt) and snap.head is not None)
++ if fits and short and prompt[:len(snap.ids)] == snap.ids and (
+ best is None or len(snap.ids) > len(best.ids)):
+ best = snap
+ return best
+@@ -938,7 +940,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]:
+- from .decode import DepthPolicy, dflash_decode, mtp_decode, prefill, serial_decode, take_snapshot
++ from .decode import DepthPolicy, dflash_decode, mtp_decode, prefill, serial_decode, take_snapshot, whole
+ from .drafter_choice import DrafterChoice, auto_decode
+
+ auto, use_mtp, use_dflash = self._drafters(code)
+@@ -973,11 +975,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)
+- first = prefill(self.e, prompt, sampling, mtp=use_mtp, drafter=drafter, resume=resume, feed=feed)
++ # a replay of a kept prompt (``decode.whole``: its state and head's logits row) prefills nothing and keeps
++ # nothing new; a prompt's own end state keeps the head's row it sampled from, for a later replay
++ replay = whole(hit, prompt)
++ end = point == len(prompt) and not replay
++ first = prefill(self.e, prompt, sampling, mtp=use_mtp, drafter=drafter, resume=resume, feed=feed,
++ keep_head=end)
+ prefill_s = time.perf_counter() - t0
+- if point == len(prompt):
+- kept.append(take_snapshot(self.e, prompt, self.e.last_hidden if use_mtp else None, mtp=use_mtp,
+- drafter=drafter))
++ if end:
++ snap = take_snapshot(self.e, prompt, self.e.last_hidden if use_mtp else None, mtp=use_mtp,
++ drafter=drafter)
++ snap.head, self.e.head = self.e.head, None
++ kept.append(snap)
+ if self.shared and draft and feed is None and hit is not None: # what it resumed from is used again
+ self.cache = [c for c in self.cache if c is not hit] + [hit]
+ for snap in kept:
+diff --git tensorfold/families/glm5_next/cuda/multi.py tensorfold/families/glm5_next/cuda/multi.py
+index 9eafb09..8741f33 100644
+--- tensorfold/families/glm5_next/cuda/multi.py
++++ tensorfold/families/glm5_next/cuda/multi.py
+@@ -287,6 +287,7 @@ class Lane:
+ stops: list[int] = field(default_factory=list) # prompt positions whose states are kept (before the end)
+ point: int | None = None # where the prompt's own state is kept (engine.grid_point), or None
+ shared: list[int] = field(default_factory=list)
++ head: Any = None # a replay's first-token logits row (its kept prompt's, ``decode.whole``)
+ decoding: bool = False
+ paused: bool = False
+ t0: float = 0.0
+@@ -665,6 +666,11 @@ class MultiDecoder:
+ if hit.drafter_end != cut or hit.drafter_rows is None:
+ raise RuntimeError("a kept prompt without DFlash2's window was chosen for a DFlash2 stream")
+ put_draft_window(self._ctx(lane), cut, hit.drafter_rows)
++ if cut == len(prompt): # a replay: its one FILL samples the kept head's row, prefilling nothing
++ if hit.head is None:
++ raise RuntimeError(f"the kept prompt {a['kid']} is the whole prompt of stream {a['sid']} but "
++ f"kept no head row")
++ lane.head = hit.head.clone()
+ self._touch(hit)
+ # where its prompt states are kept: the grid point (or the end) and rank 0's shared-prefix points
+ if a["draft"] and feed is None:
+@@ -688,20 +694,24 @@ class MultiDecoder:
+ raise RuntimeError(f"rank {self.rank} holds no kept prompt {kid}")
+
+ def _resume(self, prompt: list[int]):
++ """The longest kept strict prefix of ``prompt``, or the whole prompt when it kept its head's logits row (a
++ replay of an earlier prompt), whose DFlash2 window came along."""
+ best = None
+ for c in self.kept:
+ n = len(c.ids)
+ fits = c.drafter_end == n and c.drafter_rows is not None or self.drafts is None
+ fits = fits and not (self.grid and n % self.grid)
+- if fits and n < len(prompt) and prompt[:n] == c.ids and (best is None or n > len(best.ids)):
++ short = n < len(prompt) or (n == len(prompt) and c.head is not None)
++ if fits and short and prompt[:n] == c.ids and (best is None or n > len(best.ids)):
+ best = c
+ return best
+
+ def _touch(self, c) -> None:
+ self.kept = [k for k in self.kept if k is not c] + [c]
+
+- def _keep(self, lane: Lane, n: int) -> None:
+- """Both ranks: the lane's state at prompt position n (== its pos) becomes a kept prompt in its extent."""
++ def _keep(self, lane: Lane, n: int, head=None) -> None:
++ """Both ranks: the lane's state at prompt position n (== its pos) becomes a kept prompt in its extent;
++ ``head``: at the prompt's end, the logits row its first token is sampled from (kept for a replay)."""
+
+ from .decode import take_snapshot
+
+@@ -714,6 +724,7 @@ class MultiDecoder:
+ if lane.dflash:
+ snap.drafter_end = n
+ snap.drafter_rows = draft_window(self._ctx(lane), n)
++ snap.head = head
+ snap.kid = self.next_kid
+ self.next_kid += 1
+ snap.extent = lane.extent
+@@ -731,7 +742,7 @@ class MultiDecoder:
+ x = c.extent
+ x.kept = [k for k in x.kept if k is not c]
+ c.rec = c.conv = None
+- c.tail = None
++ c.tail = c.head = None
+ c.drafter_rows = None
+ self._settle(x)
+
+@@ -970,19 +981,23 @@ class MultiDecoder:
+ prompt = s.prompt
+ n = len(prompt)
+ start = lane.st.pos
+- if not start < stop <= n or stop - start > e.prefill_rows:
++ replay = lane.head is not None # resumed at the prompt's end: no rows, the kept head's row
++ if not (start < stop <= n or replay and start == stop == n) or stop - start > e.prefill_rows:
+ raise RuntimeError(f"stream {lane.sid}: a prompt chunk {start} .. {stop} of {n}")
+ t = time.perf_counter()
+ prev = e.use(lane.st)
+ try:
+- out = prefill_chunk(e, prompt, start, stop - start, drafter=self._ctx(lane) if lane.dflash else None,
+- feed=lane.feed, mtp=False, head=stop == n)
++ if replay:
++ out, lane.head = lane.head, None
++ else:
++ out = prefill_chunk(e, prompt, start, stop - start, drafter=self._ctx(lane) if lane.dflash else None,
++ feed=lane.feed, mtp=False, head=stop == n)
+ if stop < n:
+ if stop in lane.stops:
+ self._keep(lane, stop)
+ return None
+- if lane.point == n:
+- self._keep(lane, n)
++ if lane.point == n and not replay:
++ self._keep(lane, n, head=out[:1].clone()) # before a grammar's mask writes into the row
+ logits = out[:1]
+ if lane.constraint is not None: # the first token's row, under the reply's grammar
+ lane.constraint.mask(logits, lane.constraint.window([0], [-1]), self.w.vocab_offset)
diff --git a/patches/0046-glm-visible-pools.patch b/patches/0046-glm-visible-pools.patch
new file mode 100644
index 0000000..10700a7
--- /dev/null
+++ b/patches/0046-glm-visible-pools.patch
@@ -0,0 +1,212 @@
+diff --git tensorfold/families/glm5_next/cuda/sparse.py tensorfold/families/glm5_next/cuda/sparse.py
+index bc5362a..36d697a 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
+ @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,
+- RS: tl.constexpr, FP8: tl.constexpr):
++ RS: tl.constexpr, FP8: tl.constexpr, K: tl.constexpr):
+ """Decode rows, program (row, g): the row's index queries and head weights loaded once, then pool blocks g,
+ g + G, .. each through _scores' arithmetic for that row (the same key mask, dot tile, warps and head sum, so
+- RB = 1's bits). SEG False: NP columns a row from one position (POS[0] + r; pools past the row's -inf); SEG: a
+- segmented window's row r (skipped when dense) over its own visible pools, keys at its stream's base / 4. FP8
+- (TF_GLM_KV=fp8): pooled keys as kv8 rows RS bytes apart, each pool's scale on its dots, as in _scores."""
++ RB = 1's bits). SEG False: rows from one position (POS[0] + r), the blocks holding a row's first
++ _visible_bound columns (pools past the row's -inf; later columns of the NP-column bucket are not written: the
++ selection reads the same bound); SEG: a segmented window's row r (skipped when dense) over its own visible
++ pools, keys at its stream's base / 4. FP8 (TF_GLM_KV=fp8): pooled keys as kv8 rows RS bytes apart, each pool's
++ scale on its dots, as in _scores."""
+
+ 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,
+ else:
+ npool = (tl.load(POS) + r + 1) // 4
+ pbase = tl.zeros((), tl.int64)
+- nb = (NP + BP - 1) // BP
++ nb = (_visible_bound(NP, tl.load(POS), r, K) + BP - 1) // BP
+ if g >= nb:
+ return
+ d = tl.arange(0, D)
+@@ -191,11 +193,16 @@ def _order_key(s):
+
+
+ @triton.jit
+-def _select_rows(S, OUT, NP, K: tl.constexpr, BLOCK: 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.
++ Rows NPS scores apart; VIS: the row's first visible_bound() columns only (row r at position POS[0] + r)."""
+
+ r = tl.program_id(0).to(tl.int64)
+- row = S + r * NP
++ row = S + r * NPS
++ if VIS:
++ NP = _visible_bound(NPS, tl.load(POS), r, K)
++ else:
++ NP = NPS
+ 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):
+ equal_seen += tl.sum(eq, 0)
+
+
+-def top_pools(scores: torch.Tensor, k: int) -> 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.
++ The scores past its complete pools are -inf with the highest indices, so they rank below every column kept
++ (ties to the lower pool): the K best of the first bound columns are the K best of all NPS. A row with fewer
++ than K complete pools takes columns 0 .. K - 1 either way (its pools, then the lowest -inf ones)."""
++ return tl.minimum(NPS, tl.maximum((P + r + 1) // 4, K))
++
++
++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`` (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."""
+ R, NP = scores.shape
+ if NP < k or not scores.is_contiguous():
++ if pos is not None:
++ raise ValueError("top_pools: visible bounds need contiguous rows of at least k scores")
+ return _top_pools(scores, k)
+ if R < SPLIT_ROWS and NP >= SPLIT_FROM: # decode rows at long context: each row across chunk programs
+- return select_split(scores, k)
++ return select_split(scores, k, pos=pos)
+ # 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, 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
+ 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
+- 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
++ # selection writes the tokens and counts itself (split), or _tokens from its pools: select_tokens' formulas
++ # (each row's pools' tokens ascending, then its incomplete pool's visible tokens; rows within the dense limit
++ # count 0)
+ width = TOPK_POOLS * POOL + POOL - 1
+- # all rows at once: the 512 pools' tokens ascending, then the incomplete last pool's visible tokens; rows within the dense limit count 0
+- q = pos_dev.to(torch.int64) + torch.arange(R, device=dev)
+- npool = (q + 1) // POOL
+- tokens = torch.empty((R, width), dtype=torch.int32, device=dev)
+- tokens[:, :TOPK_POOLS * POOL] = (pools[:, :, None] * POOL + torch.arange(POOL, device=dev)).reshape(R, -1)
+- tail = npool[:, None] * POOL + torch.arange(POOL - 1, device=dev)
+- tail_ok = tail <= q[:, None]
+- tokens[:, TOPK_POOLS * POOL:] = torch.where(tail_ok, tail, -1)
+- counts = torch.where(npool > TOPK_POOLS, TOPK_POOLS * POOL + tail_ok.sum(1), 0).to(torch.int32)
++ tokens = torch.empty((R, width), dtype=torch.int32, device=qi.device)
++ counts = torch.empty((R,), dtype=torch.int32, device=qi.device)
++ if R < SPLIT_ROWS and np_max >= SPLIT_FROM:
++ select_split(scores, TOPK_POOLS, pos=pos_dev, tokens=tokens, counts=counts)
++ else:
++ pools = top_pools(scores, TOPK_POOLS, pos=pos_dev) # ascending pool index
++ _tokens[(R,)](pools, pos_dev, tokens, counts, W=width, K=TOPK_POOLS, PL=POOL, BLOCK=1024, num_warps=4)
+ return tokens, counts
+
+
+@@ -720,10 +741,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,
+- PL: tl.constexpr, CHS: tl.constexpr, CP: tl.constexpr, STEP: tl.constexpr, SEG: tl.constexpr):
++ PL: tl.constexpr, CHS: tl.constexpr, CP: tl.constexpr, STEP: tl.constexpr, SEG: tl.constexpr,
++ VIS: tl.constexpr, TOKS: tl.constexpr):
+ """Program (row, chunk), STEP 0..3: pass STEP over the chunk; STEP 4: its selected pools, as pool ids OUT[r, :K]
+- (SEG False: NPC scores a row) or (SEG: the row's visible pools, dense rows skipped) as _seg_select's tokens,
+- tail and count. TOT [R, 4, 256] zeroed before step 0; HIST [R, CP, 256], GT [R, CP] int32."""
++ (SEG False: NPC scores a row, or with VIS the first _visible_bound of them for row r at POS[0] + r; chunks past
++ it exit; TOKS, with VIS: as select_tokens' tokens, tail and count instead, every row) or (SEG: the row's
++ visible pools, dense rows skipped) as _seg_select's tokens, tail and count. TOT [R, 4, 256] zeroed before step 0;
++ HIST [R, CP, 256], GT [R, CP] int32."""
+
+ 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
+ return
+ qpos = tl.load(POS + r).to(tl.int64)
+ NP = (qpos + 1) // PL
++ npool = NP
+ else:
+- qpos = 0
+- NP = NPC
++ if VIS:
++ qpos = tl.load(POS).to(tl.int64) + r
++ NP = _visible_bound(NPC, tl.load(POS), r, K)
++ else:
++ qpos = r * 0
++ NP = NPC
++ npool = (qpos + 1) // PL
+ 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
+ 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)
+- if SEG:
++ if SEG or TOKS:
+ j = tl.arange(0, PL)
+ tl.store(TOK + r * W + slot[:, None] * PL + j[None, :],
+ (i.to(tl.int64)[:, None] * PL + j[None, :]).to(tl.int32), mask=take[:, None])
+ if c == 0:
+ jt = tl.arange(0, 4)
+ jok = jt < PL - 1
+- tail = NP * PL + jt
++ tail = npool * PL + jt
+ tok = jok & (tail <= qpos)
+ tl.store(TOK + r * W + K * PL + jt, tl.where(tok, tail, -1).to(tl.int32), mask=jok)
+ n = K * PL + tl.sum(tok.to(tl.int64), 0)
+- tl.store(CNT + r, tl.where(NP > K, n, 0).to(tl.int32))
++ tl.store(CNT + r, tl.where(npool > K, n, 0).to(tl.int32))
+ 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:
+
+
+ def select_split(scores: torch.Tensor, k: int, *, scratch: torch.Tensor | None = None, rows=None,
+- tokens: torch.Tensor | None = None, counts: torch.Tensor | None = None) -> torch.Tensor | None:
+- """The split selection: top_pools' pools [R, k] (``rows`` None), or with ``rows`` (segments.SegRows) and
++ tokens: torch.Tensor | None = None, counts: torch.Tensor | None = None,
++ pos: torch.Tensor | None = None) -> torch.Tensor | None:
++ """The split selection: top_pools' pools [R, k] (``rows`` None; ``pos`` as in top_pools; with ``pos``, tokens
++ and counts: select_tokens' tokens and counts written into them instead, None returned), or with ``rows`` (segments.SegRows) and
+ 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 =
+ gt = scratch[R * (1024 + cp * 256):R * (1024 + cp * 257)]
+ tot.zero_()
+ seg = rows is not None
+- out = None if seg else torch.empty((R, k), dtype=torch.int64, device=scores.device)
++ toks = not seg and tokens is not None
++ if toks and pos is None:
++ raise ValueError("select_split: tokens of rows without positions")
++ out = None if seg or toks else torch.empty((R, k), dtype=torch.int64, device=scores.device)
+ dummy = scratch
+ for step in range(5):
+- _select_split[(R, cp)](scores, scores.stride(0), NP, rows.pos if seg else dummy, rows.sparse if seg else dummy,
+- tot, hist, gt, out if out is not None else dummy, tokens if seg else dummy,
+- counts if seg else dummy, W=TOKENS, K=k, PL=POOL, CHS=chs, CP=cp, STEP=step, SEG=seg,
+- num_warps=warps)
++ _select_split[(R, cp)](scores, scores.stride(0), NP, rows.pos if seg else (dummy if pos is None else pos),
++ rows.sparse if seg else dummy, tot, hist, gt, out if out is not None else dummy,
++ tokens if tokens is not None else dummy, counts if counts is not None else dummy,
++ W=TOKENS, K=k, PL=POOL, CHS=chs, CP=cp, STEP=step, SEG=seg,
++ VIS=pos is not None and not seg, TOKS=toks, num_warps=warps)
+ return out
diff --git a/patches/0047-cuda-context-errors.patch b/patches/0047-cuda-context-errors.patch
new file mode 100644
index 0000000..74f42bb
--- /dev/null
+++ b/patches/0047-cuda-context-errors.patch
@@ -0,0 +1,201 @@
+diff --git tensorfold/cuda/http.py tensorfold/cuda/http.py
+index da26749..9bf5ddd 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):
+ _log_error(exc)
+ return self._json(400, {"error": {"message": _error_message(exc)}})
+ return self._json(200, reply)
++ field = "messages" if chat else "prompt" # the field an error's code names (OpenAI's param)
+ try:
+ 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, 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):
+ 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, 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):
+ 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, 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
++++ tensorfold/families/glm5_next/cuda/app.py
+@@ -6,6 +6,7 @@ from pathlib import Path
+ from typing import Any, Callable
+
+ from tensorfold.cuda.server import App, PreparedRequest, RequestError
++from tensorfold.server.errors import CONTEXT_LIMIT
+ from tensorfold.families.glm5_next.cuda.kept_reasoning import KeptReasoning
+ from tensorfold.families.glm5_next.prompts import agent_history, thinking_off
+
+@@ -75,8 +76,10 @@ class GlmApp(App):
+ if need <= limit:
+ return super().check(body, prepared=prepared)
+ detail = f"{prompt} prompt tokens plus max_tokens {int(asked)}" if asked else f"a {prompt}-token prompt"
+- return (f"this request needs a {need}-token context ({detail}), and this server was started for {limit}: "
+- f"shorten the prompt or reply{self._restart(need, ' both ranks')}")
++ # v0.6.0 (68c6e35, Apache-2.0): OpenAI's wording, so prepare refuses it as context_length_exceeded
++ return (f"{CONTEXT_LIMIT} {limit} tokens: this request needs a {need}-token context ({detail}), which exceeds "
++ f"the context window this server was started for; shorten the prompt or reply"
++ f"{self._restart(need, ' both ranks')}")
+
+ 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
+--- 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)
++
++
++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["param"] = param
++ body["code"] = exc.code
++ return body
+diff --git tensorfold/server/prompts.py tensorfold/server/prompts.py
+index 52e8009..3b3a23b 100644
+--- tensorfold/server/prompts.py
++++ tensorfold/server/prompts.py
+@@ -5,7 +5,7 @@ from dataclasses import dataclass
+ import threading
+ from typing import Any
+
+-from tensorfold.server.errors import CapacityError, RequestError
++from tensorfold.server.errors import CapacityError, RequestError, refusal
+ from tensorfold.server.messages import _normalize_tool_call_arguments, normalize_messages
+
+
+@@ -67,7 +67,7 @@ def prepare_images(frontend, messages, render, *, context_limit=None):
+ else:
+ prepared = frontend.prepare(render(template), images, max_prompt_tokens=context_limit)
+ except (ImageInputError, ValueError, ImportError) as exc:
+- raise RequestError(str(exc)) from exc
++ raise refusal(str(exc)) from exc # a prompt past the window: context_length_exceeded
+ finally:
+ slot.release()
+ return RenderedPrompt(list(prepared.token_ids), vision=prepared)
+diff --git tensorfold/vision/glm.py tensorfold/vision/glm.py
+index b6f7dde..0cda666 100644
+--- tensorfold/vision/glm.py
++++ tensorfold/vision/glm.py
+@@ -22,6 +22,8 @@ from typing import Any
+
+ import numpy as np
+
++from tensorfold.server.errors import CONTEXT_LIMIT
++
+ from .images_http import ImageInputError
+
+ IMAGE, VIDEO = "<|image|>", "<|video|>"
+@@ -463,8 +465,10 @@ class GlmVision:
+ rest = rest[v + len(VIDEO_SPAN):]
+ ids = self.tok.encode("".join(pieces), add_special_tokens=False).ids
+ if max_prompt_tokens and len(ids) >= max_prompt_tokens:
+- raise ValueError(f"the prompt with its images is {len(ids):,} tokens; this server's window is "
+- f"{max_prompt_tokens:,}: send fewer or smaller images, or a shorter video")
++ # v0.6.0's context refusal wording (68c6e35, Apache-2.0): served as context_length_exceeded
++ raise ValueError(f"{CONTEXT_LIMIT} {max_prompt_tokens} tokens: the prompt with its images is {len(ids):,} "
++ f"tokens, which exceeds the context window; send fewer or smaller images, or a shorter "
++ f"video")
+ positions = [p for p, t in enumerate(ids) if t == self.image_token]
+ rows = sum(self._rows(kind, x) for kind, x in items)
+ if len(positions) != rows:
diff --git a/patches/0048-cuda-metrics.patch b/patches/0048-cuda-metrics.patch
new file mode 100644
index 0000000..a93ca55
--- /dev/null
+++ b/patches/0048-cuda-metrics.patch
@@ -0,0 +1,487 @@
+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/0049-glm-l2-prefetch.patch b/patches/0049-glm-l2-prefetch.patch
new file mode 100644
index 0000000..2012eac
--- /dev/null
+++ b/patches/0049-glm-l2-prefetch.patch
@@ -0,0 +1,628 @@
+diff --git tensorfold/families/glm5_next/cuda/decode.py tensorfold/families/glm5_next/cuda/decode.py
+index 524eda3..4c85db5 100644
+--- tensorfold/families/glm5_next/cuda/decode.py
++++ tensorfold/families/glm5_next/cuda/decode.py
+@@ -100,6 +100,13 @@ class Engine:
+ self.w = w
+ self.grid = grid
+ w.meta["long_context"] = long_context
++ from . import l2pf
++
++ pf = l2pf.Settings.from_env() # TF_GLM_L2PF: installed before any graph capture
++ if pf.on and torch.cuda.is_available() and w.meta.get("l2pf") is None:
++ w.meta["l2pf"] = l2pf.Prefetch(w, pf)
++ if w.rank == 0:
++ print(f"[tensorfold] {w.meta['l2pf'].summary()}", flush=True)
+ self.rows, self.prefill_rows = max_rows, prefill_rows
+ 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
+--- 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
+ from tensorfold.cuda.kernels import prefill_attention, qmm as shared
+
+-from . import glue, kda as kda_mod, kv8, latent, prof, qmm, sparse
++from . import glue, kda as kda_mod, kv8, l2pf, latent, prof, qmm, sparse
+ 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
+ return qmm.matmul(x, q, xs, out=out, f32=f32, part=b.sk)
+
+
+-def partials(w: Weights, b: Buffers, R: int, fill, label: str | None = None) -> torch.Tensor | None:
++def partials(w: Weights, b: Buffers, R: int, fill, label: str | None = None, site: tuple | None = None
++ ) -> torch.Tensor | None:
+ """``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) ->
+ sp.partial(fill)
+ return None
+ fill(0, R)
++ if site is not None and l2pf.ACTIVE is not None: # TF_GLM_L2PF: the next reads into L2 during the gather
++ l2pf.ACTIVE.site(*site)
+ if label is None:
+ return gather(w, b, R)
+ with prof.timed(label):
+ return gather(w, b, R)
+
+
+-def out_proj(w: Weights, b: Buffers, x: torch.Tensor, q: qmm.Q4, xs: torch.Tensor, R: int) -> torch.Tensor | None:
++def out_proj(w: Weights, b: Buffers, x: torch.Tensor, q: qmm.Q4, xs: torch.Tensor, R: int,
++ site: tuple | None = None) -> torch.Tensor | None:
+ def fill(lo: int, hi: int) -> None: # rows are independent: any row range gives the same bits
+ mm(b, x[lo:hi], q, None if xs is None else xs[lo:hi], b.part[lo:hi], f32=True)
+
+- return partials(w, b, R, fill)
++ return partials(w, b, R, fill, site=site)
+
+
+ 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
+ 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])
++ l2pf.site(layer.index, "o")
+ 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
+ st.cur[li] = 1 - cur
+ _shift_conv(st.conv[li:li + 1], b.kproj[:, :R], R)
+ with prof.timed("kda: out + all-gather"):
+- return out_proj(w, b, out, k.o, None if pre else qmm.group_sums(out, b.kxs[:R]), R)
++ return out_proj(w, b, out, k.o, None if pre else qmm.group_sums(out, b.kxs[:R]), R, site=(layer.index, "a"))
+
+
+ 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
+ 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])
++ l2pf.site(layer.index, "o")
+ with prof.timed("kda: recurrence"):
+ out = kda_mod.chain_segments(seg, p, k.b_off, b.ka[:R], b.kg[:R], slots.conv[:, li], k.conv,
+ slots.rec[:, :, li], k.a_log, k.dt_bias, k.norm, c.eps, c.lower, R,
+ scratch.views[li])
+ with prof.timed("kda: out + all-gather"):
+- return out_proj(w, b, out, k.o, qmm.group_sums(out, b.kxs[:R]), R)
++ return out_proj(w, b, out, k.o, qmm.group_sums(out, b.kxs[:R]), R, site=(layer.index, "a"))
+
+
+ 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
+ dsa_front(layer, w, b, lo, hi)
+ HL = a.heads
+ if a.absorb is not None:
+- return _dsa_latent(a, w, kc, pos_dev, b, R, nch, index, host_pos, sparse_np)
++ return _dsa_latent(a, w, kc, pos_dev, b, R, nch, index, host_pos, sparse_np, layer=layer.index)
+ 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
+
+
+ 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:
++ 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."""
+
+ c = w.cfg
+@@ -613,6 +619,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)
++ l2pf.site(layer, "o")
+ 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
+ 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)
+- return out_proj(w, b, o, a.o, qmm.group_sums(o, b.xs_ao[:R]), R)
++ return out_proj(w, b, o, a.o, qmm.group_sums(o, b.xs_ao[:R]), R, site=(layer, "a"))
+
+
+ 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
+ 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])
++ l2pf.site(layer.index, "o")
+ with prof.timed("dsa: attention"):
+ ol = latent.seg_attention(qa, lc, rows, tokens, counts, s, scale=c.qk_dim ** -0.5, out=s.ol[:R])
+ with prof.timed("dsa: expand"):
+ o = latent.expand_v(ol, a.absorb, b.vn[:R]).view(R, HL * c.v_dim)
+- return out_proj(w, b, o, a.o, qmm.group_sums(o, b.xs_ao[:R]), R)
++ return out_proj(w, b, o, a.o, qmm.group_sums(o, b.xs_ao[:R]), R, site=(layer.index, "a"))
+
+
+ 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
+ m = layer.mlp
+ for lo, hi in undone(R, done):
+ mlp_front(layer, w, b, lo, hi)
+- return out_proj(w, b, b.act[:R], m.down, b.xs_act[:R], R)
++ return out_proj(w, b, b.act[:R], m.down, b.xs_act[:R], R, site=(layer.index, "f"))
+
+
+ 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
+ # EXL3: the routed slots through the trellis kernels, the shared expert (last slot) through BF16 matmuls
+ from . import exl3_mm
+
++ if l2pf.ACTIVE is not None and done is None:
++ # TF_GLM_L2PF: the shared expert before the routed experts (disjoint buffers, the same kernels: the same
++ # bits), while the L2 still holds what site "a" prefetched for it
++ shared_front(layer, w, b, 0, R)
++ done = (0, R)
+ 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
+ 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])
+
+- return partials(w, b, R, fill, "moe: all-gather")
++ return partials(w, b, R, fill, "moe: all-gather", site=(layer.index, "f"))
+ 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
+ with prof.timed("moe: combine"):
+ glue.combine(b.ey[lo:hi], b.wts[lo:hi], b.part[lo:hi])
+
+- return partials(w, b, R, fill, "moe: all-gather")
++ return partials(w, b, R, fill, "moe: all-gather", site=(layer.index, "f"))
+
+
+ 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
+ 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)."""
+
++ c = w.cfg
++ pf = w.meta.get("l2pf")
++ if pf is not None and not b.prefill and R <= pf.s.rows and l2pf.ACTIVE is None:
++ l2pf.ACTIVE = pf # TF_GLM_L2PF: this decode window's sites prefetch (joined below)
++ try:
++ return _compute(w, st, b, R, logits=logits, nch=nch, host_pos=host_pos, sparse_np=sparse_np,
++ inject=inject, head=head, mixer=mixer)
++ finally:
++ pf.join()
++ l2pf.ACTIVE = None
++ return _compute(w, st, b, R, logits=logits, nch=nch, host_pos=host_pos, sparse_np=sparse_np, inject=inject,
++ head=head, mixer=mixer)
++
++
++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, head: bool = True, mixer=None):
+ c = w.cfg
+ glue.embed(b.ids[:R], w.embed, c.hidden, c.streams, b.x[:R])
+ if inject is not None:
+diff --git tensorfold/families/glm5_next/cuda/l2pf.cpp tensorfold/families/glm5_next/cuda/l2pf.cpp
+new file mode 100644
+index 0000000..3e9b3b5
+--- /dev/null
++++ tensorfold/families/glm5_next/cuda/l2pf.cpp
+@@ -0,0 +1,20 @@
++#include <torch/extension.h>
++#include <c10/cuda/CUDAGuard.h>
++
++void l2pf_cuda(const at::Tensor&, int64_t, int64_t, int64_t, int64_t, int64_t, const at::Tensor&);
++
++// Prefetch TABLE[first : first + count] ((address, bytes) int64 pieces) into L2; see l2pf.cu.
++void prefetch(const at::Tensor& table, int64_t first, int64_t count, int64_t mode, int64_t blocks, int64_t threads,
++ const at::Tensor& sink) {
++ TORCH_CHECK(table.is_cuda() && table.scalar_type() == at::kLong && table.is_contiguous() && table.dim() == 2 &&
++ table.size(1) == 2, "l2pf: table [n, 2] int64 on the GPU");
++ TORCH_CHECK(first >= 0 && count >= 0 && first + count <= table.size(0), "l2pf: pieces out of the table");
++ TORCH_CHECK(mode >= 0 && mode <= 2 && blocks >= 1 && threads >= 32 && threads % 32 == 0, "l2pf: launch");
++ TORCH_CHECK(sink.is_cuda() && sink.scalar_type() == at::kInt, "l2pf: sink int32 on the GPU");
++ c10::cuda::CUDAGuard guard(table.device());
++ l2pf_cuda(table, first, count, mode, blocks, threads, sink);
++}
++
++PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
++ m.def("prefetch", &prefetch);
++}
+diff --git tensorfold/families/glm5_next/cuda/l2pf.cu tensorfold/families/glm5_next/cuda/l2pf.cu
+new file mode 100644
+index 0000000..61909d0
+--- /dev/null
++++ tensorfold/families/glm5_next/cuda/l2pf.cu
+@@ -0,0 +1,64 @@
++// L2 prefetch of weight ranges for GLM-5.3-Flash's decode windows (l2pf.py): a small kernel on a side stream asks
++// the memory system to bring the next kernels' weights into L2 while the main stream waits on an all-gather or runs
++// latency-bound glue. It only loads or prefetches (no store, atomic or reduction), so no result can change.
++//
++// TABLE [n, 2] int64: (address, bytes) pieces, each 16-byte aligned and at most a few hundred KiB (the host splits).
++// MODE 0 ("bulk"): one cp.async.bulk.prefetch.L2 a piece (the TMA unit walks it; sm_90+).
++// MODE 1 ("lines"): prefetch.global.L2::evict_last on every 128-byte line of a piece, a warp's lanes on adjacent lines.
++// MODE 2 ("touch"): ld.global.cg of every line's first 16 bytes (a real load: the kernel lasts as long as the reads).
++//
++// Adapted from jayleaton/glm53-tensorfold-spark patches/0460 (l2pf.cu; Apache-2.0, Copyright 2026 Jay Leaton).
++// Changes: one kernel for the three modes over a table of pre-split pieces (the host cuts ranges into pieces, so no
++// per-thread chunk loop), lines mode a warp a piece with prefetch.global.L2::evict_last, touch mode as loads here.
++
++#include <ATen/ATen.h>
++#include <ATen/cuda/CUDAContext.h>
++#include <cstdint>
++
++namespace {
++
++__global__ void l2pf_kernel(const long long* __restrict__ table, int n, int mode, unsigned* __restrict__ sink) {
++ const int lane = threadIdx.x & 31;
++ const int warp = (blockIdx.x * blockDim.x + threadIdx.x) >> 5;
++ const int warps = (gridDim.x * blockDim.x) >> 5;
++ if (mode == 0) {
++ for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < n; i += gridDim.x * blockDim.x) {
++ const unsigned long long a = (unsigned long long)table[2 * i];
++ const unsigned bytes = (unsigned)table[2 * i + 1];
++#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 900
++ asm volatile("cp.async.bulk.prefetch.L2.global [%0], %1;" :: "l"(a), "r"(bytes) : "memory");
++#else
++ for (unsigned o = 0; o < bytes; o += 128)
++ asm volatile("prefetch.global.L2 [%0];" :: "l"(a + o));
++#endif
++ }
++ return;
++ }
++ unsigned acc = 0;
++ for (int i = warp; i < n; i += warps) { // a warp a piece, its lanes on adjacent lines
++ const unsigned long long a = (unsigned long long)table[2 * i];
++ const unsigned bytes = (unsigned)table[2 * i + 1];
++ for (unsigned o = lane * 128u; o < bytes; o += 32u * 128u) {
++ if (mode == 1) {
++ asm volatile("prefetch.global.L2::evict_last [%0];" :: "l"(a + o));
++ } else {
++ unsigned x, y, z, w;
++ asm volatile("ld.global.cg.v4.u32 {%0, %1, %2, %3}, [%4];"
++ : "=r"(x), "=r"(y), "=r"(z), "=r"(w) : "l"(a + o));
++ acc ^= x ^ y ^ z ^ w;
++ }
++ }
++ }
++ if (mode == 2 && acc == 0x9e3779b9u && sink != nullptr) sink[0] = acc; // keeps the loads; never true in practice
++}
++
++} // namespace
++
++void l2pf_cuda(const at::Tensor& table, int64_t first, int64_t count, int64_t mode, int64_t blocks, int64_t threads,
++ const at::Tensor& sink) {
++ if (count <= 0) return;
++ const long long* t = reinterpret_cast<const long long*>(table.data_ptr<int64_t>()) + 2 * first;
++ l2pf_kernel<<<(unsigned)blocks, (unsigned)threads, 0, at::cuda::getCurrentCUDAStream()>>>(
++ t, (int)count, (int)mode, reinterpret_cast<unsigned*>(sink.data_ptr<int>()));
++ C10_CUDA_KERNEL_LAUNCH_CHECK();
++}
+diff --git tensorfold/families/glm5_next/cuda/l2pf.py tensorfold/families/glm5_next/cuda/l2pf.py
+new file mode 100644
+index 0000000..f62a38e
+--- /dev/null
++++ tensorfold/families/glm5_next/cuda/l2pf.py
+@@ -0,0 +1,319 @@
++"""L2 prefetch of the next kernels' weights in decode windows (TF_GLM_L2PF, off by default; the same bits).
++
++A decode window's layer alternates DRAM-bound matmuls (projections, routed and shared experts, the head) with phases
++that leave DRAM idle: the two all-gathers a layer (the RoCE wait), the hyper-connection glue, the router and top-k,
++the KDA recurrence and the latent attention core. At a few sites a layer, a small kernel on a side stream asks for
++the weights the main stream reads next to be brought into L2 (``l2pf.cu``) while it is in such a phase; the matmul
++that follows then finds part of its bytes in L2 instead of DRAM. The prefetch only reads, and every model kernel keeps
++its inputs, outputs and stream order, so replies keep their bits.
++
++Sites (``Prefetch.site``, keyed by (layer index, name)):
++
++- ``a``, at the attention block's all-gather: the FFN's hyper-connection weights and norm, the router, and the shared
++ expert's gate/up and down (a dense MLP's gate/up and down); with the prefetcher on, the MoE runs its shared expert
++ before the routed experts (disjoint buffers, the same kernels: the same bits), so the routed experts' ~100+ MB
++ stream does not evict it first.
++- ``f``, at the FFN's all-gather: the next layer's hyper-connection weights and input norm, then its input
++ projections (KDA: proj, f/g low-rank; DSA: proj, q_b, the indexer's keys); after the last layer the final norm and
++ the head.
++- ``o``, after the attention block's input projections, while the recurrence / attention core runs: its output
++ projection.
++
++Each site takes up to TF_GLM_L2PF_MB (default 8) MiB, small tensors first (scales, biases, norms), then the large
++matrices' leading bytes. TF_GLM_L2PF_SITES (default ``afo``) picks the sites. TF_GLM_L2PF=1|bulk (one
++cp.async.bulk.prefetch.L2 per piece), ``lines`` (prefetch.global.L2::evict_last per line) or ``touch`` (ld.global.cg
++per line). Windows over TF_GLM_L2PF_ROWS (default 64) rows and prompt chunks skip every site.
++
++Adapted from jayleaton/glm53-tensorfold-spark patches/0460 (l2pf.py / l2pf.cu; Apache-2.0, Copyright 2026 Jay
++Leaton): the sites at the two all-gathers and after the attention projections, the shared expert first, a budget a
++site, bulk / lines / touch mechanisms, a 4-bit matrix's chunk heads for one-wave launches (``q4_heads``), the side
++stream forked at a site and joined before a forward returns. Changes: written onto this engine's forward (hooks in
++``forward.compute`` / ``partials`` / the KDA and DSA blocks and their multi-stream ``*_segments`` forms, so batched
++verify windows prefetch too); one device table of (address, bytes) pieces for every site with each site's grid sized
++at load; DSA's ``o`` site fires after absorb_q and takes kv_b's value half (this engine's latent layout) before the
++output projection; the next layer's KDA / DSA small weights (f/g low-rank, conv, norms, the indexer's) join site
++``f``; no expert (``e``) or MTP sites; ``touch`` loads inside the same kernel; default 8 MiB a site."""
++
++from __future__ import annotations
++
++import dataclasses
++import os
++from functools import lru_cache
++from typing import Any, Iterable
++
++import torch
++
++MODES = {"1": 0, "bulk": 0, "lines": 1, "touch": 2}
++PIECE = 32 << 10 # bytes a table piece covers at most (a bulk prefetch's size, a warp's walk); TF_GLM_L2PF_KB
++ALIGN = 16 # cp.async.bulk wants 16-byte addresses and sizes
++
++
++class Settings:
++ mode: int = -1 # -1: off
++ mb: float = 8.0
++ sites: str = "afo"
++ rows: int = 64
++ blocks: int = 0 # 0: enough for the site's pieces (a thread a piece in bulk mode, a warp a piece else)
++ threads: int = 128
++ piece: int = PIECE
++
++ @classmethod
++ def from_env(cls, env=None) -> "Settings":
++ env = os.environ if env is None else env
++ s = cls()
++ v = (env.get("TF_GLM_L2PF", "") or "0").strip().lower()
++ if v not in ("0", "off", *MODES):
++ raise ValueError(f"TF_GLM_L2PF: 0, 1 (bulk), bulk, lines or touch, not {v!r}")
++ s.mode = MODES.get(v, -1)
++ try:
++ s.mb = float(env.get("TF_GLM_L2PF_MB", "") or 8.0)
++ except ValueError:
++ s.mb = -1.0
++ if not 0 < s.mb <= 64:
++ raise ValueError("TF_GLM_L2PF_MB: above 0 and at most 64 (MiB a site)")
++ s.sites = (env.get("TF_GLM_L2PF_SITES", "") or "afo").strip().lower()
++ if not s.sites or set(s.sites) - set("afo"):
++ raise ValueError(f"TF_GLM_L2PF_SITES: letters of 'afo', not {s.sites!r}")
++ s.rows = int(env.get("TF_GLM_L2PF_ROWS", "") or 64)
++ s.blocks = int(env.get("TF_GLM_L2PF_BLOCKS", "") or 0)
++ s.threads = int(env.get("TF_GLM_L2PF_THREADS", "") or 128)
++ s.piece = int(env.get("TF_GLM_L2PF_KB", "") or PIECE >> 10) << 10
++ if s.blocks < 0 or s.threads < 32 or s.threads % 32 or s.threads > 1024:
++ raise ValueError("TF_GLM_L2PF_BLOCKS / _THREADS: 0 (auto) or more blocks of 32..1024 threads (whole warps)")
++ if not 1 << 10 <= s.piece <= 1 << 20:
++ raise ValueError("TF_GLM_L2PF_KB: 1 .. 1024 KiB a piece")
++ return s
++
++ @property
++ def on(self) -> bool:
++ return self.mode >= 0
++
++ def code(self) -> str:
++ return "off" if not self.on else f"{self.mode}:{self.mb}:{self.sites}:{self.rows}:{self.blocks}:{self.threads}:{self.piece}"
++
++
++@lru_cache(maxsize=1)
++def _ext():
++ from pathlib import Path
++
++ from tensorfold.cuda.build import load
++
++ here = Path(__file__).parent
++ return load(name="tensorfold_glm_l2pf_v2", sources=[str(here / "l2pf.cpp"), str(here / "l2pf.cu")],
++ extra_cuda_cflags=["-O3"], verbose=False)
++
++
++def tensors(obj: Any) -> list[torch.Tensor]:
++ """The CUDA tensors an object's weights hold (dataclass / plain-object fields in order, lists, tuples), each once."""
++
++ out: list[torch.Tensor] = []
++ seen: set[int] = set()
++
++ def walk(t: Any, depth: int = 0) -> None:
++ if depth > 6 or t is None:
++ return
++ if isinstance(t, torch.Tensor):
++ if t.numel() and t.data_ptr() not in seen:
++ seen.add(t.data_ptr())
++ out.append(t)
++ elif isinstance(t, (list, tuple)):
++ for v in t:
++ walk(v, depth + 1)
++ elif isinstance(t, dict):
++ for v in t.values():
++ walk(v, depth + 1)
++ elif hasattr(t, "__dict__") and not isinstance(t, (int, float, str, bool, torch.device)):
++ for v in vars(t).values():
++ walk(v, depth + 1)
++
++ walk(obj)
++ return out
++
++
++ONE_WAVE = 192 # qmm programs resident at once on GB10 (4 CTAs an SM x 48 SMs)
++
++
++def q4_heads(q, left: int) -> list[tuple[int, int]]:
++ """A 4-bit matrix (``qmm.Q4``: words [N/64, K/64, 8, 32, 2], one contiguous chunk of K * 32 / SK bytes a
++ (64-column tile, K slice), what one decode program streams): the first ``left / chunks`` bytes of EVERY chunk, so
++ each program of a one-wave launch starts on L2 hits and the launch's slowest program is shortened too (a
++ tensor's first bytes would only help its first programs). [] for a launch of more than one wave or heads under
++ 512 bytes. (jayleaton/glm53-tensorfold-spark patches/0460 ``_q4_heads``, Apache-2.0, Copyright 2026 Jay Leaton;
++ changes: our qmm's split_k, (address, bytes) pairs.)"""
++
++ from . import qmm
++
++ w = q.weight
++ if not isinstance(w, torch.Tensor) or not w.is_contiguous():
++ return []
++ chunks = -(-int(q.n) // qmm.BN) * qmm.split_k(int(q.n), int(q.k))
++ total = w.numel() * w.element_size()
++ if chunks <= 0 or chunks > ONE_WAVE or total % chunks:
++ return []
++ size = total // chunks
++ per = min(size, left // chunks) // ALIGN * ALIGN
++ if per < 512 or w.data_ptr() % ALIGN or size % ALIGN:
++ return []
++ return [(w.data_ptr() + c * size, per) for c in range(chunks)]
++
++
++def _span(t: torch.Tensor, left: int) -> tuple[int, int] | None:
++ a = t.data_ptr()
++ n = t.numel() * t.element_size()
++ lo = a - a % ALIGN
++ hi = min(a + n, lo + left)
++ hi += (-hi) % ALIGN
++ return (lo, hi - lo) if hi > lo else None
++
++
++def ranges(groups: Iterable[Any], budget: int) -> list[tuple[int, int]]:
++ """(address, bytes) ranges of ``groups`` (weight objects in the order the main stream reads them) up to
++ ``budget`` bytes: within a group its small tensors first (scales, biases, norms), then a 4-bit matrix's chunk
++ heads when its decode launch is one wave (``q4_heads``), else the large tensors' leading bytes; 16-byte aligned."""
++
++ out: list[tuple[int, int]] = []
++ left = budget
++ for g in groups:
++ ts = sorted(tensors(g), key=lambda x: x.numel() * x.element_size())
++ heads = []
++ if all(hasattr(g, a) for a in ("weight", "scales", "biases", "n", "k")) and isinstance(g.weight, torch.Tensor):
++ small = sum(t.numel() * t.element_size() for t in ts if t is not g.weight)
++ heads = q4_heads(g, left - small) if left > small else []
++ if heads:
++ ts = [t for t in ts if t is not g.weight]
++ for t in ts:
++ if left < ALIGN:
++ return out
++ sp = _span(t, left)
++ if sp is not None:
++ out.append(sp)
++ left -= sp[1]
++ if heads and left >= sum(n for _, n in heads):
++ out += heads
++ left -= sum(n for _, n in heads)
++ return out
++
++
++def pieces(spans: list[tuple[int, int]], piece: int = PIECE) -> list[tuple[int, int]]:
++ out = []
++ for a, n in spans:
++ for o in range(0, n, piece):
++ out.append((a + o, min(piece, n - o)))
++ return out
++
++
++class Prefetch:
++ """The sites' tables for one set of weights (one device table; (first, count) a site) and the side stream."""
++
++ def __init__(self, w, settings: Settings | None = None) -> None:
++ self.s = settings or Settings.from_env()
++ self.w = w
++ self.sites: dict[tuple[int, str], tuple[int, int]] = {}
++ self.bytes: dict[tuple[int, str], int] = {}
++ budget = int(self.s.mb * (1 << 20))
++ rows: list[tuple[int, int]] = []
++ layers = list(w.layers)
++ for i, layer in enumerate(layers):
++ nxt = layers[i + 1] if i + 1 < len(layers) else None
++ plan = {"a": self._ffn(layer), "f": self._next(nxt), "o": self._out(layer)}
++ for name, groups in plan.items():
++ if name not in self.s.sites or not groups:
++ continue
++ spans = ranges(groups, budget)
++ p = pieces(spans, self.s.piece)
++ if p:
++ self.sites[(layer.index, name)] = (len(rows), len(p), self._grid(len(p)))
++ self.bytes[(layer.index, name)] = sum(n for _, n in spans)
++ rows += p
++ dev = w.device
++ self.table = torch.tensor(rows or [(0, 0)], dtype=torch.int64, device=dev).view(-1, 2).contiguous()
++ self.sink = torch.zeros((1,), dtype=torch.int32, device=dev)
++ self.side = torch.cuda.Stream(device=dev) if torch.cuda.is_available() else None
++ if self.side is not None:
++ _ext() # built / loaded now, before any graph capture
++ self.forked = False
++ self.launches = 0
++
++ def _grid(self, n: int) -> int:
++ """Blocks for a site of ``n`` pieces: TF_GLM_L2PF_BLOCKS, or a thread a piece (bulk) / a warp a piece."""
++
++ if self.s.blocks:
++ return self.s.blocks
++ per = self.s.threads if self.s.mode == 0 else self.s.threads // 32
++ return max(1, min(48, -(-n // per)))
++
++ # -- what each site prefetches ---------------------------------------------------------------------------------
++ def _ffn(self, layer) -> list:
++ g: list = [layer.ffn_hc, layer.post_norm]
++ if layer.mlp is not None:
++ g += [layer.mlp.gu, layer.mlp.down]
++ elif layer.moe is not None:
++ g += [layer.moe.router, layer.moe.bias]
++ if layer.moe.shared is not None:
++ g += [layer.moe.shared.gu, layer.moe.shared.down]
++ return g
++
++ def _next(self, nxt) -> list:
++ if nxt is None:
++ return [self.w.norm, self.w.head]
++ g: list = [nxt.attn_hc, nxt.in_norm]
++ if nxt.kda is not None:
++ k = nxt.kda
++ g += [k.fb, k.gb, k.conv, k.a_log, k.dt_bias, k.proj]
++ elif nxt.dsa is not None:
++ a = nxt.dsa
++ g += [a.q_norm, a.kv_norm, a.proj, a.q_b]
++ if a.index is not None:
++ g += [a.index.kw, a.index.gate]
++ return g
++
++ def _out(self, layer) -> list:
++ """KDA: its output projection. DSA (fired after absorb_q, before the attention core): the value half of kv_b
++ that expand_v reads, then the output projection."""
++
++ if layer.kda is not None:
++ return [layer.kda.o]
++ if layer.dsa is not None:
++ a = layer.dsa.absorb
++ value = [getattr(a, n) for n in ("wvs", "wvb", "sv", "wvw", "wv") if getattr(a, n, None) is not None]
++ return value + [layer.dsa.o]
++ return []
++
++ # -- the forward's calls ------------------------------------------------------------------------------------------
++ def site(self, index: int, name: str) -> None:
++ """Fork the side stream at this point of the main stream and prefetch the site's ranges there."""
++
++ key = self.sites.get((index, name))
++ if key is None or self.side is None:
++ return
++ first, count, grid = key
++ main = torch.cuda.current_stream()
++ self.side.wait_stream(main)
++ with torch.cuda.stream(self.side):
++ _ext().prefetch(self.table, first, count, self.s.mode, grid, self.s.threads, self.sink)
++ self.forked = True
++ self.launches += 1
++
++ def join(self) -> None:
++ """The main stream waits for the side stream (a captured graph's branches rejoin before its end)."""
++
++ if self.forked:
++ torch.cuda.current_stream().wait_stream(self.side)
++ self.forked = False
++
++ def summary(self) -> str:
++ per = {}
++ for (_, name), n in self.bytes.items():
++ per.setdefault(name, []).append(n)
++ parts = [f"{k} {len(v)} sites {sum(v) / len(v) / (1 << 20):.1f} MiB" for k, v in sorted(per.items())]
++ mode = {0: "bulk", 1: "lines", 2: "touch"}[self.s.mode]
++ return f"L2 prefetch in decode windows ({mode}, up to {self.s.mb:g} MiB a site): " + ", ".join(parts)
++
++
++ACTIVE: Prefetch | None = None # set by forward.compute for a decode window while it runs
++
++
++def site(index: int, name: str) -> None:
++ if ACTIVE is not None:
++ ACTIVE.site(index, name)
diff --git a/patches/0050-glm-exl3-decode-loads.patch b/patches/0050-glm-exl3-decode-loads.patch
new file mode 100644
index 0000000..e1020d9
--- /dev/null
+++ b/patches/0050-glm-exl3-decode-loads.patch
@@ -0,0 +1,259 @@
+diff --git tensorfold/families/glm5_next/cuda/exl3.cpp tensorfold/families/glm5_next/cuda/exl3.cpp
+index 908afbe..19b09ff 100644
+--- tensorfold/families/glm5_next/cuda/exl3.cpp
++++ tensorfold/families/glm5_next/cuda/exl3.cpp
+@@ -19,7 +19,7 @@ void exl3_rot_rows_cuda(const at::Tensor&, int64_t, const at::Tensor&, at::Tenso
+ void exl3_dec_cuda(const at::Tensor&, const at::Tensor&, const at::Tensor&, const at::Tensor&, const at::Tensor&,
+ const at::Tensor&, const at::Tensor&, at::Tensor&, int64_t, int64_t, int64_t, int64_t, int64_t,
+ int64_t, int64_t, int64_t, int64_t, bool, const at::Tensor&, const at::Tensor&,
+- const at::Tensor&, at::Tensor&, double, at::Tensor&);
++ const at::Tensor&, at::Tensor&, double, at::Tensor&, int64_t);
+
+ static void check(const at::Tensor& x, at::ScalarType t, const char* name) {
+ TORCH_CHECK(x.is_cuda() && x.scalar_type() == t && x.is_contiguous(), name,
+@@ -115,7 +115,7 @@ void dec(const at::Tensor& X0, const at::Tensor& X1, const at::Tensor& T0, const
+ const at::Tensor& counts, const at::Tensor& members, at::Tensor Z, int64_t mats, int64_t K, int64_t N,
+ int64_t P, int64_t SK, int64_t max_items, int64_t slots, int64_t fuse, bool xrow,
+ const at::Tensor& sv0, const at::Tensor& sv1, const at::Tensor& su2, at::Tensor out, double limit,
+- at::Tensor done) {
++ at::Tensor done, int64_t ld) {
+ const int64_t E = T0.size(0);
+ for (auto* t : {&X0, &X1, &sv0, &sv1, &su2}) check(*t, at::kHalf, "dec: fp16 input");
+ for (auto* t : {&T0, &T1, &items, &counts, &members}) check(*t, at::kInt, "dec: int32 input");
+@@ -125,9 +125,11 @@ void dec(const at::Tensor& X0, const at::Tensor& X1, const at::Tensor& T0, const
+ TORCH_CHECK(fuse != 1 || (out.scalar_type() == at::kFloat && out.numel() >= P * N), "dec: Y fp32 [P, N]");
+ TORCH_CHECK(fuse != 2 || (out.scalar_type() == at::kHalf && out.numel() >= P * N &&
+ done.numel() >= max_items * (N / 128)), "dec: Xd fp16 [P, N] and done counts");
++ // loads 1..3 read every block's item row before its count check (one round trip): items sized for the grid
++ TORCH_CHECK(ld == 0 || items.numel() >= 3 * max_items, "dec: items [max_items, 3] for the 16-byte load path");
+ c10::cuda::CUDAGuard guard(X0.device());
+ exl3_dec_cuda(X0, X1, T0, T1, items, counts, members, Z, mats, K, N, P, SK, max_items, E, slots, fuse, xrow,
+- sv0, sv1, su2, out, limit, done);
++ sv0, sv1, su2, out, limit, done, ld);
+ }
+
+ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
+diff --git tensorfold/families/glm5_next/cuda/exl3.cu tensorfold/families/glm5_next/cuda/exl3.cu
+index 363fa23..38824db 100644
+--- tensorfold/families/glm5_next/cuda/exl3.cu
++++ tensorfold/families/glm5_next/cuda/exl3.cu
+@@ -64,6 +64,16 @@ __device__ __forceinline__ uint32_t load_pair(const half* x, bool ok) {
+ return ok ? *reinterpret_cast<const uint32_t*>(x) : 0u;
+ }
+
++// 16 bytes of trellis words, read once a window (no L1 allocation); asm volatile keeps it where it stands relative
++// to the (volatile) mma, so the ring depth is what the code says (patches/0580 of jayleaton/glm53-tensorfold-spark).
++__device__ __forceinline__ uint4 ldg_nc_v4(const uint32_t* p) {
++ uint4 v;
++ asm volatile("ld.global.nc.L1::no_allocate.v4.u32 {%0,%1,%2,%3}, [%4];"
++ : "=r"(v.x), "=r"(v.y), "=r"(v.z), "=r"(v.w)
++ : "l"(p));
++ return v;
++}
++
+ // Grid (item, n block, mat * SK + split) -> Z[mat][split][pair][n]; warps sum fixed k ranges, added in warp order.
+ // SEQ (prompt chunks): grid (.., .., mat); one program runs the SK splits in turn and writes Z[mat][0][pair][n] =
+ // ((0 + split 0) + split 1) + ..., the epilogue's own sum, so an SK = 1 epilogue gives the same bits without the
+@@ -328,7 +338,16 @@ __global__ void down_epilogue_kernel(const float* __restrict__ Z, const int* __r
+ // to finish (an atomic count, reset for the next launch) runs gateup_epilogue_kernel's arithmetic on the item's
+ // rows and 128 columns, reading the partials in split order: the same sums whichever block finishes last.
+ // XROW: X holds one row a token (rot_rows, a layer whose experts share one suh), pair p reads row p / slots.
+-template <int NT, int W, int STEPS, int FUSE, bool XROW>
++// LD (TF_GLM_EXL3_LOADS; data movement only, every chain and sum as above, so the same bits):
++// 0: 32-bit __ldg of word `lane` of each tile, one k step ahead, after the count -> item -> members round trips;
++// 1: adapted from jayleaton/glm53-tensorfold-spark patches/0580 (exl3_ld.cu ld_kernel, LD_NC; Apache-2.0,
++// Copyright 2026 Jay Leaton). Changes: in our dec_kernel (its items / counts plan, fused epilogues and XROW
++// inputs kept), PD fixed at compile time, no probes / PDL. The count and the item are read together and the
++// first PD k steps' trellis words are issued before the member rows reach shared memory; the words come as
++// ld.global.nc.L1::no_allocate.v4 (lane l: bytes 16 l .. of each 512 B of a step, NT / 4 loads a lane), PD
++// steps in flight, through a 1 KB staging area in the warp's own slice of `red` (two __syncwarp a step), read
++// back as word `lane` of each tile.
++template <int NT, int W, int STEPS, int FUSE, bool XROW, int LD = 0, int PD = 1>
+ __global__ void __launch_bounds__(W * 32) dec_kernel(
+ const half* __restrict__ X0, const half* __restrict__ X1, const uint32_t* __restrict__ T0,
+ const uint32_t* __restrict__ T1, const int* __restrict__ items, const int* __restrict__ counts,
+@@ -336,9 +355,17 @@ __global__ void __launch_bounds__(W * 32) dec_kernel(
+ const half* __restrict__ sv0, const half* __restrict__ sv1, const half* __restrict__ su2, void* __restrict__ out,
+ float limit, int* __restrict__ done) {
+ static_assert(FUSE == 0 || NT * 16 == 128, "a fused epilogue needs one 128-column Hadamard block a program");
++ static_assert(LD == 0 || (NT % 4 == 0 && PD >= 1 && STEPS % PD == 0), "LD 1: NT a multiple of 4, PD | STEPS");
+ const int item = blockIdx.x, nblock = blockIdx.y;
+- if (item >= counts[0]) return;
+- const int e = items[3 * item], first = items[3 * item + 1], cnt = items[3 * item + 2];
++ int e, first, cnt;
++ if constexpr (LD == 0) {
++ if (item >= counts[0]) return;
++ e = items[3 * item], first = items[3 * item + 1], cnt = items[3 * item + 2];
++ } else { // one round trip: items holds a row for every block
++ const int total = counts[0];
++ e = items[3 * item], first = items[3 * item + 1], cnt = items[3 * item + 2];
++ if (item >= total) return;
++ }
+ if (e >= E) return; // the shared expert (id E) is not EXL3
+ const int mat = blockIdx.z / SK, split = blockIdx.z % SK;
+ const half* X = mat ? X1 : X0;
+@@ -348,7 +375,17 @@ __global__ void __launch_bounds__(W * 32) dec_kernel(
+ const int KT = K >> 4, NTILES = N >> 4;
+
+ __shared__ int rows_sh[16];
+- __shared__ float red[W][16][NT * 16];
++ __shared__ __align__(16) float red[W][16][NT * 16];
++ constexpr int NV = NT / 4; // LD 1: 16-byte loads a lane a k step
++ uint4 rv[LD == 1 ? PD : 1][LD == 1 ? NV : 1];
++ const uint32_t* tbase = T + (((size_t)e * KT + split * (KT / SK) + warp * STEPS) * NTILES + nblock * NT) * 32;
++ const size_t kstep = (size_t)NTILES * 32; // words from one k tile to the next
++ if constexpr (LD == 1) {
++#pragma unroll
++ for (int d = 0; d < PD; ++d)
++#pragma unroll
++ for (int v = 0; v < NV; ++v) rv[d][v] = ldg_nc_v4(tbase + d * kstep + 128 * v + 4 * lane);
++ }
+ if (threadIdx.x < 16) rows_sh[threadIdx.x] = (int)threadIdx.x < cnt ? members[first + threadIdx.x] : -1;
+ __syncthreads();
+ const int r0 = rows_sh[g], r1 = rows_sh[g + 8];
+@@ -367,6 +404,48 @@ __global__ void __launch_bounds__(W * 32) dec_kernel(
+ #pragma unroll
+ for (int c = 0; c < 4; ++c) acc[i][h][c] = 0.f;
+
++ if constexpr (LD == 1) {
++ uint32_t ra[PD][4];
++#pragma unroll
++ for (int d = 0; d < PD; ++d) {
++ const int k = (kt0 + d) * 16;
++ ra[d][0] = load_pair(x0 + k, r0 >= 0); ra[d][1] = load_pair(x1 + k, r1 >= 0);
++ ra[d][2] = load_pair(x0 + k + 8, r0 >= 0); ra[d][3] = load_pair(x1 + k + 8, r1 >= 0);
++ }
++ uint32_t* stage = reinterpret_cast<uint32_t*>(&red[warp][0][0]);
++ for (int kb = 0; kb < STEPS; kb += PD) {
++#pragma unroll
++ for (int d = 0; d < PD; ++d) {
++ const int s = kb + d;
++ const bool more = s + PD < STEPS;
++ uint32_t a[4], words[NT];
++#pragma unroll
++ for (int c = 0; c < 4; ++c) a[c] = ra[d][c];
++ __syncwarp(); // every lane has read the previous step back
++#pragma unroll
++ for (int v = 0; v < NV; ++v) *reinterpret_cast<uint4*>(stage + 128 * v + 4 * lane) = rv[d][v];
++ if (more) { // the slot's registers are free again
++#pragma unroll
++ for (int v = 0; v < NV; ++v)
++ rv[d][v] = ldg_nc_v4(tbase + (size_t)(s + PD) * kstep + 128 * v + 4 * lane);
++ const int k = (kt0 + s + PD) * 16;
++ ra[d][0] = load_pair(x0 + k, r0 >= 0); ra[d][1] = load_pair(x1 + k, r1 >= 0);
++ ra[d][2] = load_pair(x0 + k + 8, r0 >= 0); ra[d][3] = load_pair(x1 + k + 8, r1 >= 0);
++ }
++ __syncwarp();
++#pragma unroll
++ for (int i = 0; i < NT; ++i) words[i] = stage[i * 32 + lane];
++#pragma unroll
++ for (int i = 0; i < NT; ++i) {
++ uint32_t b0[2], b1[2];
++ decode_tile(words[i], lane, b0, b1);
++ mma16816(acc[i][0], a, b0);
++ mma16816(acc[i][1], a, b1);
++ }
++ }
++ }
++ __syncwarp(); // the staging area becomes red[warp] below
++ } else {
+ // grouped_kernel's PF loop as it is (a runtime loop: unrolling it measured slower)
+ uint32_t words[NT], a[4];
+ #pragma unroll
+@@ -402,6 +481,7 @@ __global__ void __launch_bounds__(W * 32) dec_kernel(
+ }
+ tile += (size_t)NTILES * 32;
+ }
++ }
+
+ #pragma unroll
+ for (int i = 0; i < NT; ++i)
+@@ -916,8 +996,9 @@ void exl3_dec_cuda(const at::Tensor& X0, const at::Tensor& X1, const at::Tensor&
+ const at::Tensor& items, const at::Tensor& counts, const at::Tensor& members, at::Tensor& Z,
+ int64_t mats, int64_t K, int64_t N, int64_t P, int64_t SK, int64_t max_items, int64_t E,
+ int64_t slots, int64_t fuse, bool xrow, const at::Tensor& sv0, const at::Tensor& sv1,
+- const at::Tensor& su2, at::Tensor& out, double limit, at::Tensor& done) {
++ const at::Tensor& su2, at::Tensor& out, double limit, at::Tensor& done, int64_t ld) {
+ constexpr int NT = 8, W = 4, STEPS = 16;
++ TORCH_CHECK(ld >= 0 && ld <= 3, "decode expert kernel: loads 0 (32-bit), 1 / 2 / 3 (16-byte, 1 / 2 / 4 steps ahead)");
+ TORCH_CHECK(K % (16 * SK * W) == 0 && K / (16 * SK * W) == STEPS && N % (16 * NT) == 0,
+ "decode expert kernel: 16 k steps a warp");
+ TORCH_CHECK(fuse != 1 || (SK == 1 && mats == 1), "the fused down epilogue takes one split of one matrix");
+@@ -926,15 +1007,21 @@ void exl3_dec_cuda(const at::Tensor& X0, const at::Tensor& X1, const at::Tensor&
+ auto stream = at::cuda::getCurrentCUDAStream();
+ auto h = [](const at::Tensor& t) { return reinterpret_cast<const half*>(t.data_ptr()); };
+ auto w = [](const at::Tensor& t) { return reinterpret_cast<const uint32_t*>(t.data_ptr()); };
+-#define DEC(F_, XR_) \
+- dec_kernel<NT, W, STEPS, F_, XR_><<<grid, W * 32, 0, stream>>>( \
++#define DEC1(F_, XR_, LD_, PD_) \
++ dec_kernel<NT, W, STEPS, F_, XR_, LD_, PD_><<<grid, W * 32, 0, stream>>>( \
+ h(X0), h(X1), w(T0), w(T1), items.data_ptr<int>(), counts.data_ptr<int>(), members.data_ptr<int>(), \
+ Z.data_ptr<float>(), (int)K, (int)N, (int)P, (int)SK, (int)E, (int)slots, h(sv0), h(sv1), h(su2), \
+ out.data_ptr(), (float)limit, done.data_ptr<int>())
+- if (fuse == 0) { if (xrow) DEC(0, true); else DEC(0, false); }
+- else if (fuse == 1) { if (xrow) DEC(1, true); else DEC(1, false); }
+- else { if (xrow) DEC(2, true); else DEC(2, false); }
++#define DEC(F_, XR_) \
++ if (ld == 0) DEC1(F_, XR_, 0, 1); \
++ else if (ld == 1) DEC1(F_, XR_, 1, 1); \
++ else if (ld == 2) DEC1(F_, XR_, 1, 2); \
++ else DEC1(F_, XR_, 1, 4)
++ if (fuse == 0) { if (xrow) { DEC(0, true); } else { DEC(0, false); } }
++ else if (fuse == 1) { if (xrow) { DEC(1, true); } else { DEC(1, false); } }
++ else { if (xrow) { DEC(2, true); } else { DEC(2, false); } }
+ #undef DEC
++#undef DEC1
+ C10_CUDA_KERNEL_LAUNCH_CHECK();
+ }
+
+diff --git tensorfold/families/glm5_next/cuda/exl3_mm.py tensorfold/families/glm5_next/cuda/exl3_mm.py
+index f519b9f..d79bfb2 100644
+--- tensorfold/families/glm5_next/cuda/exl3_mm.py
++++ tensorfold/families/glm5_next/cuda/exl3_mm.py
+@@ -46,6 +46,21 @@ def dec_settings() -> tuple[bool, int, bool]:
+ return on, fuse, os.environ.get("TF_GLM_EXL3_XROW", "1") != "0"
+
+
++LOADS = {"0": 0, "ldg": 0, "1": 1, "nc": 1, "nc1": 1, "nc2": 2, "nc4": 3}
++
++
++def dec_loads() -> int:
++ """TF_GLM_EXL3_LOADS: the decode kernel's trellis loads (the same bits for every value). ``0`` / ``ldg``
++ (default): 32-bit loads one k step ahead; ``nc`` / ``nc1``, ``nc2``, ``nc4``: 16-byte ld.global.nc loads 1, 2 or
++ 4 k steps ahead through a staging area, the item read with its count in one round trip and the first steps'
++ words issued before the member rows arrive (after jayleaton/glm53-tensorfold-spark patches/0580, Apache-2.0)."""
++
++ v = (os.environ.get("TF_GLM_EXL3_LOADS", "") or "0").strip().lower()
++ if v not in LOADS:
++ raise ValueError(f"TF_GLM_EXL3_LOADS: 0, nc, nc2 or nc4, not {v!r}")
++ return LOADS[v]
++
++
+ def _seq() -> bool:
+ """TF_GLM_EXL3_SEQ (default on): prompt chunks sum a matmul's K splits in one program (same bits)."""
+ import os
+@@ -58,7 +73,7 @@ def _ext():
+ from tensorfold.cuda.build import load
+
+ here = Path(__file__).parent
+- return load(name="tensorfold_glm_exl3_v18", sources=[str(here / "exl3.cpp"), str(here / "exl3.cu")],
++ return load(name="tensorfold_glm_exl3_v19", sources=[str(here / "exl3.cpp"), str(here / "exl3.cu")],
+ extra_cuda_cflags=["-O3"], verbose=False)
+
+
+@@ -197,12 +212,13 @@ def routed(x: torch.Tensor, pick: torch.Tensor, plan: grouped.Plan, ex: Exl3Expe
+ else:
+ ext.rot_in(x, x.stride(0), pick, ex.suh_g, ex.suh_u, s.xg, s.xu, R, D, slots)
+ xg, xu = s.xg, s.xu
++ ld = dec_loads()
+ ext.dec(xg, xu, ex.gt, ex.ut, plan.items, plan.counts, plan.members, s.z, 2, D, NI, P, 4, items, slots,
+- 2 if fuse & 2 else 0, xrow, ex.svh_g, ex.svh_u, ex.suh_d, s.xd, float(limit), s.done)
++ 2 if fuse & 2 else 0, xrow, ex.svh_g, ex.svh_u, ex.suh_d, s.xd, float(limit), s.done, ld)
+ if not fuse & 2:
+ ext.gateup_epilogue(s.z, pick, ex.svh_g, ex.svh_u, ex.suh_d, s.xd, R, P, NI, 4, slots, float(limit))
+ ext.dec(s.xd, s.xd, ex.dt, ex.dt, plan.items, plan.counts, plan.members, s.z, 1, NI, D, P, 1, items, slots,
+- 1 if fuse & 1 else 0, False, ex.svh_d, ex.svh_d, ex.svh_d, y, 0.0, s.done)
++ 1 if fuse & 1 else 0, False, ex.svh_d, ex.svh_d, ex.svh_d, y, 0.0, s.done, ld)
+ if not fuse & 1:
+ ext.down_epilogue(s.z, pick, ex.svh_d, y, R, P, D, 1, slots)
+ return
diff --git a/patches/0051-glm-timing-tokens.patch b/patches/0051-glm-timing-tokens.patch
new file mode 100644
index 0000000..7657794
--- /dev/null
+++ b/patches/0051-glm-timing-tokens.patch
@@ -0,0 +1,65 @@
+diff --git tensorfold/families/glm5_next/cuda/multi.py tensorfold/families/glm5_next/cuda/multi.py
+index 8741f33..863250c 100644
+--- tensorfold/families/glm5_next/cuda/multi.py
++++ tensorfold/families/glm5_next/cuda/multi.py
+@@ -467,14 +467,19 @@ class MultiDecoder:
+ verify window on the one-stream graphs and on the batched graphs, ms by rows up to the one-stream graphs'
+ widest (fastest of ``reps``; slot 0's states cleared after)."""
+
++ from .forward import stage
++ from .verify import timing_tokens
++
+ e, v = self.e, self.verify
+ start, stop = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
+ solo = v.time_rows(reps, most=self.lone_rows)
++ tokens = timing_tokens(self.w.cfg.vocab, v.rows_max) # the rows time_rows gave the batched graphs
+ out = []
+ for R in range(1, self.lone_rows + 1):
+ g = e.graphs.main.get((R, e.home.parity))
+ if g is None:
+ continue
++ stage(self.w, e.home, e.buf, tokens[:R])
+ best = float("inf")
+ for _ in range(reps + 1):
+ start.record()
+diff --git tensorfold/families/glm5_next/cuda/verify.py tensorfold/families/glm5_next/cuda/verify.py
+index 3858103..f359bc9 100644
+--- tensorfold/families/glm5_next/cuda/verify.py
++++ tensorfold/families/glm5_next/cuda/verify.py
+@@ -65,6 +65,14 @@ class SerialVerify:
+ commit(e.w, seg.st, e.buf, len(seg.tokens), keep)
+
+
++def timing_tokens(vocab: int, n: int) -> list[int]:
++ """Fixed, distinct token ids for startup timings of verify windows (rows of real text route to many experts)."""
++
++ import numpy as np
++
++ return [int(t) for t in np.random.default_rng(1234).choice(min(vocab, 150000), size=n, replace=False)]
++
++
+ class BatchedVerify:
+ """One forward over every segment's rows (``rows`` at most, ``segments.MAX_SEGS`` streams), on buffers of its
+ own; see the module docstring. ``taps``: the drafter's tap layers (DFlash2's inputs), or ()."""
+@@ -138,16 +146,19 @@ class BatchedVerify:
+ @torch.no_grad()
+ def time_rows(self, reps: int = 5, most: int | None = None) -> list[float]:
+ """ms of the captured window of each size (1 .. its rows): the fastest of ``reps`` replays, on the capture's
+- own tables (slot 0 at the pool's first rows; its states cleared after), before any stream is admitted."""
++ own tables (slot 0 at the pool's first rows; its states cleared after), before any stream is admitted. The
++ rows are ``timing_tokens`` (distinct tokens: a window of one token repeated routes every row to the same few
++ experts and times a 16-row window at about half of what 16 real rows cost)."""
+
+ from .sparse import SPARSE_FROM
+
+ index = self.e.caches.index is not None
+ out = []
+ start, stop = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
++ tokens = timing_tokens(self.w.cfg.vocab, self.rows_max)
+ for R in range(1, min(most or self.rows_max, self.rows_max) + 1):
+ g = self.graphs[R]
+- self._stage([0] * R)
++ self._stage(tokens[:R])
+ self.seg_rows.set([self._span(self.e.home, 0, R)], sparse_from=SPARSE_FROM if index else None)
+ self._write_table([(R, 0, 0, 0, R)])
+ best = float("inf")
diff --git a/patches/0052-glm-multi-prefill.patch b/patches/0052-glm-multi-prefill.patch
new file mode 100644
index 0000000..aa45eeb
--- /dev/null
+++ b/patches/0052-glm-multi-prefill.patch
@@ -0,0 +1,658 @@
+diff --git tensorfold/families/glm5_next/cuda/engine.py tensorfold/families/glm5_next/cuda/engine.py
+index 04ca1b1..7957ac7 100644
+--- tensorfold/families/glm5_next/cuda/engine.py
++++ tensorfold/families/glm5_next/cuda/engine.py
+@@ -681,7 +681,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 "
+- f"{self.multi.share:g}); {self.multi.tune.describe()}", flush=True)
++ f"{self.multi.share:g}){'; waiting prompts share prompt chunks (TF_GLM_MULTI_PREFILL)' if self.multi.group else ''}; "
++ f"{self.multi.tune.describe()}", flush=True)
+ if self.multi.row_ms is not None:
+ print("[tensorfold] --parallel batched window ms by rows: " +
+ " ".join(f"{i + 1}:{ms:.1f}" for i, ms in enumerate(self.multi.row_ms)), flush=True)
+diff --git tensorfold/families/glm5_next/cuda/forward.py tensorfold/families/glm5_next/cuda/forward.py
+index 50cd873..c363bc4 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
+ 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")
+- 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,
+- k.dt_bias, k.norm, c.eps, c.lower, R, b.kscratch if pre else st.scratch[li],
+- st.rec[1 - cur, li], pos=st.pos if pre else None)
+ 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)
++ out = kda_rows(layer, w, st, b, 0, R)
++ else:
++ 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,
++ k.dt_bias, k.norm, c.eps, c.lower, R, st.scratch[li], st.rec[1 - cur, li])
+ with prof.timed("kda: out + all-gather"):
+ return out_proj(w, b, out, k.o, None if pre else qmm.group_sums(out, b.kxs[:R]), R, site=(layer.index, "a"))
+
+
++def _scratch_rows(s, lo: int):
++ """A prompt buffer's KDA scratch from row ``lo`` on (the same storage)."""
++
++ if lo == 0:
++ return s
++ from types import SimpleNamespace
++
++ return SimpleNamespace(out=s.out[lo:], k=s.k[lo:], v=s.v[lo:], g=s.g[lo:], b=s.b[lo:])
++
++
++def kda_rows(layer: LayerW, w: Weights, st: State, b: Buffers, lo: int, n: int) -> torch.Tensor:
++ """A prompt chunk's KDA recurrence for rows lo .. lo + n of the prompt buffers (their projections done) on ``st``
++ from its position: the chain into b.kscratch.out[lo:lo + n] (returned), the layer's state committed and its conv
++ window shifted. ``kda_block`` runs a chunk as rows 0 .. R; a chunk of several streams' prompts
++ (``multi_prefill``) runs each stream's rows through this on that stream's state: the call they get alone."""
++
++ c = w.cfg
++ k = layer.kda
++ li = st.kda_index[layer.index]
++ rs = slice(lo, lo + n)
++ cur = st.cur[li]
++ with prof.timed("kda: recurrence"):
++ out = kda_mod.chain(b.kproj[0, rs], k.b_off, b.ka[rs], b.kg[rs], st.conv[li], k.conv, st.rec[cur, li],
++ k.a_log, k.dt_bias, k.norm, c.eps, c.lower, n, _scratch_rows(b.kscratch, lo),
++ st.rec[1 - cur, li], pos=st.pos)
++ st.cur[li] = 1 - cur
++ _shift_conv(st.conv[li:li + 1], b.kproj[:, rs], n)
++ return out
++
++
+ 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
+ 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."""
+
++ o = dsa_rows(a, w, lc, pos_dev, b, R, nch, index, host_pos, sparse_np, layer)
++ return out_proj(w, b, o, a.o, qmm.group_sums(o, b.xs_ao[:R]), R, site=(layer, "a"))
++
++
++def dsa_rows(a, w: Weights, lc: torch.Tensor, pos_dev: torch.Tensor, b: Buffers, R: int, nch: int | None,
++ index, host_pos: int | None, sparse_np: int | None = None, layer: int = -1, lo: int = 0) -> torch.Tensor:
++ """``_dsa_latent`` up to its output projection, for rows lo .. lo + R of the buffers (their front done) on one
++ stream's caches (``lc``, ``index``, ``pos_dev``, ``host_pos``: its first row's position): the latent write,
++ indexer update, absorb, attention and expand; returns the rows' attention output [R, heads * v_dim] (b.vn's rows).
++ A chunk of several streams' prompts (``multi_prefill``) runs each stream's rows through this: the call they get
++ alone."""
++
+ c = w.cfg
+ HL = a.heads
+ s = b.lat_s
++ rs = slice(lo, lo + R)
+ with prof.timed("dsa: latent write"):
+- latent.latent_write(b.lat[:R], lc, pos_dev)
++ latent.latent_write(b.lat[rs], lc, pos_dev)
+ # sparse_np: every row is past the dense limit (a captured graph); else the host position decides
+ all_sparse = sparse_np is not None or (host_pos is not None and host_pos >= c.dense_limit)
+ sparse_rows = index is not None and (all_sparse or (host_pos is not None and host_pos + R - 1 >= c.dense_limit))
+@@ -614,13 +656,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"):
+- mm(b, b.normed[:R], ix.kw, b.xs[:R], b.ikr[:R])
+- 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)
++ mm(b, b.normed[rs], ix.kw, b.xs[rs], b.ikr[rs])
++ glue.router(b.normed[rs], ix.gate, b.igr[rs])
++ sparse.index_update(b.ikr[rs, :c.index_dim], b.igr[rs], 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)
++ qa = latent.absorb_q(b.q[rs], a.absorb, s.qa[rs], prompt=b.prefill and latent.PROMPT_MMA)
+ l2pf.site(layer, "o")
+- ol = s.ol[:R]
++ ol = s.ol[rs]
+ 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
+ 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])
+- tokens, counts = sparse.select_tokens(b.qi[:R], b.ikr[:R, c.index_dim:], pk, host_pos, R,
++ mm(b, b.qr[rs], ix.qb, b.xs_qr[rs], b.qi[rs])
++ tokens, counts = sparse.select_tokens(b.qi[rs], b.ikr[rs, c.index_dim:], pk, host_pos, R,
+ 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
+ else:
+ 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)
+- return out_proj(w, b, o, a.o, qmm.group_sums(o, b.xs_ao[:R]), R, site=(layer, "a"))
++ return latent.expand_v(ol, a.absorb, b.vn[rs], prompt=b.prefill and latent.PROMPT_MMA).view(R, HL * c.v_dim)
+
+
+ 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:
+ glue.hc_post(x, x, g, b.post[:R], b.comb[:R])
+
+
+-def split_layers(w: Weights, st: State, b: Buffers, R: int, nch: int | None, host_pos: int | None) -> None:
++def split_layers(w: Weights, st: State, b: Buffers, R: int, nch: int | None, host_pos: int | None,
++ mixer=None) -> None:
+ """Every layer of a prompt chunk with its hyper-connection glue split by rows between the ranks
+ (``hcsplit``): the first hc_pre runs on every row as unsplit, each later one on this rank's rows, and b.normed,
+- the taps and b.hidden come back whole from the peer. The same bits as the unsplit loop and its final mean."""
++ the taps and b.hidden come back whole from the peer. The same bits as the unsplit loop and its final mean.
++ ``mixer``: the layers' KDA / DSA blocks as ``mixer(layer, done)`` instead of on ``st`` (a chunk of several
++ streams' prompts, ``multi_prefill``)."""
+
+ 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
+ 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):
+- _mixer(layer, w, st, b, R, nch, host_pos, None, done)
++ if mixer is not None:
++ mixer(layer, done)
++ else:
++ _mixer(layer, w, st, b, R, nch, host_pos, None, done)
+ 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,
+ if inject is not None:
+ rows, features = inject
+ b.x.index_copy_(0, rows, features.repeat(1, c.streams))
+- if b.prefill and b.split is not None and sparse_np is None and mixer is None and b.split.applies(R):
+- split_layers(w, st, b, R, nch, host_pos) # also leaves the taps and b.hidden[:R]
++ if b.prefill and b.split is not None and sparse_np is None and b.split.applies(R):
++ split_layers(w, st, b, R, nch, host_pos, mixer) # also leaves the taps and b.hidden[:R]
+ else:
+ for layer in w.layers:
+ layer_forward(layer, w, st, b, R, nch, host_pos, sparse_np, mixer)
+diff --git tensorfold/families/glm5_next/cuda/multi.py tensorfold/families/glm5_next/cuda/multi.py
+index 863250c..c0c7dcf 100644
+--- tensorfold/families/glm5_next/cuda/multi.py
++++ tensorfold/families/glm5_next/cuda/multi.py
+@@ -8,7 +8,10 @@ window scratch; a DFlash2 context, ``dflash2_multi.DraftContext``; host side its
+
+ Iterations (``GlmScheduler``, one worker thread on rank 0): admissions, then either one prompt chunk of the oldest
+ filling stream (FIFO, at most TF_GLM_FILL_ROWS rows while others decode, the engine's prompt chunk alone) or one
+-decode round, alternating by TF_GLM_FILL_SHARE; a prompt chunk never shares a forward with decode rows. A round: each
++decode round, alternating by TF_GLM_FILL_SHARE; a prompt chunk never shares a forward with decode rows. With
++TF_GLM_MULTI_PREFILL=1 a prompt chunk holds the next rows of several filling streams (``multi_prefill``: each
++stream's rows get the bits of a chunk of their own; the shortest remaining prompts first, within the same row
++budget). A round: each
+ decoding stream (admission order) proposes drafts under its own DFlash2 policy (copy drafts first), the combined
+ window is capped at ``MAX_WINDOW`` rows (the longest tails trimmed), one verify over every stream's rows
+ (``forward_streams``: ``verify.BatchedVerify``, one forward over every stream's rows through the segmented KDA and
+@@ -16,7 +19,7 @@ DSA kernels, or ``verify.SerialVerify``, the reference running each window as it
+ one packed all-gather for the samplers, each stream accepts and commits its own.
+
+ Rank 0 decides everything that depends on time, clients or placement; rank 1 applies it. Each iteration rank 0 sends
+-ONE message (``GlmEngine._share``): ops ADMIT, EVICT, MOVE, GROW, FILL, ROUND, FINISH, IDLE, which both ranks apply
++ONE message (``GlmEngine._share``): ops ADMIT, EVICT, MOVE, GROW, FILL, MFILL, ROUND, FINISH, IDLE, which both ranks apply
+ in order through the same code (rank 0 as it decides them). Rank 1 derives drafts itself and checks the depths rank 0
+ sent. An idle rank 1 waits on the doorbell (``GlmEngine._await_bell``), not in an all-gather. After an error the two
+ ranks cannot be trusted to agree: ``broken`` latches and every later call fails until both restart.
+@@ -39,13 +42,14 @@ import torch
+ from tensorfold.cuda.scheduler import Scheduler
+ from tensorfold.cuda.streams import Stream, next_fill
+
++from . import multi_prefill
+ from .multi_tune import MultiSettings, RoundProfile, allocate, reach_of, sample_packed, scaled_confidence
+ from .pool import ALIGN, Pool, align_up
+ from .verify import BatchedVerify, Segment, SerialVerify, Verified
+
+-ADMIT, EVICT, MOVE, GROW, FILL, ROUND, FINISH, IDLE, SLOT = range(1, 10)
++ADMIT, EVICT, MOVE, GROW, FILL, ROUND, FINISH, IDLE, SLOT, MFILL = range(1, 11)
+ OPS = {ADMIT: "ADMIT", EVICT: "EVICT", MOVE: "MOVE", GROW: "GROW", FILL: "FILL", ROUND: "ROUND", FINISH: "FINISH",
+- IDLE: "IDLE", SLOT: "SLOT"}
++ IDLE: "IDLE", SLOT: "SLOT", MFILL: "MFILL"}
+
+
+ def watchdog_seconds(value: str | None = None) -> float:
+@@ -100,6 +104,15 @@ def fill_rows(prefill_rows: int, grid: int = 0, value: str | None = None) -> int
+ return rows
+
+
++def fill_unit(grid: int) -> int:
++ """Rows a prompt chunk cut short of a stream's next stop comes in multiples of (a multi-prompt chunk's share of
++ the row budget): 64 and the prompt grid (as TF_GLM_FILL_ROWS), so every cut stays on the grid."""
++
++ import math
++
++ return math.lcm(64, grid) if grid else 64
++
++
+ def fill_share(value: str | None = None) -> float:
+ """TF_GLM_FILL_SHARE: the share of iterations prompt chunks take while other streams decode (default 0.5: a
+ chunk, a round, a chunk, ...); 1 fills every prompt before decoding on."""
+@@ -324,6 +337,15 @@ class MultiDecoder:
+ self.fill_rows = fill_rows(e.prefill_rows, self.grid)
+ self.share = fill_share()
+ self.credit = 0.0
++ # TF_GLM_MULTI_PREFILL: rank 0 groups filling streams into one chunk (rank 1 applies whatever MFILL it gets)
++ self.group = multi_prefill.enabled()
++ if self.group:
++ from . import latent
++
++ if not latent.ENABLED:
++ raise ValueError("TF_GLM_MULTI_PREFILL=1 needs the latent cache (TF_GLM_LATENT=1)")
++ self.unit = fill_unit(self.grid)
++ self.grouped = {"chunks": 0, "pieces": 0, "rows": 0} # rank 0's multi-prompt chunks, for /health
+ self.drafts = drafts
+ if self.drafts is None and engine.drafter is not None:
+ from .dflash2_multi import MultiDrafter
+@@ -390,7 +412,7 @@ class MultiDecoder:
+ "filling": sum(not l.decoding for l in lanes),
+ "paused": sum(l.decoding and l.paused for l in lanes)},
+ "pool_tokens": self.pool.rows, "pool_free_tokens": self.pool.free_rows(),
+- "kept_prompts": len(self.kept)}
++ "kept_prompts": len(self.kept), **({"multi_prefill": dict(self.grouped)} if self.group else {})}
+
+ def _check(self) -> None:
+ if self.broken is not None:
+@@ -881,6 +903,22 @@ class MultiDecoder:
+ def _iterate(self) -> list[Stream]:
+ prof = self.profiles[False] if self.profiles is not None else None # prompt chunks count there
+ lane = self._fill_turn()
++ group = self._group(lane) if lane is not None and self.group else None
++ if group is not None:
++ t = time.perf_counter()
++ rows = sum(stop - l.st.pos for l, stop in group)
++ self._emit(MFILL, [len(group), *[v for l, stop in group for v in (l.sid, stop)]])
++ self._flush()
++ firsts = self._fill_many(group)
++ for (l, _), first in zip(group, firsts):
++ if first is not None:
++ l.s.take([first], self._ends(l))
++ self.grouped["chunks"] += 1
++ self.grouped["pieces"] += len(group)
++ self.grouped["rows"] += rows
++ if prof is not None:
++ prof.fill(time.perf_counter() - t)
++ return [l.s for l, _ in group if l.s.done]
+ if lane is not None:
+ t = time.perf_counter()
+ stop = self._stop(lane)
+@@ -970,6 +1008,39 @@ class MultiDecoder:
+ rows = self.fill_rows if busy or lane.s.background else self.e.prefill_rows
+ return min(stop, pos + rows)
+
++ def _group(self, first: Lane) -> list[tuple[Lane, int]] | None:
++ """Rank 0, TF_GLM_MULTI_PREFILL=1: the (lane, stop) pieces of this iteration's prompt chunk when it can hold
++ more than one stream's rows, else None (``first`` fills alone, as without the setting). The chunk's row budget
++ is the single-stream one (TF_GLM_FILL_ROWS while others decode, else the engine's prompt chunk). Foreground
++ streams before background ones, then the fewest prompt rows left first (a short prompt's first token does not
++ wait behind a long prompt; the long one takes the rest of the budget), then admission order; each takes the
++ rows to its next stop (a kept point or its end) when they fit, else the budget left in whole ``fill_unit``s.
++ Image prompts and replays of a kept head fill alone."""
++
++ def plain(l: Lane) -> bool:
++ return not l.decoding and l.feed is None and l.head is None
++
++ if not plain(first):
++ return None
++ busy = any(l.decoding and not l.s.done for l in self.lanes.values())
++ left = self.fill_rows if busy else self.e.prefill_rows
++ lanes = sorted((l for l in self.lanes.values() if plain(l)),
++ key=lambda l: (bool(l.s.background), len(l.s.prompt) - l.st.pos, l.order))
++ out: list[tuple[Lane, int]] = []
++ for l in lanes:
++ pos, n = l.st.pos, len(l.s.prompt)
++ stop = next((p for p in l.stops if p > pos), n)
++ room = min(left, self.fill_rows if l.s.background else left)
++ if stop - pos > room:
++ stop = pos + room // self.unit * self.unit
++ if stop <= pos:
++ continue
++ out.append((l, stop))
++ left -= stop - pos
++ if left <= 0:
++ break
++ return out if len(out) > 1 else None
++
+ def _ends(self, lane: Lane) -> tuple[int, ...]:
+ return self.eos if lane.s.stop_eos else ()
+
+@@ -978,7 +1049,6 @@ class MultiDecoder:
+ """Both ranks: the lane's prompt rows pos .. stop in one chunk; its kept states; at the prompt's end its first
+ token (the stream then decodes)."""
+
+- from .copy_drafts import CopyDrafts
+ from .decode import prefill_chunk
+
+ e = self.e
+@@ -1012,15 +1082,71 @@ class MultiDecoder:
+ finally:
+ e.use(prev)
+ s.prefill_s += time.perf_counter() - t
++ self._started(lane, first)
++ return first
++
++ def _started(self, lane: Lane, first: int) -> None:
++ """Both ranks: the lane's prompt is in and its first token sampled: it decodes from the next round."""
++
++ from .copy_drafts import CopyDrafts
++
++ s = lane.s
++ prompt = s.prompt
+ lane.decoding = True
+ s.started = time.perf_counter()
+ if lane.policy is not None and self.g.copy is not None:
+ c = self.g.copy # no pads: batched windows are not the single-stream widths
+- lane.copies = CopyDrafts(list(prompt) + [first], c.match, c.most, prompt=n, reply_match=c.reply_match,
+- miss_most=c.miss_most)
++ lane.copies = CopyDrafts(list(prompt) + [first], c.match, c.most, prompt=len(prompt),
++ reply_match=c.reply_match, miss_most=c.miss_most)
+ if lane.policy is not None:
+ lane.depth = min(lane.policy.next(0, 0), s.count - 1)
+- return first
++
++ @torch.no_grad()
++ def _fill_many(self, group: Sequence[tuple[Lane, int]]) -> list[int | None]:
++ """Both ranks, TF_GLM_MULTI_PREFILL: every (lane, stop)'s prompt rows pos .. stop in ONE chunk
++ (``multi_prefill.prefill_pieces``: each lane's rows the bits of a chunk of their own); then per lane, in
++ order, what ``_fill`` does after its chunk: its kept states, and at its prompt's end its first token (all
++ first tokens sampled together, each as alone: ``sample_streams``). Returns each lane's first token or None."""
++
++ e = self.e
++ pieces = []
++ for lane, stop in group:
++ start, n = lane.st.pos, len(lane.s.prompt)
++ if lane.decoding or lane.feed is not None or lane.head is not None:
++ raise RuntimeError(f"stream {lane.sid} cannot join a multi-prompt chunk")
++ if not start < stop <= n or stop - start > e.prefill_rows:
++ raise RuntimeError(f"stream {lane.sid}: a prompt chunk {start} .. {stop} of {n}")
++ pieces.append(multi_prefill.Piece(lane.st, list(lane.s.prompt[start:stop]),
++ drafter=self._ctx(lane) if lane.dflash else None, head=stop == n))
++ t = time.perf_counter()
++ heads = multi_prefill.prefill_pieces(e, pieces)
++ parts, who = [], []
++ for k, ((lane, stop), out) in enumerate(zip(group, heads)):
++ n = len(lane.s.prompt)
++ if stop < n:
++ if stop in lane.stops:
++ self._keep(lane, stop)
++ continue
++ if lane.point == n:
++ self._keep(lane, n, head=out[:1].clone()) # before a grammar's mask writes into the row
++ logits = out[:1]
++ if lane.constraint is not None: # the first token's row, under the reply's grammar
++ lane.constraint.mask(logits, lane.constraint.window([0], [-1]), self.w.vocab_offset)
++ parts.append((logits, [n], lane.s.sampling))
++ who.append(k)
++ firsts: list[int | None] = [None] * len(group)
++ if parts:
++ for k, rows in zip(who, sample_streams(self.w, parts)):
++ lane = group[k][0]
++ firsts[k] = rows[0]
++ if lane.constraint is not None:
++ lane.constraint.advance([rows[0]])
++ dt = time.perf_counter() - t
++ for (lane, _), first in zip(group, firsts):
++ lane.s.prefill_s += dt
++ if first is not None:
++ self._started(lane, first)
++ return firsts
+
+ @torch.no_grad()
+ def _round(self, lanes: list[Lane], depths: list[int] | None = None, lone: bool = False) -> None:
+@@ -1268,6 +1394,16 @@ class MultiDecoder:
+ first = self._fill(lane, p[1])
+ if first is not None:
+ lane.s.take([first], self._ends(lane))
++ elif op == MFILL:
++ group = []
++ for sid, stop in zip(p[1:1 + 2 * p[0]:2], p[2:2 + 2 * p[0]:2]):
++ lane = self.lanes[sid]
++ if stop != self._stop_bound(lane, stop):
++ raise RuntimeError(f"rank 1: stream {sid}'s prompt chunk to {stop} passes a kept point")
++ group.append((lane, stop))
++ for (lane, _), first in zip(group, self._fill_many(group)):
++ if first is not None:
++ lane.s.take([first], self._ends(lane))
+ elif op == ROUND:
+ n = p[0]
+ sids, depths = p[1:1 + 2 * n:2], p[2:2 + 2 * n:2]
+@@ -1299,6 +1435,9 @@ class GlmScheduler(Scheduler):
+
+ def __init__(self, decoder: MultiDecoder, *, max_streams: int) -> None:
+ self.held = None
++ # TF_GLM_MULTI_PREFILL_WAIT_MS: an idle server's wait for requests arriving with the first (their prompts then
++ # share its first chunk); only with TF_GLM_MULTI_PREFILL=1
++ self.gather_s = multi_prefill.wait_ms() / 1000.0 if getattr(decoder, "group", False) else 0.0
+ super().__init__(decoder, max_streams=max_streams)
+
+ def submit(self, prompt: list[int], count: int, sampling: Any, draft: bool,
+@@ -1321,7 +1460,10 @@ class GlmScheduler(Scheduler):
+ else:
+ return value
+
+- def _admit(self, first=None) -> list[Stream]:
++ def _admit(self, first=None, until: float | None = None) -> list[Stream]:
++ """Waiting requests into free slots while they fit; ``until`` (a ``time.monotonic`` deadline): an empty queue
++ is waited on until then for more arrivals."""
++
+ done: list[Stream] = []
+ while self.decoder.live() < self.max_streams:
+ if first is not None:
+@@ -1330,7 +1472,8 @@ class GlmScheduler(Scheduler):
+ item, self.held = self.held, None
+ else:
+ try:
+- item = self.waiting.get_nowait()
++ left = until - time.monotonic() if until is not None else 0.0
++ item = self.waiting.get(timeout=left) if left > 0 else self.waiting.get_nowait()
+ except queue.Empty:
+ break
+ stream, box = item
+@@ -1395,7 +1538,9 @@ class GlmScheduler(Scheduler):
+ def _iteration(self) -> None:
+ self._yield()
+ idle = not self.decoder.live() and self.held is None
+- done = self._admit(self.waiting.get() if idle else None) # idle: wait for a request
++ first = self.waiting.get() if idle else None # idle: wait for a request
++ until = time.monotonic() + self.gather_s if idle and self.gather_s > 0 else None
++ done = self._admit(first, until)
+ try:
+ done += self.decoder.round()
+ except Exception as exc: # noqa: BLE001 (the live requests fail)
+diff --git tensorfold/families/glm5_next/cuda/multi_prefill.py tensorfold/families/glm5_next/cuda/multi_prefill.py
+new file mode 100644
+index 0000000..da57788
+--- /dev/null
++++ tensorfold/families/glm5_next/cuda/multi_prefill.py
+@@ -0,0 +1,185 @@
++"""TF_GLM_MULTI_PREFILL=1 (--parallel): one prompt chunk holds the next rows of several waiting prompts, each prompt's
++rows getting the bits they get in a chunk of their own.
++
++Without it, concurrent requests' prompts are prefilled one stream at a time (``multi.MultiDecoder``: the oldest
++filling stream's chunk, then a decode round, then the next chunk ...), so the last of four short prompts that arrive
++together waits for eight forwards (a 130-token prompt is two chunks: up to its 64-token grid point, where its state
++is kept, then its tail) and the decode rounds between them. A forward's cost is mostly fixed at short lengths (~0.12 s
++on two Sparks, the weights read once a layer whatever the rows), so a chunk of all four prompts costs little more than
++one of them.
++
++A multi-prompt chunk lays its pieces back to back ([s1 rows][s2 rows]...), as a batched verify window does, and runs
++one forward over them on the prompt buffers (``Engine.pbuf``):
++
++- the row-independent work runs once over every row: embedding, hyper-connection glue (split between the ranks,
++ ``hcsplit``, by the chunk's rows), the blocks' fronts (KDA input projections; DSA projections, norms and query
++ expansion), the output projections, the MoE router and routed experts (each pair one fp32 chain: one expert read
++ for every prompt), the shared expert, the final norm. These are the kernels a prompt chunk already relies on to
++ give a row the same bits whatever chunk it came in (``forward``'s module docstring, ``hcsplit``'s fronts);
++- what reads or writes a stream's own state runs piece by piece on that stream's ``forward.State``, through the very
++ calls a chunk of its own makes, with the piece's rows as a view of the buffers: the KDA recurrence, its state commit
++ and conv shift (``forward.kda_rows``, the chunked or serial kernel at the stream's position), and DSA's latent
++ write, indexer update, absorb, dense / sparse attention and expand (``forward.dsa_rows``, at the stream's position
++ with its own extent, index ring and chunk count);
++- after the forward, per piece in order: the head's logits of its last row when the piece ends its prompt (one row,
++ as alone), its DFlash2 taps (its own context), its commit.
++
++So a piece's bits are those of the same rows run as a chunk of their own, from the same position: a valid chunking of
++its prompt (pieces start where its own chunks would, on the prompt grid, and end at its kept points or its end).
++
++Image prompts (rows replaced by the vision tower's output) and replays of a kept prompt's head are not grouped; they
++fill alone as before. The latent cache is required (``latent.ENABLED``, the default)."""
++
++from __future__ import annotations
++
++import os
++from dataclasses import dataclass, field
++from typing import Any, Sequence
++
++import torch
++
++
++def enabled(value: str | None = None) -> bool:
++ """TF_GLM_MULTI_PREFILL: 1 groups waiting prompts into one chunk (rank 0 decides; rank 1 follows its messages),
++ 0 (default) fills them one stream at a time."""
++
++ value = (os.environ.get("TF_GLM_MULTI_PREFILL", "") if value is None else value).strip() or "0"
++ if value not in ("0", "1"):
++ raise ValueError(f"TF_GLM_MULTI_PREFILL: 0 or 1, not {value!r}")
++ return value == "1"
++
++
++def wait_ms(value: str | None = None) -> float:
++ """TF_GLM_MULTI_PREFILL_WAIT_MS: with TF_GLM_MULTI_PREFILL=1, how long an idle server waits after a request
++ arrives for more to arrive with it (so their prompts share the first chunk), ending as soon as every slot is
++ taken; 0 (default): no wait."""
++
++ value = (os.environ.get("TF_GLM_MULTI_PREFILL_WAIT_MS", "") if value is None else value).strip() or "0"
++ try:
++ ms = float(value)
++ except ValueError:
++ ms = -1.0
++ if not 0 <= ms <= 1000:
++ raise ValueError(f"TF_GLM_MULTI_PREFILL_WAIT_MS: milliseconds from 0 to 1000, not {value!r}")
++ return ms
++
++
++@dataclass(eq=False)
++class Piece:
++ """A stream's rows of a multi-prompt chunk: ``tokens`` its prompt from ``st.pos`` on; ``drafter`` its DFlash2
++ context (taps added after the forward) or None; ``head``: the piece ends its prompt (its last row's logits)."""
++
++ st: Any
++ tokens: list[int]
++ drafter: Any = None
++ head: bool = False
++ lo: int = field(default=0, init=False) # its first row in the chunk
++
++ @property
++ def rows(self) -> int:
++ return len(self.tokens)
++
++
++def layout(pieces: Sequence[Piece], rows_max: int) -> int:
++ """Each piece's first row (back to back, in order); the chunk's rows. Pieces need rows, distinct stream slots and
++ disjoint extents; the chunk at most ``rows_max`` rows."""
++
++ if not pieces:
++ raise ValueError("a multi-prompt chunk needs a piece")
++ slots = [p.st.slot for p in pieces]
++ if len(set(slots)) != len(slots):
++ raise ValueError(f"a multi-prompt chunk's pieces share a stream slot: {slots}")
++ spans = sorted((p.st.base, p.st.base + p.st.capacity) for p in pieces)
++ if any(a[1] > b[0] for a, b in zip(spans, spans[1:])):
++ raise ValueError("a multi-prompt chunk's pieces have overlapping extents")
++ at = 0
++ for p in pieces:
++ if p.rows < 1:
++ raise ValueError("a multi-prompt chunk's piece without rows")
++ p.lo = at
++ at += p.rows
++ if at > rows_max:
++ raise ValueError(f"a multi-prompt chunk of {at} rows, the prompt buffers hold {rows_max}")
++ return at
++
++
++class PieceMixer:
++ """The layers' KDA / DSA blocks of a multi-prompt chunk (``forward.compute``'s ``mixer``, ``split_layers``'
++ ``mixer(layer, done)``): fronts and output projection over every row, the stream-state work piece by piece."""
++
++ def __init__(self, w, b, pieces: Sequence[Piece], R: int) -> None:
++ self.w, self.b, self.pieces, self.R = w, b, list(pieces), R
++
++ def __call__(self, layer, done: tuple[int, int] | None = None):
++ from . import prof
++ from .forward import chunks_for, dsa_front, dsa_rows, kda_front, kda_rows, out_proj, undone
++ from . import qmm
++
++ w, b, R = self.w, self.b, self.R
++ if layer.kind == "kda":
++ k = layer.kda
++ with prof.timed("kda"):
++ with prof.timed("kda: projections"):
++ for lo, hi in undone(R, done):
++ kda_front(layer, b, lo, hi)
++ for p in self.pieces:
++ kda_rows(layer, w, p.st, b, p.lo, p.rows)
++ with prof.timed("kda: out + all-gather"):
++ return out_proj(w, b, b.kscratch.out[:R], k.o, None, R, site=(layer.index, "a"))
++ a, c = layer.dsa, w.cfg
++ if a.absorb is None:
++ raise ValueError("multi-prompt chunks need the latent cache (TF_GLM_LATENT=1)")
++ with prof.timed("dsa (total)"):
++ for lo, hi in undone(R, done):
++ dsa_front(layer, w, b, lo, hi)
++ for p in self.pieces:
++ st = p.st
++ di = st.dsa_index[layer.index]
++ dsa_rows(a, w, st.kc[di], st.pos_dev, b, p.rows, chunks_for(st, p.rows),
++ st.index[di] if st.index is not None else None, st.pos, None, layer.index, lo=p.lo)
++ o = b.vn[:R].view(R, a.heads * c.v_dim)
++ return out_proj(w, b, o, a.o, qmm.group_sums(o, b.xs_ao[:R]), R, site=(layer.index, "a"))
++
++
++def _stage(w, b, pieces: Sequence[Piece], R: int) -> None:
++ """Every piece's room checked, the chunk's token ids into the prompt buffers (``forward.stage``'s pinned copy)."""
++
++ from .forward import check_room
++
++ for p in pieces:
++ check_room(w, p.st, p.rows)
++ tokens = [int(t) for p in pieces for t in p.tokens]
++ b.staged.synchronize()
++ b.ids_host[:R].numpy()[:] = tokens
++ b.ids[:R].copy_(b.ids_host[:R], non_blocking=True)
++ b.staged.record()
++
++
++def prefill_pieces(e, pieces: Sequence[Piece]) -> list[torch.Tensor | None]:
++ """One prompt chunk over every piece (``decode.prefill_chunk`` for several streams at once): the forward, then per
++ piece its head's logits row (a copy, [1, V/world]) when it ends its prompt (else None), its DFlash2 taps and its
++ commit (each stream's position advances by its rows)."""
++
++ from . import latent
++ from .forward import commit, compute, mm
++
++ if not latent.ENABLED:
++ raise ValueError("multi-prompt chunks need the latent cache (TF_GLM_LATENT=1)")
++ w, b = e.w, e.pbuf
++ R = layout(pieces, b.rows)
++ _stage(w, b, pieces, R)
++ compute(w, None, b, R, head=False, mixer=PieceMixer(w, b, pieces, R)) # leaves b.fnormed's rows
++ heads: list[torch.Tensor | None] = []
++ for p in pieces:
++ if p.head: # the head on the piece's last row: the one-row matmul a chunk of its own runs
++ r = p.lo + p.rows - 1
++ heads.append(mm(b, b.fnormed[r:r + 1], w.head, b.fxs[r:r + 1], b.logits[:1]).clone())
++ else:
++ heads.append(None)
++ for p in pieces:
++ if p.drafter is not None:
++ p.drafter.add_taps(torch.cat([t[p.lo:p.lo + p.rows] for t in b.taps], dim=1))
++ for p in pieces:
++ commit(w, p.st, b, p.rows, p.rows)
++ return heads
diff --git a/scripts/banner.sh b/scripts/banner.sh
new file mode 100644
index 0000000..6889075
--- /dev/null
+++ b/scripts/banner.sh
@@ -0,0 +1,47 @@
+# The start.sh banner: the TensorFold ribbon as truecolour terminal art, with MIA AI LAB. `banner` prints it on a
+# terminal of 86+ columns, else nothing.
+
+_banner_wide() {
+ printf '%s\n' ' :::::••*+•: ∙ 
+ :::::∙ :***+••: ::••+++**+++++•::  ███╗ ███╗██╗ █████╗ 
+ :•::::∙ ∙ :#**++•••:: :•••••••••++****+++++• ████╗ ████║██║██╔══██╗
+ :•::::::: +*++•:::••••: :•++++•:::::•••••++++•••:  ██╔████╔██║██║███████║
+ •••::::::::∙ *+•::∙∙∙∙:•++*****••:::::::••••++•:  ██║╚██╔╝██║██║██╔══██║
+ •+•••::::::::::::∙•+::∙ ∙:•*+•:∙:+++++••••••+•:  ██║ ╚═╝ ██║██║██║ ██║
+:+++++••••::::::::::•+:∙ :+*#• ∙::•+**+••••:  ╚═╝ ╚═╝╚═╝╚═╝ ╚═╝
+++++++++•••••••••++•:•:∙ ::+*+∙ ::∙∙:::+++•∙ 
++*****++++++++++++: •: ∙::••∙ :: ∙::::•+•  █████╗ ██╗ ██╗ █████╗ ██████╗ 
+ •+*******+*++• :•:: ::: •: :::••+*+  ██╔══██╗██║ ██║ ██╔══██╗██╔══██╗
+ ::••••: ••:::::: ∙••∙::: ∙::::•••++•  ███████║██║ ██║ ███████║██████╔╝
+ :+••::∙ :•: ∙:::::::•••++•:  ██╔══██║██║ ██║ ██╔══██║██╔══██╗
+ :*+•::∙:: ∙::::::••++•  ██║ ██║██║ ███████╗██║ ██║██████╔╝
+ :+••:: ∙∙::  ╚═╝ ╚═╝╚═╝ ╚══════╝╚═╝ ╚═╝╚═════╝ 
+ ∙∙ 
+  GLM-5.3 Flash EXL3 · Dual DGX Sparks
+ TensorFold by Ash Hart '
+}
+
+_banner_narrow() {
+ printf '%s\n' ' ███╗ ███╗██╗ █████╗ 
+ :::::•+•: :::••:::  ████╗ ████║██║██╔══██╗
+ ::::∙ +*++•:: :•:••++***++•• ██╔████╔██║██║███████║
+ •::::: *+•::•••:••++•::::•••++••:  ██║╚██╔╝██║██║██╔══██║
+ :••::::::::∙••:∙ :+*+•:•••••••+•:  ██║ ╚═╝ ██║██║██║ ██║
+•+++••:::::••••∙ ∙:**∙ ∙::+*+••:  ╚═╝ ╚═╝╚═╝╚═╝ ╚═╝
++***++••++++: :: :••∙ :: :::++ 
+ :•++++++•: •:∙ :: •: ∙:::++•  █████╗ ██╗ ██╗ █████╗ ██████╗ 
+ :+•:∙ :: ∙∙::::••++•  ██╔══██╗██║ ██║ ██╔══██╗██╔══██╗
+ :+•::: ∙:::•••  ███████║██║ ██║ ███████║██████╔╝
+ ::∙  ██╔══██║██║ ██║ ██╔══██║██╔══██╗
+ ██║ ██║██║ ███████╗██║ ██║██████╔╝
+ TensorFold by Ash Hart ╚═╝ ╚═╝╚═╝ ╚══════╝╚═╝ ╚═╝╚═════╝ 
+
+  GLM-5.3 Flash EXL3 · Dual DGX Sparks'
+}
+
+banner() {
+ [[ -t 1 ]] || return 0 # a log or a pipe: no art
+ local cols
+ cols=$(tput cols 2>/dev/null || echo 120)
+ if (( cols >= 108 )); then _banner_wide; elif (( cols >= 86 )); then _banner_narrow; fi
+}
diff --git a/scripts/config.sh b/scripts/config.sh
new file mode 100644
index 0000000..441c40e
--- /dev/null
+++ b/scripts/config.sh
@@ -0,0 +1,199 @@
+# Shared settings for start.sh, stop.sh and scripts/*.sh. A setting's value comes from the first of these that sets it:
+# 1. the environment: `PORT=9000 ./start.sh`, `PULL=0 scripts/prepare.sh`
+# 2. scripts/local.sh (this setup's own values, above all WORKER; sourced as bash), then ./.env (KEY=value lines,
+# read, never run): both are yours, not the repository's; where both set a key, local.sh wins
+# 3. the defaults below
+_cfg_root=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
+if [[ -f "$_cfg_root/scripts/local.sh" ]]; then
+ declare -A _cfg_env=()
+ while IFS= read -r _n; do _cfg_env[$_n]=${!_n}; done < <(compgen -e)
+ source "$_cfg_root/scripts/local.sh"
+ # the environment wins over local.sh: put back any variable it had that local.sh changed
+ for _n in "${!_cfg_env[@]}"; do [[ "${!_n-}" == "${_cfg_env[$_n]}" ]] || export "$_n=${_cfg_env[$_n]}"; done
+ unset _cfg_env
+fi
+if [[ -f "$_cfg_root/.env" ]]; then
+ while IFS= read -r _line || [[ -n "$_line" ]]; do
+ [[ "$_line" =~ ^[[:space:]]*(export[[:space:]]+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$ ]] || continue
+ _key=${BASH_REMATCH[2]}; _value=${BASH_REMATCH[3]}
+ if [[ "$_value" =~ ^\"([^\"]*)\"[[:space:]]*(#.*)?$ || "$_value" =~ ^\'([^\']*)\'[[:space:]]*(#.*)?$ ]]; then
+ _value=${BASH_REMATCH[1]}
+ else
+ _value=${_value%%#*}; _value=${_value%"${_value##*[![:space:]]}"}
+ fi
+ [[ -n "${!_key+set}" ]] || export "$_key=$_value"
+ done < "$_cfg_root/.env"
+fi
+unset _n _line _key _value
+
+# The two Sparks: this machine serves rank 0 and the API; WORKER (ssh target, key-based) runs rank 1.
+WORKER="${WORKER:-}" # e.g. user@<worker address>; set it in scripts/local.sh
+FABRIC_PEER="${FABRIC_PEER:-}" # the worker's CX7 address when WORKER is reached over another network
+MASTER_PORT="${MASTER_PORT:-29551}" # TensorFold's rendezvous port between the ranks (keep it on the private link)
+
+MODEL_ID="${MODEL_ID:-Mia-AiLab/GLM-5.3-Flash-EXL3-TR3-4bpw}" # EXL3 routed experts (4 bpw), BF16 elsewhere
+# The checkpoint's revision (a Hugging Face commit sha; DFLASH2_REVISION below is DFlash2's): the one this recipe was
+# measured with. prepare.sh downloads exactly it, start.sh serves that snapshot from the local cache (no network), and
+# a new upstream commit changes nothing here until the pin does. Empty: the Hub's main when first downloaded. The pin
+# belongs to the default MODEL_ID; another MODEL_ID gets no pin unless you set one.
+_rev=""; [[ "$MODEL_ID" == Mia-AiLab/GLM-5.3-Flash-EXL3-TR3-4bpw ]] && _rev=9eaebb7c4e96d983dcd538e18624622ba5b820a8
+MODEL_REVISION="${MODEL_REVISION-$_rev}"
+TF_VERSION="${TF_VERSION:-v0.5.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}}"
+# pip packages the image adds on top of TensorFold (av: video input; xgrammar: response_format / structured outputs);
+# they are part of the image's hash, so a change rebuilds it like a patch does
+IMAGE_EXTRAS="av==18.1.0 xgrammar>=0.2.8,<0.3"
+image_hash() { (cat patches/*.patch 2>/dev/null; echo "$IMAGE_EXTRAS") | sha256sum | cut -c1-12; }
+GHCR_IMAGE="${GHCR_IMAGE:-ghcr.io/miaai-lab/glm-5.3-flash-exl3-2x-dgx-sparks-tensorfold}"
+CONTAINER_NAME="${CONTAINER_NAME:-glm53-flash-tf}" # the same name on both Sparks
+
+SERVED_NAME="${SERVED_NAME:-GLM-5.3-Flash-EXL3}"
+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
+# 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
+# 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
+# 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,684,928 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"
+# Prompt + reply window. With KV=fp8: 1,048,576 (the checkpoint's native window). With KV=bf16: 196,608 with DFlash2
+# (163,840 with VISION=1 and DENSE=fp8 or bf16: the tower costs rank 0 ~66k tokens of window, which q4's smaller
+# weights give back), 524,288 with mtp. start.sh falls back to the largest that fits when a start's memory budget is
+# smaller. 0: the largest the memory affords (then no memory is left to keep other conversations' prompts).
+DENSE="${DENSE:-q4}"
+if [[ "$KV" != bf16 ]]; then _ctx=1048576; elif [[ "$DRAFTER" != dflash2 ]]; then _ctx=524288
+elif [[ "$VISION" == 1 && "$DENSE" != q4 ]]; then _ctx=163840; else _ctx=196608; fi
+CONTEXT="${CONTEXT:-$_ctx}"
+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 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
+# ~1,090 -> ~1,260 tok/s; GSM8K 98.0% and HumanEval 95.1% on both (bf16: 97.2 / 96.3). Lossy: replies differ.
+# fp8: FP8 e4m3 with a scale per row and 128 columns (patch 0002), half bf16's bytes: ~+33% decode over bf16.
+# bf16: the checkpoint as it is.
+export TF_GLM_DENSE="$DENSE"
+# The ranks' all-gathers. roce (default): the small ones (a decode round's partials, the samplers; up to
+# TF_ROCE_MAX_KB below) as one-shot RDMA writes over the Sparks' RoCE link, b12x's transport (patch 0006): 11 us a
+# 16 KiB gather against NCCL's 45; decode +6% (prose 44.2 -> 46.9, code 48.7 -> 51.6). NCCL keeps the rest. nccl: NCCL
+# for all. Same bits.
+COMM="${COMM:-roce}"
+export TF_GLM_COMM="$COMM"
+# The largest all-gather in KiB that goes over RoCE (patch 0006 reads it; a setting, no patch of its own): 512 (default;
+# TensorFold's is 256) also takes the 17-32-row verify windows of concurrent requests: code at 4 streams +1.4%, prose
+# +0.5-1% (two boots each). Same bits.
+export TF_ROCE_MAX_KB="${TF_ROCE_MAX_KB:-512}"
+# Prompt-lookup ("copy") drafts (patch 0007): when the reply's last 8 tokens occurred before, the tokens that followed
+# them are verified ahead of DFlash2's; quote / edit replies +5% (80.3 -> 84.4 tok/s), prose and code unchanged. Exact.
+COPY="${COPY:-1}"
+export TF_GLM_COPY_DRAFTS="$COPY"
+# Copy drafts a round (patch 0013: verify windows up to 16 rows): 15 lets a long quote go through in one round; edit
+# replies 84 -> 119 tok/s, prose and code unchanged (two boots each). Exact.
+COPY_MAX="${COPY_MAX:-15}"
+export TF_GLM_COPY_MAX="$COPY_MAX"
+# How many DFlash2 drafts a round verifies (patch 0018): fnc7:0.3 stops a chain when the product of each draft's chance
+# under the request's own keyed sampling noise drops below 0.3 (up to 7 drafts); prose 47.2 -> 50.6 tok/s, code 51.7 ->
+# 55.5 over fc5:0.3 (two boots each). Drafts only propose: replies are the same under every policy.
+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
+# 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
+# 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
+# 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):
+# +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
+# 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
+# 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
+# (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.
+export TF_GLM_EXL3_LOADS="${TF_GLM_EXL3_LOADS:-nc}"
+# Conversations that share a system prompt reuse its prompt state (patch 0015): a 7.9k-token system prompt's second and
+# later chats prefill in 0.13 s instead of 4.24 s. Same replies. SHARED_PREFIX=0 turns it off.
+SHARED_PREFIX="${SHARED_PREFIX:-1}"
+export TF_GLM_SHARED_PREFIX="$SHARED_PREFIX"
+# The shared KV pool beyond the 1,048,576-token window (kept prompt states, several long conversations at once) grows
+# into the memory left at start. TensorFold sizes it from MemAvailable at start minus MEMORY_RESERVE_GIB
+# (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.7M 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.
+MEMORY_RESERVE_GIB="${MEMORY_RESERVE_GIB:-14.5}"
+export TENSORFOLD_MEMORY_RESERVE_GIB="$MEMORY_RESERVE_GIB"
+KV_POOL_GIB="${KV_POOL_GIB:-11}"
+export TF_GLM_CACHE_GIB="$KV_POOL_GIB"
+
+export TENSORFOLD_NO_UPDATE_CHECK="${TENSORFOLD_NO_UPDATE_CHECK:-1}"
+
+HF_CACHE="${HF_CACHE:-${HF_HOME:-$HOME/.cache/huggingface}}"
+KERNEL_CACHE="${KERNEL_CACHE:-$HOME/.cache/tensorfold-glm53}" # compiled CUDA kernels (written by the containers)
+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;
+# both together when they share a filesystem.
+MIN_FREE_GB="${MIN_FREE_GB:-180}"
+IMAGE_FREE_GB="${IMAGE_FREE_GB:-35}"
+
+# Colours only on a terminal.
+_c() { [[ -t "$1" ]] && printf '\033[%sm' "$2" || true; }
+log() { printf '%s[%s]%s %s\n' "$(_c 1 '1;36')" "$(basename "$0")" "$(_c 1 0)" "$*"; }
+warn() { printf '%s[%s] WARN:%s %s\n' "$(_c 2 '1;33')" "$(basename "$0")" "$(_c 2 0)" "$*" >&2; }
+die() { printf '%s[%s] ERROR:%s %s\n' "$(_c 2 '1;31')" "$(basename "$0")" "$(_c 2 0)" "$*" >&2; exit 1; }
+
+model_cache_dir() { local id=${1:-$MODEL_ID}; echo "$HF_CACHE/hub/models--${id//\//--}"; }
+# model_revision <id>: the pinned revision of MODEL_ID or DFLASH2_ID (empty: none, the cache's refs/main counts)
+model_revision() { if [[ "$1" == "$MODEL_ID" ]]; then echo "$MODEL_REVISION"; elif [[ "$1" == "$DFLASH2_ID" ]]; then echo "$DFLASH2_REVISION"; fi; }
+# snapshot_rev <id>: the snapshot this setup serves: the pin, else what refs/main names on this Spark
+snapshot_rev() { local rev; rev=$(model_revision "$1"); [[ -n "$rev" ]] || rev=$(cat "$(model_cache_dir "$1")/refs/main" 2>/dev/null); echo "$rev"; }
+
+# What scripts/prepare.sh last left ready on both Sparks (it writes this line to PREPARED_MARKER when it succeeds);
+# start.sh runs prepare.sh again whenever the current line differs: a missing or different image on either Spark, new
+# patches, another model, drafter or revision, another worker. Needs scripts/nodes.sh (the worker's image).
+PREPARED_MARKER="$STATE_DIR/prepared"
+prepared_state() {
+ local hash label wlabel
+ hash=$(image_hash)
+ label=$(docker image inspect -f '{{.Id}}' "$IMAGE" 2>/dev/null || echo missing)
+ wlabel=$(worker docker image inspect -f '{{.Id}}' "$IMAGE" 2>/dev/null || echo missing)
+ echo "model=$MODEL_ID@$MODEL_REVISION drafter=$DRAFTER@$DFLASH2_REVISION image=$label worker=$wlabel patches=$hash worker_host=$WORKER"
+}
diff --git a/scripts/local.sh.example b/scripts/local.sh.example
new file mode 100644
index 0000000..5a25e35
--- /dev/null
+++ b/scripts/local.sh.example
@@ -0,0 +1,3 @@
+# Copy to scripts/local.sh (not in git) and fill in this setup's values; scripts/config.sh reads it first.
[email protected] # ssh target of the second Spark (key-based: ssh-copy-id [email protected])
+# FABRIC_PEER=192.0.2.12 # the worker's CX7 address, when WORKER is reached over another network
diff --git a/scripts/nodes.sh b/scripts/nodes.sh
new file mode 100644
index 0000000..59d93a5
--- /dev/null
+++ b/scripts/nodes.sh
@@ -0,0 +1,90 @@
+# The two Sparks: the worker over ssh, and each node's RoCE link found from the route between them.
+# Sourced by start.sh, stop.sh and prepare.sh after config.sh.
+
+# Run a command on the worker (rank 1). Key-based ssh only, no prompts.
+worker() { ssh -o BatchMode=yes -o ConnectTimeout=10 -o ServerAliveInterval=15 "$WORKER" "$@"; }
+
+# The worker's Hugging Face cache: its own HF_HOME, else ~/.cache/huggingface there. prepare.sh copies the checkpoint
+# into it and start.sh mounts it into rank 1.
+worker_hf_cache() { worker 'echo "${HF_HOME:-$HOME/.cache/huggingface}"'; }
+
+need_worker() {
+ [[ -n "${WORKER:-}" ]] || die "WORKER is not set: put WORKER=user@<worker address> in scripts/local.sh (see scripts/local.sh.example)"
+ worker true 2>/dev/null || die "cannot ssh to $WORKER without a password: set up key-based ssh (ssh-copy-id $WORKER)"
+}
+
+# link_info <peer address>: this node's side of the link to <peer>: "<address> <netdev> <rdma device> <gid index>".
+# The netdev and source address come from the route to the peer; the RDMA device from sysfs; the GID index is the
+# RoCE v2 entry that holds this node's IPv4 address (an all-zero or v1 entry makes NCCL fail about a minute in).
+link_info() {
+ local peer=$1 route dev src hca idx type gid want
+ route=$(ip -o -4 route get "$peer" 2>/dev/null) || return 1
+ dev=$(sed -n 's/.* dev \([^ ]*\).*/\1/p' <<<"$route")
+ src=$(sed -n 's/.* src \([^ ]*\).*/\1/p' <<<"$route")
+ hca=$(ls /sys/class/net/"$dev"/device/infiniband 2>/dev/null | head -1)
+ idx=""
+ if [[ -n "$hca" ]]; then
+ want=$(printf '0000:0000:0000:0000:0000:ffff:%02x%02x:%02x%02x' $(tr '.' ' ' <<<"$src"))
+ for f in /sys/class/infiniband/"$hca"/ports/1/gids/*; do
+ gid=$(cat "$f" 2>/dev/null) || continue
+ [[ "$gid" == "$want" ]] || continue
+ type=$(cat /sys/class/infiniband/"$hca"/ports/1/gid_attrs/types/"${f##*/}" 2>/dev/null)
+ [[ "$type" == *"v2"* ]] && { idx=${f##*/}; break; }
+ done
+ fi
+ echo "$src $dev ${hca:--} ${idx:--}"
+}
+
+# rails <netdev> <gid index>: every RoCE device of this node on the link's subnet (the CX7's second port too, when it
+# is up and addressed there) whose RoCE v2 IPv4 GID sits at the same index, the link's own device first.
+rails() {
+ local dev=$1 gid=$2 net cidr hcas other ip idx
+ cidr=$(ip -o -4 addr show dev "$dev" | awk '{print $4}' | head -1)
+ net=$(python3 -c "import ipaddress,sys; print(ipaddress.ip_interface(sys.argv[1]).network)" "$cidr")
+ hcas=$(ls /sys/class/net/"$dev"/device/infiniband | head -1)
+ for n in /sys/class/net/*; do
+ other=${n##*/}
+ [[ "$other" == "$dev" || ! -d $n/device/infiniband || "$(cat $n/operstate 2>/dev/null)" != up ]] && continue
+ ip=$(ip -o -4 addr show dev "$other" | awk '{print $4}' | head -1)
+ [[ -n "$ip" ]] || continue
+ python3 -c "import ipaddress,sys; sys.exit(ipaddress.ip_interface(sys.argv[1]) not in ipaddress.ip_network(sys.argv[2]) and ipaddress.ip_interface(sys.argv[1]).ip not in ipaddress.ip_network(sys.argv[2]))" "$ip" "$net" || continue
+ idx=$(ls $n/device/infiniband | head -1)
+ [[ "$(cat /sys/class/infiniband/$idx/ports/1/gid_attrs/types/$gid 2>/dev/null)" == *v2* ]] || continue
+ hcas+=",$idx"
+ done
+ echo "$hcas"
+}
+
+# The same function on the worker (its definition is sent over ssh).
+worker_link_info() { worker "$(declare -f link_info); link_info $1"; }
+
+# HEAD_ADDR / HEAD_DEV / HEAD_HCA / HEAD_GID and WORKER_ADDR / WORKER_DEV / WORKER_HCA / WORKER_GID: the link the two
+# ranks talk over (NCCL and the rendezvous). FABRIC_PEER overrides the worker's link address when WORKER is reached
+# over another network.
+detect_link() {
+ local peer=${FABRIC_PEER:-${WORKER#*@}}
+ read -r HEAD_ADDR HEAD_DEV HEAD_HCA HEAD_GID <<<"$(link_info "$peer")" || true
+ [[ -n "${HEAD_ADDR:-}" ]] || die "no route from this node to $peer"
+ read -r WORKER_ADDR WORKER_DEV WORKER_HCA WORKER_GID <<<"$(worker_link_info "$HEAD_ADDR")" || true
+ [[ -n "${WORKER_ADDR:-}" ]] || die "the worker has no route back to $HEAD_ADDR"
+ # both CX7 ports when both are cabled and addressed: a prompt chunk's all-gather is ~1.8x faster on two rails
+ HEAD_HCAS=$(rails "$HEAD_DEV" "$HEAD_GID")
+ WORKER_HCAS=$(worker "$(declare -f rails); rails $WORKER_DEV $WORKER_GID")
+ [[ "${NCCL_RAILS:-2}" == 1 ]] && { HEAD_HCAS=$HEAD_HCA; WORKER_HCAS=$WORKER_HCA; }
+ [[ "$(tr ',' '\n' <<<"$HEAD_HCAS" | wc -l)" == "$(tr ',' '\n' <<<"$WORKER_HCAS" | wc -l)" ]] ||
+ { HEAD_HCAS=$HEAD_HCA; WORKER_HCAS=$WORKER_HCA; }
+ for v in HEAD_HCA HEAD_GID WORKER_HCA WORKER_GID; do
+ [[ "${!v}" != "-" ]] || die "no RoCE device or RoCE v2 GID for the link ($v): is $HEAD_DEV / $WORKER_DEV the CX7 port between the Sparks? Set FABRIC_PEER to the worker's CX7 address"
+ done
+}
+
+# NCCL over the RoCE link, per rank: that rank's netdev, RoCE devices (both rails) and GID index, 4 channels.
+# Measured between the Sparks: a decode-sized all-gather 32 us (80 with NCCL's defaults) and a prompt chunk's 32 MB
+# 1.9 ms on two rails (3.5 on one). NCCL's other knobs (protocols, buffer sizes, QPs, NCCL_NET=IB and the like) were no
+# better, and some of them kept NCCL on one rail.
+nccl_env() {
+ local dev=$1 hcas=$2 gid=$3
+ echo "-e NCCL_SOCKET_IFNAME=$dev -e NCCL_IB_HCA=$hcas -e NCCL_IB_GID_INDEX=$gid" \
+ "-e NCCL_MIN_NCHANNELS=${NCCL_CHANNELS:-4} -e NCCL_MAX_NCHANNELS=${NCCL_CHANNELS:-4}" \
+ ${NCCL_DEBUG:+-e NCCL_DEBUG=$NCCL_DEBUG}
+}
diff --git a/scripts/prepare.sh b/scripts/prepare.sh
new file mode 100755
index 0000000..eece0cb
--- /dev/null
+++ b/scripts/prepare.sh
@@ -0,0 +1,194 @@
+#!/usr/bin/env bash
+# Prepare both Sparks to serve Mia-AiLab/GLM-5.3-Flash-EXL3-TR3-4bpw with TensorFold (two ranks):
+# 1. preflight checks: docker and the GPU on both nodes, key-based ssh to the worker, the RoCE link, disk space
+# 2. the image on the head: TensorFold plus patches/*.patch on NVIDIA's PyTorch container, pulled prebuilt from
+# $GHCR_IMAGE when a matching tag is reachable (PULL=0 skips that), else built locally
+# 3. the same image on the worker: pulled there, else streamed from the head (docker save | ssh docker load)
+# 4. download the checkpoint on the head into the Hugging Face cache (~164 GiB, resumable), and DFlash2 too when
+# DRAFTER=dflash2, at their pinned revisions (MODEL_REVISION, DFLASH2_REVISION)
+# 5. verify the checkpoint with `tensorfold info`
+# 6. the same files on the worker, copied from the head over the Sparks' link (rsync), checked file by file
+# ./start.sh runs this by itself when needed. Safe to re-run: every step skips work that is already done.
+# Pass --rebuild to rebuild the image from scratch.
+set -euo pipefail
+cd "$(dirname "$(readlink -f "$0")")/.." # the repository root
+source ./scripts/config.sh
+source ./scripts/nodes.sh
+
+REBUILD=0
+for arg in "$@"; do
+ case "$arg" in
+ --rebuild) REBUILD=1 ;;
+ -h|--help) awk 'NR > 1 && /^#/ { sub(/^# ?/, ""); print; next } NR > 1 { exit }' "$0"; exit 0 ;;
+ *) die "unknown argument: $arg" ;;
+ esac
+done
+
+# ---------------------------------------------------------------- 1. preflight
+mkdir -p "$KERNEL_CACHE" "$STATE_DIR" "$HF_CACHE/hub"
+exec 9>"$STATE_DIR/prepare.lock"
+flock -n 9 || die "another prepare.sh is already running (it holds the download locks); wait for it or stop it: pgrep -af prepare.sh"
+log "Preflight checks on both Sparks"
+command -v docker >/dev/null || die "docker is not installed"
+command -v rsync >/dev/null || die "rsync is not installed on this node (sudo apt install rsync)"
+docker info >/dev/null 2>&1 || die "cannot talk to the docker daemon (is your user in the docker group?)"
+if ! command -v nvidia-smi >/dev/null; then warn "nvidia-smi not found on this node"
+elif ! nvidia-smi -L >/dev/null 2>&1; then warn "nvidia-smi failed on this node: is the NVIDIA driver working?"; fi
+docker info 2>/dev/null | grep -qi nvidia || warn "docker does not list an nvidia runtime on this node; --gpus all may fail"
+need_worker
+worker 'docker info >/dev/null 2>&1' || die "the worker ($WORKER) cannot talk to its docker daemon (docker group?)"
+worker 'nvidia-smi -L >/dev/null 2>&1' || warn "nvidia-smi failed on the worker: is the NVIDIA driver working?"
+worker 'docker info 2>/dev/null | grep -qi nvidia' || warn "docker does not list an nvidia runtime on the worker; --gpus all may fail"
+worker 'command -v rsync >/dev/null' || die "rsync is not installed on the worker (sudo apt install rsync)"
+detect_link
+log "Link: head $HEAD_ADDR ($HEAD_DEV, $HEAD_HCA, GID $HEAD_GID) <-> worker $WORKER_ADDR ($WORKER_DEV, $WORKER_HCA, GID $WORKER_GID)"
+WORKER_HF=$(worker_hf_cache)
+worker "mkdir -p '$WORKER_HF/hub' && test -w '$WORKER_HF/hub'" ||
+ die "the worker's $WORKER_HF/hub is not writable (left root-owned by a container? fix its ownership there)"
+
+PATCHES_HASH=$(image_hash)
+built_hash=$(docker image inspect -f '{{index .Config.Labels "tf.patches"}}' "$IMAGE" 2>/dev/null || true)
+free_gb() { df -BG --output=avail "$1" 2>/dev/null | tail -1 | tr -dc '0-9'; }
+worker_free_gb() { worker "df -BG --output=avail '$1' | tail -1 | tr -dc '0-9'"; }
+# Disk on the head: the checkpoint download (unless its snapshot is here) and the image (unless built from these
+# patches), both on one filesystem when Docker's root shares it with HF_CACHE
+DOCKER_ROOT=$(docker info -f '{{.DockerRootDir}}' 2>/dev/null || echo /var/lib/docker)
+need_ckpt=0; [[ -d "$(model_cache_dir)/snapshots/$(snapshot_rev "$MODEL_ID")" ]] || need_ckpt=$MIN_FREE_GB
+need_img=0; [[ $REBUILD -eq 0 && "$built_hash" == "$PATCHES_HASH" ]] || need_img=$IMAGE_FREE_GB
+if [[ "$(stat -c %d "$HF_CACHE")" == "$(stat -c %d "$DOCKER_ROOT" 2>/dev/null)" ]]; then
+ have=$(free_gb "$HF_CACHE"); (( have >= need_ckpt + need_img )) ||
+ die "only ${have} GB free under $HF_CACHE (also Docker's root); the checkpoint and the image need ~$((need_ckpt + need_img)) GB (MIN_FREE_GB, IMAGE_FREE_GB)"
+else
+ have=$(free_gb "$HF_CACHE"); (( have >= need_ckpt )) ||
+ die "only ${have} GB free under $HF_CACHE; the checkpoint needs ~${need_ckpt} GB (MIN_FREE_GB)"
+ have=$(free_gb "$DOCKER_ROOT"); (( have >= need_img )) ||
+ die "only ${have} GB free under Docker's root ($DOCKER_ROOT); the image needs ~${need_img} GB (IMAGE_FREE_GB)"
+fi
+WORKER_DOCKER_ROOT=$(worker "docker info -f '{{.DockerRootDir}}'" 2>/dev/null || echo /var/lib/docker)
+log "Disk: $(free_gb "$HF_CACHE") GB free under $HF_CACHE here, $(worker_free_gb "$WORKER_HF") GB under $WORKER_HF on the worker"
+
+# ---------------------------------------------------------------- 2. image (head)
+# Local fixes in ./patches (unified diffs against site-packages, applied with patch -p0) are baked into the image.
+# The image is rebuilt when they (or IMAGE_EXTRAS) change; the TensorFold install layer stays cached, so that takes seconds.
+prebuilt="$GHCR_IMAGE:${TF_VERSION}-${PATCHES_HASH}"
+if [[ $REBUILD -eq 0 && "${PULL:-1}" == 1 && "$built_hash" != "$PATCHES_HASH" ]]; then
+ log "Pulling the prebuilt image $prebuilt (PULL=0 builds instead)"
+ if docker pull "$prebuilt" &&
+ [[ "$(docker image inspect -f '{{index .Config.Labels "tf.patches"}}' "$prebuilt")" == "$PATCHES_HASH" ]]; then
+ docker tag "$prebuilt" "$IMAGE"; built_hash=$PATCHES_HASH
+ log "Using $prebuilt as $IMAGE"
+ else
+ warn "could not pull $prebuilt (no image for these patches, the package is not public, or no network): building it locally"
+ fi
+fi
+if [[ $REBUILD -eq 1 || "$built_hash" != "$PATCHES_HASH" ]]; then
+ docker image inspect "$BASE_IMAGE" >/dev/null 2>&1 && [[ $REBUILD -eq 0 ]] || { log "Pulling base image $BASE_IMAGE"; docker pull "$BASE_IMAGE"; }
+ log "Building $IMAGE (TensorFold $TF_VERSION, patches $PATCHES_HASH: $(compgen -G 'patches/*.patch' | wc -l) patches, plus $IMAGE_EXTRAS)"
+ nocache=(); [[ $REBUILD -eq 1 ]] && nocache=(--no-cache)
+ docker build "${nocache[@]}" -t "$IMAGE" --build-arg BASE_IMAGE="$BASE_IMAGE" \
+ --build-arg TF_SPEC="git+${TF_REPO}@${TF_VERSION}" --build-arg PATCHES_HASH="$PATCHES_HASH" --build-arg EXTRAS="$IMAGE_EXTRAS" \
+ -f - patches <<'DOCKERFILE'
+ARG BASE_IMAGE=nvcr.io/nvidia/pytorch:26.07-py3
+FROM ${BASE_IMAGE}
+ARG TF_SPEC
+ARG EXTRAS
+RUN pip install --no-cache-dir --upgrade "${TF_SPEC}" && pip install --no-cache-dir ${EXTRAS} && tensorfold --version
+COPY . /opt/tf-patches
+RUN cd "$(python -c 'import os, tensorfold; print(os.path.dirname(os.path.dirname(tensorfold.__file__)))')" && \
+ for p in /opt/tf-patches/*.patch; do [ -e "$p" ] || continue; echo "applying $p"; patch -p0 --forward < "$p" || exit 1; done && \
+ python -c "import tensorfold.cuda.server, tensorfold.families.glm5_next.cuda.engine, tensorfold.vision.glm, av, xgrammar"
+ARG PATCHES_HASH
+LABEL tf.patches=${PATCHES_HASH}
+ENV HF_HOME=/root/.cache/huggingface TORCH_EXTENSIONS_DIR=/cache/torch_extensions TRITON_CACHE_DIR=/cache/triton
+WORKDIR /workspace
+DOCKERFILE
+else
+ log "Image $IMAGE already built with patches $PATCHES_HASH (use --rebuild to force)"
+fi
+docker run --rm --entrypoint tensorfold "$IMAGE" --version 2>/dev/null | tail -1
+
+# ---------------------------------------------------------------- 3. image (worker)
+image_id=$(docker image inspect -f '{{.Id}}' "$IMAGE")
+if [[ "$(worker docker image inspect -f '{{.Id}}' "$IMAGE" 2>/dev/null)" != "$image_id" ]]; then
+ wfree=$(worker_free_gb "$WORKER_DOCKER_ROOT")
+ (( wfree >= IMAGE_FREE_GB )) ||
+ die "only ${wfree} GB free under the worker's Docker root ($WORKER_DOCKER_ROOT); the image needs ~${IMAGE_FREE_GB} GB (IMAGE_FREE_GB)"
+ if [[ "${PULL:-1}" == 1 ]] && worker docker pull "$prebuilt" >/dev/null 2>&1 &&
+ [[ "$(worker docker image inspect -f '{{.Id}}' "$prebuilt")" == "$image_id" ]]; then
+ worker docker tag "$prebuilt" "$IMAGE"
+ log "Using $prebuilt as $IMAGE on the worker"
+ else
+ log "Copying $IMAGE to the worker (docker save | docker load; only missing layers are stored)"
+ docker save "$IMAGE" | worker docker load >/dev/null
+ fi
+ [[ "$(worker docker image inspect -f '{{.Id}}' "$IMAGE")" == "$image_id" ]] || die "the worker's $IMAGE differs from the head's"
+fi
+log "Image $IMAGE identical on both Sparks"
+
+# ---------------------------------------------------------------- 4. download (head)
+# One revision on both ranks: MODEL_REVISION / DFLASH2_REVISION (config.sh; empty: what the Hub calls main when first
+# downloaded, then kept).
+command -v hf >/dev/null || warn "host 'hf' CLI not found, downloading from inside the container"
+download() { # <repo id> <revision or empty>
+ if command -v hf >/dev/null; then
+ # Host CLI: resumable, parallel, writes the standard HF cache layout.
+ hf download "$1" ${2:+--revision "$2"} --cache-dir "$HF_CACHE/hub" >/dev/null
+ else
+ docker run --rm --network host --entrypoint python ${HF_TOKEN:+-e HF_TOKEN} \
+ -v "$HF_CACHE":/root/.cache/huggingface "$IMAGE" -c \
+ 'import sys; from huggingface_hub import snapshot_download; snapshot_download(sys.argv[1], revision=sys.argv[2] or None)' "$1" "$2"
+ fi
+}
+models=("$MODEL_ID"); [[ "$DRAFTER" == dflash2 ]] && models+=("$DFLASH2_ID")
+for id in "${models[@]}"; do
+ pin=$(model_revision "$id"); dir=$(model_cache_dir "$id")
+ log "Downloading $id${pin:+ @ ${pin:0:8}} into $HF_CACHE/hub (resumes if interrupted)"
+ if ! download "$id" "$pin"; then
+ # no network: a pinned snapshot already here is enough (serving reads the local cache only)
+ [[ -n "$pin" && -f "$dir/snapshots/$pin/config.json" ]] || die "$id: the download failed"
+ warn "$id: could not reach Hugging Face; using the snapshot already here (${pin:0:8})"
+ fi
+ # a download by commit sha writes no refs/main: name the pin there when nothing else is (tools that take repo ids)
+ [[ -z "$pin" || -f "$dir/refs/main" ]] || { mkdir -p "$dir/refs"; printf %s "$pin" > "$dir/refs/main"; }
+ rev=$(snapshot_rev "$id")
+ [[ -n "$rev" && -d "$dir/snapshots/$rev" ]] || die "$id: no snapshot${rev:+ $rev} after the download"
+ log "Checkpoint: $dir/snapshots/$rev ($(du -shL "$dir/snapshots/$rev" | cut -f1))"
+done
+
+# ---------------------------------------------------------------- 5. verify (head)
+# before the copy: the worker gets only a checkpoint TensorFold reads
+log "Verifying checkpoint with tensorfold info"
+docker run --rm --entrypoint tensorfold -e HF_HUB_OFFLINE=1 -v "$HF_CACHE":/root/.cache/huggingface "$IMAGE" \
+ info "/root/.cache/huggingface/hub/models--${MODEL_ID//\//--}/snapshots/$(snapshot_rev "$MODEL_ID")"
+
+# ---------------------------------------------------------------- 6. the same files on the worker
+for id in "${models[@]}"; do
+ dir=$(model_cache_dir "$id"); rev=$(snapshot_rev "$id")
+ # every file of the snapshot, with its size (links followed), as the head has it
+ manifest=$(cd "$dir/snapshots/$rev" && find -L . -type f -printf '%P %s\n' | sort)
+ wdir="$WORKER_HF/hub/${dir##*/}"
+ have=$(worker "cd '$wdir/snapshots/$rev' 2>/dev/null && find -L . -type f -printf '%P %s\n' | sort" || true)
+ if [[ "$have" == "$manifest" ]]; then
+ log "Worker has $id @ ${rev:0:8}"
+ continue
+ fi
+ need=$(( $(du -sLB1G "$dir/snapshots/$rev" | cut -f1) + 5 ))
+ wfree=$(worker_free_gb "$WORKER_HF")
+ (( wfree >= need )) || die "only ${wfree} GB free under $WORKER_HF on the worker, $id needs ~${need} GB"
+ log "Copying $id @ ${rev:0:8} to the worker over the Sparks' link (~${need} GB, resumes)"
+ worker "mkdir -p '$wdir/refs' '$wdir/snapshots'"
+ # the blobs this revision uses, then its snapshot links and refs/main (the cache layout huggingface_hub keeps)
+ (cd "$dir" && find "snapshots/$rev" -type l -printf '%l\n' | sed 's#^\(\.\./\)*##' | sort -u) > "$STATE_DIR/blobs"
+ rsync -a --partial --files-from="$STATE_DIR/blobs" "$dir/" "$WORKER:$wdir/" \
+ -e "ssh -o BatchMode=yes" ${RSYNC_OPTS:-}
+ rsync -a "$dir/snapshots/$rev" "$WORKER:$wdir/snapshots/" -e "ssh -o BatchMode=yes"
+ # refs/main as the head has it (with a pin: only when the worker has none)
+ if [[ -z "$(model_revision "$id")" ]]; then worker "printf %s '$rev' > '$wdir/refs/main'"
+ else worker "test -f '$wdir/refs/main' || printf %s '$rev' > '$wdir/refs/main'"; fi
+ have=$(worker "cd '$wdir/snapshots/$rev' && find -L . -type f -printf '%P %s\n' | sort")
+ [[ "$have" == "$manifest" ]] || die "the worker's copy of $id differs from the head's after the copy"
+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."
diff --git a/scripts/publish-image.sh b/scripts/publish-image.sh
new file mode 100755
index 0000000..0e0723b
--- /dev/null
+++ b/scripts/publish-image.sh
@@ -0,0 +1,40 @@
+#!/usr/bin/env bash
+# Push the image scripts/prepare.sh built to GitHub Container Registry as $GHCR_IMAGE:<TensorFold version>-<image hash>
+# and :latest, labelled with this repository (so the package takes the repository's visibility and access).
+# The image hash is config.sh's image_hash (patches/*.patch plus IMAGE_EXTRAS), the same value prepare.sh writes into
+# the image's tf.patches label and looks for when it pulls: prepare.sh pulls $GHCR_IMAGE:<TensorFold version>-<hash>.
+# Run it on the head Spark (the one that runs ./start.sh); the worker gets the image from the head or the registry.
+# Needs a GitHub token with write:packages: `gh auth login -s write:packages`, or GHCR_TOKEN / GITHUB_TOKEN set.
+# Usage: scripts/publish-image.sh
+set -euo pipefail
+cd "$(dirname "$(readlink -f "$0")")/.."
+source ./scripts/config.sh
+
+REPO_URL="${REPO_URL:-https://github.com/MiaAI-Lab/GLM-5.3-Flash-EXL3-2x-DGX-Sparks-TensorFold}"
+docker image inspect "$IMAGE" >/dev/null 2>&1 || die "image $IMAGE missing, run scripts/prepare.sh first"
+hash=$(docker image inspect -f '{{index .Config.Labels "tf.patches"}}' "$IMAGE")
+[[ "$hash" == "$(image_hash)" ]] ||
+ die "$IMAGE was built from other patches or extras ($hash, not $(image_hash)); run scripts/prepare.sh first"
+tag="${TF_VERSION}-${hash}"
+
+token="${GHCR_TOKEN:-${GITHUB_TOKEN:-$(gh auth token 2>/dev/null || true)}}"
+[[ -n "$token" ]] || die "no GitHub token: run gh auth login -s write:packages, or set GHCR_TOKEN"
+user="${GHCR_USER:-$(gh api user --jq .login 2>/dev/null || echo "${GHCR_IMAGE#ghcr.io/}" | cut -d/ -f1)}"
+
+log "Labelling $IMAGE as $GHCR_IMAGE:$tag"
+docker build -q -t "$GHCR_IMAGE:$tag" -t "$GHCR_IMAGE:latest" \
+ --label org.opencontainers.image.source="$REPO_URL" \
+ --label org.opencontainers.image.licenses=Apache-2.0 \
+ --label org.opencontainers.image.description="GLM-5.3-Flash EXL3 on two DGX Sparks: TensorFold $TF_VERSION with patches $hash" \
+ - <<<"FROM $IMAGE" >/dev/null
+# the labels above sit on top of the built image: its tf.patches label must come through unchanged
+[[ "$(docker image inspect -f '{{index .Config.Labels "tf.patches"}}' "$GHCR_IMAGE:$tag")" == "$hash" ]] ||
+ die "$GHCR_IMAGE:$tag lost its tf.patches label"
+log "Pushing $GHCR_IMAGE:$tag and :latest (~25 GB uncompressed; only changed layers upload)"
+# log in with a throwaway Docker config, so no registry credential stays in ~/.docker after the push
+login_dir=$(mktemp -d)
+trap 'rm -rf -- "$login_dir"' EXIT
+echo "$token" | DOCKER_CONFIG="$login_dir" docker login ghcr.io -u "$user" --password-stdin >/dev/null
+DOCKER_CONFIG="$login_dir" docker push "$GHCR_IMAGE:$tag"
+DOCKER_CONFIG="$login_dir" docker push "$GHCR_IMAGE:latest"
+log "Done: docker pull $GHCR_IMAGE:$tag"
diff --git a/start.sh b/start.sh
new file mode 100755
index 0000000..881114f
--- /dev/null
+++ b/start.sh
@@ -0,0 +1,327 @@
+#!/usr/bin/env bash
+# Serve GLM-5.3 Flash EXL3 (Mia-AiLab/GLM-5.3-Flash-EXL3-TR3-4bpw) with TensorFold on two DGX Sparks, end to end:
+# runs scripts/prepare.sh on both Sparks when the image or the checkpoint is not ready yet (first run, or after patches
+# change), starts rank 1 on the worker and rank 0 here, which serves the API on port 8888, waits until the OpenAI API
+# answers, then runs a smoke test. Stop it with ./stop.sh.
+#
+# Usage: ./start.sh [restart] [extra tensorfold serve args]
+# ./start.sh # scripts/config.sh defaults: 4 requests at once, a 1,048,576-token window,
+# # FP8 KV cache, DFlash2 drafts, 4-bit dense weights, images and video
+# # (if the server already runs, says so and leaves it alone)
+# ./start.sh restart # stop both ranks (./stop.sh), then start them again, e.g. to apply changed
+# # settings or patches; the new arguments are checked before stopping
+# ./start.sh restart --parallel 2 --context 524288
+# CONTEXT=131072 ./start.sh restart
+# KV=bf16 ./start.sh restart # the exact bf16 KV cache (and a 196,608 window)
+# DRAFTER=mtp ./start.sh restart # the checkpoint's own MTP head instead of DFlash2 (one request at a time)
+# Extra arguments go to both ranks after the defaults, so they win (the last value of a flag counts).
+# Setup: WORKER=user@<worker address> in scripts/local.sh (key-based ssh).
+# Settings, from the environment, scripts/local.sh or ./.env (defaults and measured effects in scripts/config.sh):
+# serving CONTEXT, PARALLEL, KV, DENSE, DRAFTER, DRAFT_POLICY, COPY, COPY_MAX, COPY_CODE, SPLIT, KDA_CHUNKED,
+# SHARED_PREFIX, MULTI_PREFILL, KV_POOL_GIB, MEMORY_RESERVE_GIB, 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,
+# STATE_DIR, HF_HUB_OFFLINE=0 (let TensorFold reach the Hub; default serves from the local cache only)
+# image IMAGE, TF_VERSION, TF_REPO, BASE_IMAGE, GHCR_IMAGE, CONTAINER_NAME
+# setup PREPARE (auto | 1 | 0), PULL, MIN_FREE_GB, IMAGE_FREE_GB, RSYNC_OPTS, HF_TOKEN (prepare.sh's downloads);
+# FOREGROUND=1 (stay attached to rank 0's log, exit with its code); WAIT_TIMEOUT (seconds, default 1800);
+# STOP_TIMEOUT (stop.sh)
+# decode TF_GLM_L2PF (1), TF_GLM_EXL3_LOADS (nc), TF_ROCE_MAX_KB (512), TF_GLM_MULTI_LONE (1)
+# ranks every TENSORFOLD_*, TF_GLM_* and TF_ROCE_* variable goes to both ranks, e.g.
+# TENSORFOLD_GLM_IMAGE_TOKENS, TENSORFOLD_MEMORY_RESERVE_GIB, TF_GLM_KEEP_REASONING=0
+set -euo pipefail
+cd "$(dirname "$(readlink -f "$0")")"
+source ./scripts/config.sh
+source ./scripts/nodes.sh
+
+usage() { awk 'NR > 1 && /^#/ { sub(/^# ?/, ""); print; next } NR > 1 { exit }' "$0"; }
+WAIT_TIMEOUT="${WAIT_TIMEOUT:-1800}"
+MODE=start
+case "${1:-}" in
+ restart) MODE=restart; shift ;;
+ help) usage; exit 0 ;;
+esac
+for arg in "$@"; do [[ "$arg" == -h || "$arg" == --help ]] && { usage; exit 0; }; done
+
+# 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")
+[[ "$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"
+[[ "$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
+[[ "$KV_POOL_GIB" =~ ^[0-9]+([.][0-9]+)?$ ]] || die "KV_POOL_GIB is a number of GiB, not $KV_POOL_GIB"
+[[ "$MEMORY_RESERVE_GIB" =~ ^[0-9]+([.][0-9]+)?$ ]] || die "MEMORY_RESERVE_GIB is a number of GiB, not $MEMORY_RESERVE_GIB"
+[[ "$COPY_MAX" =~ ^([1-9]|1[0-5])$ ]] || die "COPY_MAX is 1 to 15, not $COPY_MAX"
+[[ "$DRAFT_POLICY" == f* ]] || die "DRAFT_POLICY is a DFlash2 policy (fc5:0.3, fnc7:0.3, fcost7:noisy ...), not $DRAFT_POLICY"
+# decode settings the ranks read at load (scripts/config.sh): checked here so a typo fails before anything is stopped
+[[ "$TF_GLM_MULTI_LONE" =~ ^[01]$ ]] || die "TF_GLM_MULTI_LONE is 0 or 1, not $TF_GLM_MULTI_LONE"
+[[ "$TF_GLM_L2PF" =~ ^(0|off|1|bulk|lines|touch)$ ]] || die "TF_GLM_L2PF is 0, 1 (bulk), lines or touch, not $TF_GLM_L2PF"
+[[ "$TF_GLM_EXL3_LOADS" =~ ^(0|ldg|1|nc|nc1|nc2|nc4)$ ]] || die "TF_GLM_EXL3_LOADS is 0, nc, nc2 or nc4, not $TF_GLM_EXL3_LOADS"
+[[ "$TF_ROCE_MAX_KB" =~ ^[1-9][0-9]*$ ]] || die "TF_ROCE_MAX_KB is a size in KiB (512: up to 32-row windows over RoCE), not $TF_ROCE_MAX_KB"
+if [[ "$THINKING" == 1 ]]; then SERVE_ARGS+=(--thinking); else SERVE_ARGS+=(--no-thinking); fi
+[[ "$VISION" == 1 ]] && SERVE_ARGS+=(--vision)
+[[ "$VISION" == 1 && "$VISION_URLS" == 1 ]] && SERVE_ARGS+=(--vision-urls)
+SERVE_ARGS+=("$@")
+# The effective value of a flag (its last occurrence, as --flag value or --flag=value).
+arg_value() {
+ local flag=$1 value="" i
+ for (( i = 0; i < ${#SERVE_ARGS[@]}; i++ )); do
+ case "${SERVE_ARGS[i]}" in
+ "$flag") value="${SERVE_ARGS[i + 1]:-}" ;;
+ "$flag="*) value="${SERVE_ARGS[i]#*=}" ;;
+ esac
+ done
+ echo "$value"
+}
+# Where to reach the server from this machine: a wildcard bind answers on loopback.
+API_HOST="$HOST"; [[ "$HOST" == 0.0.0.0 || "$HOST" == "::" ]] && API_HOST=127.0.0.1
+[[ "$API_HOST" == *:* ]] && API_HOST="[$API_HOST]"
+URL="http://$API_HOST:$PORT"
+
+running_here() { [[ "$(docker inspect -f '{{.State.Running}}' "$CONTAINER_NAME" 2>/dev/null)" == true ]]; }
+running_worker() { [[ "$(worker docker inspect -f '{{.State.Running}}' "$CONTAINER_NAME" 2>/dev/null)" == true ]]; }
+served_name() {
+ curl -s --max-time 5 "$URL/v1/models" 2>/dev/null |
+ python3 -c 'import json,sys; print(json.load(sys.stdin)["data"][0]["id"])' 2>/dev/null
+}
+
+# ---------------------------------------------------------------- banner and progress
+B=$'\033[1m'; M=$'\033[1;35m'; G=$'\033[1;32m'; D=$'\033[2m'; R=$'\033[0m'
+[[ -t 1 ]] || { B=; M=; G=; D=; R=; }
+source ./scripts/banner.sh
+echo
+banner # the TensorFold ribbon and MIA AI LAB (terminals only)
+printf '\n%s Mia'"'"'s TensorFold Start Script%s\n' "$M" "$R"
+printf '%s %s · 2 x DGX Spark · %s at once · %s-token window · %s KV · %s drafts · port %s%s\n\n' "$D" "$MODEL_ID" \
+ "$(arg_value --parallel)" "$(arg_value --context)" "$KV" "$DRAFTER" "$PORT" "$R"
+STEPS=5
+step() { printf '%s[%s/%s]%s %s%s%s\n' "$M" "$1" "$STEPS" "$R" "$B" "$2" "$R"; }
+
+command -v docker >/dev/null || die "docker is not installed"
+mkdir -p "$KERNEL_CACHE" "$STATE_DIR"
+exec 8>"$STATE_DIR/start.lock"
+flock -n 8 || die "another ./start.sh is already running; wait for it to finish"
+need_worker
+
+# ---------------------------------------------------------------- already running?
+if [[ "$MODE" == start ]] && running_here && running_worker; then
+ log "$CONTAINER_NAME is already running on both Sparks (model: $(served_name || echo "not answering yet"), port $PORT): nothing to do."
+ log "Use ./start.sh restart to restart it (e.g. with new settings), or ./stop.sh to stop it."
+ exit 0
+fi
+
+# ---------------------------------------------------------------- 1. setup
+# scripts/prepare.sh (image and checkpoint on both Sparks) runs whenever what it last prepared differs from now: the
+# first run, new patches, another model, drafter or worker. PREPARE=1 forces it, PREPARE=0 skips it.
+step 1 "Setup: image and checkpoint on both Sparks"
+if [[ "${PREPARE:-auto}" == 1 || ( "${PREPARE:-auto}" != 0 && "$(prepared_state 2>/dev/null)" != "$(cat "$PREPARED_MARKER" 2>/dev/null)" ) ]]; then
+ log "Not ready yet: running scripts/prepare.sh (the first time this pulls the image, downloads ~166 GiB and copies both to the worker)"
+ ./scripts/prepare.sh
+else
+ log "Ready: $IMAGE and $MODEL_ID on both Sparks${PREPARE:+ (PREPARE=$PREPARE)}"
+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"
+# The snapshots both ranks serve (config.sh's pins, else refs/main), as paths under the containers' cache mount: the
+# ranks read them offline, whatever the Hub's main is now. The worker's cache is its own HF_HOME (prepare.sh copies
+# into the same place).
+WORKER_HF=$(worker_hf_cache)
+snapshot() { # <repo id>: its snapshot path in the container, checked on both Sparks
+ local id=$1 rev sub
+ rev=$(snapshot_rev "$id")
+ [[ -n "$rev" ]] || die "$id not in $HF_CACHE: $why download it"
+ sub="hub/models--${id//\//--}/snapshots/$rev"
+ [[ -f "$HF_CACHE/$sub/config.json" ]] || die "$id @ ${rev:0:8} not in $HF_CACHE: $why download it"
+ worker "test -f '$WORKER_HF/$sub/config.json'" || die "$id @ ${rev:0:8} not on the worker ($WORKER_HF): $why copy it there"
+ echo "/root/.cache/huggingface/$sub"
+}
+MODEL_ARG=$(snapshot "$MODEL_ID")
+if [[ "$DRAFTER" == dflash2 ]]; then DRAFTER_ARG=$(snapshot "$DFLASH2_ID")
+else DRAFTER_ARG=none; fi # the checkpoint's MTP head, even when DFlash2 is downloaded
+SERVE_ARGS=(--drafter "$DRAFTER_ARG" "${SERVE_ARGS[@]}") # a --drafter on the command line comes later and wins
+
+# ---------------------------------------------------------------- 2. checks
+step 2 "Checks: arguments, link, previous server, port, memory"
+# tensorfold's own parser, in a throwaway container without the GPU: a typo fails here, before anything is stopped
+docker run --rm --entrypoint python "$IMAGE" -c \
+ 'import sys; from tensorfold.cli import build_parser; build_parser().parse_args(sys.argv[1:])' \
+ serve "$MODEL_ARG" --tp 2 --rank 0 --master 127.0.0.1 --host "$HOST" --port "$PORT" "${SERVE_ARGS[@]}" >/dev/null ||
+ die "tensorfold serve rejects these arguments (see above); nothing was changed"
+detect_link
+log "Link: $HEAD_ADDR ($HEAD_DEV) <-> $WORKER_ADDR ($WORKER_DEV), RoCE $HEAD_HCAS / $WORKER_HCAS"
+here_up=0; running_here && here_up=1
+worker_up=0; running_worker && worker_up=1
+if (( here_up || worker_up )); then # after the setup and the checks: down only while restarting,
+ if [[ "$MODE" == start ]]; then # or when a start that failed halfway left one rank up
+ if (( here_up )); then log "Only rank 0 is running (here): stopping it, then starting both ranks"
+ else log "Only rank 1 is running (on $WORKER): stopping it, then starting both ranks"; fi
+ fi
+ ./stop.sh
+fi
+left_here=0; docker ps -a --format '{{.Names}}' | grep -qx "$CONTAINER_NAME" && left_here=1
+left_worker=0; worker "docker ps -a --format '{{.Names}}' | grep -qx '$CONTAINER_NAME'" 2>/dev/null && left_worker=1
+if (( left_here || left_worker )); then
+ where="on both Sparks"; (( left_worker )) || where="here"; (( left_here )) || where="on the worker"
+ log "Removing the previous (stopped) container $CONTAINER_NAME $where"
+ (( left_here == 0 )) || docker rm -f "$CONTAINER_NAME" >/dev/null
+ (( left_worker == 0 )) || worker "docker rm -f '$CONTAINER_NAME' >/dev/null"
+fi
+if ss -ltn "sport = :$PORT" 2>/dev/null | grep -q LISTEN; then
+ die "port $PORT is already in use: $(ss -ltnp "sport = :$PORT" 2>/dev/null | tail -n +2)"
+fi
+# TensorFold budgets each Spark's free memory minus MEMORY_RESERVE_GIB (14.5); the defaults want ~110 GiB free at start on each.
+# With less, rank 0 refuses the window and names one that fits, which the load below then starts again with.
+here_gb=$(free -g | awk '/^Mem:/ {print $7}')
+there_gb=$(worker "free -g | awk '/^Mem:/ {print \$7}'")
+if (( here_gb >= 110 && there_gb >= 110 )); then
+ log "Arguments OK, port $PORT free, ${here_gb} GiB memory available here, ${there_gb} GiB on the worker"
+else
+ (( here_gb >= 110 )) ||
+ warn "only ${here_gb} GiB memory available here (the default needs ~110): stop other GPU workloads (docker ps), or lower CONTEXT"
+ (( there_gb >= 110 )) ||
+ warn "only ${there_gb} GiB memory available on the worker (the default needs ~110): stop other GPU workloads there (ssh $WORKER docker ps), or lower CONTEXT"
+fi
+
+# TensorFold's own switches (TENSORFOLD_*, TF_GLM_*, TF_ROCE_*) reach both ranks with their values: rank 1's docker
+# command runs over ssh, where this shell's environment does not reach. None of them is a secret.
+ENV_ARGS=(-e HF_HUB_OFFLINE="${HF_HUB_OFFLINE:-1}")
+while IFS='=' read -r name _; do ENV_ARGS+=(-e "$name=${!name}"); done < <(env | grep -E '^(TENSORFOLD|TF_GLM|TF_ROCE)_[A-Z0-9_]+=' || true)
+RUN_ARGS=(--gpus all --ipc=host --network host --shm-size 16g --device /dev/infiniband --cap-add IPC_LOCK
+ --ulimit memlock=-1 --ulimit stack=67108864)
+
+# ---------------------------------------------------------------- 3. launch, 4. load (a second try when the window does not fit)
+# No token goes into the containers: the ranks read only the local cache (HF_HUB_OFFLINE=1), and with HF_HUB_OFFLINE=0
+# huggingface_hub finds the token file in the mounted cache.
+launch() {
+ local rank1 rank0 worker_cmd remote a
+ rank1=(tensorfold serve "$MODEL_ARG" --tp 2 --rank 1 --master "$HEAD_ADDR" --master-port "$MASTER_PORT" "${SERVE_ARGS[@]}")
+ rank0=(tensorfold serve "$MODEL_ARG" --tp 2 --rank 0 --master "$HEAD_ADDR" --master-port "$MASTER_PORT"
+ --name "$SERVED_NAME" --host "$HOST" --port "$PORT" "${SERVE_ARGS[@]}")
+ log "Rank 1 on $WORKER: ${rank1[*]}"
+ log "Rank 0 here: ${rank0[*]}"
+ worker_cmd=(docker run -d --name "$CONTAINER_NAME" "${RUN_ARGS[@]}" "${ENV_ARGS[@]}"
+ $(nccl_env "$WORKER_DEV" "$WORKER_HCAS" "$WORKER_GID")
+ -v "$WORKER_HF:/root/.cache/huggingface" -v '$HOME/.cache/tensorfold-glm53:/cache'
+ "$IMAGE" "${rank1[@]}")
+ remote=""; for a in "${worker_cmd[@]}"; do
+ case "$a" in '$HOME'*) remote+=" \"$a\"" ;; *) remote+=" $(printf '%q' "$a")" ;; esac
+ done
+ worker "mkdir -p \$HOME/.cache/tensorfold-glm53 &&$remote" >/dev/null || die "could not start rank 1 on $WORKER"
+ docker run -d --name "$CONTAINER_NAME" "${RUN_ARGS[@]}" "${ENV_ARGS[@]}" \
+ $(nccl_env "$HEAD_DEV" "$HEAD_HCAS" "$HEAD_GID") \
+ -v "$HF_CACHE":/root/.cache/huggingface -v "$KERNEL_CACHE":/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
+# takes the other one down: a lone rank would wait for its peer forever.
+foreground() {
+ local watch w code
+ trap './stop.sh; exit 130' INT TERM
+ ( exec 8>&- # not holding start.sh's lock once start.sh has exited
+ while sleep 30; do
+ running_here || exit 0
+ worker true 2>/dev/null || continue # the worker out of reach for a moment says nothing about rank 1
+ running_worker && continue
+ warn "rank 1 on $WORKER exited: stopping rank 0"
+ docker stop -t "${STOP_TIMEOUT:-30}" "$CONTAINER_NAME" >/dev/null 2>&1
+ exit 1
+ done ) &
+ watch=$!
+ docker logs -f "$CONTAINER_NAME" || true
+ kill "$watch" 2>/dev/null || true
+ w=0; wait "$watch" || w=$?
+ code=$(docker inspect -f '{{.State.ExitCode}}' "$CONTAINER_NAME" 2>/dev/null || echo 1)
+ [[ "$w" != 1 || "$code" != 0 ]] || code=1 # rank 1 failed, even if rank 0 then shut down cleanly
+ worker "docker stop -t ${STOP_TIMEOUT:-30} '$CONTAINER_NAME'" >/dev/null 2>&1 || true
+ exit "$code"
+}
+# NVIDIA's container banner, without its license notice (GOVERNING TERMS ...), which stays visible
+NOISE='^\s*$|^=+$|^== PyTorch ==|^NVIDIA Release|Copyright|All rights reserved|PyTorch Version|Various files include|NOTE: CUDA Forward|Using CUDA|cuda-compatibility|Container image|torch/utils/_pytree\.py.*register_constant'
+LOGS_PID=""
+trap 'kill $LOGS_PID 2>/dev/null || true' EXIT
+# GPU memory a container's processes hold so far (GiB); on the worker through ssh, with this definition
+gpu_gib() {
+ local pids
+ pids=$(docker top "$1" -eo pid 2>/dev/null | tail -n +2 | paste -sd'|')
+ [[ -n "$pids" ]] || { echo 0; return; }
+ nvidia-smi --query-compute-apps=pid,used_memory --format=csv,noheader,nounits 2>/dev/null |
+ awk -F', *' -v re="^($pids)$" '$1 ~ re { s += $2 } END { printf "%.1f", s / 1024 }'
+}
+fail() {
+ kill $LOGS_PID 2>/dev/null || true
+ sleep 0.5
+ printf '\n%s── rank 0 (here): last server log lines ──%s\n' "$D" "$R"
+ docker logs --tail 25 "$CONTAINER_NAME" 2>&1 | sed 's/^/ │ /'
+ printf '%s── rank 1 (%s): last server log lines ──%s\n' "$D" "$WORKER" "$R"
+ worker docker logs --tail 25 "$CONTAINER_NAME" 2>&1 | sed 's/^/ │ /'
+ die "$1"
+}
+for attempt in 1 2; do
+ step 3 "Launch: container $CONTAINER_NAME, rank 1 on $WORKER, then rank 0 here"
+ launch
+ [[ "${FOREGROUND:-0}" == 1 ]] && foreground
+ step 4 "Loading: ~80 GiB of weights on each Spark (2-6 min; the very first start also compiles CUDA kernels)"
+ # docker logs is the background job, so killing it ends the whole pipeline (no orphaned `docker logs -f`)
+ docker logs -f "$CONTAINER_NAME" > >(grep --line-buffered -v -E "$NOISE" | sed -u "s/^/ ${D}│${R} /") 2>&1 &
+ LOGS_PID=$!
+ start=$SECONDS; next_beat=15; refit=""
+ until curl -sf --max-time 5 "$URL/v1/models" >/dev/null 2>&1; do
+ if ! running_here; then
+ # the memory at this start holds a smaller window than asked: once, take the largest one TensorFold names
+ refit=$(docker logs "$CONTAINER_NAME" 2>&1 | sed -n 's/.*largest fitting prompt-plus-reply window: \([0-9]*\) tokens.*/\1/p' | tail -1)
+ [[ -n "$refit" && $attempt == 1 ]] && break
+ fail "rank 0 exited (code $(docker inspect -f '{{.State.ExitCode}}' "$CONTAINER_NAME")) before it was ready"
+ fi
+ (( SECONDS - start < WAIT_TIMEOUT )) ||
+ fail "not ready after ${WAIT_TIMEOUT}s (WAIT_TIMEOUT); both ranks are still running: docker logs -f $CONTAINER_NAME"
+ if (( SECONDS - start >= next_beat )); then
+ running_worker ||
+ fail "rank 1 on $WORKER exited (code $(worker docker inspect -f '{{.State.ExitCode}}' "$CONTAINER_NAME" 2>/dev/null || echo "?")) before the server was ready"
+ estimate=$(docker logs "$CONTAINER_NAME" 2>&1 | sed -n 's/.*startup estimate \([0-9.]*\) GiB.*/\1/p' | tail -1)
+ printf ' %s⋯ %ss elapsed, %s%s GiB on the GPU here, %s on the worker%s\n' "$D" "$((SECONDS - start))" \
+ "$(gpu_gib "$CONTAINER_NAME")" "${estimate:+ of ~$estimate}" \
+ "$(worker "$(declare -f gpu_gib); gpu_gib $CONTAINER_NAME" 2>/dev/null || echo "?")" "$R"
+ next_beat=$((next_beat + 15))
+ fi
+ sleep 3
+ done
+ kill $LOGS_PID 2>/dev/null || true
+ sleep 0.3
+ [[ -z "$refit" ]] && break
+ warn "this start's memory budget holds a ${refit}-token window, not $(arg_value --context): starting again with --context $refit"
+ CONTEXT=$refit
+ SERVE_ARGS+=(--context "$refit")
+ ./stop.sh >/dev/null
+done
+log "Server answered after $((SECONDS - start))s"
+
+# ---------------------------------------------------------------- 5. smoke test
+# Thinking off and greedy, so that a short reply has text (the model thinks first otherwise); no text fails the start.
+step 5 "Smoke test: one chat completion through both ranks"
+SERVED=$(served_name || echo "$SERVED_NAME")
+if smoke=$(curl -s --max-time 180 "$URL/v1/chat/completions" -H 'Content-Type: application/json' \
+ -d "{\"model\": \"$SERVED\", \"max_tokens\": 32, \"temperature\": 0, \"chat_template_kwargs\": {\"enable_thinking\": false}, \"messages\": [{\"role\": \"user\", \"content\": \"Reply with OK.\"}]}" |
+ python3 -c 'import json,sys; r = json.load(sys.stdin); c = r["choices"][0]["message"].get("content") or ""; assert c.strip(); print(repr(c.strip()[:40]) + ",", r["usage"]["completion_tokens"], "tokens,", r.get("tensorfold", {}).get("decode_s"), "s")' 2>/dev/null); then
+ log "OK: $smoke"
+else
+ fail "the smoke test request failed (no reply text); both ranks are still running"
+fi
+
+IP=$(hostname -I 2>/dev/null | awk '{print $1}')
+[[ "$HOST" == 0.0.0.0 || "$HOST" == "::" ]] || IP="$HOST"
+printf '\n%s ✔ %s is now LIVE! on port %s%s\n\n' "$G" "$SERVED" "$PORT" "$R"
+cat <<EOF
+ API http://${IP:-<spark-address>}:$PORT/v1 (model: $SERVED)
+ Window $(arg_value --context) tokens · $(arg_value --parallel) at once · $KV KV · $DRAFTER drafts · $DENSE dense weights$( [[ "$VISION" == 1 ]] && echo " · images and video")$( [[ "$COMM" == roce ]] && echo " · RoCE all-gathers")$( [[ "$SPLIT" == 1 ]] && echo " · split prefill")$( [[ "$KDA_CHUNKED" == 1 ]] && echo " · chunked KDA")
+ Drafts $DRAFT_POLICY · copy drafts $( [[ "$COPY" == 1 ]] && echo "up to $COPY_MAX$( [[ "$COPY_CODE" == 1 ]] && echo ", code rules")" || echo off) · shared system prompts $( [[ "$SHARED_PREFIX" == 1 ]] && echo on || echo off)
+ Logs docker logs -f $CONTAINER_NAME (rank 1: ssh $WORKER docker logs -f $CONTAINER_NAME)
+ Restart ./start.sh restart
+ Stop ./stop.sh
+
+EOF
diff --git a/stop.sh b/stop.sh
new file mode 100755
index 0000000..9d3a937
--- /dev/null
+++ b/stop.sh
@@ -0,0 +1,49 @@
+#!/usr/bin/env bash
+# Stop the server that ./start.sh started on both Sparks and remove its containers, freeing their GPU memory. The
+# ranks get STOP_TIMEOUT seconds (default 30) to shut down; requests still running are cut off (it does not drain
+# them), so stop.sh says when there are any.
+# Usage: ./stop.sh Env: CONTAINER_NAME, PORT, WORKER (see scripts/config.sh), STOP_TIMEOUT
+set -euo pipefail
+cd "$(dirname "$(readlink -f "$0")")"
+source ./scripts/config.sh
+source ./scripts/nodes.sh
+
+# Where the containers are: here (rank 0) and on the worker (rank 1)
+here=0; docker ps -a --format '{{.Names}}' | grep -qx "$CONTAINER_NAME" && here=1
+there=0
+if [[ -z "${WORKER:-}" ]]; then
+ warn "WORKER is not set (scripts/local.sh): rank 1 was left alone"
+elif ! worker true 2>/dev/null; then
+ warn "cannot reach the worker ($WORKER) over ssh: rank 1 was left alone"
+elif worker "docker ps -a --format '{{.Names}}' | grep -qx '$CONTAINER_NAME'"; then
+ there=1
+fi
+if (( here == 0 && there == 0 )); then
+ log "No container named $CONTAINER_NAME on either Spark: nothing to stop"
+ exit 0
+fi
+where="on both Sparks"; (( there )) || where="here"; (( here )) || where="on the worker"
+
+if [[ "$(docker inspect -f '{{.State.Running}}' "$CONTAINER_NAME" 2>/dev/null)" == true ]]; then
+ api_host="$HOST"; [[ "$HOST" == 0.0.0.0 || "$HOST" == "::" ]] && api_host=127.0.0.1
+ [[ "$api_host" == *:* ]] && api_host="[$api_host]"
+ busy=$(curl -s --max-time 3 "http://$api_host:$PORT/health" 2>/dev/null |
+ python3 -c 'import json,sys; print(json.load(sys.stdin).get("requests_running", 0))' 2>/dev/null || echo 0)
+ (( busy == 0 )) || warn "$busy request(s) still running will be cut off"
+fi
+log "Stopping $CONTAINER_NAME $where (up to ${STOP_TIMEOUT:-30}s)"
+
+stop_here() {
+ docker stop -t "${STOP_TIMEOUT:-30}" "$CONTAINER_NAME" >/dev/null 2>&1 || true
+ docker rm -f "$CONTAINER_NAME" >/dev/null
+ log "Stopped and removed rank 0 here"
+}
+stop_worker() {
+ worker "docker stop -t ${STOP_TIMEOUT:-30} '$CONTAINER_NAME' >/dev/null 2>&1; docker rm -f '$CONTAINER_NAME' >/dev/null" ||
+ { warn "could not stop rank 1 on $WORKER"; return 1; }
+ log "Stopped and removed rank 1 on $WORKER"
+}
+wpid=""; if (( there )); then stop_worker & wpid=$!; fi
+if (( here )); then stop_here; fi
+[[ -z "$wpid" ]] || wait "$wpid" || exit 0 # a warning above said what is left
+log "Stopped and removed $CONTAINER_NAME $where; its GPU memory is free again"
diff --git a/tools/bench.py b/tools/bench.py
new file mode 100755
index 0000000..535fe02
--- /dev/null
+++ b/tools/bench.py
@@ -0,0 +1,93 @@
+#!/usr/bin/env python3
+"""Prefill and decode benchmark against the running server.
+
+Every prompt is fresh random prose (a new seed per run), so no kept prompt state (prefix reuse) ever matches and every
+token is prefilled. Reports the server's own prefill seconds and decode tokens/s.
+
+Usage: tools/bench.py [label] (API_URL, default http://127.0.0.1:$PORT with PORT 8888; DECODE_ONLY=1 skips prefill)
+"""
+import json
+import os
+import random
+import statistics
+import sys
+import time
+import urllib.error
+import urllib.request
+
+API_URL = os.environ.get("API_URL", "http://127.0.0.1:" + os.environ.get("PORT", "8888")).rstrip("/")
+URL = API_URL + "/v1/chat/completions"
+WORDS = ("time year people way day man thing woman life child world school state family student group country "
+ "problem hand part place case week company system program question work government number night point "
+ "home water room mother area money story fact month lot right study book eye job word business issue "
+ "side kind head house service friend father power hour game line end member law car city community name "
+ "president team minute idea kid body information back parent face others level office door health person "
+ "art war history party result change morning reason research girl guy moment air teacher force education "
+ "river mountain signal engine garden theory market winter method bridge letter window voice paper field").split()
+SIZES = [(1_000, 3), (4_000, 3), (16_000, 2), (64_000, 1)] # (approx prompt tokens, runs)
+
+
+def prose(tokens: int, seed: int) -> str:
+ rng = random.Random(seed)
+ out = []
+ while len(out) < tokens * 0.72: # ~1.14 tokens a word: the prompt comes out at ~0.82 x tokens
+ sentence = [rng.choice(WORDS) for _ in range(rng.randint(6, 16))]
+ out += sentence[:-1] + [sentence[-1] + "."]
+ return " ".join(out)
+
+
+def open_url(req: urllib.request.Request, timeout: float):
+ """urlopen, with a one-line message instead of a traceback when the server is not there or refuses."""
+
+ try:
+ return urllib.request.urlopen(req, timeout=timeout)
+ except urllib.error.HTTPError as exc:
+ sys.exit(f"the server at {API_URL} answered {exc.code}: {exc.read().decode(errors='replace')[:300]}")
+ except urllib.error.URLError as exc:
+ sys.exit(f"cannot reach the server at {API_URL} ({exc.reason}): is it running? (./start.sh)")
+
+
+def run(prompt: str, max_tokens: int, temperature=None) -> dict:
+ body = {"model": os.environ.get("MODEL", "GLM-5.3-Flash-EXL3"), "stream": True, "max_tokens": max_tokens,
+ "stream_options": {"include_usage": True}, "messages": [{"role": "user", "content": prompt}]}
+ if temperature is not None:
+ body["temperature"] = temperature
+ req = urllib.request.Request(URL, json.dumps(body).encode(), {"Content-Type": "application/json"})
+ start, first, stats = time.time(), None, {}
+ for line in open_url(req, 3600):
+ line = line.decode().strip()
+ if not line.startswith("data:") or line.endswith("[DONE]"):
+ continue
+ chunk = json.loads(line[5:])
+ delta = (chunk.get("choices") or [{}])[0].get("delta", {})
+ if first is None and (delta.get("content") or delta.get("reasoning_content")):
+ first = time.time()
+ if "tensorfold" in chunk:
+ stats = {**chunk["tensorfold"], **chunk.get("usage", {})}
+ stats["ttft"] = (first or time.time()) - start
+ return stats
+
+
+def main() -> None:
+ label = sys.argv[1] if len(sys.argv) > 1 else "run"
+ seed = int(time.time())
+ print(f"== {label}")
+ for tokens, runs in ([] if os.environ.get("DECODE_ONLY") else SIZES):
+ rs = [run(prose(tokens, seed + i * 7919 + tokens) + "\n\nSummarize the text above in one sentence.", 16)
+ for i in range(runs)]
+ assert all(r.get("cached", 0) == 0 for r in rs), "prompt cache hit: prompts are not fresh"
+ n = statistics.median(r["prompt_tokens"] for r in rs)
+ pre = statistics.median(r["prefill_s"] for r in rs)
+ ttft = statistics.median(r["ttft"] for r in rs)
+ each = ", ".join("%.2f" % r["prefill_s"] for r in rs)
+ print(f"prefill {n:>7,.0f} tok: {pre:7.2f} s {n / pre:6.0f} tok/s TTFT {ttft:6.2f} s"
+ f" ({runs} run{'s' if runs > 1 else ''}, each {each} s)")
+ for name, prompt, temp in (("code greedy", "Write a Python quicksort with docstring and tests.", 0),
+ ("chat sampled", "Explain why the sky is blue in a few paragraphs.", None)):
+ rs = [run(prompt, 256, temp) for _ in range(5)]
+ tps = [r.get("decode_tps") or r["completion_tokens"] / r["decode_s"] for r in rs] # parallel mode: no decode_tps
+ print(f"decode {name:12s}: {statistics.median(tps):5.1f} tok/s (median of 5)")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tools/needle.py b/tools/needle.py
new file mode 100755
index 0000000..c0d2066
--- /dev/null
+++ b/tools/needle.py
@@ -0,0 +1,39 @@
+#!/usr/bin/env python3
+"""Needle in a haystack at ~195k tokens: a passphrase hidden at ~60% depth of random prose, asked for greedily.
+
+Usage: tools/needle.py [label] [size] (size: bench.prose's length parameter, the prompt comes out at ~0.8 x size
+tokens; default 248000, ~195k tokens. API_URL / PORT as in bench.py). Exit code 1 if the answer is wrong.
+"""
+import json
+import os
+import sys
+import time
+import urllib.request
+
+sys.dont_write_bytecode = True # no tools/__pycache__ from importing bench
+from bench import URL, open_url, prose # noqa: E402
+
+SECRET = "violet-harbor-7291"
+
+
+def main() -> None:
+ label = sys.argv[1] if len(sys.argv) > 1 else "needle"
+ size = int(sys.argv[2]) if len(sys.argv) > 2 else 248_000
+ hay = prose(size, 777).split(". ")
+ at = int(len(hay) * 0.6)
+ hay.insert(at, f"Remember this: the secret passphrase is {SECRET}")
+ prompt = ". ".join(hay) + "\n\nWhat is the secret passphrase mentioned in the text above? Reply with the passphrase only."
+ body = {"model": os.environ.get("MODEL", "GLM-5.3-Flash-EXL3"), "max_tokens": 2048, "temperature": 0, "seed": 1234,
+ "messages": [{"role": "user", "content": prompt}]}
+ t0 = time.time()
+ req = urllib.request.Request(URL, json.dumps(body).encode(), {"Content-Type": "application/json"})
+ reply = json.load(open_url(req, 3600))
+ content = reply["choices"][0]["message"].get("content") or ""
+ ok = SECRET in content
+ print(f"{label}: needle {reply['usage']['prompt_tokens']} tok, prefill {reply['tensorfold'].get('prefill_s')} s, "
+ f"total {time.time() - t0:.1f} s, answer {content.strip()[-80:]!r}: {'CORRECT' if ok else 'WRONG'}", flush=True)
+ sys.exit(0 if ok else 1)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tools/toolcheck.py b/tools/toolcheck.py
new file mode 100755
index 0000000..7e14bc8
--- /dev/null
+++ b/tools/toolcheck.py
@@ -0,0 +1,37 @@
+#!/usr/bin/env python3
+"""A tool call with an array parameter must come back with that argument as a JSON array (typed by the schema).
+
+Usage: tools/toolcheck.py (API_URL / PORT as in bench.py). Exit code 1 on failure.
+"""
+import json
+import os
+import sys
+import urllib.request
+
+sys.dont_write_bytecode = True # no tools/__pycache__ from importing bench
+from bench import URL, open_url # noqa: E402
+TOOLS = [{"type": "function", "function": {
+ "name": "add_tags", "description": "Attach tags to a document.",
+ "parameters": {"type": "object", "required": ["doc_id", "tags"], "properties": {
+ "doc_id": {"type": "integer", "description": "The document id."},
+ "tags": {"type": "array", "items": {"type": "string"}, "description": "The tags to attach."}}}}}]
+
+
+def main() -> None:
+ body = {"model": os.environ.get("MODEL", "GLM-5.3-Flash-EXL3"), "max_tokens": 1024, "temperature": 0, "tools": TOOLS,
+ "messages": [{"role": "user", "content": "Tag document 42 with 'urgent', 'finance' and 'q3' using the tool."}]}
+ req = urllib.request.Request(URL, json.dumps(body).encode(), {"Content-Type": "application/json"})
+ msg = json.load(open_url(req, 600))["choices"][0]["message"]
+ calls = msg.get("tool_calls") or []
+ ok = False
+ for c in calls:
+ args = json.loads(c["function"]["arguments"])
+ print(f"tool call {c['function']['name']}({json.dumps(args)})")
+ ok |= c["function"]["name"] == "add_tags" and isinstance(args.get("tags"), list) and len(args["tags"]) >= 3 \
+ and isinstance(args.get("doc_id"), int)
+ print("toolcheck:", "OK: tags is a JSON array" if ok else f"FAILED: {msg}")
+ sys.exit(0 if ok else 1)
+
+
+if __name__ == "__main__":
+ main()