Skip to content

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

Python

Patch 0104: faster decode at three Sparks - 32-head attention tiles from 5 rows when a rank has 17 to 24 heads

BadAd848fcf859491a3
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 54a3f69..62cf7f0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -3,6 +3,15 @@
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
+
+- **Three-Spark decode attention in one wave** (patch `0104-glm-seg-attention-tp3-tiles`, by [BadAd84](https://github.com/BadAd84)):
+ `seg_head_block` gave 32-head tiles from 8 rows, sized for two Sparks' 32 heads a rank. At three Sparks
+ (22 / 21 heads) the 16-head tiles are two programs a row and chunk, so from 5 rows they pass the GB10's
+ 48 SMs and run in two waves. A rank of 17 to 24 heads now takes 32-head tiles from 5 rows; 16 and 32 heads
+ keep 8. The chunk pass at 5 / 6 / 7 rows on one GB10: 92.4 / 103.3 / 108.1 -> 65.3 / 65.9 / 66.4 us a
+ call; the same bits. GPU check: `tools/seg_head_block_check.py`.
+
## v1.10 (2026-10-08): the effort line at the tail (opt-in), a kept-state share, and a checked second rail
Image: `v0.6.0-a1897d591f70` (`sha256:bc34d7d63f978cf601f42863b284bc95a567c50c10e9adb0866a635be568bf5f`), 96 patches (v1.9.1's plus `0096`, `0097`). Tested live on two
diff --git a/CREDITS.md b/CREDITS.md
index 521996e..7959087 100644
--- a/CREDITS.md
+++ b/CREDITS.md
@@ -139,6 +139,7 @@ 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 of
dispram 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.
+- `0104-glm-seg-attention-tp3-tiles` (32-head tiles from 5 rows at 17-24 heads): 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): by
Lukasz 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.md
index 2bace9c..0da04c4 100644
--- a/README.md
+++ b/README.md
@@ -635,6 +635,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, attention | `0104-glm-seg-attention-tp3-tiles` | a rank of 17-24 heads (TP=3: 22 / 21) takes its heads in one 32-head tile a row from 5 rows instead of 8 (`seg_head_block(R, H)`); 16 heads (TP=4) and 32 (TP=2) keep 8 (by [BadAd84](https://github.com/BadAd84)) | TP=3: the chunk pass at 5-7 rows 92-108 -> 65-66 us a call (one GB10); 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 +712,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/seg_head_block_check.py [--time]` | patch 0104's checks: `seg_attention` under the new rule against the old rule's tiles bit for bit at 22 and 21 heads, and the launch grid at 21, 22 and 32 heads; 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/0104-glm-seg-attention-tp3-tiles.patch b/patches/0104-glm-seg-attention-tp3-tiles.patch
new file mode 100644
index 0000000..d706e2b
--- /dev/null
+++ b/patches/0104-glm-seg-attention-tp3-tiles.patch
@@ -0,0 +1,45 @@
+# The DSA layers' decode attention (latent.seg_attention) gives a rank of 17-24 heads (TP=3: 22 / 21) one 32-head
+# tile a row from 5 rows instead of 8 (seg_head_block(R, H)). Its 16-head tiles are two programs a row and chunk, which
+# from 5 rows pass the GB10's 48 SMs and run in two waves. 16 heads (TP=4) and 32 (TP=2) a rank keep the 8-row rule. Heads a tile
+# never change a row's bits (head_block). tools/seg_head_block_check.py.
+
+diff --git tensorfold/families/glm5_next/cuda/latent.py tensorfold/families/glm5_next/cuda/latent.py
+--- tensorfold/families/glm5_next/cuda/latent.py
++++ tensorfold/families/glm5_next/cuda/latent.py
+@@ -815,13 +815,22 @@ def seg_chunks() -> int:
+
+
+ SEG_WIDE_ROWS = 8 # segmented windows from this many rows take 32-head tiles (keys read once; fewer programs)
++# Patch 0104: a rank of more than HB and at most SEG_FEW_HEADS heads (TP=3: 22 on rank 0, 21 on ranks 1 and 2) takes them from
++# SEG_FEW_WIDE_ROWS rows. Its 16-head tiles are two programs a row and chunk (16 + 6 heads), so from 5 rows x 5 chunks
++# they pass the GB10's 48 SMs and run in two waves, while one 22-head tile a row stays in one wave up to 9 rows.
++# Measured cold on a GB10 (11 calls a graph, L2 flushed, 180k-596k, the same bits in every arm): 5 / 6 / 7
++# rows 93.6 / 104.6 / 108.7 us a call with 16 heads, 66.8 / 67.2 / 67.7 with 22; 1-4 rows stay with 16 (58-59 vs
++# 61-66). TP=2's 32 heads a rank keep SEG_WIDE_ROWS (its own measurement), and so do TP=4's 16 (one 16-head tile a row already).
++SEG_FEW_HEADS = 24
++SEG_FEW_WIDE_ROWS = 5
+
+
+-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_head_block(R: int, H: int) -> int:
++ """Heads per program of a segmented window of R rows of H heads a rank: 16 for a few rows (more programs in
++ flight), 32 (a rank's heads in one tile) from SEG_WIDE_ROWS, or from SEG_FEW_WIDE_ROWS with HB < H <= SEG_FEW_HEADS
++ heads. 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_FEW_WIDE_ROWS if HB < H <= SEG_FEW_HEADS else SEG_WIDE_ROWS) else HB
+
+
+ def seg_attention(qa: torch.Tensor, cache: torch.Tensor, rows, tokens: torch.Tensor | None,
+@@ -841,7 +850,7 @@ def seg_attention(qa: torch.Tensor, cache: torch.Tensor, rows, tokens: torch.Ten
+ else:
+ W = tokens.shape[1]
+ n = nch * R * H
+- hb = seg_head_block(R) if hb is None else hb
++ hb = seg_head_block(R, H) 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}")
+ vals, scl, rs, fp8 = _cache_parts(cache, LW)
diff --git a/tools/seg_head_block_check.py b/tools/seg_head_block_check.py
new file mode 100644
index 0000000..2d10498
--- /dev/null
+++ b/tools/seg_head_block_check.py
@@ -0,0 +1,169 @@
+#!/usr/bin/env python3
+"""tools/seg_head_block_check.py [--time]: patch 0104 - latent.seg_head_block(R, H): a rank of 17-24 heads (TP=3:
+22 / 21) takes its heads in one 32-head tile a row from 5 rows, not 8; 16 (TP=4) and 32 (TP=2) heads keep the 8-row rule.
+Run in the image built with patch 0104, on one GPU:
+docker run --rm --gpus all --entrypoint python -v "$PWD/tools/seg_head_block_check.py:/c.py" <image> /c.py
+
+1. bits: latent.seg_attention under the new rule returns, for every call, the whole output (pre-filled with NaN) of the
+ same call with the old rule's tiles (32 heads from 8 rows, else 16) forced through ``hb``: windows of 1-16 rows in
+ 1, 2 and 4 streams at ~180k / ~300k / ~596k, 22 and 21 heads, sparse rows over 2,051 selected tokens, and a dense
+ window (rows over their stream's first keys, ``tokens`` None); heads a tile never change a row's bits;
+2. mechanism: the launch grid of the Triton chunk pass (_seg_chunks, recorded) has ceil(H / 32) head blocks exactly
+ where the rule says: from 5 rows at 22 and 21 heads, from 8 rows at 32 heads (TP=2), else ceil(H / 16).
+The CUDA chunk pass of patch 0108 (when the image has it) is switched off here (TF_GLM_SEG_CHUNKS_CUDA=0): it gives
+either tile the same bits and does not read the head tile. One PASS / FAIL line a check; exits 1 on any FAIL (on an
+image without the patch: at the first check).
+
+--time: cold (L2 flushed), 11 calls a CUDA graph (each its own keys), the new rule against the old one at 4-8 rows,
+22 heads (TP=3 rank 0); at 32 heads (TP=2) the rule does not change."""
+import inspect
+import os
+import statistics
+import sys
+
+os.environ["TF_GLM_SEG_CHUNKS_CUDA"] = "0"
+os.environ["TF_GLM_LATENT_STAGES"] = "3"
+
+import torch # noqa: E402
+import triton # noqa: E402
+
+from tensorfold.families.glm5_next.cuda import kv8, latent, sparse # noqa: E402
+from tensorfold.families.glm5_next.cuda.segments import SegRows # noqa: E402
+
+fails = 0
+
+
+def check(ok, msg):
+ global fails
+ print(("PASS " if ok else "FAIL ") + msg, flush=True)
+ fails += not ok
+
+
+def old_rule(R):
+ """seg_head_block before the patch (SEG_WIDE_ROWS = 8 at any head count)."""
+ return latent.HB_WIDE if R >= 8 else latent.HB
+
+
+check("H" in inspect.signature(latent.seg_head_block).parameters and hasattr(latent, "SEG_FEW_HEADS"),
+ "patch 0104 applied: seg_head_block(R, H)")
+if fails:
+ print("1 FAIL", flush=True)
+ sys.exit(1)
+dev = torch.device("cuda")
+g = torch.Generator(device=dev).manual_seed(88)
+LW = 512
+TOK = sparse.TOKENS
+grids = []
+real = latent._seg_chunks
+
+
+class Recorder:
+ def __getitem__(self, grid):
+ grids.append(tuple(grid))
+ return real[grid]
+
+
+latent._seg_chunks = Recorder()
+
+
+def cache_for(rows):
+ c = kv8.zeros(rows, LW, "fp8", dev)
+ codes = torch.randint(0, 0x7E, (rows, LW), dtype=torch.int32, device=dev, generator=g)
+ sign = torch.randint(0, 2, (rows, LW), dtype=torch.int32, device=dev, generator=g) * 0x80
+ c[:, :LW] = (codes | sign).to(torch.uint8)
+ c[:, LW:LW + 4] = torch.tensor([2.0 ** -8], dtype=torch.float32, device=dev).view(torch.uint8).repeat(rows, 1)
+ return c
+
+
+def selections(streams, rows_per, ctx):
+ toks = torch.zeros((streams * rows_per, TOK + 1), dtype=torch.int32, device=dev)
+ for st in range(streams):
+ pools = torch.randperm(ctx // 4 - 1, device=dev, generator=g)[:sparse.TOPK_POOLS].sort().values
+ t = (pools[:, None] * 4 + torch.arange(4, device=dev)[None, :]).reshape(-1)
+ for j in range(rows_per):
+ p = ctx + j
+ sel = torch.cat([t, torch.arange(p // 4 * 4, p + 1, device=dev)])[:TOK]
+ toks[st * rows_per + j, :sel.numel()] = sel.to(torch.int32)
+ return toks
+
+
+def window(streams, rows_per, ctx, H, dense=False):
+ R = streams * rows_per
+ stride = ctx + 4096
+ cache = cache_for(streams * stride)
+ rows = SegRows(R, dev, max_segs=max(4, streams))
+ rows.pos.copy_(torch.tensor([ctx + j for _ in range(streams) for j in range(rows_per)], dtype=torch.int32))
+ rows.base.copy_(torch.tensor([s * stride for s in range(streams) for _ in range(rows_per)], dtype=torch.int32))
+ qa = (torch.randn((R, H, LW), device=dev, generator=g) * 0.5).to(torch.bfloat16)
+ s = latent.LatentScratch(max(R, 32), H, latent.seg_chunks(), dev, lw=LW)
+ if dense:
+ rows.sparse.fill_(0)
+ return R, cache, rows, None, None, qa, s
+ rows.sparse.fill_(1)
+ counts = torch.full((R,), TOK, dtype=torch.int32, device=dev)
+ return R, cache, rows, selections(streams, rows_per, ctx), counts, qa, s
+
+
+def run(R, cache, rows, toks, counts, qa, s, hb):
+ out = torch.full(qa.shape, float("nan"), dtype=torch.bfloat16, device=dev)
+ grids.clear()
+ latent.seg_attention(qa, cache, rows, toks, counts, s, scale=0.0625, out=out, hb=hb)
+ torch.cuda.synchronize()
+ return out, list(grids)
+
+
+for H in (22, 21):
+ for streams, ctx, rlist, dense in ((1, 180000, range(1, 17), False), (2, 300000, (1, 2, 3, 4, 6), False),
+ (4, 596000, (1, 2, 3, 6), False), (1, 1500, (1, 3, 5, 7, 9), True)):
+ for rp in rlist:
+ R, cache, rows, toks, counts, qa, s = window(streams, rp, ctx, H, dense)
+ new, g_new = run(R, cache, rows, toks, counts, qa, s, None)
+ old, _ = run(R, cache, rows, toks, counts, qa, s, old_rule(R))
+ want = latent.HB_WIDE if R >= 5 else latent.HB
+ check(not torch.isnan(new.float()).any() and torch.equal(new.view(torch.int16), old.view(torch.int16))
+ and len(g_new) == 1 and g_new[0][1] == triton.cdiv(H, want),
+ f"{H} heads, {streams} x {rp} rows ({R}) at {ctx}{' dense' if dense else ''}: the old rule's bits, "
+ f"grid {g_new} ({triton.cdiv(H, want)} head blocks wanted)")
+ del cache, s
+ torch.cuda.empty_cache()
+check(all(latent.seg_head_block(R, 32) == old_rule(R) for R in range(1, 25)),
+ "32 heads a rank (TP=2): the old rule at 1-24 rows")
+check(all(latent.seg_head_block(R, H) == (latent.HB_WIDE if R >= 5 else latent.HB)
+ for H in (17, 21, 22, 24) for R in range(1, 25)), "17-24 heads a rank (TP=3): 32-head tiles from 5 rows")
+check(all(latent.seg_head_block(R, H) == old_rule(R) for H in (16, 25) for R in range(1, 25)),
+ "16 heads (TP=4) and 25 heads a rank: the old rule")
+
+if "--time" in sys.argv and fails == 0:
+ latent._seg_chunks = real
+ flush = torch.empty((256 << 20,), dtype=torch.uint8, device=dev)
+
+ def graph_us(call):
+ call()
+ torch.cuda.synchronize()
+ gr = torch.cuda.CUDAGraph()
+ with torch.cuda.graph(gr):
+ call()
+ times = []
+ for _ in range(20):
+ flush.fill_(1)
+ a, b = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
+ a.record()
+ gr.replay()
+ b.record()
+ torch.cuda.synchronize()
+ times.append(a.elapsed_time(b) * 1e3 / 11)
+ return statistics.median(times)
+
+ for streams, rp, ctx in ((1, 4, 180000), (1, 5, 180000), (1, 6, 180000), (1, 7, 180000), (1, 8, 180000),
+ (1, 5, 596000), (1, 6, 596000), (2, 3, 300000), (4, 2, 596000)):
+ R, cache, rows, _, counts, qa, s = window(streams, rp, ctx, 22)
+ tl = [selections(streams, rp, ctx) for _ in range(11)] # each call (a layer) its own keys
+ out = torch.empty(qa.shape, dtype=torch.bfloat16, device=dev)
+ res = [graph_us(lambda hb=hb: [latent.seg_attention(qa, cache, rows, t, counts, s, scale=0.0625, out=out,
+ hb=hb) for t in tl]) for hb in (old_rule(R), None)]
+ print(f"TIME 22 heads, {streams} x {rp} rows at {ctx}: old rule {res[0]:.1f} -> {res[1]:.1f} us a call "
+ f"({100 * (res[1] / res[0] - 1):+.1f}%)", flush=True)
+ del cache, s, tl
+ torch.cuda.empty_cache()
+print("ALL PASS" if fails == 0 else f"{fails} FAIL", flush=True)
+sys.exit(1 if fails else 0)