GLM-5.3-Flash EXL3 on 2x DGX Spark with TensorFold
Python
Patch 0086: long-context cold prefill - the indexer's prompt scoring takes one row and 32 pool blocks a program
BadAd8472a443439e9c
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 515fb07..bd60aba 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++- **Long-context cold prefill** (patch `0086-glm-prompt-scores-loop`): what grows with context in a cold prefill is+ the indexer's prompt scoring and selection (nsys on rank 0, two cold prompts of 35k and 226k tokens: the whole+ prefill 585 -> 687 us of kernel time a prompt token, `_scores` 16.3 -> 103.6 of it, `_select_rows` 3.0 ->+ 25.6, everything else flat). `0009`'s `_scores` ran 4 rows and one 64-pool block a program and reloaded each+ row's 8 KB of queries for every block; it now takes one row and 32 blocks a program (`SCORE_LOOP`), the row's+ queries and head weights loaded once, each block computed exactly as a 1-row program did. A 512-row block at+ row positions 35k / 113k / 300k: 1.354 / 4.298 / 11.304 -> 0.867 / 2.766 / 7.250 ms (8 warps, or one dot over+ all rows' heads, is faster still but changes the head sum's rounding). Every score bit and selection+ identical (`tools/scores_loop_check.py`, 37 checks). Live on three Sparks: the same prompts cold, 35k 17.87 ->+ 17.47 s, 226k 138.27 -> 126.60 s, replies byte-identical. `TF_GLM_SCORE_RB` is retired.+## 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..6c68578 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.+- `0086-glm-prompt-scores-loop` (the prompt scoring, one row and many pool blocks a program): 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..f089278 100644--- a/README.md+++ b/README.md@@ -562,6 +562,7 @@ applied with `patch -p0` in filename order); `start.sh` rebuilds or re-pulls the| KV cache | `0038-glm-kv-fp8` | the DSA latent cache and the indexer's pooled keys as FP8 rows (`KV=fp8`) | the 1M window with 4 requests fits || KV pool | `0072-glm-display-kv` | the first DSA latent planes in a span ending in the GPU's display reservation, which `MemAvailable` does not count; the pool's row copies of those planes by a kernel (a memcpy may not cross the span's two registrations) (`DISPLAY_KV_MIB`, by ezoushen) | 1792 MiB: ~277k more tokens at `PARALLEL=8`; the same bits, decode and prefill || Prompt | `0001-glm-exl3-prompt-experts`, `0004-glm-prompt-kernels`, `0009-glm-prefill-kernels`, `0020-glm-prompt-experts-order`, `0024-glm-prompt-select-rows`, `0028-glm-lean-prompt-scratch` | EXL3 expert kernels that keep a prompt chunk's rows in L2, launched in a better order; each row's input rotated once; dense attention only where the sparse pass needs it; token selection in blocks of 512 rows; smaller prompt scratch | faster prefill, less memory at 1M |+| Prompt, indexer | `0086-glm-prompt-scores-loop` | a prompt chunk's indexer scoring (`0009`'s `_scores`) takes one row and 32 pool blocks a program (`SCORE_LOOP`), the row's queries loaded once, instead of 4 rows and one block (`TF_GLM_SCORE_RB`, retired), which reloaded every row's queries for each 64-pool block | the scoring 36% faster at long context (the part of a cold prefill that grows with it); cold prefill at 226k 138.3 -> 126.6 s; the same bits || Prompt, two Sparks | `0010-glm-hc-split`, `0033-glm-prefill-overlap2`, `0017-glm-overlap-priority`, `0022-glm-overlap-normal-priority`, `0064-glm-split-connect-early` | hyper-connection glue split by rows between the Sparks, exchanges overlapped with the next rows' work (`SPLIT`); the split's send/receive connection opened before the weights and the cache pool (issue #36) | 50k prefill ~1,270 -> ~1,730 tok/s with 0009 and 0020; decode rounds pay ~1.5% || Prompt, KDA | `0012-glm-kda-chunked`, `0014-glm-kda-chunked-gb10`, `0039-glm-kda-chunked-kernel` | the linear-attention layers' prompt chunks in chunked (WY) form, one CUDA kernel (`KDA_CHUNKED`) | 50k prefill 29.3 -> 26.4 s, 149k 91.1 -> 84.5 s (one start each) || Prompt reuse | `0008-glm-prompt-grid`, `0015-glm-shared-prefix`, `0042-glm-prompt-replay`, `0054-glm-image-prompt-reuse`, `0060-glm-keep-thinking`, `0063-glm-kept-cap-superseded-first`, `0071-glm-shared-prefix-copy`, `0077-glm-kept-cap-shared-by-recency`, `0078-glm-take-over-decide-then-copy` | prompt chunks and kept states on a token grid; a shared system prompt's state reused (copied out of the conversation that wrote it, which keeps its own state, by ezoushen, #43); an identical prompt resumes from its kept end state; prompts with pictures resume too, their kept states told apart by each picture's content (by abhicnv007, issue #11); earlier turns' reasoning kept in the prompt (`TF_GLM_CLEAR_THINKING`, by kky42, #23); past the kept-state cap a conversation's superseded states go first (by Alexbob0, #32), and shared-prefix states by recency only, so a new agent run still finds its system prompt (diagnosed and the fix proposed by meleesciony, #75); a fresh conversation after a long one clones only the kept states that stay, not every one first (reserved +14.8 -> +1.4 GiB after 256k, 21 turns; upstream #421) | [Performance](#performance) |diff --git a/patches/0086-glm-prompt-scores-loop.patch b/patches/0086-glm-prompt-scores-loop.patchnew file mode 100644index 0000000..f220b53--- /dev/null+++ b/patches/0086-glm-prompt-scores-loop.patch@@ -0,0 +1,131 @@+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+@@ -93,43 +93,43 @@++ @triton.jit+ 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."""++ D: tl.constexpr, BP: tl.constexpr, L: tl.constexpr, RS: tl.constexpr, FP8: tl.constexpr):++ """Program (row, L pool blocks): s_p = sum_h w_h relu(scale * qi_h . pool_p) up to the row's position, heads++ padded to HP. FP8 (TF_GLM_KV=fp8): the pooled keys' e4m3 codes on the tensor cores, each pool's power-of-two scale++ on its dots. One row and L blocks a program, the row's queries and head weights loaded once for them (rows a++ program and one block, TF_GLM_SCORE_RB, reloaded a row's queries for every block); each block computes exactly as++ a 1-row program did, the same bits (tools/scores_loop_check.py)."""++- rb = tl.program_id(0)+- pb = tl.program_id(1)++ r = tl.program_id(0)++ g = tl.program_id(1)+ P = tl.load(POS)+- p = pb * BP + tl.arange(0, BP)+- # tiles past this row block's last visible complete pool store -inf without dot products (the same allocations)+- visible = (P + tl.minimum((rb + 1) * RB, R)) // 4+- if pb * BP >= visible:+- for i in tl.static_range(RB):+- r = rb * RB + i+- if r < R:+- tl.store(OUT + r * NP + p, float("-inf"), mask=p < NP)+- return+ d = tl.arange(0, D)+ hh = tl.arange(0, HP)+ hok = hh < H+- 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:+- npool = (P + 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+- 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"))+- tl.store(OUT + r * NP + p, sc, mask=p < NP)++ npool = (P + r + 1) // 4++ 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 j in range(0, L):++ pb = g * L + j++ p = pb * BP + tl.arange(0, BP)++ if pb * BP < NP:++ # blocks past the row's last visible complete pool store -inf without dot products (speed only: their++ # dots would be masked to -inf below)++ if pb * BP >= npool:++ tl.store(OUT + r * NP + p, float("-inf"), mask=p < NP)++ else:++ kok = p < npool++ k = tl.load(PK + p[:, None].to(tl.int64) * RS + d[None, :], mask=kok[:, None], other=0.0).to(tl.bfloat16)++ dots = tl.dot(q, tl.trans(k)) # [HP, BP] fp32; keys past npool loaded as 0++ if FP8:++ ks = row_scales(PKS, p.to(tl.int64), kok, D, RS)++ dots = dots * ks[None, :]++ sc = tl.sum(w[:, None] * tl.maximum(dots * scale, 0.0), axis=0)++ sc = tl.where(p < npool, sc, float("-inf"))++ tl.store(OUT + r * NP + p, sc, mask=p < NP)++++++SCORE_LOOP = 32 # pool blocks a _scores program takes (speed only; GB10: 32 >= 16 > 8 > 4)+++ @triton.jit+@@ -288,18 +288,6 @@+ 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+-+-+ @triton.jit+ 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+@@ -365,7 +353,8 @@+ 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;++ - _scores takes one row a program and SCORE_LOOP pool blocks, a row's keys masked to its own pools before its++ dot;+ - one kernel (_tokens) writes tokens and counts with select_tokens' integer formulas."""++ dev = qi.device+@@ -377,7 +366,6 @@+ 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()+ 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)+@@ -386,10 +374,10 @@+ 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), 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,+- RS=rs, FP8=fp8, num_warps=4)++ _scores[(n, triton.cdiv(triton.cdiv(NP, 64), SCORE_LOOP))](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,++ L=SCORE_LOOP, 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)diff --git a/tools/scores_loop_check.py b/tools/scores_loop_check.pynew file mode 100644index 0000000..476be34--- /dev/null+++ b/tools/scores_loop_check.py@@ -0,0 +1,150 @@+#!/usr/bin/env python3+"""Checks for patch 0086 (the indexer's prompt scoring, one row and SCORE_LOOP pool blocks a program), run on a GPU+inside the image that scripts/prepare.sh built:++ docker run --rm --gpus all --entrypoint python -v "$PWD/tools/scores_loop_check.py:/c.py" tensorfold-glm53:v0.6.0 \+ /c.py++The patched sparse._select_prompt against a copy of it with the kernel before the patch (copied below, launched as+before: 4 rows and one 64-pool block a program, 4 warps): every score block each hands to top_pools is captured and+compared BIT FOR BIT (the whole [rows, NP] block, -inf columns included; buffers pre-filled so an unwritten score shows+up), then the selection's counts and counted rows' tokens. Cases, for FP8 and bf16 pooled keys: 512-row chunks at row+positions 0 (dense), 1,800 (across SPARSE_FROM), 35k, 113k, 300k and the cache's end; 1, 300 and 1,024 rows (two+blocks: the second block's offset). Needs ~3 GiB of GPU memory. Exit code 1 when a check fails.+"""+import sys++import torch+import triton+import triton.language as tl++from tensorfold.families.glm5_next.cuda import kv8, sparse+from tensorfold.families.glm5_next.cuda.kv8 import row_scales++H, D, KEY = 32, 128, 128+CAP = 1_048_576+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 _scores_before(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):+ """sparse._scores before patch 0086, verbatim."""++ rb = tl.program_id(0)+ pb = tl.program_id(1)+ P = tl.load(POS)+ p = pb * BP + tl.arange(0, BP)+ visible = (P + tl.minimum((rb + 1) * RB, R)) // 4+ if pb * BP >= visible:+ for i in tl.static_range(RB):+ r = rb * RB + i+ if r < R:+ tl.store(OUT + r * NP + p, float("-inf"), mask=p < NP)+ return+ d = tl.arange(0, D)+ hh = tl.arange(0, HP)+ hok = hh < H+ 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)+ 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:+ npool = (P + 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))+ 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"))+ tl.store(OUT + r * NP + p, sc, mask=p < NP)+++def old_select_prompt(qi, wts, pk, pos, R, np_max, pos_dev):+ """sparse._select_prompt before patch 0086 (the old kernel at its default 4 rows a program)."""+ NP = sparse.pool_count(pos, R, np_max)+ B = min(R, sparse.SELECT_ROWS)+ buf = torch.full((B * sparse.pool_bucket(pos, R, np_max),), 7.0, dtype=torch.float32, device=dev)+ pkv, pks, rs, fp8 = kv8.parts(pk)+ width = sparse.TOPK_POOLS * sparse.POOL + sparse.POOL - 1+ tokens = torch.empty((R, width), dtype=torch.int32, device=dev)+ counts = torch.empty((R,), dtype=torch.int32, device=dev)+ 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_before[(triton.cdiv(n, 4), triton.cdiv(NP, 64))](qi[a:a + n], wts[a:a + n], wts.stride(0), pkv, pks,+ scores, at, n, NP, D ** -0.5,+ 1.0 / 5.656854249492381, H=H, HP=32, D=D, BP=64,+ RB=4, RS=rs, FP8=fp8, num_warps=4)+ pools = sparse.top_pools(scores, sparse.TOPK_POOLS)+ sparse._tokens[(n,)](pools, at, tokens[a:a + n], counts[a:a + n], W=width, K=sparse.TOPK_POOLS,+ PL=sparse.POOL, BLOCK=1024, num_warps=4)+ return tokens, counts+++captured = []+_top_pools = sparse.top_pools+++def capturing_top_pools(scores, k, pos=None):+ captured.append(scores.clone())+ return _top_pools(scores, k, pos)+++def run(fn, *args):+ """fn's tokens and counts, and the score blocks it handed to top_pools (the empty-allocated buffers are pre-filled+ with 7.0 so an unwritten score shows up)."""+ captured.clear()+ empty = torch.empty++ def filled(*a, **kw):+ t = empty(*a, **kw)+ if t.dtype == torch.float32:+ t.fill_(7.0)+ return t+ sparse.top_pools, torch.empty = capturing_top_pools, filled+ try:+ tokens, counts = fn(*args)+ torch.cuda.synchronize()+ finally:+ sparse.top_pools, torch.empty = _top_pools, empty+ return tokens, counts, list(captured)+++check("patch 0086 applied: SCORE_LOOP 32", getattr(sparse, "SCORE_LOOP", None) == 32, f"{getattr(sparse, 'SCORE_LOOP', None)}")+torch.manual_seed(0)+raw = torch.randn(CAP // sparse.POOL + 2, KEY, device=dev)+caches = {"fp8": kv8.quantize_rows(raw), "bf16": raw.to(torch.bfloat16)}+np_max = raw.shape[0] - 2+cases = [(P, 512) for P in (0, 1_800, 35_000, 113_000, 300_000, CAP - 512)] + [(40_000, 1), (40_000, 300), (113_000, 1_024)]+for kind, pk in caches.items():+ for P, R in cases:+ qi = torch.randn(R, H * D, device=dev, dtype=torch.bfloat16)+ ikr = torch.randn(R, KEY + H, device=dev, dtype=torch.bfloat16)+ wts = ikr[:, KEY:]+ pos_dev = torch.tensor([P], device=dev, dtype=torch.int64)+ t0, c0, s0 = run(old_select_prompt, qi, wts, pk, P, R, np_max, pos_dev)+ t1, c1, s1 = run(sparse._select_prompt, qi, wts, pk, P, R, np_max, pos_dev)+ bits = len(s0) == len(s1) and all(torch.equal(a.view(torch.int32), b.view(torch.int32)) for a, b in zip(s0, s1))+ diff = sum(int((a.view(torch.int32) != b.view(torch.int32)).sum()) for a, b in zip(s0, s1)) if len(s0) == len(s1) else -1+ check(f"{kind} {R} rows at {P}: every score bit ({len(s1)} block(s))", bits, f"{diff} differ, blocks {len(s0)}/{len(s1)}")+ counted = c0 > 0+ same = torch.equal(c0, c1) and torch.equal(t0[counted], t1[counted])+ check(f"{kind} {R} rows at {P}: counts and counted rows' tokens", same,+ f"counts differ {int((c0 != c1).sum())}, tokens differ {int((t0[counted] != t1[counted]).sum())}")+ del qi, ikr, s0, s1+ torch.cuda.empty_cache()+print("ALL PASS" if fails == 0 else f"{fails} FAIL", flush=True)+sys.exit(1 if fails else 0)