Skip to content

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

Python

Patch 0102: faster prefill - a prompt chunk's dense 4-bit projections on the tile each shape runs fastest on

BadAd84c3486ec7ef26
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 54a3f69..474cafd 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
+
+- **A prompt chunk's dense projections on a faster tile** (patch `0102-glm-prompt-matmul-tile`, by [BadAd84](https://github.com/BadAd84)):
+ `forward.mm` launched every 4-bit prompt projection on the extension's default tile 0. It now launches
+ tile 9 (128 x 128 on four 64 x 64 warps, two blocks an SM) where K >= 1024 and the grid has 96 or more
+ blocks, else tile 3. A tile only picks which warp computes an output, so the bits are the same. A
+ 2,048-row chunk's dense projections on one GB10: 178.1 -> 152.2 ms at TP=3 shapes, 238.1 -> 200.7 ms at
+ TP=2 shapes. `TF_GLM_PROMPT_TILE=0`: tile 0. GPU check: `tools/prompt_tile_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..19d484a 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.
+- `0102-glm-prompt-matmul-tile` (a prompt chunk's dense projections on tile 9 or 3): 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..5f2ef77 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_PROMPT_TILE` | `1` | patch 0102: a prompt chunk's dense 4-bit projections launch the tile the shape runs fastest on (tile 9 or 3); `0`: tile 0 as before. 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` |
@@ -627,6 +628,7 @@ applied with `patch -p0` in filename order); `start.sh` rebuilds or re-pulls the
| KV pool, kindling | `0087-glm-display-kv-dispram` | `0072`'s span with its reservation half from kindling spark-os's `dispramd` instead of a DRM dumb buffer, which kindling's `nvidia_drm` (no modeset) cannot make; the rest of `0072` runs unchanged (`DISPLAY_KV_BACKEND=dispram`) (by [BadAd84](https://github.com/BadAd84)) | 2032 MiB: +317,440 tokens at `PARALLEL=4` on three Sparks; the display check 53/53 |
| 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 (by [BadAd84](https://github.com/BadAd84)) | 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, matmuls | `0102-glm-prompt-matmul-tile` | a prompt chunk's dense 4-bit projections on tile 9 (128 x 128, four 64 x 64 warps) where K >= 1024 and the grid has 96 or more blocks, else tile 3, instead of tile 0 (`TF_GLM_PROMPT_TILE`) (by [BadAd84](https://github.com/BadAd84)) | a 2,048-row chunk's projections -15% (one GB10, TP=3 and TP=2 shapes); 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) |
@@ -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/prompt_tile_check.py [--time]` | patch 0102's checks: the tile rule, and `forward.mm`'s output against tile 0's bit for bit at every projection shape of a 2,048-row chunk at TP=3 and TP=2; 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/0102-glm-prompt-matmul-tile.patch b/patches/0102-glm-prompt-matmul-tile.patch
new file mode 100644
index 0000000..15c8ffa
--- /dev/null
+++ b/patches/0102-glm-prompt-matmul-tile.patch
@@ -0,0 +1,40 @@
+# GLM's dense 4-bit projections of a prompt chunk (forward.mm -> the shared prefill matmul) launch the tile the shape
+# runs fastest on, instead of the extension's default tile 0: tile 9 (128 x 128 on four 64 x 64 warps, two blocks an SM)
+# where K >= 1024 and the grid has 96 or more 128 x 128 blocks, tile 3 (64 x 64) otherwise (forward.prompt_tile,
+# measured on a GB10 at every projection of a 2,048-row chunk). A tile only picks which warp computes an output: every
+# output is the same fp32 mma chain over K, so the bits are tile 0's. TF_GLM_PROMPT_TILE=0: tile 0 as before. Python
+# only. tools/prompt_tile_check.py.
+
+diff --git tensorfold/families/glm5_next/cuda/forward.py tensorfold/families/glm5_next/cuda/forward.py
+--- tensorfold/families/glm5_next/cuda/forward.py
++++ tensorfold/families/glm5_next/cuda/forward.py
+@@ -421,11 +421,28 @@ def gather(w: Weights, b: Buffers, R: int) -> torch.Tensor:
+ return out.view(b.world, R, d)
+
+
++# patch 0102: TF_GLM_PROMPT_TILE=0 launches every prompt projection on tile 0 as before (an A/B on one image)
++PROMPT_TILES = __import__("os").environ.get("TF_GLM_PROMPT_TILE", "1") != "0"
++
++
++def prompt_tile(m: int, n: int, k: int) -> int:
++ """The shared prefill matmul's tile for an (m, n, k) projection of a prompt chunk (patch 0102). Every tile runs
++ each output's one fp32 mma chain over K in the same order (the tile only picks which warp computes it), so the
++ bits are tile 0's. Tile 9 (128 x 128 on four 64 x 64 warps, two blocks an SM) where its blocks fill the GPU twice
++ over and K is long; tile 3 (64 x 64 blocks) for narrow, short-K or few-block shapes. Measured on a GB10 at every
++ projection one 2,048-row chunk runs on a TP=3 rank: the chunk's dense projections -14% against tile 0 (the
++ default before), outputs identical bit for bit (tools/prompt_tile_check.py)."""
++
++ if not PROMPT_TILES:
++ return 0
++ return 9 if k >= 1024 and -(-m // 128) * -(-n // 128) >= 96 else 3
++
++
+ def mm(b: Buffers, x: torch.Tensor, q, xs: torch.Tensor | None, out: torch.Tensor, f32: bool = False) -> torch.Tensor:
+ """A projection: 4-bit ones of a prompt chunk on the shared prefill matmul, the rest on ``qmm.matmul``."""
+
+ if b.prefill and isinstance(q, qmm.Q4):
+- return shared.prefill_matmul(x, q, f32=f32, out=out)
++ return shared.prefill_matmul(x, q, f32=f32, out=out, tile=prompt_tile(x.shape[0], q.n, q.k))
+ return qmm.matmul(x, q, xs, out=out, f32=f32, part=b.sk)
+
+
diff --git a/tools/prompt_tile_check.py b/tools/prompt_tile_check.py
new file mode 100644
index 0000000..ae4489c
--- /dev/null
+++ b/tools/prompt_tile_check.py
@@ -0,0 +1,179 @@
+#!/usr/bin/env python3
+"""tools/prompt_tile_check.py [--time]: patch 0102 - GLM's dense 4-bit projections of a prompt chunk (forward.mm ->
+the shared prefill matmul) launch forward.prompt_tile's tile (9 where K >= 1024 and the grid has 96 or more 128 x 128
+blocks, else 3) instead of tile 0. Run in the image built with patch 0102, on one GPU:
+docker run --rm --gpus all --entrypoint python -v "$PWD/tools/prompt_tile_check.py:/c.py" <image> /c.py
+
+At every projection shape a 2,048-row prompt chunk runs on rank 0, at TP=3 (22 of 64 heads) and TP=2 (32), from the
+model's geometry (tp.split_sizes; the row counts are hcsplit's pieces of the chunk):
+1. forward.prompt_tile gives the measured table at TP=3, and tile 0 with TF_GLM_PROMPT_TILE=0;
+2. forward.mm on a prompt chunk's buffers launches the shared prefill matmul with that tile (recorded) and its output
+ equals tile 0's bit for bit (bf16 and fp32 outputs as the call sites use them, pre-filled with NaN so an unwritten
+ slot shows): a tile only picks which warp computes an output, each output is the same fp32 mma chain over K;
+3. the output against the dequantized weights times x in float64 (the kernel computes the projection).
+One PASS / FAIL line a check; exits 1 on any FAIL (on an image without the patch: at the first check).
+
+--time: each shape's time a call on tile 0 and on the rule (CUDA-graph replays), and a chunk's total weighted by the
+calls a chunk makes."""
+import sys
+from types import SimpleNamespace
+
+import torch
+
+from tensorfold.cuda.kernels import qmm as shared
+from tensorfold.families.glm5_next.cuda import forward, qmm, tp
+
+HEADS, LIN, DENSE, SHARED, HID = 64, 64, 12288, 2048, 4096 # GLM-5.3-Flash's split dimensions and hidden size
+KDA, DSA, MOE, DEN = 34, 11, 42, 3 # layers of each kind (calls a chunk per row piece)
+
+
+def shapes(world):
+ """(label, M, N, K, fp32 out, calls a chunk) for rank 0 of ``world``."""
+ h, lh = tp.split_sizes(HEADS, world, 1)[0], tp.split_sizes(LIN, world, 1)[0]
+ dn, sh = tp.split_sizes(DENSE, world, 128)[0], tp.split_sizes(SHARED, world, 128)[0]
+ if world == 3: # hcsplit's pieces of a 2,048-row chunk at three ranks: 683 own rows (384 + 299), 1,365 others
+ front, post, moe = ((384, 1), (299, 1), (1365, 1)), ((384, 2), (299, 1), (298, 1), (683, 1)), \
+ ((384, 3), (299, 2), (298, 1))
+ else: # two ranks: 1,024 own rows in two 512-row pieces, 1,024 others
+ front, post, moe = ((512, 2), (1024, 1)), ((512, 4),), ((512, 4),)
+ out = []
+ for m, c in front:
+ out += [(f"kda proj {m}", m, 3 * lh * 128 + 256 + lh, HID, False, KDA * c),
+ (f"kda fb/gb {m}", m, lh * 128, 128, False, 2 * KDA * c),
+ (f"dsa proj {m}", m, 2048, HID, False, DSA * c), (f"dsa q_b {m}", m, h * 256, 1536, False, DSA * c),
+ (f"dense gu {m}", m, 2 * dn, HID, False, DEN * c)]
+ for m, c in post:
+ out += [(f"kda o {m}", m, HID, lh * 128, True, KDA * c), (f"dsa o {m}", m, HID, h * 256, True, DSA * c),
+ (f"dense down {m}", m, HID, dn, True, DEN * c)]
+ for m, c in moe:
+ out += [(f"shared gu {m}", m, 2 * sh, HID, False, MOE * c), (f"shared down {m}", m, HID, sh, True, MOE * c)]
+ return out + [("idx kw 2048", 2048, 256, HID, False, DSA), ("idx qb 2048", 2048, 4096, 1536, False, DSA)]
+
+
+EXPECTED = { # TP=3 (m, n, k) -> the tile measured fastest on a GB10 (every tile of the extension tried)
+ (384, 8726, 4096): 9, (299, 8726, 4096): 9, (1365, 8726, 4096): 9,
+ (384, 2816, 128): 3, (299, 2816, 128): 3, (1365, 2816, 128): 3,
+ (384, 2048, 4096): 3, (299, 2048, 4096): 3, (1365, 2048, 4096): 9,
+ (384, 5632, 1536): 9, (299, 5632, 1536): 9, (1365, 5632, 1536): 9,
+ (384, 8192, 4096): 9, (299, 8192, 4096): 9, (1365, 8192, 4096): 9,
+ (384, 4096, 2816): 9, (299, 4096, 2816): 9, (298, 4096, 2816): 9, (683, 4096, 2816): 9,
+ (384, 4096, 5632): 9, (299, 4096, 5632): 9, (298, 4096, 5632): 9, (683, 4096, 5632): 9,
+ (384, 4096, 4096): 9, (299, 4096, 4096): 9, (298, 4096, 4096): 9, (683, 4096, 4096): 9,
+ (384, 1536, 4096): 3, (299, 1536, 4096): 3, (298, 1536, 4096): 3,
+ (384, 4096, 768): 3, (299, 4096, 768): 3, (298, 4096, 768): 3,
+ (2048, 256, 4096): 3, (2048, 4096, 1536): 9,
+}
+fails = 0
+
+
+def check(ok, msg):
+ global fails
+ print(("PASS " if ok else "FAIL ") + msg, flush=True)
+ fails += not ok
+
+
+def make(n, k, dev, g):
+ npad = (n + 127) // 128 * 128
+ w = torch.randint(-2 ** 31, 2 ** 31 - 1, (npad // 64, k // 64, 8, 32, 2), dtype=torch.int32,
+ device=dev, generator=g)
+ s = (torch.rand((k // 64, npad), device=dev, generator=g) * 0.02 + 0.001).to(torch.bfloat16)
+ b = (torch.rand((k // 64, npad), device=dev, generator=g) * 0.02 - 0.01).to(torch.bfloat16)
+ return qmm.Q4(w, s, b, n, k)
+
+
+def oracle(x, q):
+ words, s, b = shared.unpack(shared.Q4(q.weight, q.scales, q.biases, q.n, q.k, q.gs))
+ w = qmm.dequantize(words, s, b).to(torch.bfloat16).double() # [n, k], bf16(q * s + b) as the kernel rounds
+ return x.double() @ w.t()
+
+
+def graph_time(fn, reps=50):
+ """Best of 5 timings of reps calls replayed from one CUDA graph, in us a call."""
+ st = torch.cuda.Stream()
+ st.wait_stream(torch.cuda.current_stream())
+ with torch.cuda.stream(st):
+ for _ in range(3):
+ fn()
+ torch.cuda.current_stream().wait_stream(st)
+ gr = torch.cuda.CUDAGraph()
+ with torch.cuda.graph(gr):
+ for _ in range(10):
+ fn()
+ gr.replay()
+ torch.cuda.synchronize()
+ a, b = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
+ best = 1e9
+ for _ in range(5):
+ a.record()
+ for _ in range(reps // 10):
+ gr.replay()
+ b.record()
+ torch.cuda.synchronize()
+ best = min(best, a.elapsed_time(b) / reps * 1e3)
+ return best
+
+
+def main():
+ check(hasattr(forward, "prompt_tile"), "patch 0102 applied: forward.prompt_tile")
+ if fails:
+ print("1 FAIL", flush=True)
+ sys.exit(1)
+ timing = "--time" in sys.argv
+ dev = torch.device("cuda")
+ g = torch.Generator(device=dev).manual_seed(83)
+ table = {(m, n, k): forward.prompt_tile(m, n, k) for _, m, n, k, _, _ in shapes(3)}
+ bad = {key: (t, EXPECTED.get(key)) for key, t in table.items() if EXPECTED.get(key) != t}
+ check(not bad and len(table) == len(EXPECTED), f"prompt_tile at TP=3 = the measured table over {len(table)} shapes "
+ f"({bad or 'all match'})")
+ was = forward.PROMPT_TILES
+ forward.PROMPT_TILES = False # what TF_GLM_PROMPT_TILE=0 sets at import
+ check(all(forward.prompt_tile(m, n, k) == 0 for m, n, k in table), "TF_GLM_PROMPT_TILE=0: tile 0 everywhere")
+ forward.PROMPT_TILES = was
+ seen = []
+ orig = shared.prefill_matmul
+
+ def rec(x, q, *, f32=False, tile=0, out=None):
+ seen.append(tile)
+ return orig(x, q, f32=f32, tile=tile, out=out)
+
+ b = SimpleNamespace(prefill=True, sk=None)
+ for world in (3, 2):
+ old_t = new_t = 0.0
+ for label, m, n, k, f32, calls in shapes(world):
+ label = f"TP={world} {label}"
+ q = make(n, k, dev, g)
+ x = torch.randn((m, k), device=dev, generator=g).to(torch.bfloat16)
+ dt, iv = (torch.float32, torch.int32) if f32 else (torch.bfloat16, torch.int16)
+ ref = torch.full((m, n), float("nan"), device=dev, dtype=dt)
+ orig(x, q, f32=f32, tile=0, out=ref) # the kernel as forward.mm launched it before
+ out = torch.full((m, n), float("nan"), device=dev, dtype=dt)
+ seen.clear()
+ forward.shared.prefill_matmul = rec
+ try:
+ forward.mm(b, x, q, None, out, f32=f32)
+ finally:
+ forward.shared.prefill_matmul = orig
+ want = forward.prompt_tile(m, n, k)
+ same = torch.equal(out.view(iv), ref.view(iv)) and not torch.isnan(out).any()
+ check(seen == [want] and same, f"{label}: mm launched tile {seen} (want [{want}]), output == tile 0's: "
+ f"{same}")
+ if label.endswith(("1365", "683", "1024")) or "shared down" in label or "idx" in label:
+ r = oracle(x, q)
+ err = ((out.double() - r).abs().max() / r.abs().max()).item()
+ check(err < (2e-4 if f32 else 1e-2), f"{label}: against the float64 oracle, max error {err:.2e} of max")
+ if timing:
+ t0 = graph_time(lambda: orig(x, q, f32=f32, tile=0, out=ref))
+ t1 = graph_time(lambda: forward.mm(b, x, q, None, out, f32=f32))
+ old_t, new_t = old_t + calls * t0, new_t + calls * t1
+ print(f"TIME {label} ({m} x {n} x {k}, {calls} calls): tile 0 {t0:.1f} us, tile {want} {t1:.1f} us "
+ f"({100 * (t1 / t0 - 1):+.1f}%)", flush=True)
+ if timing:
+ print(f"TIME TP={world}: a 2,048-row chunk's dense 4-bit projections {old_t / 1e3:.1f} -> "
+ f"{new_t / 1e3:.1f} ms "
+ f"({100 * (new_t / old_t - 1):+.1f}%)", flush=True)
+ print("ALL PASS" if fails == 0 else f"{fails} FAIL", flush=True)
+ sys.exit(1 if fails else 0)
+
+
+if __name__ == "__main__":
+ main()