GLM-5.3-Flash EXL3 on 2x DGX Spark with TensorFold
Python
Patch 0101: faster prompts at long context - a prompt chunk's pool selection from one pass over the scores
BadAd84229846fb553c
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 54a3f69..4c0af4a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -3,6 +3,16 @@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 pool selection in one pass** (patch `0101-glm-prompt-select-floor`, by [BadAd84](https://github.com/BadAd84)):+ `_select_rows` read a row's scores five times (four radix passes and the write), and at long context a+ row has hundreds of thousands of pools. `prompt_pools` reads them once: a strided sample sets a floor,+ one pass compacts the pools at or above it in pool order, and the radix select runs over those in+ registers; a row with fewer than 512 or more than CAP candidates takes `_select_rows` itself, so the+ pools and ties are the same. A 512-row block at 590k 6.24 -> 1.51 ms on one GB10. GPU check:+ `tools/select_floor_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..37f1c53 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.+- `0101-glm-prompt-select-floor` (a prompt chunk's pool selection from one pass over the scores): 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..984848b 100644--- a/README.md+++ b/README.md@@ -627,6 +627,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, indexer | `0101-glm-prompt-select-floor` | a prompt chunk's top-512 pool selection from one pass over the scores (`prompt_pools`): a sampled floor, the pools at or above it compacted in pool order, `_select_rows`' radix select over them in registers; a row whose candidates miss [512, CAP] takes `_select_rows` itself (by [BadAd84](https://github.com/BadAd84)) | a 512-row block at 590k 6.24 -> 1.51 ms (one GB10); the same pools || 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 +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/select_floor_check.py [--time]` | patch 0101's checks: `prompt_pools` against `_top_pools` and `_select_rows` for every row (every path, ties, -inf, a short scratch), and `_select_prompt` against its copy before the patch; 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/0101-glm-prompt-select-floor.patch b/patches/0101-glm-prompt-select-floor.patchnew file mode 100644index 0000000..65f5525--- /dev/null+++ b/patches/0101-glm-prompt-select-floor.patch@@ -0,0 +1,160 @@+# A prompt chunk's DSA top-k selection from one pass over the scores (sparse.prompt_pools / _select_floor) instead of+# _select_rows' five. A strided sample of the row sets a floor, one pass compacts the pools at or above it in pool order+# into a scratch (2 x CAP int32 a row), and _select_rows' radix select and write run over those candidates in registers.+# The candidates are an upper set of the row's order: with between K and CAP of them, the K best of the row and every+# tie at the K-th best are among them, so the pools and ties are _select_rows'. A row whose count misses [K, CAP] takes+# _select_rows itself. The floor only picks the path; CAP, TARGET, the sample, BLOCK and warps are speed only.+# tools/select_floor_check.py.++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+@@ -273,6 +273,123 @@ def top_pools(scores: torch.Tensor, k: int, pos: torch.Tensor | None = None) ->+ return out++++# Patch 0101: prompt rows' selection from one pass over the scores instead of _select_rows' five. A row's++# candidates are every pool whose key is at or above a floor (an upper set of the row's order), compacted in pool++# order; with between K and CAP of them, the K best of the row are the K best of the candidates and every tie at++# the K-th best is among them, so _select_rows' radix select and write over the candidates (in registers) take the++# same pools and ties. Any floor gives the same pools: it is the key prefix (16 bits) of a strided sample's rank++# that expects about TARGET candidates, and a row whose count misses [K, CAP] (ties, all-equal or skewed scores)++# takes _select_rows itself. Speed only: CAP, TARGET, the sample, BLOCK and warps (measured on++# GB10; tools/select_floor_check.py proves the pools).++PROMPT_TILES = ((12288, 1024, 724), (32768, 2048, 1024), (1 << 62, 4096, 2048)) # (most scores a row, CAP, TARGET)++PROMPT_SECTORS = 512 # the sample: 512 runs of 8 scores (32 bytes) spread over the row++++++def _radix_step(hist, need, prefix, fixed, p: tl.constexpr):++ """_select_rows' pass p (8 bits from the top) from its histogram: the K-th best's digit into the prefix, the++ count still needed among the pools equal to the prefix so far, the prefix's fixed bits."""++ bins = tl.arange(0, 256)++ at_or_above = tl.sum(hist, 0) - tl.cumsum(hist, 0) + hist # pools with this digit or a higher one++ digit = tl.max(tl.where(at_or_above >= need, bins, 0), 0)++ need -= tl.sum(tl.where(bins > digit, hist, 0), 0)++ prefix = prefix | (digit.to(tl.uint32) << (24 - 8 * p))++ fixed = fixed | (tl.full((), 0xFF, tl.uint32) << (24 - 8 * p))++ return need, prefix, fixed++++++def _tile_select(u, idx, ok, OUT, r, K: tl.constexpr):++ """_select_rows on a tile: keys u of pools idx (ascending) where ok, the K best's pools ascending into OUT[r]."""++ prefix = tl.zeros((), dtype=tl.uint32)++ fixed = tl.zeros((), dtype=tl.uint32)++ need = K++ for p in tl.static_range(4):++ hist = tl.histogram(((u >> (24 - 8 * p)) & 0xFF).to(tl.int32), 256, mask=ok & ((u & fixed) == prefix))++ need, prefix, fixed = _radix_step(hist, need, prefix, fixed, p)++ eq = (ok & (u == prefix)).to(tl.int32)++ take = (ok & (u > prefix)) | ((eq == 1) & (tl.cumsum(eq, 0) - eq < need))++ t = take.to(tl.int32)++ tl.store(OUT + r * K + tl.cumsum(t, 0) - t, idx.to(tl.int64), mask=take)++++++def _sample_floor(row, NP, NS: tl.constexpr, TARGET: tl.constexpr):++ """A floor key for a row of NP scores: the 16-bit prefix of the sample's rank that scales to TARGET pools (NS++ runs of 8 scores at even spacing, 32-byte aligned; on rows under NS * 8 scores runs repeat). Speed only."""++ s = tl.arange(0, NS * 8)++ j = ((s // 8).to(tl.int64) * NP // NS) // 8 * 8 + s % 8++ su = _order_key(tl.load(row + j, mask=j < NP, other=0.0))++ prefix = tl.zeros((), dtype=tl.uint32)++ fixed = tl.zeros((), dtype=tl.uint32)++ need = tl.maximum(TARGET * (NS * 8) // NP, 1)++ for p in tl.static_range(2):++ hist = tl.histogram(((su >> (24 - 8 * p)) & 0xFF).to(tl.int32), 256, mask=(su & fixed) == prefix)++ need, prefix, fixed = _radix_step(hist, need, prefix, fixed, p)++ return prefix++++++def _select_floor(S, OUT, CAND, NP, K: tl.constexpr, CAP: tl.constexpr, NS: tl.constexpr, TARGET: tl.constexpr,++ BLOCK: tl.constexpr):++ """Program r: row r's (NP scores) K best pools ascending into OUT[r], as _select_rows (patch 0101's comment++ above). A row of at most CAP scores is one tile; else one pass compacts the pools at or above the floor++ (keys, then pools) into CAND[r] (2 * CAP int32), and the tile is those, or the row takes _select_rows."""++ r = tl.program_id(0).to(tl.int64)++ row = S + r * NP++ c = tl.arange(0, CAP)++ if NP <= CAP:++ ok = c < NP++ _tile_select(_order_key(tl.load(row + c, mask=ok, other=0.0)), c, ok, OUT, r, K)++ else:++ lo = _sample_floor(row, NP, NS, TARGET)++ ck = CAND + r * (2 * CAP)++ n = 0++ for b in range(0, NP, BLOCK):++ i = b + tl.arange(0, BLOCK)++ ok = i < NP++ u = _order_key(tl.load(row + i, mask=ok, other=0.0))++ sel = ok & (u >= lo)++ t = sel.to(tl.int32)++ m = tl.sum(t, 0)++ if m > 0:++ at = n + tl.cumsum(t, 0) - t++ put = sel & (at < CAP)++ tl.store(ck + at, u.to(tl.int32, bitcast=True), mask=put)++ tl.store(ck + CAP + at, i, mask=put)++ n += m++ if (n >= K) & (n <= CAP):++ tl.debug_barrier() # the candidates other threads stored, before reading them++ ok = c < n++ u = tl.load(ck + c, mask=ok, other=0).to(tl.uint32, bitcast=True)++ _tile_select(u, tl.load(ck + CAP + c, mask=ok, other=0), ok, OUT, r, K)++ else:++ _select_rows(S, OUT, NP, S, K, 1024, False)++++++def prompt_tile(np_: int) -> tuple[int, int]:++ """_select_floor's CAP and TARGET for rows of np_ scores (speed only)."""++ return next((cap, target) for most, cap, target in PROMPT_TILES if np_ <= most)++++++def prompt_pools(scores: torch.Tensor, k: int, scratch: torch.Tensor | None = None) -> torch.Tensor:++ """top_pools' pools for prompt rows (no visible bounds), by _select_floor: one program a row, 4,096 scores a++ step for blocks of up to 32 rows (fewer programs than the GB10's 48 SMs), else 1,024; ``scratch``: int32, at++ least R * 2 * CAP (prompt_tile)."""++ R, NP = scores.shape++ if NP < k or not scores.is_contiguous():++ raise ValueError("prompt_pools: contiguous rows of at least k scores")++ cap, target = prompt_tile(NP)++ if scratch is None:++ scratch = torch.empty((R * 2 * cap,), dtype=torch.int32, device=scores.device)++ elif scratch.dtype != torch.int32 or scratch.numel() < R * 2 * cap:++ raise ValueError(f"prompt_pools: the scratch needs {R * 2 * cap} int32")++ out = torch.empty((R, k), dtype=torch.int64, device=scores.device)++ _select_floor[(R,)](scores, out, scratch, NP, K=k, CAP=cap, NS=PROMPT_SECTORS, TARGET=target,++ BLOCK=4096 if R <= 32 else 1024, num_warps=8)++ return out+++++ def pool_bucket(pos: int, R: int, np_max: int) -> int:+ """Pools to score for rows pos .. pos + R - 1: the visible ones rounded up to a power of two (at least 1024), at most the capacity's."""+ visible = (pos + R) // POOL + 1+@@ -355,6 +472,7 @@ def _select_prompt(qi: torch.Tensor, wts: torch.Tensor, pk: torch.Tensor, pos: i+ The scores buffer keeps pool_bucket's size (the allocator's few sizes), used as a contiguous [R, NP] prefix;+ - _scores takes one row a program and SCORE_LOOP pool blocks, a row's keys masked to its own pools before its+ dot;++ - prompt_pools selects (patch 0101: one pass over the scores, top_pools' pools);+ - one kernel (_tokens) writes tokens and counts with select_tokens' integer formulas."""++ dev = qi.device+@@ -370,6 +488,7 @@ def _select_prompt(qi: torch.Tensor, wts: torch.Tensor, pk: torch.Tensor, pos: i+ tokens = torch.empty((R, width), dtype=torch.int32, device=dev)+ counts = torch.empty((R,), dtype=torch.int32, device=dev)+ pkv, pks, rs, fp8 = kv8.parts(pk)++ cand = torch.empty((B * 2 * prompt_tile(NP)[0],), dtype=torch.int32, device=dev) # prompt_pools' candidates+ for a in range(0, R, B):+ n = min(B, R - a)+ at = pos_dev if a == 0 else pos_dev + a+@@ -378,7 +497,7 @@ def _select_prompt(qi: torch.Tensor, wts: torch.Tensor, pk: torch.Tensor, pos: i+ 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++ pools = prompt_pools(scores, TOPK_POOLS, cand) # 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)+ return tokens, countsdiff --git a/tools/select_floor_check.py b/tools/select_floor_check.pynew file mode 100644index 0000000..45f3006--- /dev/null+++ b/tools/select_floor_check.py@@ -0,0 +1,289 @@+#!/usr/bin/env python3+"""tools/select_floor_check.py [--time]: patch 0101 - the prompt rows' selection (sparse.prompt_pools / _select_floor:+one pass that compacts the pools at or above a sampled floor, then _select_rows' radix select over them in registers,+or _select_rows itself when the candidates miss [K, CAP]) - checked on the GPU against the reference (_top_pools: a+stable sort's k best, ties to the lower pool, ascending) and against the old path's _select_rows (BLOCK 1,024, 4 warps,+as top_pools launched it for prompt rows) for EVERY row. Run in the image built with patch 0101, on one GPU:+docker run --rm --gpus all --entrypoint python -v "$PWD/tools/select_floor_check.py:/c.py" <image> /c.py+One PASS / FAIL line a check; exits 1 on any FAIL (on an image without the patch: at the first check).++Kernel cases, at rows of 1,000 .. 148,480 scores (every prompt_tile; 64 rows = BLOCK 1,024 and 8 rows = BLOCK 4,096):+random, bf16-rounded (ties, keys with zero low bits), a few distinct values, all equal, +0 / -0 ties, -inf past each+row's own visible pools (some rows with fewer than 512 visible: count 0), and rows built for each path (the floor+recomputed here from the sample's formula, so each crafted row is checked to take the path it is built for): ties at+the K-th best inside the candidates, 511 and 512 candidates (around K), CAP + 1 and CAP + 2,000 candidates with the+best pools last (dropped past CAP), exactly CAP, the K-th best below a masked lane's 0.0 (the last BLOCK 4,096 step+past the row's end); a row of NP candidates stores nothing past its 2 * CAP scratch, and a short scratch is refused.+End to end: sparse._select_prompt (patched) against a copy of the one before patch 0101 (top_pools), every token and+count of every row, and each score block's pools against _top_pools; FP8 and bf16 pooled keys; 512-row chunks at row+positions 0, 1,800, 35k, 113k, 300k, 450k, 590k and the cache's end; 1, 32, 64, 300, 577 (512 + 65), 520 (512 + 8) and+1,024 rows.++--time: the selection of one 512-row block, top_pools (before) against prompt_pools, CUDA events, on the scores+_scores gives random FP8 keys at 35k, 113k, 300k and 590k (the indexer is replicated: the same shapes at TP=2 and+TP=3)."""+import statistics+import sys++import torch+import triton++from tensorfold.families.glm5_next.cuda import kv8, sparse++H, D, KEY = 32, 128, 128+CAP = 1_048_576+K = sparse.TOPK_POOLS+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 keys(x):+ """_order_key in torch (int64): unsigned order = the scores' order, -0 as +0."""+ bits = (x + 0.0).view(torch.int32).to(torch.int64) & 0xFFFFFFFF+ return torch.where(bits >= 2 ** 31, bits ^ 0xFFFFFFFF, bits | 2 ** 31)+++def sample_cols(np_):+ """_sample_floor's sample columns for rows of np_ scores (those at or past np_ load as 0.0)."""+ s = torch.arange(sparse.PROMPT_SECTORS * 8, device=dev)+ return ((s // 8) * np_ // sparse.PROMPT_SECTORS) // 8 * 8 + s % 8+++def candidates(x):+ """Each row's candidate count by _select_floor's floor, recomputed (-1: the row is one tile)."""+ R, NP = x.shape+ cap, target = sparse.prompt_tile(NP)+ if NP <= cap:+ return torch.full((R,), -1, dtype=torch.int64, device=dev)+ k = keys(x)+ j = sample_cols(NP)+ su = torch.where(j < NP, k[:, j.clamp(max=NP - 1)], 2 ** 31)+ jj = max(target * sparse.PROMPT_SECTORS * 8 // NP, 1)+ floor = (torch.topk(su, jj, dim=1).values[:, -1:] >> 16) << 16+ return (k >= floor).sum(1)+++def prod_rows(x):+ out = torch.empty((x.shape[0], K), dtype=torch.int64, device=dev)+ sparse._select_rows[(x.shape[0],)](x, out, x.shape[1], x, K=K, BLOCK=1024, VIS=False, num_warps=4)+ return out+++paths = {"tile": 0, "candidates": 0, "fallback": 0}+++def kernel_case(name, x, want=None):+ """prompt_pools(x) against _top_pools and the old path's _select_rows, every row; want: the path every row must+ take ("tile", "candidates", "fallback")."""+ x = x.contiguous()+ cap = sparse.prompt_tile(x.shape[1])[0]+ n = candidates(x)+ kind = torch.where(n < 0, 0, torch.where((n >= K) & (n <= cap), 1, 2))+ for i, p in enumerate(paths):+ paths[p] += int((kind == i).sum())+ if want is not None:+ w = list(paths).index(want)+ check(f"{name}: every row takes the {want} path", bool((kind == w).all()), f"candidates {n.tolist()[:8]}")+ ref = sparse._top_pools(x, K)+ got = sparse.prompt_pools(x, K)+ old = prod_rows(x)+ torch.cuda.synchronize()+ bad = (got != ref).any(1)+ check(f"{name}: pools = _top_pools and _select_rows, every row", torch.equal(got, ref) and torch.equal(old, ref),+ f"{int(bad.sum())} rows differ (first {bad.nonzero()[:4].flatten().tolist()}), "+ f"_select_rows equal {torch.equal(old, ref)}")+++check("patch 0101 applied: prompt_pools", hasattr(sparse, "prompt_pools") and hasattr(sparse, "_select_floor"))+if fails:+ print("1 FAIL", flush=True)+ sys.exit(1)+torch.manual_seed(0)+for NP in (1_000, 1_024, 4_096, 5_120, 9_216, 12_288, 13_312, 28_672, 32_768, 33_792, 75_776, 148_480):+ for R in (64, 8):+ g = torch.Generator(device=dev).manual_seed(NP + R)+ x = torch.randn(R, NP, device=dev, generator=g)+ kernel_case(f"{NP} x {R} random", x)+ kernel_case(f"{NP} x {R} bf16-rounded", x.to(torch.bfloat16).float())+ kernel_case(f"{NP} x {R} 8 values", torch.randint(0, 8, (R, NP), device=dev, generator=g).float())+ kernel_case(f"{NP} x {R} all equal", torch.full((R, NP), 0.25, device=dev))+ z = torch.where(torch.rand(R, NP, device=dev, generator=g) < 0.5, -0.0, 0.0)+ z[:, :400] = 1.0+ z[:, 700:] = -1.0 - torch.rand(R, NP - 700, device=dev, generator=g)+ kernel_case(f"{NP} x {R} +0 / -0 ties at the K-th", z[:, torch.randperm(NP, device=dev, generator=g)])+ vis = torch.randint(0, NP + 1, (R,), device=dev, generator=g)+ vis[: R // 4] = torch.randint(0, K + 1, (R // 4,), device=dev, generator=g) # rows with count 0+ y = torch.where(torch.arange(NP, device=dev) < vis[:, None], x, float("-inf"))+ kernel_case(f"{NP} x {R} -inf past each row's pools", y)++# crafted rows for the candidates' paths (rows of 148,480 scores: CAP 4,096)+NP = 148_480+cap = sparse.prompt_tile(NP)[0]+cols = sample_cols(NP)+rest = torch.ones(NP, dtype=torch.bool, device=dev)+rest[cols] = False+others = rest.nonzero().flatten()+g = torch.Generator(device=dev).manual_seed(78)+x = torch.randn(8, NP, device=dev, generator=g) * 0.5 # below 4.0+spots = others[torch.randperm(others.numel(), device=dev, generator=g)[:700]]+x[:, spots[:400]] = 5.0+x[:, spots[400:]] = 4.0 # the K-th best: a 4.0 tie+kernel_case("crafted ties at the K-th best among the candidates", x, "candidates")+x = torch.rand(8, NP, device=dev, generator=g)+x[:, cols[:511]] = 9.0+kernel_case("crafted 511 candidates (one short of K)", x, "fallback")+x = torch.rand(8, NP, device=dev, generator=g)+x[:, cols[:512]] = 9.0+kernel_case("crafted 512 candidates (K)", x, "candidates")+x = torch.full((8, NP), 0.5, device=dev)+x[:, cols] = 1.0+x[:, others[-2000:]] = 2.0 # the best pools come last+kernel_case("crafted CAP + 2,000 candidates, the best last", x, "fallback")+x = torch.full((8, NP), 0.5, device=dev)+x[:, cols] = 1.0+x[:, others[-(cap - cols.numel() + 1):]] = 2.0+kernel_case("crafted CAP + 1 candidates, the best last", x, "fallback")+x = torch.full((8, NP), 0.5, device=dev)+x[:, cols[:cap // 2]] = 1.0+x[:, others[-(cap - cap // 2):]] = 2.0+kernel_case("crafted exactly CAP candidates, the best last", x, "candidates")+NP = 16_000 # 8 rows: BLOCK 4,096, the last step's 384 lanes past NP+cols = sample_cols(NP)+rest = torch.ones(NP, dtype=torch.bool, device=dev)+rest[cols] = False+x = -1.0 - torch.rand(8, NP, device=dev, generator=g) # below a masked lane's 0.0+x[:, rest.nonzero().flatten()[:400]] = 1.0 # unsampled: the floor is < 0+kernel_case("crafted K-th best below 0.0 with lanes past the row", x, "candidates")+NP = 148_480+cap = sparse.prompt_tile(NP)[0]+scratch = torch.full((2 * cap + NP,), 0x5A5A5A5A, dtype=torch.int32, device=dev)+sparse.prompt_pools(torch.full((1, NP), 0.25, device=dev), K, scratch)+torch.cuda.synchronize()+check("a row of NP candidates stores nothing past its 2 * CAP scratch", bool((scratch[2 * cap:] == 0x5A5A5A5A).all()),+ f"{int((scratch[2 * cap:] != 0x5A5A5A5A).sum())} written")+try:+ sparse.prompt_pools(torch.zeros((2, NP), device=dev), K, scratch[:4 * cap - 1])+ refused = False+except ValueError:+ refused = True+check("prompt_pools refuses a scratch under R * 2 * CAP int32", refused)+check(f"every path taken (rows: {paths})", all(v > 0 for v in paths.values()))+++def old_select_prompt(qi, wts, pk, pos, R, np_max, pos_dev):+ """sparse._select_prompt before patch 0101 (top_pools), verbatim otherwise."""+ dev = qi.device+ NP = sparse.pool_count(pos, R, np_max)+ B = min(R, sparse.SELECT_ROWS)+ buf = torch.empty((B * sparse.pool_bucket(pos, R, np_max),), dtype=torch.float32, device=dev)+ H = wts.shape[1]+ D = qi.shape[1] // H+ wscale = 1.0 / 5.656854249492381 if H == 32 else H ** -0.5+ 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)+ pkv, pks, rs, fp8 = kv8.parts(pk)+ 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)+ sparse._scores[(n, triton.cdiv(triton.cdiv(NP, 64), sparse.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=sparse.SCORE_LOOP, 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+++blocks = []+_prompt_pools = sparse.prompt_pools+++def checking_prompt_pools(scores, k, scratch=None):+ out = _prompt_pools(scores, k, scratch)+ blocks.append(bool(torch.equal(out, sparse._top_pools(scores, k))))+ return out+++def run(fn, *args):+ """fn's tokens and counts, every empty-allocated buffer pre-filled (an unwritten or stale value shows up)."""+ empty = torch.empty++ def filled(*a, **kw):+ t = empty(*a, **kw)+ t.fill_(7.0 if t.dtype == torch.float32 else 0x5A5A5A5A if t.dtype == torch.int32 else -5)+ return t+ sparse.prompt_pools, torch.empty = checking_prompt_pools, filled+ try:+ tokens, counts = fn(*args)+ torch.cuda.synchronize()+ finally:+ sparse.prompt_pools, torch.empty = _prompt_pools, empty+ return tokens, counts+++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, 450_000, 590_000, CAP - 512)]+ + [(40_000, 1), (590_000, 32), (40_000, 64), (300_000, 300), (300_000, 577), (590_000, 520), (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 = run(old_select_prompt, qi, wts, pk, P, R, np_max, pos_dev)+ blocks.clear()+ t1, c1 = run(sparse._select_prompt, qi, wts, pk, P, R, np_max, pos_dev)+ check(f"{kind} {R} rows at {P}: each block's pools = _top_pools ({len(blocks)} block(s))",+ len(blocks) == triton.cdiv(R, sparse.SELECT_ROWS) and all(blocks), f"{blocks}")+ check(f"{kind} {R} rows at {P}: every row's tokens and count", torch.equal(c0, c1) and torch.equal(t0, t1),+ f"counts differ {int((c0 != c1).sum())}, tokens differ {int((t0 != t1).sum())}")+ del qi, ikr, t0, t1+ torch.cuda.empty_cache()+++def bench(fn, reps=20):+ """Median of reps timed calls (CUDA events) after 3 warm-up calls, in ms."""+ for _ in range(3):+ fn()+ torch.cuda.synchronize()+ ts = []+ for _ in range(reps):+ a, b = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)+ a.record()+ fn()+ b.record()+ torch.cuda.synchronize()+ ts.append(a.elapsed_time(b))+ return statistics.median(ts)+++if "--time" in sys.argv and fails == 0:+ pk = caches["fp8"]+ pkv, pks, rs, fp8 = kv8.parts(pk)+ R = 512+ for P in (35_000, 113_000, 300_000, 590_000):+ NP = sparse.pool_count(P, R, np_max)+ qi = torch.randn(R, H * D, device=dev, dtype=torch.bfloat16)+ wts = torch.randn(R, H, device=dev, dtype=torch.bfloat16)+ scores = torch.empty((R, NP), device=dev)+ sparse._scores[(R, triton.cdiv(triton.cdiv(NP, 64), sparse.SCORE_LOOP))](+ qi, wts, wts.stride(0), pkv, pks, scores, torch.tensor([P], device=dev), R, NP, D ** -0.5, 1 / 32 ** 0.5,+ H=H, HP=H, D=D, BP=64, L=sparse.SCORE_LOOP, RS=rs, FP8=fp8, num_warps=4)+ cand = torch.empty((R * 2 * sparse.prompt_tile(NP)[0],), dtype=torch.int32, device=dev)+ t0 = bench(lambda: sparse.top_pools(scores, K))+ t1 = bench(lambda: sparse.prompt_pools(scores, K, cand))+ print(f"TIME {R} rows at {P}: {NP} pools, top_pools {t0:.3f} ms -> prompt_pools {t1:.3f} ms "+ f"({100 * (t1 / t0 - 1):+.1f}%)", flush=True)+ del scores, cand, qi, wts+print("ALL PASS" if fails == 0 else f"{fails} FAIL", flush=True)+sys.exit(1 if fails else 0)