GLM-5.3-Flash EXL3 on 2x DGX Spark with TensorFold
Python
Patch 0085: long-context decode - the split selection's last pass sums only the chunks before its own
BadAd84fa40ead78bdb
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 515fb07..6da9e4e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -3,6 +3,21 @@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++- **Long-context decode** (patch `0085-glm-select-split-loop`): the DSA indexer's split top-k selection+ (`select_split`, in `0029`'s segmented decode windows) ran its last pass as one `CP x 256` tile per chunk program,+ masked to the chunks before it. `CP` comes from the selection scratch, which `verify.py` sizes for the whole KV+ pool (5,791,744 rows at `PARALLEL=4` on three Sparks: 512 chunks a row), not the row's context, so every program+ loaded and summed the full table: on rank 0 at 226k, 5.3 ms a launch and 92% of the growth of one request's decode+ round from 35k (nsys: the selection 9.3 -> 56.9 ms of a round's GPU time, everything else +4.3). The pass now sums+ only the earlier chunks' histograms, 16 at a time (`SPLIT_BLK`). The whole selection call, scoring included, at 16+ rows: 0.96 -> 0.10 ms at 35k, 5.79 -> 0.28 at 226k, 15.68 -> 0.64 at 590k, 27.87 -> 1.08 at 1.04M; four requests x+ 8 rows at 590k 32.46 -> 1.27 (11 layers a round). Integer sums in another order: the tokens and counts are+ identical (`tools/select_split_check.py`: 149 checks against the kernel before the patch and a torch oracle).+ Live on three Sparks (`PARALLEL=4`), one request: decode at 35k / 226k / 590k 182.6 / 111.2 / 66.2 ->+ 203.0 / 191.0 / 184.4 tok/s, replies byte-identical.+## v1.8 (2026-10-06): pictures read once, quoted markers, capacity refusals, and the take-over memory fixImage: `v0.6.0-31557ed1cef6` (`sha256:cbb4b3c66273e2965dd40a7227e7a5243db333fe250113fb3987462ad4f12588`), 82 patches, for two and three Sparks (v1.7.1's plus `0078`-`0083`). Every change below was alsodiff --git a/CREDITS.md b/CREDITS.mdindex 08c4ae3..31f52d1 100644--- a/CREDITS.md+++ b/CREDITS.md@@ -118,6 +118,8 @@ checkpoint's ShapleyMcg attribution and the drafter's license).[johnwhited](https://github.com/johnwhited) (#48); the admission check and the abort-on-delivery-failure semanticsfollow [vLLM](https://github.com/vllm-project/vllm) v1's `check_admission` and generate-abort behaviour(Apache 2.0) as a reference.+- `0085-glm-select-split-loop` (the split selection's last pass over the earlier chunks only): by+ [BadAd84](https://github.com/BadAd84).- Every patch, except the parts credited above: by MiaAI-Lab, developed with[Claude Code](https://claude.com/claude-code), under the Apache License 2.0; the TensorFold code the patches modify orquote as context stays under TensorFold's licenses (Apache 2.0, and MIT for code written before v0.6.0; seediff --git a/README.md b/README.mdindex 5956b8c..24f8968 100644--- a/README.md+++ b/README.md@@ -568,6 +568,7 @@ applied with `patch -p0` in filename order); `start.sh` rebuilds or re-pulls the| Decode | `0013-glm-decode-rounds`, `0016-glm-decode-kernels`, `0019-glm-decode-kernels2`, `0031-glm-decode-index-regs` | verify windows of up to 16 rows; faster decode matmuls, hyper-connection mixing and indexer scoring | faster decode rounds; long copy drafts (`COPY_MAX` 15: edit replies 84 -> 119 tok/s) || Decode, memory | `0046-glm-l2-prefetch`, `0047-glm-exl3-decode-loads` | the next kernels' weights prefetched into L2 during each layer's all-gathers (`TF_GLM_L2PF`, adapted from jayleaton/glm53-tensorfold-spark's patch 0460); the routed experts' trellis as 16-byte non-coherent loads a step ahead (`TF_GLM_EXL3_LOADS`, adapted from its patch 0580) | with `TF_ROCE_MAX_KB=512`: one request's prose 48.36 -> 49.68 tok/s, code 59.54 -> 61.49 (+2.7% / +3.3%); 4 at once prose 74.8 -> 76.6, code 100.0 -> 102.7 (two starts each); the same bits || Decode, indexer | `0043-glm-visible-pools` | a decode row's token scoring and split selection bounded to the pools it can see (TensorFold v0.6.0 bounds its one-program selection, PR #140) | the same tokens |+| 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 | one request at 226k: the selection 5.79 -> 0.28 ms a layer (11 a round); the same tokens || Link | `0006-cuda-roce-allgather`, `0052-cuda-roce-startup` | the small all-gathers as one-shot RDMA writes over RoCE (`COMM=roce`; up to 512 KiB, `TF_ROCE_MAX_KB`: code at 4 streams +1.4%); until the engine is built, each eager gather first waits for the peer in an NCCL barrier, and the RoCE kernel builds during setup (`TF_ROCE_WAIT_S`, 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 |diff --git a/patches/0085-glm-select-split-loop.patch b/patches/0085-glm-select-split-loop.patchnew file mode 100644index 0000000..bb04f9c--- /dev/null+++ b/patches/0085-glm-select-split-loop.patch@@ -0,0 +1,55 @@+diff --git tensorfold/families/glm5_next/cuda/sparse.py tensorfold/families/glm5_next/cuda/sparse.py+--- tensorfold/families/glm5_next/cuda/sparse.py++++ tensorfold/families/glm5_next/cuda/sparse.py+@@ -751,7 +751,7 @@+ @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,+- VIS: tl.constexpr, TOKS: tl.constexpr):++ VIS: tl.constexpr, TOKS: tl.constexpr, BLK: 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 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+@@ -797,13 +797,20 @@+ 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)++ # earlier chunks: scores above the prefix at bytes 0..2 (GT), at byte 3 and equal to it (their last histograms),++ # BLK chunks an iteration over the chunks before this one only: a CP x 256 tile masked to them costs every++ # program the whole table (CP is the scratch's, sized for the pool, not the row's context)++ gt = tl.zeros((), dtype=tl.int32)++ equal_seen = tl.zeros((), dtype=tl.int32)++ cb = tl.arange(0, BLK)++ for c0 in range(0, c, BLK):++ ci = c0 + cb++ before = ci < c++ last = tl.load(HIST + (r * CP + ci[:, None]) * 256 + bins[None, :], mask=before[:, None], other=0)++ gt += tl.sum(tl.load(GT + r * CP + ci, mask=before, other=0), 0)++ gt += tl.sum(tl.sum(tl.where(bins[None, :] > d, last, 0), 1), 0)++ equal_seen += tl.sum(tl.sum(tl.where(bins[None, :] == d, last, 0), 1), 0)++ written = gt + 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)+@@ -827,6 +834,7 @@+ 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++SPLIT_BLK = 16 # step 4's earlier chunks an iteration (speed only)+++ def split_chunk(np_: int) -> int:+@@ -872,5 +880,5 @@+ 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)++ VIS=pos is not None and not seg, TOKS=toks, BLK=SPLIT_BLK, num_warps=warps)+ return outdiff --git a/tools/select_split_check.py b/tools/select_split_check.pynew file mode 100644index 0000000..408b505--- /dev/null+++ b/tools/select_split_check.py@@ -0,0 +1,242 @@+#!/usr/bin/env python3+"""Checks for patch 0085 (the split selection's last step over the chunks before its own only), run on a GPU inside+the image that scripts/prepare.sh built:++ docker run --rm --gpus all --entrypoint python -v "$PWD/tools/select_split_check.py:/c.py" tensorfold-glm53:v0.6.0 \+ /c.py++The patched sparse.select_split against the kernel before the patch (copied below; the whole token and count+buffers) and against an independent torch oracle (each sparse row's 512 best complete pools, ties to the lower pool,+ascending, then its incomplete pool's tokens):+ - segmented windows through seg_select_tokens (the indexer's own scores) at the engine's scratch width (a pool of+ 5,791,744 rows: 512 chunk programs a row), a stream-sized one (1,048,592: 128) and a small one (65,536: 8 programs+ of 2,048 scores); 1 to 4 streams, dense and sparse rows, rows across a chunk boundary, 2,060 to 1.04M tokens+ - tie-heavy (8 values), all-equal and signed-zero / -inf / huge scores straight into select_split+ - SPLIT_BLK 1, 4 and 32 give the bits of the default 16+Needs ~1 GiB of GPU memory (a free Spark, or the server stopped). Exit code 1 when a check fails.+"""+import sys+from functools import partial++import torch+import triton+import triton.language as tl++from tensorfold.families.glm5_next.cuda import kv8, segments, sparse+from tensorfold.families.glm5_next.cuda.sparse import _order_key, _split_digits, _visible_bound++H, D, KEY = 32, 128, 128+WIDTHS = {"cp512": 5_791_744, "cp128": 1_048_592, "cp8": 65_536}+K, PL, W = sparse.TOPK_POOLS, sparse.POOL, sparse.TOKENS+dev = torch.device("cuda")+fails = 0+++def check(name, ok, detail=""):+ global fails+ print(("PASS " if ok else "FAIL ") + name + ("" if ok else f": {detail}"), flush=True)+ fails += 0 if ok else 1+++def _select_split_before(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, VIS: tl.constexpr, TOKS: tl.constexpr,+ BLK: tl.constexpr):+ """_select_split before patch 0085 (step 4: one CP x 256 tile masked to the earlier chunks); BLK unused."""++ 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+ npool = NP+ else:+ 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+ 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:+ 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+ 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 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 = 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(npool > K, n, 0).to(tl.int32))+ else:+ tl.store(OUT + r * K + slot, i.to(tl.int64), mask=take)+++PATCHED = sparse._select_split+++def order_key(s):+ """_order_key in int64: the float32 scores' order as unsigned 32-bit keys (-0 counted as +0)."""+ b = (s.float() + 0.0).view(torch.int32).to(torch.int64)+ return (b & 0xFFFFFFFF) ^ torch.where(b < 0, torch.full_like(b, 0xFFFFFFFF), torch.full_like(b, 0x80000000))+++def oracle(scores, pos, spr):+ """Each sparse row's K best complete pools (ties to the lower pool) ascending as tokens, its incomplete pool's+ tokens after them (-1 past its position), and its count (0: dense rows, and rows of K pools or fewer)."""+ R = scores.shape[0]+ toks = torch.full((R, W), -1, dtype=torch.int32)+ cnt = torch.zeros(R, dtype=torch.int32)+ for r in range(R):+ q = int(pos[r])+ npool = (q + 1) // PL+ if not int(spr[r]) or npool <= K:+ continue+ best = torch.sort(-order_key(scores[r, :npool]), stable=True).indices[:K]+ sel = torch.sort(best).values+ toks[r, :K * PL] = (sel[:, None] * PL + torch.arange(PL)).reshape(-1).to(torch.int32)+ n = K * PL+ for j in range(PL - 1):+ t = npool * PL + j+ toks[r, K * PL + j] = t if t <= q else -1+ n += int(t <= q)+ cnt[r] = n+ return toks, cnt+++def make(contexts, rows_each):+ R = sum(rows_each)+ rows = segments.SegRows(R, dev, max_segs=max(segments.SEGS_DEFAULT, len(contexts)))+ segs, base = [], 0+ for ctx, n in zip(contexts, rows_each):+ segs.append((base, ctx - n, n))+ base += -(-ctx // segments.EXTENT) * segments.EXTENT+ pk = kv8.quantize_rows(torch.randn(base // PL + 2, KEY, device=dev))+ rows.set(segs)+ torch.cuda.synchronize()+ qi = torch.randn(R, H * D, device=dev, dtype=torch.bfloat16)+ ikr = torch.randn(R, KEY + H, device=dev, dtype=torch.bfloat16)+ return qi, ikr[:, KEY:], pk, rows, R+++def run(fn, scratch, R, kernel=None):+ """fn's tokens and counts (buffers reset first, so every unwritten slot compares too)."""+ scratch.tokens.fill_(-1)+ scratch.counts.fill_(-7)+ if kernel is not None:+ sparse._select_split = kernel+ try:+ fn()+ torch.cuda.synchronize()+ finally:+ sparse._select_split = PATCHED+ return scratch.tokens[:R].cpu(), scratch.counts[:R].cpu()+++def compare(name, got, ref, o, pos, spr):+ same = torch.equal(got[0], ref[0]) and torch.equal(got[1], ref[1])+ bad = [r for r in range(got[0].shape[0]) if int(got[1][r]) != int(o[1][r])+ or (int(o[1][r]) > 0 and not torch.equal(got[0][r], o[0][r]))]+ check(f"{name}: the bits before the patch", same,+ f"{int((got[0] != ref[0]).sum())} tokens, {int((got[1] != ref[1]).sum())} counts differ")+ check(f"{name}: oracle", not bad, f"rows {bad[:6]} (pos {[int(pos[r]) for r in bad[:6]]}, "+ f"count {[int(got[1][r]) for r in bad[:6]]} vs {[int(o[1][r]) for r in bad[:6]]})")+++def special(shape, kind, npool_max):+ g = torch.Generator(device=dev).manual_seed(5)+ s = torch.zeros(shape, device=dev)+ if kind == "ties":+ s[:, :npool_max] = torch.randint(0, 8, (shape[0], npool_max), device=dev, generator=g).float()+ elif kind == "special":+ v = torch.randn(shape[0], npool_max, device=dev, generator=g)+ pick = torch.randint(0, 8, v.shape, device=dev, generator=g)+ v = torch.where(pick == 0, torch.full_like(v, -0.0), v)+ v = torch.where(pick == 1, torch.full_like(v, float("-inf")), v)+ v = torch.where(pick == 2, torch.full_like(v, 3.0e38), v)+ v = torch.where(pick == 3, torch.full_like(v, -3.0e38), v)+ v = torch.where(pick == 4, torch.zeros_like(v), v)+ s[:, :npool_max] = v+ return s # "equal": all zeros+++def seg_case(name, contexts, rows_each, widths, blk_sweep=False):+ qi, wts, pk, rows, R = make(contexts, rows_each)+ pos, spr = rows.pos[:R].cpu(), rows.sparse[:R].cpu()+ npool_max = (int(pos.max()) + 1) // PL+ for wname in widths:+ scratch = segments.SelectScratch(R, WIDTHS[wname], dev)+ label = f"{name} {wname}"+ call = partial(sparse.seg_select_tokens, qi, wts, pk, rows, scratch)+ got = run(call, scratch, R)+ scores = scratch.scores[:R].cpu()+ ref = run(call, scratch, R, _select_split_before)+ compare(label, got, ref, oracle(scores, pos, spr), pos, spr)+ for kind in ("ties", "equal", "special"):+ s = special(scratch.scores[:R].shape, kind, npool_max)+ direct = partial(sparse.select_split, s, K, scratch=scratch.split, rows=rows, tokens=scratch.tokens[:R],+ counts=scratch.counts[:R])+ compare(f"{label} {kind} scores", run(direct, scratch, R), run(direct, scratch, R, _select_split_before),+ oracle(s.cpu(), pos, spr), pos, spr)+ del s, direct+ if blk_sweep:+ for blk in (1, 4, 32):+ sparse.SPLIT_BLK = blk+ try:+ alt = run(call, scratch, R)+ finally:+ sparse.SPLIT_BLK = 16+ check(f"{label}: SPLIT_BLK {blk} = 16's bits", torch.equal(alt[0], got[0]) and torch.equal(alt[1], got[1]))+ del scratch, call+ torch.cuda.empty_cache()+++check("patch 0085 applied: SPLIT_BLK 16", getattr(sparse, "SPLIT_BLK", None) == 16, f"{getattr(sparse, 'SPLIT_BLK', None)}")+torch.manual_seed(0)+seg_case("1 x 16 @ 2,060 (dense/sparse edge)", [2_060], [16], ("cp512", "cp128", "cp8"))+seg_case("1 x 16 @ 49,160 (chunk edge)", [49_160], [16], ("cp512", "cp128", "cp8"))+seg_case("1 x 16 @ 35k", [35_000], [16], ("cp512", "cp128", "cp8"))+seg_case("1 x 16 @ 226k", [226_000], [16], ("cp512", "cp128"))+seg_case("1 x 16 @ 590k", [590_000], [16], ("cp512", "cp128"), blk_sweep=True)+seg_case("1 x 3 @ 1.04M", [1_040_000], [3], ("cp512", "cp128"))+seg_case("4 streams mixed", [1_000, 50_000, 300_000, 700_000], [3, 8, 5, 16], ("cp512", "cp128"), blk_sweep=True)+print(f"{'ALL PASS' if fails == 0 else f'{fails} FAIL'}", flush=True)+sys.exit(1 if fails else 0)