GLM-5.3-Flash EXL3 on 2x DGX Spark with TensorFold
Python
Patch 0103: faster decode - 4-bit decode matmuls reduce through the partials buffer instead of a cluster at few rows
BadAd84b0470187d6e0
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 54a3f69..3df9970 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -3,6 +3,19 @@Every change to this recipe, newest first. Each release names the image it serves: `scripts/prepare.sh` pulls`ghcr.io/miaai-lab/glm-5.3-flash-exl3-2x-dgx-sparks-tensorfold` by the digest pinned in `scripts/config.sh`.+## Unreleased++- **Decode matmuls without clusters where they cost more than they save** (patch+ `0103-glm-qmm-decode-noclusters`, by [BadAd84](https://github.com/BadAd84)): the decode 4-bit matmuls reduce their K slices through+ the partials buffer and `reduce_kernel` instead of a thread-block cluster when the window has at most 64+ rows and the weight holds fewer than 28 Mi values: the same slice-ordered fp32 sums, so the same bits. On+ a GB10 the cluster's launch and syncs cost 20-60% on those latency-bound matrices (a shared expert's+ gate/up at one row 29.3 -> 18.4 us), at the shapes of two, three and four Sparks; from 32 Mi the clusters+ mostly win, and no shape sits between. Live on three Sparks: real code 89.5 / 88.6 -> 90.6 / 90.0 tok/s,+ prose 64.7 / 64.5 -> 66.4 / 66.6. `TF_GLM_QMM_CLUSTERS=1`: the clusters as before. The extension is renamed+ `tensorfold_qmm_v5`, so a kernel folder with v4's build does not serve it. GPU check:+ `tools/qmm_noclusters_check.py`.+## v1.10 (2026-10-08): the effort line at the tail (opt-in), a kept-state share, and a checked second railImage: `v0.6.0-a1897d591f70` (`sha256:bc34d7d63f978cf601f42863b284bc95a567c50c10e9adb0866a635be568bf5f`), 96 patches (v1.9.1's plus `0096`, `0097`). Tested live on twodiff --git a/CREDITS.md b/CREDITS.mdindex 521996e..2535cc1 100644--- a/CREDITS.md+++ b/CREDITS.md@@ -139,6 +139,8 @@ checkpoint's ShapleyMcg attribution and the drafter's license).[kindling spark-os](https://github.com/kindlingai/kindling-spark-os) by Matt Mastracci (Kindling AI). Nothing ofdispram ships here: the ranks import the host's client (`python/dispram.py`, GPL-3.0 with a bundling exception)mounted read-only at run time and talk to `dispramd` (AGPL-3.0) over its socket.+- `0103-glm-qmm-decode-noclusters` (decode matmuls reduce through the partials buffer at few rows): by+ [BadAd84](https://github.com/BadAd84).- `0090-glm-expert-launch-order` (`TF_GLM_EXL3_DEC_ORDER`: the launch order of the expert decode kernel's blocks): byLukasz Raczylo ([lukaszraczylo](https://github.com/lukaszraczylo)), in[PR #95](https://github.com/MiaAI-Lab/GLM-5.3-Flash-EXL3-2x-DGX-Sparks-TensorFold/pull/95).diff --git a/README.md b/README.mdindex 2bace9c..eea5526 100644--- a/README.md+++ b/README.md@@ -522,6 +522,7 @@ sets a value wins: the environment, then `scripts/local.sh`, then `.env`, then t| `TF_ROCE_WAIT_S` | `300` | seconds a RoCE all-gather waits for the other Spark before it fails (1 to 3600; the patch's own default is 20, which a late peer on long prompts outlasted, issue #54); until the engine is built, each gather first meets the peer in an NCCL barrier, so a long first start (kernels compiling) does not run into it || `TF_GLM_MULTI_WINDOW` | `32`, `64` past 4 requests | with `PARALLEL` above 1, the rows of every request's verify window together in a round (16 to 64 in steps of 8): with more requests at once each one's drafts get fewer of them (8 requests' code: 141.2 / 160.3 / 167.0 tok/s at 32 / 48 / 64 rows); past 32 rows `TF_ROCE_MAX_KB` rises with it (64: 1024) unless you set it. Exact at any size || `TF_GLM_MULTI_LONE` | `0` | `1`: with `PARALLEL` above 1, a request decoding alone runs on the one-stream graphs (+0.6-0.9%), but its move to the pool's first rows evicts other conversations' kept prompts there (issues #12, #13); `0`: on the batched ones |+| `TF_GLM_QMM_CLUSTERS` | unset | `1`: decode windows' 4-bit matmuls reduce every 2-8 K-slice split in a thread-block cluster, the rule before patch `0103`; unset: the buffer path at up to 64 rows under 28 Mi weight values (the same bits either way) || `TF_GLM_CACHE_ENTRIES` | `32` | kept prompt states at most (TensorFold's default is 8); past this count a conversation's earlier (superseded) states go first, then the least recently used, however much of the pool is free (patch `0063`, @Alexbob0); shared-prefix states (a system block) go by recency only, so a new run of an agent still finds its system prompt (patch `0077`, issue #75, @meleesciony). An agent request keeps 1 to 3 (issue #17); each costs ~45 MiB at start, reserved out of the pool's `KV_POOL_GIB` budget (the pool shrinks by it, the estimate does not change), flat in the context length. Symptom of too few: `/health` `kept_prompts` stuck at the count while `pool_free_tokens` is large (issue #84, @jdecker76); see `TF_GLM_CACHE_SHARE_PCT` || `TF_GLM_CACHE_SHARE_PCT` | `0` (off) | make the kept-state count at least this share of the `KV_POOL_GIB` budget (patch `0097`, issue #84 by @jdecker76): on two Sparks at the defaults each state reserves ~91 MiB of a ~7.5 GiB budget, so 32 states already take ~38%: `50` gives ~42 states, the ceiling ~63 (each costs pool tokens), so the pool's tokens, not 32 finished one-shot conversations, decide when a live conversation goes. Any count is cut to three quarters of the budget (logged at start): past that the reservation would exceed the estimate. Set the same on every Spark || `TF_GLM_KEPT_BYTES_GIB` | `0` (no cap) | a byte budget for the kept states together (patch `0089`, by Thomas Wade, [ThomasWadeZ](https://github.com/ThomasWadeZ), PR #65): the device memory they own outside the pool (recurrent state, DFlash2 window copies: hundreds of MB each with long contexts); past it states are dropped in the entry cap's order (not written to the spill tier) and freed blocks go back to the driver. The author runs `4`; `kept_bytes` / `kept_bytes_cap` in `/health` |@@ -635,6 +636,7 @@ applied with `patch -p0` in filename order); `start.sh` rebuilds or re-pulls the| Decode, memory | `0090-glm-expert-launch-order` | the decode expert kernel's blocks launched so that the eight 128-column blocks of one k slice run together and read contiguous memory (`TF_GLM_EXL3_DEC_ORDER=1` or `2`; default `0`, the old order), by Lukasz Raczylo ([lukaszraczylo](https://github.com/lukaszraczylo)) | the author's run: one request +2.2% tok/s (4 at once noisy); the same bits for every value; not yet measured here || Decode, indexer | `0043-glm-visible-pools` | a decode row's token scoring and split selection bounded to the pools it can see (TensorFold v0.6.0 bounds its one-program selection, PR #140) | the same tokens || Decode, indexer | `0085-glm-select-split-loop` | the split selection's last pass sums the histograms of the chunks before its own, 16 at a time (`SPLIT_BLK`), instead of loading the row's whole chunk table masked to them: that table is the selection scratch's, sized for the pool (512 chunks a row at `PARALLEL=4` on three Sparks), not the row's context (by [BadAd84](https://github.com/BadAd84)) | one request at 226k: the selection 5.79 -> 0.28 ms a layer (11 a round); the same tokens |+| Decode, matmuls | `0103-glm-qmm-decode-noclusters` | decode windows' 4-bit matmuls reduce their K slices through the partials buffer instead of a thread-block cluster at up to 64 rows and under 28 Mi weight values (the cluster's launch and syncs cost 20-60% there; measured at the shapes of two, three and four Sparks); `TF_GLM_QMM_CLUSTERS=1` keeps the clusters; the extension renamed `tensorfold_qmm_v5` (by [BadAd84](https://github.com/BadAd84)) | 3 Sparks: real code / prose decode +1.4 / +2.9%; the same bits || Link | `0006-cuda-roce-allgather`, `0052-cuda-roce-startup` | the small all-gathers as one-shot RDMA writes over RoCE (`COMM=roce`; up to 512 KiB, `TF_ROCE_MAX_KB`: code at 4 streams +1.4%); until the engine is built, each eager gather first waits for the peer in an NCCL barrier, and the RoCE kernel builds during setup (`TF_ROCE_WAIT_S`, 300 s here; errors print the proxy's counters); an idle rank 1 waiting on a socket is TensorFold v0.6.0's (#132) | 11 us a 16 KiB gather against NCCL's 45, decode +6%; an idle server holds no GPU or CPU core; a first start whose ranks drift apart while building kernels no longer fails || Drafts | `0007-glm-copy-drafts`, `0032-glm-code-copy-drafts`, `0018-glm-noise-policies`, `0021-glm-dflash-policy-env`, `0025-glm-dflash2-ring` | copy (prompt-lookup) drafts ahead of DFlash2's (`COPY`, `COPY_CODE`); DFlash2 stop rules aware of the sampling noise (`DRAFT_POLICY`); kept prompt states' DFlash2 window with shared prefixes (the ring itself and `TF_GLM_MTP` are TensorFold v0.6.0's; the recipe sets `TF_GLM_MTP=auto`, so the MTP head is not loaded when DFlash2 drafts) | `COPY`: quote / edit replies 80.3 -> 84.4 tok/s; `COPY_CODE`: code 55.4 -> 56.2, edit 120 -> 125; `DRAFT_POLICY` over `fc5:0.3`: prose 47.2 -> 50.6 tok/s, code 51.7 -> 55.5; memory for the window || Drafts, tooling | `0011-glm-draft-sim` | records of DFlash2's drafts for an offline simulator of stop rules (`TF_GLM_DRAFT_DUMP`, off) | how the stop rules were tuned |@@ -711,6 +713,7 @@ with [sparkDash](https://github.com/MiaAI-Lab/sparkDash) ([Performance](#perform| `tools/needle.py [label] [size]` | hides a passphrase in a ~195k-token prompt (the prompt comes out at ~0.8 x `size` tokens) and checks the model returns it || `tools/toolcheck.py` | makes a tool call with an array parameter and checks it comes back as a JSON array || `tools/display_kv_check.py [--gpu]` | patch 0072's checks, run in the image (`docker run ... --entrypoint python`, see the file): the setting, the span's mapping and unwinding through a fake driver, the carved planes and the pool's copies; with `--gpu`, the real span on a Spark whose display reservation is free |+| `tools/qmm_noclusters_check.py [--time]` | patch 0103's checks: the installed 4-bit matmul against a build of the same sources with the old cluster rule, bit for bit at every decode shape of TP=4, TP=3 and TP=2 and at the 28 Mi edge, the path each call takes (and with `TF_GLM_QMM_CLUSTERS=1`), and a CUDA graph on side streams; run in the image on one GPU (`docker run --gpus all ... --entrypoint python`, see the file); `--time` prints the old and new paths' times || `tools/pool_pressure.py [size]` | on a fresh server with nothing else sending requests: two conversations of ~`size` tokens (default 30000) take a turn each, others fill the pool, then each takes another turn; exit 1 when a turn resumes less than 90% of its previous prompt, 2 when the kept-prompt cap stops the fill first (a smaller pool runs it faster: `CONTEXT=131072 KV_POOL_GIB=0.5`) || `tools/pool_room_check.py` | patch 0074's checks, run in the image (`docker run ... --entrypoint python`, see the file): the pool's room-making on a CPU arena, what it evicts and moves, and rank 1 replaying the same ops || `tools/test_queued_cancellation.py --source-root DIR` | patch 0073's checks on the CPU, against TensorFold's source with the patches applied (no GPU, no server): requests that wait while every slot is busy and whose client leaves are dropped at once, in queue order; `--expect-stock` before 0073 shows the old wait |diff --git a/patches/0103-glm-qmm-decode-noclusters.patch b/patches/0103-glm-qmm-decode-noclusters.patchnew file mode 100644index 0000000..56f1ea9--- /dev/null+++ b/patches/0103-glm-qmm-decode-noclusters.patch@@ -0,0 +1,103 @@+# Decode windows' 4-bit matmuls (tensorfold/cuda/kernels/qmm: every dense projection, the shared expert and DFlash2's+# drafter) reduce their K slices through the partials buffer and reduce_kernel instead of a thread-block cluster when+# the window has at most 64 rows and the weight holds fewer than 28 Mi values. The same slice-ordered fp32 sums and one+# rounding, so the same bits; on a GB10 the cluster's launch and its two cluster.sync cost 20-60% on those latency-bound+# matrices, while the bandwidth-bound ones keep their clusters. Prompt chunks (more rows) are unchanged.+# TF_GLM_QMM_CLUSTERS=1: clusters for every reduced K split, as before. The extension is renamed tensorfold_qmm_v5, so+# a kernel folder holding v4's build does not serve it. tools/qmm_noclusters_check.py.++diff --git tensorfold/cuda/kernels/qmm.cpp tensorfold/cuda/kernels/qmm.cpp+--- tensorfold/cuda/kernels/qmm.cpp++++ tensorfold/cuda/kernels/qmm.cpp+@@ -1,7 +1,7 @@+ #include <torch/extension.h>+ #include <c10/cuda/CUDAGuard.h>++-bool qmm_clusters(int, bool);++bool qmm_clusters(int, bool, long long, long long, long long);+ 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&,+@@ -37,7 +37,7 @@ void qmm(const at::Tensor& x, const at::Tensor& xs, const at::Tensor& w, const a+ out.scalar_type() == (f32 ? at::kFloat : at::kBFloat16), "out: (M, n)");+ c10::cuda::CUDAGuard guard(x.device());+ at::Tensor p;+- if (sk > 1 && !qmm_clusters(static_cast<int>(sk), reduce)) {++ if (sk > 1 && !qmm_clusters(static_cast<int>(sk), reduce, m, n, k)) {+ p = part.has_value() ? *part : at::empty({sk, m, n}, x.options().dtype(at::kFloat));+ TORCH_CHECK(p.is_cuda() && p.is_contiguous() && p.scalar_type() == at::kFloat && p.numel() >= sk * m * n,+ "part: at least (SK, M, n) fp32");+@@ -68,7 +68,7 @@ void qmm_cfg(const at::Tensor& x, const at::Tensor& xs, const at::Tensor& w, con+ out.scalar_type() == (f32 ? at::kFloat : at::kBFloat16), "out: (M, n)");+ c10::cuda::CUDAGuard guard(x.device());+ at::Tensor p;+- if (sk > 1 && !qmm_clusters(static_cast<int>(sk), true)) {++ if (sk > 1 && !qmm_clusters(static_cast<int>(sk), true, m, n, k)) {+ 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");+ }+diff --git tensorfold/cuda/kernels/qmm.cu tensorfold/cuda/kernels/qmm.cu+--- tensorfold/cuda/kernels/qmm.cu++++ tensorfold/cuda/kernels/qmm.cu+@@ -327,8 +327,29 @@ void dispatch_cfg(int cfg, const at::Tensor& x, const at::Tensor& xs, const at::+ } // namespace++ // Clusters hold up to 8 K slices (the portable size) from sm_90; more, unreduced slices or older GPUs use the buffer.+-bool qmm_clusters(int SK, bool reduce) {+- return SK > 1 && SK <= 8 && reduce && at::cuda::getCurrentDeviceProperties()->major >= 9;++// Patch 0103: windows of up to CLUSTER_ROWS rows also use the buffer (and reduce_kernel) unless the weight holds++// at least CLUSTER_VALUES values. The same sums in the same order (slice 0 + slice 1 + ... in fp32, then one++// rounding), so the same bits. Measured on GB10 (cold L2, 1-64 rows) at GLM-5.3-Flash's rank-0 decode shapes for two,++// three and four ranks: the cluster launch and its two cluster.sync cost 20-60% on the latency-bound matrices (shared++// expert gate/up 18.8 -> 12.4 us at TP=4, DSA q_a|kv_a 31.5 -> 22.9, DFlash2's qkv 38.1 -> 25.0 at TP=3, at one row);++// the buffer is as fast or faster for every matrix up to 25 Mi values (TP=4's KDA proj 69.9 -> 65.4 us; its dense++// gate/up at 24 Mi within 1% up to 16 rows, 4-8% slower at 32-64), while from 32 Mi the clusters mostly win (TP=3's++// dense gate/up at 32 Mi 82.0 vs 84.9 us, KDA proj at 34 Mi 88.5 vs 89.5, DFlash2's taps fc at 80 Mi 206 vs 216;++// TP=2's DSA o at 32 Mi is 4-13% faster on the buffer at 1 and 32-64 rows and keeps its clusters, as before). 28 Mi++// sits between, over 10% from the nearest shape on either side. TF_GLM_QMM_CLUSTERS=1: clusters for every reduced K++// split, the rule before this patch. Prompt chunks (more rows) are unchanged.++constexpr long long CLUSTER_ROWS = 64;++constexpr long long CLUSTER_VALUES = 28LL << 20;++static bool clusters_always() {++ static const bool always = [] {++ const char* v = std::getenv("TF_GLM_QMM_CLUSTERS");++ return v != nullptr && v[0] == '1' && v[1] == '\0';++ }();++ return always;++}++bool qmm_clusters(int SK, bool reduce, long long M, long long N, long long K) {++ return SK > 1 && SK <= 8 && reduce && at::cuda::getCurrentDeviceProperties()->major >= 9 &&++ (clusters_always() || M > CLUSTER_ROWS || N * K >= CLUSTER_VALUES);+ }++ // ``qmm_cuda`` for decode rows (M <= 16, groups of 64, K slices reduced) on tile config ``cfg``.+@@ -336,7 +357,7 @@ void qmm_cfg_cuda(const at::Tensor& x, const at::Tensor& xs, const at::Tensor& w+ 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 = qmm_clusters(SK, true);++ const bool cluster = qmm_clusters(SK, true, M, N, x.size(1));+ 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);+@@ -356,7 +377,7 @@ void qmm_cuda(const at::Tensor& x, const at::Tensor& xs, const at::Tensor& w, co+ const at::Tensor& biases, at::Tensor& out, const at::Tensor& part, int N, int SK, int gs, int bm,+ bool f32, bool reduce) {+ const int M = x.size(0);+- const bool cluster = qmm_clusters(SK, reduce);++ const bool cluster = qmm_clusters(SK, reduce, M, N, x.size(1));+ #define GO(G, F, C) dispatch<G, F, C>(bm, x, xs, w, scales, biases, out, part, N, SK)+ if (gs == 64) {+ if (f32) { if (cluster) GO(64, true, true); else GO(64, true, false); }+diff --git tensorfold/cuda/kernels/qmm.py tensorfold/cuda/kernels/qmm.py+--- 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_v4", sources=[str(here / "qmm.cpp"), str(here / "qmm.cu"),++ return load(name="tensorfold_qmm_v5", 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)+diff --git a/tools/qmm_noclusters_check.py b/tools/qmm_noclusters_check.pynew file mode 100644index 0000000..7ab794a--- /dev/null+++ b/tools/qmm_noclusters_check.py@@ -0,0 +1,287 @@+#!/usr/bin/env python3+"""tools/qmm_noclusters_check.py [--time]: patch 0103 - decode windows' 4-bit matmuls (tensorfold/cuda/kernels/qmm)+reduce their K slices through the partials buffer and reduce_kernel instead of a thread-block cluster when the window+has at most 64 rows and the weight holds fewer than 28 Mi values. Run in the image built with patch 0103, on one GPU+(sm_90 or newer, where the clusters exist):+docker run --rm --gpus all --entrypoint python -v "$PWD/tools/qmm_noclusters_check.py:/c.py" <image> /c.py++NEW = the installed extension (qmm._ext()); OLD = the same sources with qmm_clusters' rule put back to the one before+the patch (clusters for every 2-8 reduced K slices on sm_90+), built here. At GLM-5.3-Flash's rank-0 decode shapes at+TP=4, TP=3 and TP=2 (every dense projection, the shared expert, DFlash2's matrices) and 1-128 rows:+1. bits: NEW's output equals OLD's bit for bit through both entry points (``qmm`` with the row bucket, ``qmm_cfg`` with+ every decode tile config 0-15 for rows <= 16), outputs pre-filled with NaN;+2. mechanism: NEW launches reduce_kernel (the buffer path) exactly when sk > 1, rows <= 64 and n * k < 28 Mi+ (torch.profiler's kernel names), OLD never does; with TF_GLM_QMM_CLUSTERS=1 (read once a process: a child+ process) NEW runs the cluster where it would take the buffer;+3. graphs: matmuls on three side streams captured in one CUDA graph and replayed with new inputs equal OLD's eager+ outputs (the buffer path's partials are allocated per call, stream-ordered);+4. the extension loads under a new name (tensorfold_qmm_v5), so a kernel folder holding v4's build does not serve it.+One PASS / FAIL line a check; exits 1 on any FAIL (on an image without the patch: at the first check); an error that+stops the check (a CUDA fault in the extension) is a FAIL too.++--time: CUDA-graph us a call, OLD -> NEW, cold L2 (enough weight copies to pass the L2), rows 1, 4, 8, 32, 64, at+TP=4, 3 and 2."""+import hashlib+import os+import subprocess+import re+import shutil+import sys+import tempfile++import torch++from tensorfold.cuda.build import load+from tensorfold.cuda.kernels import qmm as installed+from tensorfold.families.glm5_next.cuda import tp++SRC = ("qmm.cpp", "qmm.cu", "qmm_prefill.cu", "qmm_prefill8.cu")+OLD_RULE = ("bool qmm_clusters(int SK, bool reduce, long long, long long, long long) {\n"+ " return SK > 1 && SK <= 8 && reduce && at::cuda::getCurrentDeviceProperties()->major >= 9;\n}\n")+ROWS = (1, 2, 3, 4, 8, 12, 16, 24, 32, 48, 64, 65, 96, 128)+fails = 0+++def check(ok, msg):+ global fails+ print(("PASS " if ok else "FAIL ") + msg, flush=True)+ fails += not ok+++def shapes(world):+ """(label, n, k, fp32 out) of rank 0's decode matmuls at ``world`` ranks (DFlash2 by tp.draft_parts); "edge": two+ shapes either side of the 28 Mi rule (no GLM-5.3-Flash matrix sits there)."""+ if world == "edge":+ return [("28 Mi values exactly", 7168, 4096, False), ("just under 28 Mi", 7040, 4096, False)]+ h, lh = tp.split_sizes(64, world, 1)[0], tp.split_sizes(64, world, 1)[0]+ dn, sh = tp.split_sizes(12288, world, 128)[0], tp.split_sizes(2048, world, 128)[0]+ vocab = tp.split_sizes(154880, world, 64)[0]+ dq, dkv, dmlp = (x[0] for x in tp.draft_parts(32, 8, 12288, world))+ return [("kda proj", 3 * lh * 128 + 256 + lh, 4096, False), ("kda o", 4096, lh * 128, True),+ ("dsa o", 4096, h * 256, True), ("shared gate/up", 2 * sh, 4096, False), ("shared down", 4096, sh, True),+ ("kda f_b/g_b", lh * 128, 128, False), ("dsa q_a|kv_a", 2048, 4096, False),+ ("dsa q_b", h * 256, 1536, False), ("idx wq_b", 4096, 1536, False), ("idx wk|w", 160, 4096, False),+ ("dense gate/up", 2 * dn, 4096, False), ("dense down", 4096, dn, True),+ ("draft taps fc", 4096, 20480, False), ("draft ctx kv", 2 * dkv * 128, 4096, False),+ ("draft qkv", (dq + 2 * dkv) * 128, 4096, False), ("draft o_proj", 4096, dq * 128, True),+ ("draft gate/up", 2 * dmlp, 4096, False), ("draft down", 4096, dmlp, True),+ ("draft head", vocab, 4096, False)]+++def old_build(kdir):+ """The installed sources with qmm_clusters' body put back to the rule before the patch, built under its own name."""+ work = tempfile.mkdtemp(prefix="qmm-old-")+ for f in os.listdir(kdir):+ if f.endswith((".cu", ".cpp", ".cuh", ".h")):+ shutil.copy(os.path.join(kdir, f), work)+ cu = os.path.join(work, "qmm.cu")+ src = open(cu).read()+ new, n = re.subn(r"bool qmm_clusters\(int SK, bool reduce, long long M, long long N, long long K\) \{\n.*?\n\}\n",+ lambda _: OLD_RULE, src, flags=re.S)+ if n != 1:+ return None, work+ open(cu, "w").write(new)+ h = hashlib.sha256(b"".join(open(os.path.join(work, f), "rb").read() for f in sorted(os.listdir(work))))+ return load(name=f"qmm_check_old_{h.hexdigest()[:12]}", sources=[os.path.join(work, f) for f in SRC],+ extra_cuda_cflags=["-O3"], verbose=False), work+++def main():+ kdir = os.path.dirname(installed.__file__)+ src = open(os.path.join(kdir, "qmm.cu")).read()+ check("long long M, long long N, long long K)" in src and "CLUSTER_VALUES" in src,+ "patch 0103 applied: qmm_clusters takes the window's shape")+ if fails:+ print("1 FAIL", flush=True)+ sys.exit(1)+ py = open(os.path.join(kdir, "qmm.py")).read()+ check('name="tensorfold_qmm_v5"' in py and 'name="tensorfold_qmm_v4"' not in py,+ "the extension loads as tensorfold_qmm_v5 (not v4's build from a shared kernel folder)")+ timing = "--time" in sys.argv+ dev = torch.device("cuda")+ check(torch.cuda.get_device_capability()[0] >= 9, "the GPU has thread-block clusters (sm_90 or newer)")+ eo, work = old_build(kdir)+ check(eo is not None, "OLD: qmm_clusters' body found and put back to the rule before the patch")+ if eo is None:+ print(f"{fails} FAIL", flush=True)+ sys.exit(1)+ en = installed._ext()+ g = torch.Generator(device=dev).manual_seed(86)++ def weights(n, k):+ words = torch.randint(-2 ** 31, 2 ** 31 - 1, (n, k // 8), dtype=torch.int32, device=dev, generator=g)+ sc = (torch.rand((n, k // 64), device=dev, generator=g) * 0.02 + 0.001).to(torch.bfloat16)+ bi = ((torch.rand((n, k // 64), device=dev, generator=g) - 0.5) * 0.02).to(torch.bfloat16)+ return installed.pack(words, sc, bi, 64)++ def run(ext, x, xs, q, sk, f32, cfg=None):+ out = torch.full((x.shape[0], q.n), float("nan"), dtype=torch.float32 if f32 else torch.bfloat16, device=dev)+ if cfg is None:+ ext.qmm(x, xs, q.weight, q.scales, q.biases, out, None, q.n, sk, 64, installed.bucket(x.shape[0]), f32,+ True)+ else:+ ext.qmm_cfg(x, xs, q.weight, q.scales, q.biases, out, None, q.n, sk, f32, cfg)+ return out++ def bits(t):+ return t.view(torch.int32) if t.dtype == torch.float32 else t.view(torch.int16)++ def reduces(ext, x, xs, q, sk, f32, cfg=None):+ """Whether the call launched reduce_kernel (the buffer path), from the profiler's kernel names."""+ torch.cuda.synchronize()+ with torch.profiler.profile(activities=[torch.profiler.ProfilerActivity.CUDA]) as prof:+ run(ext, x, xs, q, sk, f32, cfg)+ torch.cuda.synchronize()+ names = [e.name for e in prof.events() if e.device_type == torch.autograd.DeviceType.CUDA]+ return any("qmm_kernel" in nm for nm in names), any("reduce_kernel" in nm for nm in names)++ if "--clusters-child" in sys.argv: # the opt-out check's child: TF_GLM_QMM_CLUSTERS=1 in its env+ n, k = 2 * tp.split_sizes(2048, 3, 128)[0], 4096+ x = (torch.randn((1, k), device=dev, generator=g) * 0.5).to(torch.bfloat16)+ _, red = reduces(en, x, installed.group_sums(x, 64), weights(n, k), installed.split_k(n, k, 64), False)+ print(f"CHILD {'buffer' if red else 'cluster'}", flush=True)+ sys.exit(0)++ seen = set()+ for world in (4, 3, 2, "edge"):+ for label, n, k, f32 in shapes(world):+ if (n, k, f32) in seen:+ continue+ seen.add((n, k, f32))+ label = (f"TP={world} " if world != "edge" else "") + f"{label} ({n} x {k})"+ q = weights(n, k)+ sk = installed.split_k(n, k, 64)+ differ, wrong, calls = [], [], 0+ for m in ROWS:+ x = (torch.randn((m, k), device=dev, generator=g) * 0.5).to(torch.bfloat16)+ xs = installed.group_sums(x, 64)+ ref = run(eo, x, xs, q, sk, f32)+ if torch.isnan(ref.float()).any():+ differ.append(f"m={m}: OLD left a slot unwritten")+ for cfg in [None] + (list(range(16)) if m <= 16 else []):+ calls += 1+ try:+ if not torch.equal(bits(run(en, x, xs, q, sk, f32, cfg)), bits(ref)):+ differ.append(f"m={m} cfg {cfg}")+ except RuntimeError as exc: # the extension refusing a call is a failure, reported+ differ.append(f"m={m} cfg {cfg}: NEW raised {str(exc).splitlines()[0][:100]}")+ want = sk > 1 and m <= 64 and n * k < (28 << 20)+ for cfg in (None, 0) if m <= 16 else (None,):+ try:+ ran_n, red_n = reduces(en, x, xs, q, sk, f32, cfg)+ ran_o, red_o = reduces(eo, x, xs, q, sk, f32, cfg)+ except RuntimeError as exc:+ wrong.append(f"m={m} cfg {cfg}: raised {str(exc).splitlines()[0][:100]}")+ continue+ if not ran_n or not ran_o or red_n != want or (sk > 1 and red_o):+ wrong.append(f"m={m} cfg {cfg}: NEW {'buffer' if red_n else 'cluster'}, OLD "+ f"{'buffer' if red_o else 'cluster'}, want {'buffer' if want else 'cluster'}")+ check(not differ, f"{label}: {calls} NEW calls == OLD bit for bit at rows {ROWS[0]}-{ROWS[-1]} "+ f"({differ[:3] or 'all equal'})")+ check(not wrong, f"{label}: sk {sk}, the buffer path exactly at rows <= 64 below 28 Mi values "+ f"({wrong[:3] or 'as wanted'})")+ del q+ child = subprocess.run([sys.executable, os.path.abspath(__file__), "--clusters-child"], capture_output=True,+ text=True, env={**os.environ, "TF_GLM_QMM_CLUSTERS": "1"})+ check("CHILD cluster" in child.stdout,+ "TF_GLM_QMM_CLUSTERS=1: a 1-row TP=3 shared gate/up runs its cluster, the rule before the patch "+ f"({(child.stdout.strip().splitlines() or [child.stderr.strip()[-200:]])[-1]})")++ picks = [s for s in shapes(3) if s[0] in ("kda o", "shared gate/up", "dsa q_a|kv_a", "draft qkv")]+ qs = [weights(n, k) for _, n, k, _ in picks]+ m = 2+ xin = [torch.zeros((m, k), dtype=torch.bfloat16, device=dev) for _, _, k, _ in picks]+ xsin = [torch.zeros((m, k // 64), dtype=torch.float32, device=dev) for _, _, k, _ in picks]+ outs = [torch.zeros((m, n), dtype=torch.float32 if f32 else torch.bfloat16, device=dev) for _, n, _, f32 in picks]+ streams = [torch.cuda.Stream() for _ in range(3)]++ def body():+ main_st = torch.cuda.current_stream()+ for i, (_, n, k, f32) in enumerate(picks):+ st = streams[i % 3]+ st.wait_stream(main_st)+ with torch.cuda.stream(st):+ for _ in range(3): # repeated calls: partials buffers recycled within the stream+ en.qmm(xin[i], xsin[i], qs[i].weight, qs[i].scales, qs[i].biases, outs[i], None, n,+ installed.split_k(n, k, 64), 64, installed.bucket(m), f32, True)+ main_st.wait_stream(st)++ bad = []+ try:+ side = torch.cuda.Stream()+ side.wait_stream(torch.cuda.current_stream())+ with torch.cuda.stream(side):+ body()+ torch.cuda.current_stream().wait_stream(side)+ graph = torch.cuda.CUDAGraph()+ with torch.cuda.graph(graph):+ body()+ for rep in range(2):+ for i, (_, n, k, f32) in enumerate(picks):+ xin[i].copy_((torch.randn((m, k), device=dev, generator=g) * (0.5 + rep)).to(torch.bfloat16))+ xsin[i].copy_(installed.group_sums(xin[i], 64))+ outs[i].fill_(float("nan"))+ graph.replay()+ torch.cuda.synchronize()+ for i, (label, n, k, f32) in enumerate(picks):+ ref = run(eo, xin[i], xsin[i], qs[i], installed.split_k(n, k, 64), f32)+ if not torch.equal(bits(outs[i]), bits(ref)):+ bad.append(f"replay {rep}: {label}")+ except RuntimeError as exc:+ bad.append(f"raised {str(exc).splitlines()[0][:100]}")+ check(not bad, f"a CUDA graph of matmuls on three side streams, replayed twice with new inputs == OLD eager "+ f"({bad or 'all equal'})")++ if timing:+ def timed(ext, x, xs, qcopies, sk, f32, reps=20):+ out = run(ext, x, xs, qcopies[0], sk, f32)++ def body2():+ for q in qcopies:+ ext.qmm(x, xs, q.weight, q.scales, q.biases, out, None, q.n, sk, 64, installed.bucket(x.shape[0]),+ f32, True)+ st = torch.cuda.Stream()+ st.wait_stream(torch.cuda.current_stream())+ with torch.cuda.stream(st):+ body2()+ torch.cuda.current_stream().wait_stream(st)+ gr = torch.cuda.CUDAGraph()+ with torch.cuda.graph(gr):+ body2()+ gr.replay()+ torch.cuda.synchronize()+ e0, e1 = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)+ e0.record()+ for _ in range(reps):+ gr.replay()+ e1.record()+ torch.cuda.synchronize()+ return e0.elapsed_time(e1) * 1e3 / reps / len(qcopies)++ for world in (4, 3, 2):+ for label, n, k, f32 in shapes(world):+ q0 = weights(n, k)+ copies = max(2, min(64, -(-(256 << 20) // q0.nbytes())))+ qc = [q0] + [installed.Q4(q0.weight.clone(), q0.scales.clone(), q0.biases.clone(), n, k, 64)+ for _ in range(copies - 1)]+ sk = installed.split_k(n, k, 64)+ line = []+ for m in (1, 4, 8, 32, 64):+ x = (torch.randn((m, k), device=dev, generator=g) * 0.5).to(torch.bfloat16)+ xs = installed.group_sums(x, 64)+ to, tn = timed(eo, x, xs, qc, sk, f32), timed(en, x, xs, qc, sk, f32)+ line.append(f"{m}: {to:.1f} -> {tn:.1f}")+ print(f"TIME TP={world} {label} ({n} x {k}, sk {sk}) us a call, rows " + ", ".join(line), flush=True)+ del qc, q0+ torch.cuda.empty_cache()+ shutil.rmtree(work, ignore_errors=True)+ print("ALL PASS" if fails == 0 else f"{fails} FAIL", flush=True)+ sys.exit(1 if fails else 0)+++if __name__ == "__main__":+ try:+ main()+ except Exception as exc: # noqa: BLE001 - an error in the extension under test (e.g. a CUDA fault) is a failure+ print(f"FAIL the check stopped on {type(exc).__name__}: {str(exc).strip().splitlines()[0][:150]}", flush=True)+ sys.exit(1)