Skip to content

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

Python

Patch 0107: faster decode with several agents at long context - a decode window's DSA indexer, scoring in CUDA and selection in one pass, the same tokens

BadAd84bfce53a0a99d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 54a3f69..dc848f7 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -3,6 +3,20 @@
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 decode window's indexer, twice as fast with four agents** (patch `0107-glm-decode-indexer`, by [BadAd84](https://github.com/BadAd84)):
+ the same tokens and counts in less time. (1) The Triton scoring's grid is 512 programs a segment (was
+ 256). (2) Segments of 4 or more rows are scored by `seg_scores.cu`, which stores `_seg_scores`' scores
+ with patch 0105's instruction sequence (the same bits under Triton 3.7) while a CTA converts each FP8 key tile once for up to 8 of the
+ segment's rows; fewer rows stay on Triton (memory-bound there). (3) Windows of 8 or more rows select
+ each row's pools by `_seg_select_floor`, one pass over its scores (patch 0101's method), instead of
+ `select_split`'s five. The indexer call on one GB10, 4 streams x 8 rows at 596k: 1,296 -> 647 us
+ (x11 layers a round); 1 x 16 rows 635 -> 344 us. Live on three Sparks with four agents at ~596k, every
+ stream's round -2 to -4%. Under another Triton release (`sparse.TRITON_PTX`), or when the build fails, the
+ Triton scoring serves (logged once). `TF_GLM_SEG_SCORES_CUDA=0` / `TF_GLM_SEG_SELECT_FLOOR=0`: the old scoring /
+ selection. Applies after `0101`, `0105` and `0106`. GPU check: `tools/decode_indexer_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..e7ddefe 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 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.
+- `0107-glm-decode-indexer` (a decode window's indexer: the scoring in CUDA, the selection in one pass): 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..1c3c524 100644
--- a/README.md
+++ b/README.md
@@ -522,6 +522,8 @@ 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_SEG_SCORES_CUDA` | `1` | patch 0107: a decode window's FP8 indexer scoring for segments of 4 or more rows from `seg_scores.cu` (the same bits as the Triton kernel under Triton 3.7, whose PTX it reproduces), built when the engine starts; `0`: the Triton kernel for every segment, which also serves (logged once) under another Triton release or when the build fails |
+| `TF_GLM_SEG_SELECT_FLOOR` | `1` | patch 0107: windows of 8 or more rows select each row's pools in one pass over its scores (`_seg_select_floor`, the same tokens); `0`: `select_split` |
| `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` |
@@ -635,6 +637,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, indexer | `0107-glm-decode-indexer` | a decode window's indexer: the Triton scoring grid 512 (was 256); segments of 4+ rows scored by a CUDA kernel (`seg_scores.cu`, patch 0105's instruction sequence under Triton 3.7, one converted key tile for up to 8 rows; its pool table sized for any window once); windows of 8+ rows selected in one pass (`_seg_select_floor`) (`TF_GLM_SEG_SCORES_CUDA`, `TF_GLM_SEG_SELECT_FLOOR`); under another Triton release, or when the build fails, the Triton scoring serves (by [BadAd84](https://github.com/BadAd84)) | 4 agents at 596k: the indexer 1.30 -> 0.65 ms a layer, every stream's round -2 to -4%; the same tokens (Triton 3.7) |
| 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 +714,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/decode_indexer_check.py [--time]` | patch 0107's checks: `seg_select_tokens` with each switch on against off, the whole scores scratch, tokens and counts bit for bit (1-6 streams, 1-16 rows, 180k-600k, adversarial data, CUDA graphs, crafted selections), the grid, the routing, the extension's pool table never replaced, the build at engine start, and the Triton scoring serving when the build fails or Triton is not 3.7; 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/0107-glm-decode-indexer.patch b/patches/0107-glm-decode-indexer.patch
new file mode 100644
index 0000000..9b19b90
--- /dev/null
+++ b/patches/0107-glm-decode-indexer.patch
@@ -0,0 +1,550 @@
+# The DSA indexer of a decode window (sparse.seg_select_tokens), the same tokens and counts in less time: (1) the Triton
+# scoring's grid, 512 programs a segment (was 256), every score's bits unchanged; (2) segments of 4 or more rows scored
+# by a CUDA kernel (seg_scores.cu) with the prompt scoring's instruction sequence (patch 0105), a CTA converting each
+# FP8 key tile once for up to 8 of a segment's rows, the fewer-row segments by _seg_scores as before (memory-bound
+# there, where Triton reads faster), launched after it over the pool table the kernel writes; (3) windows of 8 or more
+# rows select by _seg_select_floor, one program a sparse row and one pass over its scores (patch 0101's method), instead
+# of select_split's five passes, the candidates in select_split's own scratch. Every stored score, token and count is
+# the same. The extension (tensorfold_glm_segscores_v1) is built / loaded by decode.Engine's constructor, and like
+# patch 0105's not used (logged once; _seg_scores serves) under another Triton release than sparse.TRITON_PTX (3.7) or
+# when its build fails. TF_GLM_SEG_SCORES_CUDA=0 / TF_GLM_SEG_SELECT_FLOOR=0: the Triton scoring / select_split.
+# Applies after patches 0101, 0105 and 0106 (the floor helpers, decode.py's start-up loads).
+# tools/decode_indexer_check.py.
+
+diff --git tensorfold/families/glm5_next/cuda/decode.py tensorfold/families/glm5_next/cuda/decode.py
+--- tensorfold/families/glm5_next/cuda/decode.py
++++ tensorfold/families/glm5_next/cuda/decode.py
+@@ -206,6 +206,8 @@ class Engine:
+
+ if latent.onepass_cuda(): # patch 0106: the prompt chunks' sparse attention, likewise
+ latent._onepass_ext()
++ if sparse.seg_scores_cuda(): # patch 0107: the decode windows' scoring, likewise
++ sparse._seg_scores_ext()
+ self.slots = Slots(w, streams, max_rows)
+ self.home = self.st = State(w, capacity, max_rows, caches=self.caches, slots=self.slots)
+ self.last_hidden: torch.Tensor | None = None
+diff --git tensorfold/families/glm5_next/cuda/seg_scores.cu tensorfold/families/glm5_next/cuda/seg_scores.cu
+new file mode 100644
+--- /dev/null
++++ tensorfold/families/glm5_next/cuda/seg_scores.cu
+@@ -0,0 +1,298 @@
++// Patch 0107: the DSA indexer's decode scoring for a segmented window (sparse._seg_scores as seg_select_tokens launches
++// it: FP8 pooled keys, 32 heads x 128, 64-pool blocks, 4 warps) as a CUDA kernel that computes every score with the
++// Triton kernel's own instruction sequence (prompt_scores.cu's, whose sequence _seg_scores shares: the same
++// tile, warps and epilogue), so every bit is the same, while a CTA converts each key tile once into shared memory for
++// up to 8 of a segment's rows. Triton's _seg_scores loads each tile once a program too, but converts it, lays it out
++// and masks it again for every row: at 4 streams x 8 rows x 596k it ran at 1.9x the keys' memory time (the tensor
++// cores' work alone 0.7x). With few rows the scoring is memory-bound and Triton's programs read faster (measured: 1-3
++// rows ~10% faster), so a segment of fewer than ``min_rows`` rows is left to _seg_scores, launched next over the pool
++// table this kernel writes. tools/decode_indexer_check.py.
++//
++// Per score (prompt_scores.cu's header has the Triton PTX it reads): keys e4m3 -> bf16 (exact); dots[32 heads, 64
++// pools] = mma.sync m16n8k16 bf16 -> fp32, one chain over the 8 k16 steps from +0, the kWidth = 4 k order; per element
++// (dot * ks[pool]) * scale, max(., 0); per pool the head sum fma(w24, x24, fma(w16, x16, fma(w0, x0, w8 * x8))), then
++// shfl_xor 16, 8, 4. A row's score is stored for its visible pools only (p < (pos + 1) / 4), as _seg_scores stores
++// them; the keys a row does not see change none of its stored columns (a column's mma chain reads its own key only),
++// so Triton's per-row key mask is not repeated.
++//
++// Work: CTA (row group, block g, segment) takes the segment's pool blocks g, g + gridDim.y, .. (below its device-side
++// pool count; neighbouring blocks read at once, as Triton's grid does), ST - 1 tiles in flight through cp.async; a
++// group's rows share its 8 warps (a row's n8 tiles split over 8 / rows-rounded-up warps).
++
++#include <ATen/cuda/CUDAContext.h>
++#include <c10/cuda/CUDAGuard.h>
++#include <cuda_bf16.h>
++#include <cuda_fp16.h>
++#include <stdint.h>
++#include <torch/extension.h>
++
++namespace {
++
++constexpr int H = 32, D = 128, BP = 64, KS = D / 16; // heads, key width, pools a block, k16 steps
++constexpr int CH = D * 2 / 16; // 16-byte chunks of a bf16 key row (16)
++constexpr int RB = 8; // rows a CTA, one a warp
++
++__device__ __forceinline__ void mma16816(float (&d)[4], const uint32_t (&a)[4], uint32_t b0, uint32_t b1) {
++ asm volatile("mma.sync.aligned.m16n8k16.row.col.f32.bf16.bf16.f32 {%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, "
++ "{%0,%1,%2,%3};\n"
++ : "+f"(d[0]), "+f"(d[1]), "+f"(d[2]), "+f"(d[3])
++ : "r"(a[0]), "r"(a[1]), "r"(a[2]), "r"(a[3]), "r"(b0), "r"(b1));
++}
++
++__device__ __forceinline__ void ldsm_x4(uint32_t (&r)[4], const void* p) {
++ const unsigned s = (unsigned)__cvta_generic_to_shared(p);
++ asm volatile("ldmatrix.sync.aligned.m8n8.x4.shared.b16 {%0,%1,%2,%3}, [%4];\n"
++ : "=r"(r[0]), "=r"(r[1]), "=r"(r[2]), "=r"(r[3])
++ : "r"(s));
++}
++
++// two e4m3 codes (low byte first) -> their bf16 values (low first), exactly: e4m3 -> f16 -> f32 -> bf16
++__device__ __forceinline__ uint32_t e4m3x2_bf16x2(uint32_t two) {
++ uint32_t h2, r;
++ const unsigned short v = (unsigned short)two;
++ asm("cvt.rn.f16x2.e4m3x2 %0, %1;" : "=r"(h2) : "h"(v));
++ asm("{\n .reg .b16 lo, hi;\n .reg .f32 a, b;\n mov.b32 {lo, hi}, %1;\n cvt.f32.f16 a, lo;\n cvt.f32.f16 b, hi;\n"
++ " cvt.rn.bf16x2.f32 %0, b, a;\n}" : "=r"(r) : "r"(h2));
++ return r;
++}
++
++// The physical 16-byte chunk of logical chunk c in key row p (ldmatrix's 8 rows on distinct bank groups).
++__device__ __forceinline__ int swz(int p, int c) { return c ^ (p & 7); }
++
++// Key tiles stream through ST stages of raw shared memory (cp.async, ST - 1 tiles in flight while one is converted):
++// a stage is a tile's 64 rows of 128 e4m3 codes, then their 64 fp32 scales; rows at or past the segment's pool count
++// are zero-filled (their columns are never stored). ``convert`` turns a stage into the bf16 tile, tile[p][chunk] in
++// mma slot order, and the scales into ks[p].
++constexpr int STAGE = BP * D + BP * 4; // bytes a raw stage
++constexpr int TPP = RB * 32 / BP, GPT = KS / TPP; // threads a pool, k16 groups a thread (convert)
++
++__device__ __forceinline__ void cp_async(uint32_t dst, const void* src, int bytes, bool ok) {
++ if (bytes == 16)
++ asm volatile("cp.async.cg.shared.global [%0], [%1], 16, %2;\n" ::"r"(dst), "l"(src), "r"(ok ? 16 : 0));
++ else
++ asm volatile("cp.async.ca.shared.global [%0], [%1], 4, %2;\n" ::"r"(dst), "l"(src), "r"(ok ? 4 : 0));
++}
++
++__device__ __forceinline__ void cp_commit() { asm volatile("cp.async.commit_group;\n" ::); }
++
++template <int N>
++__device__ __forceinline__ void cp_wait() { asm volatile("cp.async.wait_group %0;\n" ::"n"(N)); }
++
++// tile pb's codes and scales into stage ``raw`` (``any`` false: past the CTA's blocks, an empty group, so the count
++// of groups cp_wait sees stays uniform)
++__device__ __forceinline__ void issue(const uint8_t* __restrict__ PK, int RS, long long pbase, int NP, int pb,
++ bool any, uint8_t* raw) {
++ if (any) {
++ const uint32_t base = (uint32_t)__cvta_generic_to_shared(raw);
++#pragma unroll
++ for (int k = 0; k < BP * (D / 16) / (RB * 32); ++k) {
++ const int c = threadIdx.x + k * RB * 32, i = c / (D / 16), part = c % (D / 16);
++ const int p = pb * BP + i;
++ const bool ok = p < NP;
++ cp_async(base + i * D + 16 * part, PK + (size_t)(pbase + (ok ? p : 0)) * RS + 16 * part, 16, ok);
++ }
++ if (threadIdx.x < BP) {
++ const int p = pb * BP + threadIdx.x;
++ const bool ok = p < NP;
++ cp_async(base + BP * D + 4 * threadIdx.x, PK + (size_t)(pbase + (ok ? p : 0)) * RS + D, 4, ok);
++ }
++ }
++ cp_commit();
++}
++
++__device__ __forceinline__ void convert(const uint8_t* raw, uint4* tile, float* ks) {
++ const int tid = threadIdx.x, i = tid / TPP, part = tid % TPP;
++#pragma unroll
++ for (int gg = 0; gg < GPT; ++gg) {
++ const int j = part * GPT + gg; // k16 group: k = 16 j .. 16 j + 15
++ const uint4 c = *reinterpret_cast<const uint4*>(raw + i * D + 16 * j);
++ const uint32_t in[4] = {c.x, c.y, c.z, c.w};
++ uint32_t wv[8]; // wv[m]: values (2m, 2m + 1) of the group
++#pragma unroll
++ for (int m = 0; m < 8; ++m) wv[m] = e4m3x2_bf16x2(in[m >> 1] >> (16 * (m & 1)));
++ // group j: 32-block b = j / 2, half u = j % 2; word m = 2 t + h goes to step 2 b + h, slots 8 u + 2 t + e
++ tile[i * CH + swz(i, 4 * (j >> 1) + (j & 1))] = make_uint4(wv[0], wv[2], wv[4], wv[6]); // h = 0
++ tile[i * CH + swz(i, 4 * (j >> 1) + 2 + (j & 1))] = make_uint4(wv[1], wv[3], wv[5], wv[7]); // h = 1
++ }
++ if (part == 0) ks[i] = reinterpret_cast<const float*>(raw + BP * D)[i];
++}
++
++template <int ST>
++__global__ void __launch_bounds__(RB * 32) seg_scores_kernel(
++ const __nv_bfloat16* __restrict__ QI, const __nv_bfloat16* __restrict__ W, int w_stride,
++ const uint8_t* __restrict__ PK, int RS, float* __restrict__ OUT, long long o_stride,
++ const int32_t* __restrict__ POS, const int32_t* __restrict__ SPR, const int32_t* __restrict__ SEG_START,
++ const int32_t* __restrict__ SEG_ROWS, const int32_t* __restrict__ SEG_PBASE, const int32_t* __restrict__ SEG_POOLS,
++ int32_t* __restrict__ TRI_POOLS, int min_rows, float scale, float wscale) {
++ extern __shared__ __align__(16) uint8_t smem[];
++ uint4* tile = reinterpret_cast<uint4*>(smem); // 16 KB: one key tile, bf16
++ float* ks = reinterpret_cast<float*>(smem + BP * CH * 16); // its 64 scales
++ uint8_t* raw = smem + BP * CH * 16 + BP * 4; // ST raw stages
++ const int s = blockIdx.z, G = gridDim.y;
++ const int nr = SEG_ROWS[s];
++ // segments of fewer than min_rows rows are the Triton kernel's (launched next, over TRI_POOLS: their pool counts,
++ // 0 for the segments scored here); a few rows' scoring is memory-bound, where Triton's programs read faster
++ if (blockIdx.x == 0 && blockIdx.y == 0 && threadIdx.x == 0) TRI_POOLS[s] = nr < min_rows ? SEG_POOLS[s] : 0;
++ if (nr < min_rows || (int)blockIdx.x * RB >= nr) return; // the whole CTA: not this kernel's, or past the rows
++ const int npm = SEG_POOLS[s]; // pools the segment's last row sees (0: dense)
++ const int nblk = (npm + BP - 1) / BP;
++ const int b0 = (int)blockIdx.y; // blocks b0, b0 + G, .. (neighbours read together)
++ if (b0 >= nblk) return;
++ const long long pbase = SEG_PBASE[s];
++ // the CTA's rows (up to RB) share its warps: WPR = RB / (its rows rounded up to a power of two) warps a row, each
++ // taking every WPR-th n8 tile of a key tile (which warp computes a column changes none of its arithmetic)
++ const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31, g = lane >> 2, t = lane & 3;
++ const int nrc = min(RB, nr - (int)blockIdx.x * RB);
++ const int wpr = nrc > 4 ? 1 : nrc > 2 ? 2 : nrc > 1 ? 4 : 8;
++ const int slot = warp / wpr, sub = warp % wpr;
++ const int i = (int)blockIdx.x * RB + slot;
++ const int r = SEG_START[s] + (slot < nrc ? i : 0);
++ const bool live = slot < nrc && SPR[r] != 0;
++ const int npool = live ? (POS[r] + 1) / 4 : 0;
++
++ // this warp's row: query fragments of both m16 tiles for the 8 k16 steps (prompt_scores.cu's), the 4 head weights
++ uint32_t qa[2][KS][4];
++ float wh[4];
++#pragma unroll
++ for (int mt = 0; mt < 2; ++mt)
++#pragma unroll
++ for (int st = 0; st < KS; ++st) {
++ const __nv_bfloat16* q0 = QI + ((size_t)r * H + 16 * mt + g) * D;
++ const __nv_bfloat16* q1 = q0 + 8 * D;
++ const int k = 32 * (st >> 1) + 4 * t + 2 * (st & 1);
++ qa[mt][st][0] = *reinterpret_cast<const uint32_t*>(q0 + k);
++ qa[mt][st][1] = *reinterpret_cast<const uint32_t*>(q1 + k);
++ qa[mt][st][2] = *reinterpret_cast<const uint32_t*>(q0 + k + 16);
++ qa[mt][st][3] = *reinterpret_cast<const uint32_t*>(q1 + k + 16);
++ }
++ {
++ const int hs[4] = {g, g + 8, 16 + g, 24 + g};
++#pragma unroll
++ for (int x = 0; x < 4; ++x) wh[x] = __fmul_rn(__bfloat162float(W[(size_t)r * w_stride + hs[x]]), wscale);
++ }
++
++ float* orow = OUT + (size_t)r * o_stride;
++#pragma unroll
++ for (int k = 0; k < ST - 1; ++k) issue(PK, RS, pbase, npm, b0 + k * G, b0 + k * G < nblk, raw + k * STAGE);
++ for (int pb = b0, jt = 0; pb < nblk; pb += G, ++jt) {
++ const int p0 = pb * BP;
++ cp_wait<ST - 2>(); // this thread's copies of tile pb landed
++ __syncthreads(); // everyone's; the previous tile's dots are done
++ convert(raw + (jt % ST) * STAGE, tile, ks);
++ // tile pb + (ST - 1) G into the stage converted last iteration
++ const int nx = pb + (ST - 1) * G;
++ issue(PK, RS, pbase, npm, nx, nx < nblk, raw + ((jt + ST - 1) % ST) * STAGE);
++ __syncthreads();
++ if (p0 >= npool) continue; // the row sees none of them (or no row)
++#pragma unroll 2
++ for (int n = sub; n < BP / 8; n += wpr) { // n8 tile: pools p0 + 8 n .. + 7
++ float acc[2][4];
++#pragma unroll
++ for (int mt = 0; mt < 2; ++mt)
++#pragma unroll
++ for (int c = 0; c < 4; ++c) acc[mt][c] = 0.0f;
++#pragma unroll
++ for (int j = 0; j < KS; j += 2) { // steps j, j + 1 from one ldmatrix.x4
++ uint32_t b[4];
++ const int pr = 8 * n + (lane & 7), c = 2 * j + (lane >> 3);
++ ldsm_x4(b, &tile[pr * CH + swz(pr, c)]);
++#pragma unroll
++ for (int mt = 0; mt < 2; ++mt) {
++ mma16816(acc[mt], qa[mt][j], b[0], b[1]);
++ mma16816(acc[mt], qa[mt][j + 1], b[2], b[3]);
++ }
++ }
++ const int pc = 8 * n + 2 * t;
++ float sv[2];
++#pragma unroll
++ for (int e = 0; e < 2; ++e) { // pool columns pc, pc + 1
++ const float k = ks[pc + e];
++ const float x0 = fmaxf(__fmul_rn(scale, __fmul_rn(acc[0][e], k)), 0.0f); // head g
++ const float x8 = fmaxf(__fmul_rn(scale, __fmul_rn(acc[0][2 + e], k)), 0.0f); // g + 8
++ const float x16 = fmaxf(__fmul_rn(scale, __fmul_rn(acc[1][e], k)), 0.0f); // 16 + g
++ const float x24 = fmaxf(__fmul_rn(scale, __fmul_rn(acc[1][2 + e], k)), 0.0f); // 24 + g
++ float v = __fmul_rn(wh[1], x8);
++ v = __fmaf_rn(wh[0], x0, v);
++ v = __fmaf_rn(wh[2], x16, v);
++ v = __fmaf_rn(wh[3], x24, v);
++ v = __fadd_rn(v, __shfl_xor_sync(0xffffffffu, v, 16));
++ v = __fadd_rn(v, __shfl_xor_sync(0xffffffffu, v, 8));
++ v = __fadd_rn(v, __shfl_xor_sync(0xffffffffu, v, 4));
++ sv[e] = v;
++ }
++ const int p = p0 + pc;
++ if (g == 0) {
++ if (p + 1 < npool)
++ *reinterpret_cast<float2*>(orow + p) = make_float2(sv[0], sv[1]);
++ else if (p < npool)
++ orow[p] = sv[0];
++ }
++ }
++ }
++}
++
++template <int ST>
++void launch(dim3 grid, cudaStream_t stream, const __nv_bfloat16* QI, const __nv_bfloat16* W, int w_stride,
++ const uint8_t* PK, int RS, float* OUT, long long o_stride, const int32_t* POS, const int32_t* SPR,
++ const int32_t* SS, const int32_t* SR, const int32_t* SB, const int32_t* SP, int32_t* TP, int min_rows,
++ float scale, float wscale) {
++ constexpr int bytes = BP * CH * 16 + BP * 4 + ST * STAGE;
++ static bool sized = false; // over 48 KB needs the opt-in (once a process)
++ if (!sized) {
++ C10_CUDA_CHECK(cudaFuncSetAttribute(seg_scores_kernel<ST>, cudaFuncAttributeMaxDynamicSharedMemorySize, bytes));
++ sized = true;
++ }
++ seg_scores_kernel<ST><<<grid, RB * 32, bytes, stream>>>(QI, W, w_stride, PK, RS, OUT, o_stride, POS, SPR, SS, SR,
++ SB, SP, TP, min_rows, scale, wscale);
++}
++
++} // namespace
++
++// _seg_scores' stores, bit for bit, for the segments of at least ``min_rows`` rows: OUT[r, p] (row stride o_stride)
++// for each of their sparse rows r and its visible pools p < (POS[r] + 1) / 4; nothing else is scored here. TRI_POOLS
++// [segs] (int32) <- SEG_POOLS for the other segments, 0 for these: _seg_scores launched after it over TRI_POOLS
++// scores exactly the rest. QI [R, 32 * 128] bf16 contiguous rows, W bf16 head weights (row stride w_stride, unit
++// column stride), PK an FP8 pooled-key arena (rows of 128 e4m3 codes then the row's fp32 scale, RS bytes apart; a
++// segment's pool p at row SEG_PBASE + p), the int32 SegRows tables (POS, SPR per row; SEG_START, SEG_ROWS, SEG_PBASE,
++// SEG_POOLS per segment, ``segs`` of them). ``blocks``: CTAs a segment's pool blocks are split over, ``stages``: raw
++// key tiles a CTA holds (2-4); ``min_rows`` (speed only, like both).
++void seg_scores(const at::Tensor& QI, const at::Tensor& W, int64_t w_stride, const at::Tensor& PK, int64_t RS,
++ at::Tensor OUT, int64_t o_stride, const at::Tensor& POS, const at::Tensor& SPR,
++ const at::Tensor& SEG_START, const at::Tensor& SEG_ROWS, const at::Tensor& SEG_PBASE,
++ const at::Tensor& SEG_POOLS, at::Tensor TRI_POOLS, int64_t segs, double scale, double wscale,
++ int64_t blocks, int64_t stages, int64_t min_rows) {
++ TORCH_CHECK(QI.is_cuda() && QI.scalar_type() == at::kBFloat16 && W.scalar_type() == at::kBFloat16 &&
++ OUT.scalar_type() == at::kFloat && PK.element_size() == 1, "seg scores: dtypes");
++ for (const at::Tensor* x :
++ std::initializer_list<const at::Tensor*>{&POS, &SPR, &SEG_START, &SEG_ROWS, &SEG_PBASE, &SEG_POOLS, &TRI_POOLS})
++ TORCH_CHECK(x->scalar_type() == at::kInt && x->is_contiguous(), "seg scores: int32 SegRows tables");
++ TORCH_CHECK(QI.dim() == 2 && QI.is_contiguous() && QI.size(1) == H * D && W.stride(-1) == 1 &&
++ OUT.stride(-1) == 1 && SEG_START.numel() >= segs && SEG_ROWS.numel() >= segs &&
++ SEG_PBASE.numel() >= segs && SEG_POOLS.numel() >= segs && TRI_POOLS.numel() >= segs &&
++ POS.numel() >= QI.size(0) && SPR.numel() >= QI.size(0), "seg scores: shapes");
++ TORCH_CHECK(o_stride % 2 == 0 && reinterpret_cast<uintptr_t>(OUT.data_ptr()) % 8 == 0,
++ "seg scores: score rows 8-byte aligned (float2 stores)");
++ TORCH_CHECK(RS % 16 == 0 && RS >= D + 4 && PK.is_contiguous(), "seg scores: an FP8 key cache of 16-byte rows");
++ TORCH_CHECK(blocks >= 1 && blocks <= 65535 && segs >= 1 && segs <= 65535 && stages >= 2 && stages <= 4 &&
++ min_rows >= 1, "seg scores: grid / stages / rows");
++ const int64_t R = QI.size(0);
++ if (R <= 0) return;
++ const c10::cuda::CUDAGuard guard(QI.device());
++ const dim3 grid((unsigned)((R + RB - 1) / RB), (unsigned)blocks, (unsigned)segs);
++ const cudaStream_t stream = at::cuda::getCurrentCUDAStream();
++ auto qi = reinterpret_cast<const __nv_bfloat16*>(QI.data_ptr());
++ auto w = reinterpret_cast<const __nv_bfloat16*>(W.data_ptr());
++ auto pk = reinterpret_cast<const uint8_t*>(PK.data_ptr());
++ auto go = [&](auto f) {
++ f(grid, stream, qi, w, (int)w_stride, pk, (int)RS, OUT.data_ptr<float>(), (long long)o_stride,
++ POS.data_ptr<int32_t>(), SPR.data_ptr<int32_t>(), SEG_START.data_ptr<int32_t>(),
++ SEG_ROWS.data_ptr<int32_t>(), SEG_PBASE.data_ptr<int32_t>(), SEG_POOLS.data_ptr<int32_t>(),
++ TRI_POOLS.data_ptr<int32_t>(), (int)min_rows, (float)scale, (float)wscale);
++ };
++ if (stages == 2) go(launch<2>);
++ else if (stages == 3) go(launch<3>);
++ else go(launch<4>);
++ C10_CUDA_KERNEL_LAUNCH_CHECK();
++}
++
++PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("seg_scores", &seg_scores); }
+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
+@@ -821,9 +821,55 @@ def _seg_select(S, s_stride, POS, SPR, TOK, CNT, W: tl.constexpr, K: tl.constexp
+ tl.store(CNT + r, tl.where(NP > K, n, 0).to(tl.int32))
+
+
+-SEG_SCORE_GRID = 256 # _seg_scores programs a segment (grid stride over its pool blocks): speed only
++# _seg_scores programs a segment (grid stride over its pool blocks): speed only. Patch 0107: 512 (was 256), long
++# contexts' scoring a little faster (with patch 0085's selection, the indexer call at 1 x 16 rows x 1.04M
++# 1.076 -> 1.043 ms, 4 streams x 8 rows x 590k 1.266 -> 1.243 on GB10), every score's bits unchanged
++SEG_SCORE_GRID = 512
+ SEG_SPLIT = True # seg_select_tokens: the split selection (select_split), else one program a row (_seg_select)
+ SEG_SELECT = (4096, 8) # _seg_select's scores a step and warps: speed only (the selection is exact integer logic)
++# Patch 0107: a segmented window's FP8 scoring: segments of at least SEG_SCORE_CUDA_ROWS rows from seg_scores.cu, the
++# rest from _seg_scores (the same stores, bit for bit, either way); the CUDA kernel's CTAs a segment and raw key tiles
++# in flight. All three speed only (measured on GB10, 1-4 streams x 1-16 rows at 180k-596k)
++SEG_SCORE_CUDA_ROWS = 4
++SEG_SCORE_CTAS = 96
++SEG_SCORE_STAGES = 2
++
++
++def seg_scores_cuda() -> bool:
++ """TF_GLM_SEG_SCORES_CUDA (default on): a segmented decode window's FP8 pool scores for its segments of
++ SEG_SCORE_CUDA_ROWS or more rows from seg_scores.cu, which stores _seg_scores' scores with _scores' instruction
++ sequence (prompt_scores.cu's: the same tile, warps and epilogue), a CTA converting each key tile once for up to 8
++ of a segment's rows instead of once a row; the fewer-row segments (memory-bound, where Triton reads faster) from
++ _seg_scores as before. 0: _seg_scores for all. Off as well when the extension is not used (another Triton release
++ than TRITON_PTX, or a failed build or load: ``_seg_scores_ext``). tools/decode_indexer_check.py."""
++ import os
++
++ return os.environ.get("TF_GLM_SEG_SCORES_CUDA", "1") != "0" and _SEG_SCORES_FAILED is None
++
++
++_SEG_SCORES_EXT = None
++_SEG_SCORES_FAILED = None # why seg_scores.cu is not used (then _seg_scores serves every segment)
++
++
++def _seg_scores_ext():
++ """The extension, built / loaded once; None when it is not used (as ``_scores_ext``)."""
++ global _SEG_SCORES_EXT, _SEG_SCORES_FAILED
++ if _SEG_SCORES_EXT is None and _SEG_SCORES_FAILED is None:
++ from pathlib import Path
++
++ from tensorfold.cuda.build import load
++
++ try:
++ if not triton_matches_ptx():
++ raise RuntimeError(f"Triton {triton.__version__}: the kernel reproduces Triton {TRITON_PTX}'s PTX")
++ _SEG_SCORES_EXT = load(name="tensorfold_glm_segscores_v1",
++ sources=[str(Path(__file__).parent / "seg_scores.cu")],
++ extra_cuda_cflags=["-O3"], verbose=False)
++ except Exception as exc:
++ _SEG_SCORES_FAILED = f"{type(exc).__name__}: {(str(exc).strip().splitlines() or [''])[-1][:200]}"
++ print(f"[tensorfold] seg_scores.cu is not used ({_SEG_SCORES_FAILED}); decode windows score with the "
++ "Triton kernel", flush=True)
++ return _SEG_SCORES_EXT
+
+
+ def seg_select_tokens(qi: torch.Tensor, wts: torch.Tensor, pk: torch.Tensor, rows, scratch) -> tuple[torch.Tensor,
+@@ -843,13 +889,34 @@ def seg_select_tokens(qi: torch.Tensor, wts: torch.Tensor, pk: torch.Tensor, row
+ D = qi.shape[1] // H
+ wscale = 1.0 / 5.656854249492381 if H == 32 else H ** -0.5 # select_tokens' constants
+ scores = scratch.scores
+- grid = min(SEG_SCORE_GRID, triton.cdiv(scores.shape[1], 64))
+ pkv, pks, rs, fp8 = kv8.parts(pk)
++ pools = rows.seg_pools
++ ext = _seg_scores_ext() if fp8 and H == 32 and D == 128 and seg_scores_cuda() else None
++ if ext is not None:
++ # patch 0107: the segments of SEG_SCORE_CUDA_ROWS or more rows scored by seg_scores.cu (the same stores,
++ # bit for bit), which writes the other segments' pool counts (0 for its own) for _seg_scores below. Its pool
++ # table is sized for any window (MAX_SEGS) at its first use, so it never grows: a captured graph keeps
++ # pointing at live memory
++ pools = getattr(scratch, "seg_scores_pools", None)
++ if pools is None:
++ from .segments import MAX_SEGS
++
++ pools = scratch.seg_scores_pools = torch.zeros((MAX_SEGS,), dtype=torch.int32, device=scores.device)
++ ext.seg_scores(qi, wts, wts.stride(0), pk, rs, scores, scores.stride(0), rows.pos, rows.sparse,
++ rows.seg_start, rows.seg_rows, rows.seg_pbase, rows.seg_pools, pools, rows.max_segs,
++ D ** -0.5, wscale, SEG_SCORE_CTAS, SEG_SCORE_STAGES, SEG_SCORE_CUDA_ROWS)
++ grid = min(SEG_SCORE_GRID, triton.cdiv(scores.shape[1], 64))
+ _seg_scores[(rows.max_segs, grid)](qi, wts, wts.stride(0), pkv, pks, scores, scores.stride(0), rows.pos,
+- rows.sparse, rows.seg_start, rows.seg_rows, rows.seg_pbase, rows.seg_pools,
++ rows.sparse, rows.seg_start, rows.seg_rows, rows.seg_pbase, pools,
+ D ** -0.5, wscale, H=H, HP=max(16, triton.next_power_of_2(H)), D=D, BP=64,
+ G=grid, RS=rs, FP8=fp8, num_warps=4)
+ tokens, counts = scratch.tokens[:R], scratch.counts[:R]
++ if SEG_SPLIT and R >= SEG_FLOOR_ROWS and seg_select_floor() and scratch.split.numel() >= R * 2 * SEG_FLOOR[0]:
++ # patch 0107: one program a row and one pass over its scores (the same tokens and counts, every bit)
++ _seg_select_floor[(R,)](scores, scores.stride(0), rows.pos, rows.sparse, tokens, counts, scratch.split,
++ W=TOKENS, K=TOPK_POOLS, PL=POOL, CAP=SEG_FLOOR[0], NS=PROMPT_SECTORS,
++ TARGET=SEG_FLOOR[1], BLOCK=SEG_FLOOR[2], num_warps=SEG_FLOOR[3])
++ return tokens, counts
+ if SEG_SPLIT:
+ select_split(scores[:R], TOPK_POOLS, scratch=scratch.split, rows=rows, tokens=tokens, counts=counts)
+ return tokens, counts
+@@ -858,6 +925,124 @@ def seg_select_tokens(qi: torch.Tensor, wts: torch.Tensor, pk: torch.Tensor, row
+ return tokens, counts
+
+
++# ------------------------------------------------------------------------- one-pass segmented selection ---
++# Patch 0107: a decode window's selection with one program a sparse row reading its scores once, patch 0101's prompt
++# selection (_select_floor) for segmented rows: a floor key from a sample of the row (_sample_floor), one pass that
++# compacts the pools at or above it (keys, then pools, in pool order) into CAND, and the radix select over those in
++# registers, writing their tokens as _seg_select does. Every pool above the K-th best is at or above the floor when
++# at least K are (so the K best of the candidates are the row's K best, ties in pool order alike); a row with fewer
++# than K candidates or more than CAP takes _seg_select's own passes over the whole row. The same tokens, tail and
++# count as _seg_select and select_split: integer logic, no order to keep. select_split reads a row's scores five
++# times (four histograms and the output pass: 383 us a call at 4 streams x 8 rows x 596k on GB10, 1.9x the scores
++# kernel's memory time again); with many rows a program a row keeps the GB10 busy, with few select_split's chunk
++# programs do (SEG_FLOOR_ROWS).
++
++def _seg_take(TOK, r, take, idx, written, W: tl.constexpr, PL: tl.constexpr):
++ """The tokens of pools idx where take, at slots written + their rank among them (ascending), as _seg_select
++ writes them; returns written + their count."""
++ t = take.to(tl.int32)
++ slot = (written + tl.cumsum(t, 0) - t).to(tl.int64)
++ j = tl.arange(0, PL)
++ tl.store(TOK + r * W + slot[:, None] * PL + j[None, :], (idx.to(tl.int64)[:, None] * PL + j[None, :]).to(tl.int32),
++ mask=take[:, None])
++ return written + tl.sum(t, 0)
++
++
++def _seg_select_floor(S, s_stride, POS, SPR, TOK, CNT, CAND, W: tl.constexpr, K: tl.constexpr, PL: tl.constexpr,
++ CAP: tl.constexpr, NS: tl.constexpr, TARGET: tl.constexpr, BLOCK: tl.constexpr):
++ """Program r (a sparse row): _seg_select's tokens, tail and count from one pass over the row's visible scores
++ (the comment above); a dense row gets count 0. CAND: int32, 2 * CAP a row."""
++
++ r = tl.program_id(0).to(tl.int64)
++ if tl.load(SPR + r) == 0:
++ tl.store(CNT + r, 0)
++ return
++ qpos = tl.load(POS + r).to(tl.int64)
++ NP = (qpos + 1) // PL
++ row = S + r * s_stride
++ c = tl.arange(0, CAP)
++ n = NP
++ ck = CAND + r * (2 * CAP)
++ if NP > CAP:
++ lo = _sample_floor(row, NP, NS, TARGET)
++ n = NP * 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.to(tl.int32), mask=put)
++ n += m
++ tl.debug_barrier() # the candidates other threads stored, before reading them
++ if (n >= K) & (n <= CAP):
++ ok = c < n
++ if NP > CAP:
++ u = tl.load(ck + c, mask=ok, other=0).to(tl.uint32, bitcast=True)
++ idx = tl.load(ck + CAP + c, mask=ok, other=0)
++ else:
++ u = _order_key(tl.load(row + c, mask=ok, other=0.0))
++ idx = c
++ 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))
++ _seg_take(TOK, r, take, idx, 0, W, PL)
++ else: # _seg_select's passes over the whole row
++ prefix = tl.zeros((), dtype=tl.uint32)
++ fixed = tl.zeros((), dtype=tl.uint32)
++ need = K
++ for p in tl.static_range(4):
++ hist = tl.zeros((256,), dtype=tl.int32)
++ 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))
++ 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)
++ written = 0
++ equal_seen = 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))
++ eq = (ok & (u == prefix)).to(tl.int32)
++ take = (ok & (u > prefix)) | ((eq == 1) & (tl.cumsum(eq, 0) - eq + equal_seen < need))
++ written = _seg_take(TOK, r, take, i, written, W, PL)
++ equal_seen += tl.sum(eq, 0)
++ jt = tl.arange(0, 4)
++ jok = jt < PL - 1
++ tail = NP * PL + jt
++ tok = jok & (tail <= qpos)
++ tl.store(TOK + r * W + K * PL + jt, tl.where(tok, tail, -1).to(tl.int32), mask=jok)
++ cnt = K * PL + tl.sum(tok.to(tl.int64), 0)
++ tl.store(CNT + r, tl.where(NP > K, cnt, 0).to(tl.int32))
++
++
++SEG_FLOOR_ROWS = 8 # windows of at least this many rows select by _seg_select_floor (speed only)
++SEG_FLOOR = (4096, 2048, 4096, 8) # its CAP, TARGET, scores a step and warps (speed only: the selection is exact)
++
++
++def seg_select_floor() -> bool:
++ """TF_GLM_SEG_SELECT_FLOOR (default on): windows of SEG_FLOOR_ROWS or more rows select each sparse
++ row's pools by _seg_select_floor (one pass over its scores) instead of select_split (five); the same tokens and
++ counts. 0: select_split. tools/decode_indexer_check.py."""
++ import os
++
++ return os.environ.get("TF_GLM_SEG_SELECT_FLOOR", "1") != "0"
++
++
+ # ----------------------------------------------------------------------------------- split top-k selection ---
+ # _select_rows' radix select with each row's scores split into CHS-score chunks, one program a (row, chunk), in five
+ # launches. Passes 0..3: every program takes the digits so far from the row's total histograms (TOT, integer
diff --git a/tools/decode_indexer_check.py b/tools/decode_indexer_check.py
new file mode 100644
index 0000000..62b57e4
--- /dev/null
+++ b/tools/decode_indexer_check.py
@@ -0,0 +1,582 @@
+#!/usr/bin/env python3
+"""tools/decode_indexer_check.py [--time]: patch 0107 - the DSA indexer of a decode window (sparse.seg_select_tokens):
+ - the Triton scoring's grid, SEG_SCORE_GRID, 512 programs a segment (was 256): speed only;
+ - the scoring of segments of SEG_SCORE_CUDA_ROWS (4) or more rows from seg_scores.cu, which stores _seg_scores'
+ scores with the prompt scoring's instruction sequence (prompt_scores.cu, patch 0105), the segments of fewer rows
+ from _seg_scores as before (TF_GLM_SEG_SCORES_CUDA=0: _seg_scores for all);
+ - the selection of windows of SEG_FLOOR_ROWS (8) or more rows by _seg_select_floor, one program a sparse row and one
+ pass over its scores (patch 0101's method), instead of select_split's five passes (TF_GLM_SEG_SELECT_FLOOR=0:
+ select_split).
+Run in the image built with patch 0107, on one GPU:
+docker run --rm --gpus all --entrypoint python -v "$PWD/tools/decode_indexer_check.py:/c.py" <image> /c.py
+
+Scoring, through sparse.seg_select_tokens with TF_GLM_SEG_SCORES_CUDA=1 against =0: the whole scores scratch
+(pre-filled with a NaN sentinel, so every store and every non-store counts), tokens and counts bit-identical:
+windows of 1-6 streams and 1-16 rows a stream at 180k-600k (the scratch as wide as the engine's: the whole pool), a
+stream straddling the dense limit beside a dense segment, unaligned positions, uneven rows; every non-NaN e4m3 code,
+arbitrary key scales, large / tiny / zero queries, negative head weights; other CTA counts and stages (speed only);
+one CUDA graph replayed over new positions; the routing (the extension and _seg_scores each run once, over the pool
+table the extension writes; bf16 caches stay on Triton); the extension alone stores its own segments only; the
+extension's pool table sized for any window (MAX_SEGS) at its first use and never replaced, so a window of more
+segments after a graph was captured does not move it.
+Selection, _seg_select_floor against select_split, the whole tokens [R, 2051] and counts [R]: the entry point at 8-32
+rows; crafted scores (tie-heavy: more than CAP candidates, bf16-rounded, -inf / -0.0 / +0.0, a sample that misleads
+the floor: fewer than K candidates, plain random), rows sparse below the dense limit (count 0), an overflowing row
+that must store nothing past its own 2 * CAP scratch words; other speed constants; one CUDA graph over new positions;
+the routing (8+ rows on, fewer rows / =0 / a scratch too small: select_split).
+Grid: the Triton scoring launched with min(512, pool blocks) programs a segment, the same scores as with 256.
+Start-up: decode.Engine's constructor loads (on a fresh image, builds) the scoring extension before any request for
+FP8 caches with DSA layers and the switch on; not with TF_GLM_SEG_SCORES_CUDA=0, bf16 caches or no DSA layer.
+Not used - a failed build or load, or another Triton release than sparse.TRITON_PTX: nothing raised, logged once
+and not retried, the switch reads off, and the window gets the Triton scoring's scores, tokens and counts.
+One PASS / FAIL line a check; exits 1 on any FAIL (on an image without the patch: at the first check).
+
+--time: the whole indexer call (scores + selection; cold: 11 calls a CUDA graph, each its own layer's keys, L2 flushed
+between replays), v1.10 (grid 256, both switches 0) -> grid 512 -> + CUDA scoring -> + one-pass selection. The
+indexer is replicated: its shapes are the same at TP=2 and TP=3."""
+import os
+import statistics
+import sys
+from types import SimpleNamespace
+
+import torch
+
+from tensorfold.families.glm5_next.cuda import decode, forward, hcsplit, kv8, sparse
+from tensorfold.families.glm5_next.cuda.segments import EXTENT, SegRows, SelectScratch
+
+dev = torch.device("cuda")
+IH, ID = 32, 128
+POOL_ROWS = 5_791_744
+SENT = 0x7FC0BEEF
+fails = 0
+g = torch.Generator(device=dev).manual_seed(95)
+
+
+def check(ok, msg):
+ global fails
+ print(("PASS " if ok else "FAIL ") + msg, flush=True)
+ fails += not ok
+
+
+check(all(hasattr(sparse, a) for a in ("seg_scores_cuda", "_seg_scores_ext", "seg_select_floor", "_seg_select_floor")),
+ "patch 0107 applied: sparse.seg_scores_cuda, sparse.seg_select_floor")
+if fails:
+ print("1 FAIL", flush=True)
+ sys.exit(1)
+SHIPPED = (sparse.SEG_SCORE_CTAS, sparse.SEG_SCORE_STAGES)
+FLOOR = (sparse.SEG_FLOOR_ROWS, sparse.SEG_FLOOR)
+flush = torch.empty((256 << 20,), dtype=torch.uint8, device=dev)
+
+
+def layout(streams, room=0):
+ """[(ctx, rows)] -> segments [(base, pos, rows)] and the arena's token rows (``room``: tokens past each stream's
+ window inside its extent, for positions moved later)."""
+ segs, base = [], 0
+ for ctx, n in streams:
+ segs.append((base, ctx, n))
+ base += -(-(ctx + n + 64 + room) // EXTENT) * EXTENT
+ return segs, base
+
+
+def keys(rows_, adversarial=False):
+ if not adversarial:
+ return kv8.quantize_rows(torch.randn(rows_, ID, device=dev, generator=g) *
+ torch.rand(rows_, 1, device=dev, generator=g) * 4)
+ pk = kv8.quantize_rows(torch.zeros(rows_, ID, device=dev))
+ codes = torch.randint(0, 255, (rows_, ID), device=dev, generator=g, dtype=torch.int32)
+ codes = torch.where((codes & 0x7F) == 0x7F, codes ^ 1, codes) # no NaN codes (0x7F / 0xFF)
+ pk[:, :ID] = codes.to(torch.uint8)
+ sc = torch.rand(rows_, device=dev, generator=g) * 3 + 1e-3 # arbitrary scales
+ pk[:, ID:ID + 4] = sc.view(torch.uint8).view(rows_, 4)
+ return pk
+
+
+def queries(R, adversarial=False):
+ qi = torch.randn(R, IH * ID, device=dev, generator=g)
+ wts = torch.randn(R, IH, device=dev, generator=g)
+ if adversarial:
+ mag = torch.tensor([1e-30, 1e-3, 1.0, 1e3, 3e4], device=dev)
+ pick = mag[torch.randint(0, 5, (R, IH, 1), device=dev, generator=g)]
+ qi = qi * pick.reshape(R, IH, 1).expand(R, IH, ID).reshape(R, -1)
+ qi[:, ::7] = 0.0
+ qi[:, 3::11] = -0.0
+ wts = wts * 100
+ return qi.to(torch.bfloat16), wts.to(torch.bfloat16)
+
+
+def window(streams, adversarial=False, max_segs=None, room=0):
+ segs, base = layout(streams, room)
+ R = sum(n for _, n in streams)
+ rows = SegRows(R, dev, max_segs=max_segs or max(4, len(streams)))
+ rows.set(segs)
+ pk = keys(base // sparse.POOL + 2, adversarial)
+ qi, wts = queries(R, adversarial)
+ return qi, wts, pk, rows, R, segs
+
+
+def run(qi, wts, pk, rows, sel, cuda):
+ os.environ["TF_GLM_SEG_SCORES_CUDA"] = "1" if cuda else "0"
+ sel.scores.view(torch.int32).fill_(SENT)
+ sel.tokens.fill_(-7)
+ sel.counts.fill_(-7)
+ t, c = sparse.seg_select_tokens(qi, wts, pk, rows, sel)
+ torch.cuda.synchronize()
+ return sel.scores.clone(), t.clone(), c.clone()
+
+
+def same3(a, b):
+ return (torch.equal(a[0].view(torch.int32), b[0].view(torch.int32)) and torch.equal(a[1], b[1])
+ and torch.equal(a[2], b[2]))
+
+
+def bits(name, streams, adversarial=False, arms=(None,)):
+ qi, wts, pk, rows, R, _ = window(streams, adversarial)
+ sel = SelectScratch(R, POOL_ROWS, dev)
+ ref = run(qi, wts, pk, rows, sel, False)
+ stored = int((ref[0].view(torch.int32)[:R] != SENT).sum())
+ for arm in arms:
+ sparse.SEG_SCORE_CTAS, sparse.SEG_SCORE_STAGES = SHIPPED if arm is None else arm
+ got = run(qi, wts, pk, rows, sel, True)
+ diff = int((got[0].view(torch.int32) != ref[0].view(torch.int32)).sum())
+ check(same3(got, ref), f"scores {name}, CTAs {sparse.SEG_SCORE_CTAS} stages {sparse.SEG_SCORE_STAGES}: "
+ f"scores ({stored} stored), tokens, counts bit-identical ({diff} score words differ)")
+ sparse.SEG_SCORE_CTAS, sparse.SEG_SCORE_STAGES = SHIPPED
+ del sel
+ torch.cuda.empty_cache()
+
+
+def entry(qi, wts, pk, rows, sel, floor):
+ os.environ["TF_GLM_SEG_SELECT_FLOOR"] = "1" if floor else "0"
+ sel.tokens.fill_(-7)
+ sel.counts.fill_(-7)
+ t, c = sparse.seg_select_tokens(qi, wts, pk, rows, sel)
+ torch.cuda.synchronize()
+ return t.clone(), c.clone()
+
+
+def direct(scores, rows, sel, R, floor, sync=True):
+ """One selection over given scores [R, NP]: _seg_select_floor as seg_select_tokens launches it, or select_split."""
+ if sync:
+ sel.tokens.fill_(-7)
+ sel.counts.fill_(-7)
+ tok, cnt = sel.tokens[:R], sel.counts[:R]
+ if floor:
+ cap, target, block, warps = sparse.SEG_FLOOR
+ sparse._seg_select_floor[(R,)](scores, scores.stride(0), rows.pos, rows.sparse, tok, cnt, sel.split,
+ W=sparse.TOKENS, K=sparse.TOPK_POOLS, PL=sparse.POOL, CAP=cap,
+ NS=sparse.PROMPT_SECTORS, TARGET=target, BLOCK=block, num_warps=warps)
+ else:
+ sparse.select_split(scores, sparse.TOPK_POOLS, scratch=sel.split, rows=rows, tokens=tok, counts=cnt)
+ if sync:
+ torch.cuda.synchronize()
+ return tok.clone(), cnt.clone()
+
+
+def same2(a, b):
+ return torch.equal(a[0], b[0]) and torch.equal(a[1], b[1])
+
+
+def differ(a, b):
+ return int((a[0] != b[0]).sum()) + int((a[1] != b[1]).sum())
+
+
+def sampled(NP):
+ """The columns _sample_floor reads in a row of NP scores."""
+ s = torch.arange(sparse.PROMPT_SECTORS * 8, device=dev)
+ return torch.unique(((s // 8) * NP // sparse.PROMPT_SECTORS) // 8 * 8 + s % 8)
+
+
+def construct(loader, kv, kinds=("dsa",)):
+ """decode.Engine's constructor with stand-ins for the buffers, caches, slots and state it builds; ``loader``
+ (``module.name``) counted, nothing built. Returns its calls."""
+ mod, name = loader
+ calls = []
+ real = getattr(mod, name)
+ saved = [(decode, "Buffers"), (decode, "State"), (forward, "Caches"), (forward, "Slots"), (forward, "index_ring"),
+ (hcsplit, "buffer_rows")]
+ saved = [(m, a, getattr(m, a)) for m, a in saved]
+ stub = SimpleNamespace
+ try:
+ setattr(mod, name, lambda: calls.append(name))
+ decode.Buffers = decode.State = forward.Caches = forward.Slots = lambda *a, **k: stub(rows=1)
+ forward.index_ring = lambda *a, **k: 0
+ hcsplit.buffer_rows = lambda rows, *a, **k: rows
+ os.environ["TF_GLM_L2PF"] = "0" # no L2 prefetch (it reads real weights)
+ w = stub(meta={}, layers=[stub(kind=k) for k in kinds], world=3, rank=0, mtp=None, head=stub(n=1),
+ cfg=stub(hidden=4096), device=torch.device("cuda"))
+ decode.Engine(w, kv=kv)
+ finally:
+ setattr(mod, name, real)
+ for m, a, v in saved:
+ setattr(m, a, v)
+ return len(calls)
+
+
+def cold_us(fn, layers=11, iters=15):
+ s = torch.cuda.Stream()
+ s.wait_stream(torch.cuda.current_stream())
+ with torch.cuda.stream(s):
+ fn()
+ torch.cuda.current_stream().wait_stream(s)
+ gr = torch.cuda.CUDAGraph()
+ with torch.cuda.graph(gr):
+ fn()
+ times = []
+ for _ in range(iters):
+ 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 / layers)
+ return statistics.median(times)
+
+
+def scoring():
+ C = sparse.SPARSE_FROM
+ for name, streams in (("4 x 8 @ 596k", [(596_000, 8)] * 4), ("4 x 4 @ 596k", [(596_001, 4)] * 4),
+ ("4 x 1 @ 596k", [(596_002, 1)] * 4), ("1 x 16 @ 596k", [(596_003, 16)]),
+ ("1 x 1 @ 596k", [(596_000, 1)]), ("1 x 5 @ 180k", [(180_001, 5)]),
+ ("1 x 16 @ 180k", [(180_002, 16)]), ("2 x 8 @ 300k", [(300_000, 8), (300_003, 8)]),
+ ("2 mixed 180k x 3 + 600k x 5", [(180_003, 3), (600_000, 5)]),
+ ("4 mixed 180k/300k/450k/600k x 8", [(180_000, 8), (300_001, 8), (450_002, 8), (600_003, 8)]),
+ ("4 uneven rows 1/16/3/12", [(250_000, 1), (400_001, 16), (590_002, 3), (200_003, 12)]),
+ ("dense limit straddled + dense segment",
+ [(C - 3, 8), (1_000, 4), (C + 1, 16), (300_000, 2)]),
+ ("6 streams x 5 @ 200k-450k", [(200_000 + 50_000 * i + i, 5) for i in range(6)]),
+ ("9 / 10 / 11 rows (a CTA's second group of 1 / 2 / 3 rows)",
+ [(450_001, 9), (300_002, 10), (596_003, 11)])):
+ bits(name, streams)
+ bits("adversarial 4 x 8 @ 300k", [(300_001, 8), (300_002, 8), (299_999, 8), (300_000, 8)], adversarial=True)
+ bits("adversarial 1 x 16 @ 180k", [(180_003, 16)], adversarial=True)
+ bits("4 x 8 @ 596k", [(596_000, 8)] * 4, arms=((1, 2), (7, 3), (48, 4), (512, 2), (96, 4)))
+ bits("dense limit straddled", [(C - 3, 8), (C + 70, 3)], arms=((1, 4), (7, 2), (512, 3)))
+ bits("1 x 16 @ 180k", [(180_002, 16)], arms=((3, 2), (200, 4)))
+
+ streams = [(400_000, 8), (590_000, 8), (200_000, 8), (500_000, 8)]
+ qi, wts, pk, rows, R, segs = window(streams, room=8_192)
+ sel = SelectScratch(R, POOL_ROWS, dev)
+ os.environ["TF_GLM_SEG_SCORES_CUDA"] = "1"
+ s = torch.cuda.Stream()
+ s.wait_stream(torch.cuda.current_stream())
+ with torch.cuda.stream(s):
+ sparse.seg_select_tokens(qi, wts, pk, rows, sel)
+ torch.cuda.current_stream().wait_stream(s)
+ gr = torch.cuda.CUDAGraph()
+ with torch.cuda.graph(gr):
+ sparse.seg_select_tokens(qi, wts, pk, rows, sel)
+ for k, shift in enumerate((0, 37, -150_001, 4_097)):
+ moved = [(b, max(1_000, p + shift * (i + 1) // 2), n) for i, (b, p, n) in enumerate(segs)]
+ rows.set(moved)
+ ref = run(qi, wts, pk, rows, sel, False)
+ sel.scores.view(torch.int32).fill_(SENT)
+ sel.tokens.fill_(-7)
+ sel.counts.fill_(-7)
+ gr.replay()
+ torch.cuda.synchronize()
+ got = (sel.scores.clone(), sel.tokens[:R].clone(), sel.counts[:R].clone())
+ check(same3(got, ref), f"scores: CUDA graph replay {k} (positions {[p for _, p, _ in moved]}) bit-identical")
+ gr = sel = None
+ torch.cuda.empty_cache()
+
+ calls, launched = [], []
+ real, real_tri = sparse._seg_scores_ext, sparse._seg_scores
+
+ class Tri: # _seg_scores' launches recorded: grid and the pool table it reads
+ def __getitem__(self, grid):
+ def go(*a, **kw):
+ launched.append((tuple(grid), a[12]))
+ return real_tri[grid](*a, **kw)
+ return go
+
+ sparse._seg_scores_ext = lambda: calls.append(1) or real()
+ sparse._seg_scores = Tri()
+ try:
+ qi, wts, pk, rows, R, _ = window([(300_000, 4)])
+ sel = SelectScratch(R, 400_000, dev)
+ run(qi, wts, pk, rows, sel, True)
+ check(len(calls) == 1 and len(launched) == 1 and launched[0][1] is getattr(sel, "seg_scores_pools", None),
+ f"TF_GLM_SEG_SCORES_CUDA=1: the extension called {len(calls)} time(s), _seg_scores launched "
+ f"{len(launched)} time(s) over the table the extension writes (want 1, 1)")
+ calls.clear()
+ launched.clear()
+ ref = run(qi, wts, pk, rows, sel, False)
+ blocks = -(-sel.scores.shape[1] // 64)
+ check(not calls and len(launched) == 1 and launched[0][1] is rows.seg_pools
+ and launched[0][0] == (rows.max_segs, min(512, blocks)),
+ f"TF_GLM_SEG_SCORES_CUDA=0: the extension called {len(calls)} time(s), _seg_scores launched "
+ f"{len(launched)} time(s) over the window's own pool counts, grid {launched[0][0] if launched else None} "
+ f"(want 0, 1, ({rows.max_segs}, {min(512, blocks)}))")
+ check(sparse.SEG_SCORE_GRID == 512, f"SEG_SCORE_GRID {sparse.SEG_SCORE_GRID} (want 512)")
+ sparse.SEG_SCORE_GRID = 256
+ got = run(qi, wts, pk, rows, sel, False)
+ sparse.SEG_SCORE_GRID = 512
+ check(same3(got, ref), "the Triton scoring at grid 256 (before the patch) stores the same bits as at 512")
+ os.environ.pop("TF_GLM_SEG_SCORES_CUDA", None)
+ check(sparse.seg_scores_cuda(), "TF_GLM_SEG_SCORES_CUDA unset: on")
+ calls.clear()
+ pkb = torch.zeros(pk.shape[0], ID, dtype=torch.bfloat16, device=dev) # a bf16 cache
+ sparse.seg_select_tokens(qi, wts, pkb, rows, sel)
+ torch.cuda.synchronize()
+ check(not calls, f"a bf16 cache: the extension called {len(calls)} time(s) (want 0: FP8 only)")
+ finally:
+ sparse._seg_scores_ext, sparse._seg_scores = real, real_tri
+ # the extension's pool table: sized for any window at its first use, never replaced (a captured graph keeps it)
+ from tensorfold.families.glm5_next.cuda.segments import MAX_SEGS
+
+ qa_, wa_, pa_, ra_, ra_n, _ = window([(300_000, 4)])
+ qb_, wb_, pb_, rb_, rb_n, _ = window([(200_000 + 50_000 * i + i, 2) for i in range(6)], max_segs=MAX_SEGS)
+ sel = SelectScratch(max(ra_n, rb_n), 600_000, dev)
+ first, err = None, None
+ try:
+ run(qa_, wa_, pa_, ra_, sel, True)
+ first = getattr(sel, "seg_scores_pools", None)
+ run(qb_, wb_, pb_, rb_, sel, True)
+ except RuntimeError as e: # a table too small for the second window: the extension refuses it
+ err = f"{type(e).__name__}: {str(e)[:120]}"
+ check(err is None and first is not None and sel.seg_scores_pools is first and first.numel() == MAX_SEGS,
+ f"the extension's pool table: {MAX_SEGS} entries at its first use ({None if first is None else first.numel()}),"
+ f" the same tensor for a {rb_.max_segs}-segment window after a {ra_.max_segs}-segment one ({err or 'no error'})")
+ sel = None
+ torch.cuda.empty_cache()
+
+ qi, wts, pk, rows, R, _ = window([(300_001, 3), (400_002, 4), (250_003, 1), (500_000, 9), (C - 3, 6)], max_segs=6)
+ sel = SelectScratch(R, 600_000, dev)
+ tp = torch.full((rows.max_segs,), -5, dtype=torch.int32, device=dev)
+ sel.scores.view(torch.int32).fill_(SENT)
+ rs = kv8.parts(pk)[2]
+ sparse._seg_scores_ext().seg_scores(qi, wts, wts.stride(0), pk, rs, sel.scores, sel.scores.stride(0), rows.pos,
+ rows.sparse, rows.seg_start, rows.seg_rows, rows.seg_pbase, rows.seg_pools, tp,
+ rows.max_segs, ID ** -0.5, 1.0 / 5.656854249492381, sparse.SEG_SCORE_CTAS,
+ sparse.SEG_SCORE_STAGES, sparse.SEG_SCORE_CUDA_ROWS)
+ torch.cuda.synchronize()
+ small = rows.seg_rows < sparse.SEG_SCORE_CUDA_ROWS
+ want_tp = torch.where(small, rows.seg_pools, torch.zeros_like(rows.seg_pools))
+ check(torch.equal(tp, want_tp), f"the extension's pool table for _seg_scores {tp.tolist()} == the counts of the "
+ f"segments under {sparse.SEG_SCORE_CUDA_ROWS} rows, 0 else {want_tp.tolist()}")
+ written = (sel.scores.view(torch.int32)[:R] != SENT).any(1)
+ seg_of = rows.seg[:R].long()
+ want_w = (~small[seg_of]) & (rows.sparse[:R] != 0) & (rows.seg_pools[seg_of] > 0)
+ check(torch.equal(written, want_w), f"rows the extension stored {written.int().tolist()} == the sparse rows of "
+ f"segments of {sparse.SEG_SCORE_CUDA_ROWS}+ rows {want_w.int().tolist()}")
+ sel = None
+ torch.cuda.empty_cache()
+ os.environ["TF_GLM_SEG_SCORES_CUDA"] = "1"
+
+
+def selection():
+ C = sparse.SPARSE_FROM
+ for name, streams in (("4 x 8 @ 596k", [(596_000, 8)] * 4), ("1 x 16 @ 596k", [(596_003, 16)]),
+ ("1 x 8 @ 596k", [(596_001, 8)]), ("4 x 3 @ 596k", [(596_002, 3)] * 4),
+ ("2 x 8 @ 300k", [(300_000, 8), (300_003, 8)]), ("1 x 16 @ 180k", [(180_002, 16)]),
+ ("4 mixed 180k/300k/450k/600k x 8", [(180_000, 8), (300_001, 8), (450_002, 8), (600_003, 8)]),
+ ("dense limit straddled + dense segment",
+ [(C - 3, 8), (1_000, 4), (C + 1, 16), (300_000, 2)]),
+ ("6 streams x 3 @ 200k-450k", [(200_000 + 50_000 * i + i, 3) for i in range(6)])):
+ qi, wts, pk, rows, R, _ = window(streams)
+ sel = SelectScratch(R, POOL_ROWS, dev)
+ ref = entry(qi, wts, pk, rows, sel, False)
+ got = entry(qi, wts, pk, rows, sel, True)
+ check(same2(got, ref), f"selection {name}: tokens and counts identical to select_split's "
+ f"({int((ref[1] > 0).sum())} sparse rows, {differ(got, ref)} words differ)")
+ sel = None
+ torch.cuda.empty_cache()
+
+ streams = [(596_000, 4), (300_001, 4), (C + 5, 4), (C - 2, 4), (180_002, 4), (14_000, 4)]
+ _, _, _, rows, R, _ = window(streams, max_segs=6)
+ sel = SelectScratch(R, 600_000, dev)
+ NP = sel.scores.shape[1]
+ cases = {}
+ cases["tie-heavy integers (8 values)"] = torch.randint(0, 8, (R, NP), device=dev, generator=g).float()
+ cases["bf16-rounded scores"] = torch.randn(R, NP, device=dev, generator=g).to(torch.bfloat16).float()
+ mixed = torch.randn(R, NP, device=dev, generator=g)
+ pick = torch.rand(R, NP, device=dev, generator=g)
+ mixed[pick < 0.2] = float("-inf")
+ mixed[(pick >= 0.2) & (pick < 0.3)] = -0.0
+ mixed[(pick >= 0.3) & (pick < 0.4)] = 0.0
+ cases["-inf / -0.0 / +0.0 mixed"] = mixed
+ few = torch.zeros(R, NP, device=dev) # the sample's top values that the rest of the row lacks
+ for r in range(R):
+ npool = (int(rows.pos[r]) + 1) // 4
+ cols = sampled(npool)
+ few[r, cols[torch.randperm(cols.numel(), device=dev, generator=g)[:60]]] = 10.0
+ cases["few high scores, all in the sample (under K candidates)"] = few
+ cases["plain random"] = torch.randn(R, NP, device=dev, generator=g)
+ for name, sc in cases.items():
+ ref = direct(sc, rows, sel, R, False)
+ got = direct(sc, rows, sel, R, True)
+ check(same2(got, ref), f"selection, {name}: identical ({differ(got, ref)} words differ)")
+ segs_lo = [(0, 1_500, 4), (EXTENT * 2, 2_045, 4), (EXTENT * 4, 2_300, 4), (EXTENT * 6, 1_100, 4)]
+ rows_lo = SegRows(16, dev, max_segs=4)
+ rows_lo.set(segs_lo, sparse_from=1_000)
+ sel_lo = SelectScratch(16, 600_000, dev)
+ sc = torch.randn(16, sel_lo.scores.shape[1], device=dev, generator=g)
+ ref = direct(sc, rows_lo, sel_lo, 16, False)
+ got = direct(sc, rows_lo, sel_lo, 16, True)
+ check(same2(got, ref) and int((ref[1] == 0).sum()) > 0,
+ f"selection, rows sparse from position 1,000 (up to K visible pools: count 0): identical "
+ f"({differ(got, ref)} words differ; {int((ref[1] == 0).sum())} rows with count 0)")
+ sel_lo = None
+ # a row with more than CAP candidates writes only its own 2 * CAP candidate slots: one overflowing sparse row
+ # (tie-heavy scores) followed by 7 dense rows, which return before touching their regions
+ _, _, _, rows_ov, R_ov, _ = window([(596_000, 1), (1_000, 7)])
+ sel_ov = SelectScratch(R_ov, 600_000, dev)
+ sc = torch.randint(0, 8, (R_ov, sel_ov.scores.shape[1]), device=dev, generator=g).float()
+ ref = direct(sc, rows_ov, sel_ov, R_ov, False)
+ sel_ov.split.fill_(0x7F7F7F7F)
+ got = direct(sc, rows_ov, sel_ov, R_ov, True)
+ cap = sparse.SEG_FLOOR[0]
+ keys_full = bool((sel_ov.split[:cap] != 0x7F7F7F7F).all())
+ outside = int((sel_ov.split[2 * cap:] != 0x7F7F7F7F).sum())
+ check(same2(got, ref) and keys_full and outside == 0,
+ f"selection, an overflowing row (more than CAP {cap} candidates: key slots full {keys_full}) beside dense "
+ f"rows: identical ({differ(got, ref)} words differ), {outside} scratch words past its 2 * CAP changed")
+ sel_ov = None
+ sc = cases["bf16-rounded scores"]
+ ref = direct(sc, rows, sel, R, False)
+ for arm in ((2048, 1024, 4096, 8), (8192, 2048, 2048, 4), (4096, 512, 1024, 8), (4096, 3000, 8192, 8)):
+ sparse.SEG_FLOOR = arm
+ got = direct(sc, rows, sel, R, True)
+ check(same2(got, ref), f"selection, SEG_FLOOR {arm}: identical ({differ(got, ref)} words differ)")
+ sparse.SEG_FLOOR_ROWS, sparse.SEG_FLOOR = FLOOR
+ sel = None
+ torch.cuda.empty_cache()
+
+ streams = [(400_000, 8), (590_000, 8), (200_000, 8), (500_000, 8)]
+ qi, wts, pk, rows, R, segs = window(streams, room=8_192)
+ sel = SelectScratch(R, POOL_ROWS, dev)
+ os.environ["TF_GLM_SEG_SELECT_FLOOR"] = "1"
+ s = torch.cuda.Stream()
+ s.wait_stream(torch.cuda.current_stream())
+ with torch.cuda.stream(s):
+ sparse.seg_select_tokens(qi, wts, pk, rows, sel)
+ torch.cuda.current_stream().wait_stream(s)
+ gr = torch.cuda.CUDAGraph()
+ with torch.cuda.graph(gr):
+ sparse.seg_select_tokens(qi, wts, pk, rows, sel)
+ for k, shift in enumerate((0, 37, -150_001, 4_097)):
+ rows.set([(b, max(1_000, p + shift * (i + 1) // 2), n) for i, (b, p, n) in enumerate(segs)])
+ ref = entry(qi, wts, pk, rows, sel, False)
+ sel.tokens.fill_(-7)
+ sel.counts.fill_(-7)
+ gr.replay()
+ torch.cuda.synchronize()
+ got = (sel.tokens[:R].clone(), sel.counts[:R].clone())
+ check(same2(got, ref), f"selection: CUDA graph replay {k} identical ({differ(got, ref)} words differ)")
+ gr = sel = None
+ torch.cuda.empty_cache()
+
+ launched = []
+ real = sparse._seg_select_floor
+
+ class Rec:
+ def __getitem__(self, grid):
+ launched.append(grid)
+ return real[grid]
+
+ sparse._seg_select_floor = Rec()
+ try:
+ for name, streams, room, env, want in (
+ ("8 rows, on", [(300_000, 8)], POOL_ROWS, "1", 1),
+ (f"{sparse.SEG_FLOOR_ROWS - 1} rows, on", [(300_000, sparse.SEG_FLOOR_ROWS - 1)], POOL_ROWS, "1", 0),
+ ("8 rows, TF_GLM_SEG_SELECT_FLOOR=0", [(300_000, 8)], POOL_ROWS, "0", 0),
+ ("8 rows, unset", [(300_000, 8)], POOL_ROWS, None, 1),
+ ("8 rows, a scratch too small for the candidates", [(5_000, 8)], 6_000, "1", 0)):
+ qi, wts, pk, rows, R, _ = window(streams)
+ sel = SelectScratch(R, room, dev)
+ launched.clear()
+ if env is None:
+ os.environ.pop("TF_GLM_SEG_SELECT_FLOOR", None)
+ else:
+ os.environ["TF_GLM_SEG_SELECT_FLOOR"] = env
+ sparse.seg_select_tokens(qi, wts, pk, rows, sel)
+ torch.cuda.synchronize()
+ check(len(launched) == want, f"selection routing, {name}: _seg_select_floor launched {len(launched)} "
+ f"time(s) (want {want})")
+ sel = None
+ finally:
+ sparse._seg_select_floor = real
+ os.environ["TF_GLM_SEG_SELECT_FLOOR"] = "1"
+
+
+def timing():
+ arms = (("v1.10", 256, "0", "0"), ("grid 512", 512, "0", "0"), ("+ CUDA scoring", 512, "1", "0"),
+ ("+ one-pass selection", 512, "1", "1"))
+ for name, streams in (("4 x 8 @ 596k", [(596_000, 8)] * 4), ("4 x 4 @ 596k", [(596_000, 4)] * 4),
+ ("4 x 2 @ 596k", [(596_000, 2)] * 4), ("4 x 1 @ 596k", [(596_000, 1)] * 4),
+ ("1 x 16 @ 596k", [(596_000, 16)]), ("1 x 8 @ 596k", [(596_000, 8)]),
+ ("1 x 3 @ 596k", [(596_000, 3)]), ("1 x 16 @ 180k", [(180_000, 16)]),
+ ("2 x 8 @ 300k", [(300_000, 8)] * 2), ("4 x 8 @ 180k", [(180_000, 8)] * 4)):
+ qi, wts, pk, rows, R, _ = window(streams)
+ layers = [pk] + [keys(pk.shape[0]) for _ in range(10)]
+ sel = SelectScratch(R, POOL_ROWS, dev)
+ res = []
+ for _, grid, sc, fl in arms:
+ sparse.SEG_SCORE_GRID = grid
+ os.environ["TF_GLM_SEG_SCORES_CUDA"], os.environ["TF_GLM_SEG_SELECT_FLOOR"] = sc, fl
+ res.append(cold_us(lambda: [sparse.seg_select_tokens(qi, wts, lk, rows, sel) for lk in layers]))
+ sparse.SEG_SCORE_GRID = 512
+ print(f"TIME the indexer call, {name}, us a call: " + ", ".join(f"{a[0]} {t:.1f}" for a, t in zip(arms, res))
+ + f" ({100 * (res[-1] / res[0] - 1):+.1f}%; x11 layers a round {11e-3 * (res[0] - res[-1]):.2f} ms)",
+ flush=True)
+ sel = layers = None
+ torch.cuda.empty_cache()
+
+
+def main():
+ scoring()
+ selection()
+ loader = (sparse, "_seg_scores_ext")
+ os.environ["TF_GLM_SEG_SCORES_CUDA"] = "1"
+ check(construct(loader, "fp8") == 1, "Engine(FP8 caches, DSA layers): the scoring extension loaded at start")
+ check(construct(loader, "bf16") == 0, "Engine(bf16 caches): not loaded (the kernel is FP8 only)")
+ check(construct(loader, "fp8", ("mla",)) == 0, "Engine(no DSA layer): not loaded")
+ os.environ["TF_GLM_SEG_SCORES_CUDA"] = "0"
+ check(construct(loader, "fp8") == 0, "TF_GLM_SEG_SCORES_CUDA=0: not loaded")
+ # the extension not used (a failed build or load; another Triton release): logged once, Triton serves
+ import contextlib
+ import io
+
+ from tensorfold.cuda import build
+
+ qi, wts, pk, rows, R, _ = window([(300_000, 8), (450_001, 4)])
+ sel = SelectScratch(R, 500_000, dev)
+ ref = run(qi, wts, pk, rows, sel, False)
+ real_load, real_ptx, real_ext = build.load, sparse.TRITON_PTX, sparse._SEG_SCORES_EXT
+ for case, ptx, want_tries in (("a failed build", real_ptx, 1), ("another Triton release", "0.0", 0)):
+ tries, buf = [], io.StringIO()
+
+ def broken(*a, **k):
+ tries.append(1)
+ raise RuntimeError("Error building extension 'tensorfold_glm_segscores_v1': nvcc not found")
+
+ build.load, sparse.TRITON_PTX, sparse._SEG_SCORES_EXT, sparse._SEG_SCORES_FAILED = broken, ptx, None, None
+ raised = first = second = got = None
+ on = True
+ try:
+ with contextlib.redirect_stdout(buf):
+ first, second = sparse._seg_scores_ext(), sparse._seg_scores_ext()
+ on = sparse.seg_scores_cuda()
+ got = run(qi, wts, pk, rows, sel, True)
+ except Exception as exc:
+ raised = exc
+ finally:
+ build.load, sparse.TRITON_PTX, sparse._SEG_SCORES_EXT, sparse._SEG_SCORES_FAILED = (real_load, real_ptx,
+ real_ext, None)
+ logged = buf.getvalue().count("seg_scores.cu is not used")
+ check(raised is None and first is None and second is None and len(tries) == want_tries and not on
+ and logged == 1,
+ f"{case}: nothing raised ({raised!r}), logged once ({logged}), loader called {len(tries)} "
+ f"(want {want_tries}), the switch reads off ({not on})")
+ check(got is not None and same3(got, ref), f"{case}: the window gets the Triton scoring's bits")
+ os.environ["TF_GLM_SEG_SCORES_CUDA"] = "1"
+ if "--time" in sys.argv and fails == 0:
+ timing()
+ print("ALL PASS" if fails == 0 else f"{fails} FAIL", flush=True)
+ sys.exit(1 if fails else 0)
+
+
+if __name__ == "__main__":
+ with torch.no_grad():
+ main()