Skip to content

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

Python

Patch 0105: faster long prompts - a prompt chunk's DSA indexer scoring as a CUDA kernel with the Triton kernel's exact instruction sequence

BadAd84d41a3e2647fc
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 54a3f69..9c2f46e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -3,6 +3,18 @@
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 indexer scoring in CUDA** (patch `0105-glm-prompt-scores-cuda`, by [BadAd84](https://github.com/BadAd84)): `_scores`
+ (patch 0086's loop) converts and loads each 64-pool FP8 key tile again for every row. `prompt_scores.cu`
+ computes every score with the Triton kernel's own instruction sequence, read from its PTX (the mma K
+ order of Triton's kWidth-4 dot layout, the epilogue's roundings, the head sum's order), while a CTA of 8
+ rows converts each tile once: the same bits under Triton 3.7, whose PTX it reproduces. A 512-row block's
+ scores on one GB10: 0.61 / 1.85 / 4.85 / 10.07 -> 0.40 / 1.30 / 3.39 / 6.77 ms at 35k / 113k / 300k / 590k.
+ The extension is built when the engine starts, not at the first long prompt. Under another Triton release
+ (`sparse.TRITON_PTX`), or when the build fails, the Triton kernel serves and the start goes on (logged once).
+ `TF_GLM_SCORES_CUDA=0`: Triton. Applies after `0101`. GPU check: `tools/prompt_scores_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..3185f91 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.
+- `0105-glm-prompt-scores-cuda` (a prompt chunk's indexer scoring in CUDA, Triton's instruction order): 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..925c166 100644
--- a/README.md
+++ b/README.md
@@ -522,6 +522,7 @@ sets a value wins: the environment, then `scripts/local.sh`, then `.env`, then t
| `TF_ROCE_WAIT_S` | `300` | seconds a RoCE all-gather waits for the other Spark before it fails (1 to 3600; the patch's own default is 20, which a late peer on long prompts outlasted, issue #54); until the engine is built, each gather first meets the peer in an NCCL barrier, so a long first start (kernels compiling) does not run into it |
| `TF_GLM_MULTI_WINDOW` | `32`, `64` past 4 requests | with `PARALLEL` above 1, the rows of every request's verify window together in a round (16 to 64 in steps of 8): with more requests at once each one's drafts get fewer of them (8 requests' code: 141.2 / 160.3 / 167.0 tok/s at 32 / 48 / 64 rows); past 32 rows `TF_ROCE_MAX_KB` rises with it (64: 1024) unless you set it. Exact at any size |
| `TF_GLM_MULTI_LONE` | `0` | `1`: with `PARALLEL` above 1, a request decoding alone runs on the one-stream graphs (+0.6-0.9%), but its move to the pool's first rows evicts other conversations' kept prompts there (issues #12, #13); `0`: on the batched ones |
+| `TF_GLM_SCORES_CUDA` | `1` | patch 0105: a prompt chunk's FP8 indexer scoring from `prompt_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, which also serves (logged once) under another Triton release or when the build fails |
| `TF_GLM_CACHE_ENTRIES` | `32` | kept prompt states at most (TensorFold's default is 8); past this count a conversation's earlier (superseded) states go first, then the least recently used, however much of the pool is free (patch `0063`, @Alexbob0); shared-prefix states (a system block) go by recency only, so a new run of an agent still finds its system prompt (patch `0077`, issue #75, @meleesciony). An agent request keeps 1 to 3 (issue #17); each costs ~45 MiB at start, reserved out of the pool's `KV_POOL_GIB` budget (the pool shrinks by it, the estimate does not change), flat in the context length. Symptom of too few: `/health` `kept_prompts` stuck at the count while `pool_free_tokens` is large (issue #84, @jdecker76); see `TF_GLM_CACHE_SHARE_PCT` |
| `TF_GLM_CACHE_SHARE_PCT` | `0` (off) | make the kept-state count at least this share of the `KV_POOL_GIB` budget (patch `0097`, issue #84 by @jdecker76): on two Sparks at the defaults each state reserves ~91 MiB of a ~7.5 GiB budget, so 32 states already take ~38%: `50` gives ~42 states, the ceiling ~63 (each costs pool tokens), so the pool's tokens, not 32 finished one-shot conversations, decide when a live conversation goes. Any count is cut to three quarters of the budget (logged at start): past that the reservation would exceed the estimate. Set the same on every Spark |
| `TF_GLM_KEPT_BYTES_GIB` | `0` (no cap) | a byte budget for the kept states together (patch `0089`, by Thomas Wade, [ThomasWadeZ](https://github.com/ThomasWadeZ), PR #65): the device memory they own outside the pool (recurrent state, DFlash2 window copies: hundreds of MB each with long contexts); past it states are dropped in the entry cap's order (not written to the spill tier) and freed blocks go back to the driver. The author runs `4`; `kept_bytes` / `kept_bytes_cap` in `/health` |
@@ -627,6 +628,7 @@ applied with `patch -p0` in filename order); `start.sh` rebuilds or re-pulls the
| KV pool, kindling | `0087-glm-display-kv-dispram` | `0072`'s span with its reservation half from kindling spark-os's `dispramd` instead of a DRM dumb buffer, which kindling's `nvidia_drm` (no modeset) cannot make; the rest of `0072` runs unchanged (`DISPLAY_KV_BACKEND=dispram`) (by [BadAd84](https://github.com/BadAd84)) | 2032 MiB: +317,440 tokens at `PARALLEL=4` on three Sparks; the display check 53/53 |
| Prompt | `0001-glm-exl3-prompt-experts`, `0004-glm-prompt-kernels`, `0009-glm-prefill-kernels`, `0020-glm-prompt-experts-order`, `0024-glm-prompt-select-rows`, `0028-glm-lean-prompt-scratch` | EXL3 expert kernels that keep a prompt chunk's rows in L2, launched in a better order; each row's input rotated once; dense attention only where the sparse pass needs it; token selection in blocks of 512 rows; smaller prompt scratch | faster prefill, less memory at 1M |
| Prompt, indexer | `0086-glm-prompt-scores-loop` | a prompt chunk's indexer scoring (`0009`'s `_scores`) takes one row and 32 pool blocks a program (`SCORE_LOOP`), the row's queries loaded once, instead of 4 rows and one block (`TF_GLM_SCORE_RB`, retired), which reloaded every row's queries for each 64-pool block (by [BadAd84](https://github.com/BadAd84)) | the scoring 36% faster at long context (the part of a cold prefill that grows with it); cold prefill at 226k 138.3 -> 126.6 s; the same bits |
+| Prompt, indexer | `0105-glm-prompt-scores-cuda` | a prompt chunk's FP8 indexer scoring as a CUDA kernel (`prompt_scores.cu`) with the Triton kernel's own instruction sequence (its PTX under Triton 3.7, `sparse.TRITON_PTX`: the kWidth-4 K order, the epilogue's roundings, the head sum's order), one converted key tile shared by 8 rows; built at engine start (`TF_GLM_SCORES_CUDA`); under another Triton release, or when the build fails, the Triton kernel serves (by [BadAd84](https://github.com/BadAd84)) | a 512-row block's scores -30 to -33% (one GB10); the same bits (Triton 3.7) |
| Prompt, two Sparks | `0010-glm-hc-split`, `0033-glm-prefill-overlap2`, `0017-glm-overlap-priority`, `0022-glm-overlap-normal-priority`, `0064-glm-split-connect-early` | hyper-connection glue split by rows between the Sparks, exchanges overlapped with the next rows' work (`SPLIT`); the split's send/receive connection opened before the weights and the cache pool (issue #36) | 50k prefill ~1,270 -> ~1,730 tok/s with 0009 and 0020; decode rounds pay ~1.5% |
| Prompt, KDA | `0012-glm-kda-chunked`, `0014-glm-kda-chunked-gb10`, `0039-glm-kda-chunked-kernel` | the linear-attention layers' prompt chunks in chunked (WY) form, one CUDA kernel (`KDA_CHUNKED`) | 50k prefill 29.3 -> 26.4 s, 149k 91.1 -> 84.5 s (one start each) |
| Prompt reuse | `0008-glm-prompt-grid`, `0015-glm-shared-prefix`, `0042-glm-prompt-replay`, `0054-glm-image-prompt-reuse`, `0060-glm-keep-thinking`, `0063-glm-kept-cap-superseded-first`, `0071-glm-shared-prefix-copy`, `0077-glm-kept-cap-shared-by-recency`, `0078-glm-take-over-decide-then-copy` | prompt chunks and kept states on a token grid; a shared system prompt's state reused (copied out of the conversation that wrote it, which keeps its own state, by ezoushen, #43); an identical prompt resumes from its kept end state; prompts with pictures resume too, their kept states told apart by each picture's content (by abhicnv007, issue #11); earlier turns' reasoning kept in the prompt (`TF_GLM_CLEAR_THINKING`, by kky42, #23); past the kept-state cap a conversation's superseded states go first (by Alexbob0, #32), and shared-prefix states by recency only, so a new agent run still finds its system prompt (diagnosed and the fix proposed by meleesciony, #75); a fresh conversation after a long one clones only the kept states that stay, not every one first (reserved +14.8 -> +1.4 GiB after 256k, 21 turns; upstream #421) | [Performance](#performance) |
@@ -711,6 +713,7 @@ with [sparkDash](https://github.com/MiaAI-Lab/sparkDash) ([Performance](#perform
| `tools/needle.py [label] [size]` | hides a passphrase in a ~195k-token prompt (the prompt comes out at ~0.8 x `size` tokens) and checks the model returns it |
| `tools/toolcheck.py` | makes a tool call with an array parameter and checks it comes back as a JSON array |
| `tools/display_kv_check.py [--gpu]` | patch 0072's checks, run in the image (`docker run ... --entrypoint python`, see the file): the setting, the span's mapping and unwinding through a fake driver, the carved planes and the pool's copies; with `--gpu`, the real span on a Spark whose display reservation is free |
+| `tools/prompt_scores_check.py [--time]` | patch 0105's checks: `prompt_scores.cu` against `_scores` bit for bit (35k-590k, arbitrary scales), a float64 oracle, `_select_prompt` both ways, the build at engine start, and the Triton kernel 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. Re-run it before raising `sparse.TRITON_PTX` for a new Triton release |
| `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/0105-glm-prompt-scores-cuda.patch b/patches/0105-glm-prompt-scores-cuda.patch
new file mode 100644
index 0000000..b6bbcc1
--- /dev/null
+++ b/patches/0105-glm-prompt-scores-cuda.patch
@@ -0,0 +1,344 @@
+# A prompt chunk's DSA indexer scoring (sparse._scores, patch 0086's Triton loop) as a CUDA kernel (prompt_scores.cu)
+# that computes every score with the Triton kernel's own instruction sequence, read from its PTX: the mma K order of
+# Triton's kWidth-4 dot layout, the epilogue's roundings, the head sum's order. A CTA of 8 rows converts each 64-pool
+# FP8 key tile once for all of them. Every score is the Triton kernel's bit for bit. FP8 caches with 32 indexer heads of
+# 128 only (the indexer is replicated: TP=2 and TP=3 alike). The extension (tensorfold_glm_scores_v1) is built / loaded
+# by decode.Engine's constructor, before any request; loaded lazily, a fresh image built it at its first long prompt
+# while every stream waited. TF_GLM_SCORES_CUDA=0: the Triton kernel, which also serves (logged once) under another
+# Triton release than the one whose PTX the kernel reproduces (sparse.TRITON_PTX, 3.7) and when the extension fails to
+# build or load. Applies after patch 0101 (both edit _select_prompt). tools/prompt_scores_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
+@@ -194,6 +194,14 @@ class Engine:
+ self.caches = Caches(w, pool_rows or capacity, streams=streams,
+ ring=index_ring(pool_rows or capacity, max(max_rows, prefill_rows)),
+ kv=kv8.kv_kind() if kv is None else kv, display=display)
++ # patch 0105: the prompt chunks' CUDA pool scoring (sparse._scores_ext) built / loaded now, before any
++ # request: loaded lazily, a fresh image built it at the first long prompt's chunk while every stream waited
++ # (~23 s)
++ if (kv8.kv_kind() if kv is None else kv) == "fp8" and any(l.kind == "dsa" for l in w.layers):
++ from . import sparse
++
++ if sparse.prompt_scores_cuda():
++ sparse._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/prompt_scores.cu tensorfold/families/glm5_next/cuda/prompt_scores.cu
+new file mode 100644
+--- /dev/null
++++ tensorfold/families/glm5_next/cuda/prompt_scores.cu
+@@ -0,0 +1,233 @@
++// Patch 0105: the DSA indexer's prompt-chunk scoring (sparse._scores, patch 0086's Triton kernel, as _select_prompt
++// 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, so every bit is the same, while a CTA of RB rows converts each
++// key tile once for all of them (Triton: every row converts and loads it again). tools/prompt_scores_check.py.
++//
++// The Triton kernel, read from its PTX / GPU IR on a GB10 (Triton 3.7):
++// - the keys' e4m3 codes -> f16x2 (cvt.rn.f16x2.e4m3x2) -> bf16 (exact: every e4m3 value is a bf16 value); keys
++// past the row's visible pools load as 0 (their scores are -inf whatever the dot);
++// - dots[32 heads, 64 pools] = mma.sync m16n8k16 bf16 -> fp32, each output one chain over the 8 k16 steps in
++// ascending order from +0, both operands in the kWidth = 4 dot layout, which spreads a lane's 4 consecutive k
++// values over two steps: k = 32 b + 16 u + 4 t + 2 h + e (lane t, e < 2) is step 2 b + h, mma slot 8 u + 2 t + e
++// (the A operand's ld.shared.v2 {a0 of step 2b, a0 of step 2b + 1}; the B operand's linear layout: registers
++// k + 1, + 2, + 16, lanes k + 4, + 8), so a step's 16 products are not a contiguous k16 group: the natural k16
++// grouping gives other bits (measured: ~13% of the scores differ);
++// - per element (dots * ks[pool]) * scale, then max(., 0);
++// - the head sum: per pool column a lane (g = lane / 4, t = lane % 4) holds heads g, g + 8, 16 + g, 24 + g, summed
++// as fma(w24, x24, fma(w16, x16, fma(w0, x0, w8 * x8))) with w_h = float(W[h]) * wscale, then over the lanes of
++// one t: s += shfl_xor(s, 16), then 8, then 4;
++// - pools past the row's visible ones -> -inf; a block past all of them -> -inf without dots.
++// Every operation below is that one in that order (explicit _rn intrinsics: no contraction or reassociation) and
++// each mma takes the same operands in the same slots. Only the grouping of the work changes: warp w of a CTA is row
++// RB * blockIdx.x + w (its queries in registers), the CTA converts each 64-pool key tile once into shared memory
++// for its RB rows (the next tile's codes read during this tile's dots), LB tiles in turn.
++
++#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, LB = 16; // rows a CTA (one a warp), tiles a CTA (measured on a GB10)
++
++__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); }
++
++// One 64-pool key tile in two halves, so the next tile's global reads run under this tile's dots: ``fetch`` reads a
++// thread's share (GPT 16-byte k16 groups of pool i) and the pool's fp32 scale into registers; ``put`` converts them
++// to bf16 into tile[p][chunk] in mma slot order (logical chunk 2 s + c: step s's slots 8 c .. 8 c + 7) and the
++// scale into ks[p] (1 where p >= NP: never read).
++struct Fetch {
++ static constexpr int T = RB * 32, TPP = T / BP, GPT = KS / TPP; // threads a pool, k16 groups a thread
++ uint4 c[GPT];
++ float s;
++};
++
++__device__ __forceinline__ void fetch(const uint8_t* __restrict__ PK, int RS, int NP, int pb, Fetch& f) {
++ const int tid = threadIdx.x, i = tid / Fetch::TPP, part = tid % Fetch::TPP;
++ const int p = pb * BP + i;
++ const bool ok = p < NP;
++ const uint8_t* row = PK + (size_t)(ok ? p : 0) * RS;
++#pragma unroll
++ for (int gg = 0; gg < Fetch::GPT; ++gg)
++ f.c[gg] = ok ? *reinterpret_cast<const uint4*>(row + 16 * (part * Fetch::GPT + gg)) : make_uint4(0, 0, 0, 0);
++ f.s = ok && part == 0 ? *reinterpret_cast<const float*>(row + D) : 1.0f;
++}
++
++__device__ __forceinline__ void put(const Fetch& f, uint4* tile, float* ks) {
++ const int tid = threadIdx.x, i = tid / Fetch::TPP, part = tid % Fetch::TPP;
++#pragma unroll
++ for (int gg = 0; gg < Fetch::GPT; ++gg) {
++ const int j = part * Fetch::GPT + gg; // k16 group: k = 16 j .. 16 j + 15
++ const uint32_t in[4] = {f.c[gg].x, f.c[gg].y, f.c[gg].z, f.c[gg].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] = f.s;
++}
++
++__global__ void __launch_bounds__(RB * 32) 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, const void* __restrict__ POS,
++ bool pos64, int R, int NP, float scale, float wscale) {
++ __shared__ __align__(16) uint4 tile[BP * CH]; // 16 KB: one key tile, bf16
++ __shared__ float ks[BP];
++ __shared__ __align__(16) float stage[RB][BP]; // a warp's 64 scores before the row's store
++ const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31, g = lane >> 2, t = lane & 3;
++ const int r = blockIdx.x * RB + warp;
++ const bool live = r < R;
++ const long long P = pos64 ? *static_cast<const int64_t*>(POS) : *static_cast<const int32_t*>(POS);
++ const int npool = live ? (int)((P + r + 1) / 4) : 0;
++ const int rlast = min(R, (int)(blockIdx.x + 1) * RB) - 1;
++ const int nmax = (int)((P + rlast + 1) / 4); // the CTA's largest visible pool count
++ const int nblk = NP / BP;
++
++ // this warp's row: query fragments of both m16 tiles for the 8 k16 steps (a0 / a1: k = 32 b + 4 t + 2 h, + 1;
++ // a2 / a3: 16 more; step s = 2 b + h), and the 4 head weights a lane sums
++ uint32_t qa[2][KS][4];
++ float wh[4];
++ {
++ const int rr = live ? r : 0;
++#pragma unroll
++ for (int mt = 0; mt < 2; ++mt)
++#pragma unroll
++ for (int s = 0; s < KS; ++s) {
++ const __nv_bfloat16* q0 = QI + ((size_t)rr * H + 16 * mt + g) * D;
++ const __nv_bfloat16* q1 = q0 + 8 * D;
++ const int k = 32 * (s >> 1) + 4 * t + 2 * (s & 1);
++ qa[mt][s][0] = *reinterpret_cast<const uint32_t*>(q0 + k);
++ qa[mt][s][1] = *reinterpret_cast<const uint32_t*>(q1 + k);
++ qa[mt][s][2] = *reinterpret_cast<const uint32_t*>(q0 + k + 16);
++ qa[mt][s][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)rr * w_stride + hs[x]]), wscale);
++ }
++
++ Fetch f;
++ bool any_next = (int)blockIdx.y * LB < nblk && (int)blockIdx.y * LB * BP < nmax;
++ if (any_next) fetch(PK, RS, NP, blockIdx.y * LB, f);
++ for (int jb = 0; jb < LB; ++jb) {
++ const int pb = blockIdx.y * LB + jb;
++ if (pb >= nblk) break;
++ const int p0 = pb * BP;
++ const bool any = any_next; // some row of the CTA sees pools of this block
++ if (any) {
++ __syncthreads(); // the previous tile is read
++ put(f, tile, ks);
++ __syncthreads();
++ }
++ any_next = jb + 1 < LB && pb + 1 < nblk && p0 + BP < nmax;
++ if (any_next) fetch(PK, RS, NP, pb + 1, f); // in flight during this tile's dots
++ if (!live) continue;
++ float* st = stage[warp];
++ if (p0 >= npool) { // the row sees none of them: -inf, no dots
++ st[2 * lane] = -INFINITY;
++ st[2 * lane + 1] = -INFINITY;
++ } else {
++#pragma unroll 2
++ for (int n = 0; n < 8; ++n) { // 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 s[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));
++ s[e] = p0 + pc + e < npool ? v : -INFINITY;
++ }
++ if (g == 0) *reinterpret_cast<float2*>(&st[pc]) = make_float2(s[0], s[1]);
++ }
++ }
++ __syncwarp();
++ *reinterpret_cast<float2*>(OUT + (size_t)r * NP + p0 + 2 * lane) = *reinterpret_cast<const float2*>(&st[2 * lane]);
++ __syncwarp();
++ }
++}
++
++} // namespace
++
++// OUT [R, NP] fp32 = the rows' pool scores, sparse._scores' outputs bit for bit: QI [R, 32 * 128] bf16 rows, W bf16
++// head weights (row stride w_stride, unit column stride), PK an FP8 pooled-key cache (rows of 128 e4m3 codes, then
++// the row's fp32 scale; RS bytes apart), POS [1] int32 or int64 (row r's position is POS + r), NP a multiple of 64.
++void scores(const at::Tensor& QI, const at::Tensor& W, int64_t w_stride, const at::Tensor& PK, int64_t RS,
++ at::Tensor OUT, const at::Tensor& POS, int64_t R, int64_t NP, double scale, double wscale) {
++ TORCH_CHECK(QI.is_cuda() && QI.scalar_type() == at::kBFloat16 && W.scalar_type() == at::kBFloat16 &&
++ OUT.scalar_type() == at::kFloat && PK.element_size() == 1 &&
++ (POS.scalar_type() == at::kInt || POS.scalar_type() == at::kLong), "prompt scores: dtypes");
++ TORCH_CHECK(QI.is_contiguous() && QI.size(-1) == H * D && QI.size(0) >= R && W.stride(-1) == 1 &&
++ OUT.is_contiguous() && OUT.numel() >= R * NP, "prompt scores: shapes");
++ TORCH_CHECK(RS % 16 == 0 && RS >= D + 4 && PK.is_contiguous(), "prompt scores: an FP8 key cache of 16-byte rows");
++ TORCH_CHECK(NP % BP == 0 && NP <= PK.numel() / RS, "prompt scores: NP a multiple of 64 within the cache");
++ if (R <= 0 || NP <= 0) return;
++ const c10::cuda::CUDAGuard guard(QI.device());
++ const int nblk = (int)(NP / BP);
++ scores_kernel<<<dim3((unsigned)((R + RB - 1) / RB), (unsigned)((nblk + LB - 1) / LB)), RB * 32, 0,
++ at::cuda::getCurrentCUDAStream()>>>(
++ reinterpret_cast<const __nv_bfloat16*>(QI.data_ptr()), reinterpret_cast<const __nv_bfloat16*>(W.data_ptr()),
++ (int)w_stride, reinterpret_cast<const uint8_t*>(PK.data_ptr()), (int)RS, OUT.data_ptr<float>(), POS.data_ptr(),
++ POS.scalar_type() == at::kLong, (int)R, (int)NP, (float)scale, (float)wscale);
++ C10_CUDA_KERNEL_LAUNCH_CHECK();
++}
++
++PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("scores", &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
+@@ -132,6 +132,54 @@ def _scores(QI, W, w_stride, PK, PKS, OUT, POS, R, NP, scale, wscale, H: tl.cons
+ SCORE_LOOP = 32 # pool blocks a _scores program takes (speed only; GB10: 32 >= 16 > 8 > 4)
+
+
++TRITON_PTX = "3.7" # the Triton release whose PTX the CUDA ports reproduce (their bits are its kernels')
++
++
++def triton_matches_ptx() -> bool:
++ """Whether the installed Triton is the release the CUDA ports were read from (TRITON_PTX). Another release may
++ order a kernel's arithmetic differently, and a port would then no longer give its Triton kernel's bits, so the
++ ports are not used with it (logged once; the Triton kernels serve)."""
++ return ".".join(triton.__version__.split(".")[:2]) == TRITON_PTX
++
++
++def prompt_scores_cuda() -> bool:
++ """TF_GLM_SCORES_CUDA (default on): a prompt chunk's FP8 pool scores from prompt_scores.cu, which
++ computes every score with _scores' own instruction sequence (its PTX under Triton TRITON_PTX: the mma K order of
++ Triton's kWidth-4 dot layout, the epilogue's roundings, the head sum's order), so the same bits, with one
++ converted key tile shared by a CTA's 8 rows; 0: _scores (Triton). Off as well when the extension is not used
++ (another Triton release, or a failed build or load: ``_scores_ext``). tools/prompt_scores_check.py."""
++ import os
++
++ return os.environ.get("TF_GLM_SCORES_CUDA", "1") != "0" and _SCORES_FAILED is None
++
++
++_SCORES_EXT = None
++_SCORES_FAILED = None # why prompt_scores.cu is not used (then _scores serves)
++
++
++def _scores_ext():
++ """The extension, built / loaded once; None when it is not used: under another Triton release than TRITON_PTX,
++ or when its build or load failed (no compiler, a toolkit the kernel does not compile with). Neither stops the
++ start: it is logged once and the Triton kernel serves."""
++ global _SCORES_EXT, _SCORES_FAILED
++ if _SCORES_EXT is None and _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")
++ _SCORES_EXT = load(name="tensorfold_glm_scores_v1",
++ sources=[str(Path(__file__).parent / "prompt_scores.cu")],
++ extra_cuda_cflags=["-O3"], verbose=False)
++ except Exception as exc:
++ _SCORES_FAILED = f"{type(exc).__name__}: {(str(exc).strip().splitlines() or [''])[-1][:200]}"
++ print(f"[tensorfold] prompt_scores.cu is not used ({_SCORES_FAILED}); prompt chunks score with the "
++ "Triton kernel", flush=True)
++ return _SCORES_EXT
++
++
+ @triton.jit
+ def _scores_rows(QI, W, w_stride, PK, PKS, OUT, o_stride, POS, SPR, BASE, R, NP, scale, wscale, H: tl.constexpr,
+ HP: tl.constexpr, D: tl.constexpr, BP: tl.constexpr, G: tl.constexpr, SEG: tl.constexpr,
+@@ -493,10 +541,15 @@ def _select_prompt(qi: torch.Tensor, wts: torch.Tensor, pk: torch.Tensor, pos: i
+ n = min(B, R - a)
+ at = pos_dev if a == 0 else pos_dev + a
+ scores = buf[:n * NP].view(n, NP)
+- _scores[(n, triton.cdiv(triton.cdiv(NP, 64), SCORE_LOOP))](qi[a:a + n], wts[a:a + n], wts.stride(0), pkv, pks,
+- scores, at, n, NP, D ** -0.5, wscale, H=H,
+- HP=max(16, triton.next_power_of_2(H)), D=D, BP=64,
+- L=SCORE_LOOP, RS=rs, FP8=fp8, num_warps=4)
++ ext = _scores_ext() if fp8 and H == 32 and D == 128 and NP % 64 == 0 and prompt_scores_cuda() else None
++ if ext is not None:
++ ext.scores(qi[a:a + n], wts[a:a + n], wts.stride(0), pk, rs, scores, at, n, NP, D ** -0.5, wscale)
++ else:
++ _scores[(n, triton.cdiv(triton.cdiv(NP, 64), SCORE_LOOP))](qi[a:a + n], wts[a:a + n], wts.stride(0), pkv,
++ pks, scores, at, n, NP, D ** -0.5, wscale, H=H,
++ HP=max(16, triton.next_power_of_2(H)), D=D,
++ BP=64, L=SCORE_LOOP, RS=rs, FP8=fp8,
++ num_warps=4)
+ pools = 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)
diff --git a/tools/prompt_scores_check.py b/tools/prompt_scores_check.py
new file mode 100644
index 0000000..d69d54a
--- /dev/null
+++ b/tools/prompt_scores_check.py
@@ -0,0 +1,248 @@
+#!/usr/bin/env python3
+"""tools/prompt_scores_check.py [--time]: patch 0105 - a prompt chunk's DSA indexer scoring (sparse._scores, Triton)
+as a CUDA kernel (prompt_scores.cu) that computes every score with the Triton kernel's own instruction sequence. Run in
+the image built with patch 0105, on one GPU:
+docker run --rm --gpus all --entrypoint python -v "$PWD/tools/prompt_scores_check.py:/c.py" <image> /c.py
+
+1. Kernel: prompt_scores.cu's whole [R, NP] output (pre-filled with NaN) equals the Triton kernel's (sparse._scores,
+ unchanged by the patch) bit for bit: 512-row blocks and a 333-row tail at row positions 2,050 / 35k / 113k / 300k /
+ 590k, int32 and int64 positions, FP8 pooled keys from kv8.quantize_rows, head weights a strided view of the
+ index-key rows (as forward lays them out); also arbitrary (not power-of-two) pool scales, which pin the epilogue's
+ product order.
+2. Oracle: against float64 scores from the dequantized keys (sum_h w_h relu(scale ks_p q_h . k_p)), finite entries
+ within fp32 tolerance, -inf exactly where the pool is past the row's position.
+3. The entry point: sparse._select_prompt over a 2,048-row chunk at 113k (four 512-row blocks) gives the same tokens
+ and counts with TF_GLM_SCORES_CUDA=1 (the CUDA kernel, counted: 4 launches) and =0 (Triton, none).
+4. Start-up: decode.Engine's constructor loads (and on a fresh image, builds) the extension, before any request, for
+ FP8 caches with DSA layers and the switch on; not with TF_GLM_SCORES_CUDA=0, a bf16 cache or no DSA layer (the
+ constructor run with stand-ins for the buffers, caches, slots and state it builds; the loader counted).
+5. The extension not used - a failed build or load (the loader raising), or another Triton release than
+ sparse.TRITON_PTX (the loader then never called): nothing raised, logged once and not retried, the switch reads off,
+ and sparse._select_prompt gives the Triton kernel's 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: a 512-row block's scores, Triton -> CUDA, at 35k, 113k, 300k and 590k (CUDA events; the indexer is
+replicated, so its shapes are the same at TP=2 and TP=3)."""
+import os
+import sys
+from types import SimpleNamespace
+
+import torch
+import triton
+
+from tensorfold.families.glm5_next.cuda import decode, forward, hcsplit, kv8, sparse
+
+H, D, KEY = 32, 128, 128
+CAP = 1_048_576
+WSCALE = 1.0 / 5.656854249492381
+fails = 0
+
+
+def check(ok, msg):
+ global fails
+ print(("PASS " if ok else "FAIL ") + msg, flush=True)
+ fails += not ok
+
+
+def ms(fn, n=10):
+ fn()
+ torch.cuda.synchronize()
+ a, b = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
+ a.record()
+ for _ in range(n):
+ fn()
+ b.record()
+ torch.cuda.synchronize()
+ return a.elapsed_time(b) / n
+
+
+class Count:
+ """sparse's CUDA extension, its ``scores`` calls counted."""
+
+ def __init__(self, ext):
+ self.ext, self.calls = ext, 0
+
+ def scores(self, *a):
+ self.calls += 1
+ return self.ext.scores(*a)
+
+
+def oracle(qi, wts, pk, P, R, NP):
+ codes = pk[:NP, :KEY].contiguous().view(torch.float8_e4m3fn).double() # [NP, 128] key values
+ ks = pk[:NP, KEY:KEY + 4].contiguous().view(torch.float32).double()[:, 0] # [NP] scales
+ q = qi.view(R, H, D).double()
+ w = wts.float().double() * float(torch.tensor(WSCALE, dtype=torch.float32))
+ dots = torch.einsum("rhd,pd->rhp", q, codes) * ks[None, None, :] * float(torch.tensor(D ** -0.5))
+ s = (w[:, :, None] * dots.clamp(min=0)).sum(1) # [R, NP]
+ vis = torch.arange(NP, device=qi.device)[None, :] < ((P + torch.arange(R, device=qi.device) + 1) // 4)[:, None]
+ return s, vis
+
+
+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 main():
+ check(hasattr(sparse, "prompt_scores_cuda") and hasattr(sparse, "_scores_ext"),
+ "patch 0105 applied: sparse.prompt_scores_cuda")
+ if fails:
+ print("1 FAIL", flush=True)
+ sys.exit(1)
+ dev = torch.device("cuda")
+ torch.manual_seed(84)
+ pk = kv8.quantize_rows(torch.randn(CAP // sparse.POOL + 2, KEY, device=dev))
+ pkv, pks, rs, fp8 = kv8.parts(pk)
+ ext = sparse._scores_ext()
+ timing = "--time" in sys.argv
+ for P in (2_050, 35_000, 113_000, 300_000, 590_000):
+ for R in (512, 333):
+ NP = sparse.pool_count(P, R, pk.shape[0] - 2)
+ 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 = torch.tensor([P], device=dev, dtype=torch.int32 if R == 512 else torch.int64)
+ ref = torch.full((R, NP), float("nan"), device=dev)
+ out = torch.full((R, NP), float("nan"), device=dev)
+
+ def tri():
+ sparse._scores[(R, triton.cdiv(triton.cdiv(NP, 64), sparse.SCORE_LOOP))](
+ qi, wts, wts.stride(0), pkv, pks, ref, pos, R, NP, D ** -0.5, WSCALE, H=H, HP=32, D=D, BP=64,
+ L=sparse.SCORE_LOOP, RS=rs, FP8=fp8, num_warps=4)
+
+ def cud():
+ ext.scores(qi, wts, wts.stride(0), pk, rs, out, pos, R, NP, D ** -0.5, WSCALE)
+
+ tri()
+ cud()
+ torch.cuda.synchronize()
+ diff = int((out.view(torch.int32) != ref.view(torch.int32)).sum())
+ check(diff == 0, f"P {P} rows {R} NP {NP} ({pos.dtype}): CUDA scores == Triton's bit for bit ({diff} of "
+ f"{R * NP} differ)")
+ if P <= 35_000 and R == 333:
+ s, vis = oracle(qi, wts, pk, P, R, NP)
+ fin = torch.isfinite(out)
+ err = torch.where(vis, (out.double() - s).abs(), torch.zeros_like(s)).max() / s.abs().max()
+ check(bool(torch.equal(fin, vis)) and err.item() < 1e-5,
+ f"P {P} rows {R}: -inf exactly past each row's pools, max error {err.item():.2e} of max")
+ if timing and R == 512 and P >= 35_000:
+ t0, t1 = ms(tri), ms(cud)
+ print(f"TIME a 512-row block's scores at {P} ({NP} pools): Triton {t0:.3f} -> CUDA {t1:.3f} ms "
+ f"({100 * (t1 / t0 - 1):+.1f}%)", flush=True)
+ # arbitrary (not power-of-two) pool scales: kv8's are powers of two, which makes the scale's place in the product
+ # chain exact either way; arbitrary ones pin Triton's order, (dot * ks) * scale
+ pk2 = pk.clone()
+ pk2[:, KEY:KEY + 4].view(torch.float32)[:, 0] = torch.rand(pk2.shape[0], device=dev) * 3 + 0.1
+ p2v, p2s, _, _ = kv8.parts(pk2)
+ P, R = 35_000, 512
+ NP = sparse.pool_count(P, R, pk2.shape[0] - 2)
+ 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 = torch.tensor([P], device=dev, dtype=torch.int32)
+ ref = torch.full((R, NP), float("nan"), device=dev)
+ out = torch.full((R, NP), float("nan"), device=dev)
+ sparse._scores[(R, triton.cdiv(triton.cdiv(NP, 64), sparse.SCORE_LOOP))](
+ qi, wts, wts.stride(0), p2v, p2s, ref, pos, R, NP, D ** -0.5, WSCALE, H=H, HP=32, D=D, BP=64,
+ L=sparse.SCORE_LOOP, RS=rs, FP8=fp8, num_warps=4)
+ ext.scores(qi, wts, wts.stride(0), pk2, rs, out, pos, R, NP, D ** -0.5, WSCALE)
+ torch.cuda.synchronize()
+ diff = int((out.view(torch.int32) != ref.view(torch.int32)).sum())
+ check(diff == 0, f"arbitrary pool scales, P {P} rows {R}: CUDA == Triton bit for bit ({diff} of {R * NP} differ)")
+ # the entry point, both ways
+ P, R = 113_000, 2048
+ qi = torch.randn(R, H * D, device=dev, dtype=torch.bfloat16)
+ ikr = torch.randn(R, KEY + H, device=dev, dtype=torch.bfloat16)
+ pos_dev = torch.tensor([P], device=dev, dtype=torch.int32)
+ got = {}
+ for flag in ("1", "0"):
+ os.environ["TF_GLM_SCORES_CUDA"] = flag
+ counter = Count(ext)
+ sparse._SCORES_EXT = counter
+ try:
+ tok, cnt = sparse._select_prompt(qi, ikr[:, KEY:], pk, P, R, pk.shape[0] - 2, pos_dev)
+ torch.cuda.synchronize()
+ finally:
+ sparse._SCORES_EXT = ext
+ got[flag] = (tok.clone(), cnt.clone(), counter.calls)
+ same = torch.equal(got["1"][0], got["0"][0]) and torch.equal(got["1"][1], got["0"][1])
+ check(same and got["1"][2] == 4 and got["0"][2] == 0,
+ f"_select_prompt 2,048 rows at 113k: tokens and counts equal CUDA vs Triton ({same}), CUDA launches "
+ f"{got['1'][2]} (want 4) / {got['0'][2]} (want 0)")
+ os.environ.pop("TF_GLM_SCORES_CUDA", None)
+ check(sparse.prompt_scores_cuda(), "TF_GLM_SCORES_CUDA unset: on")
+ # start-up
+ loader = (sparse, "_scores_ext")
+ os.environ["TF_GLM_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_SCORES_CUDA"] = "0"
+ check(construct(loader, "fp8") == 0, "TF_GLM_SCORES_CUDA=0: not loaded")
+ # the extension not used (a failed build or load; another Triton release): the start goes on, logged once, and
+ # the Triton kernel serves with the same tokens
+ import contextlib
+ import io
+
+ from tensorfold.cuda import build
+
+ os.environ["TF_GLM_SCORES_CUDA"] = "1"
+ real_load, real_ptx = build.load, sparse.TRITON_PTX
+ check(sparse.triton_matches_ptx(), f"this image's Triton {triton.__version__} is TRITON_PTX {sparse.TRITON_PTX}")
+ sparse.TRITON_PTX = triton.__version__.split(".")[0] + ".99"
+ check(not sparse.triton_matches_ptx(), f"another minor release ({sparse.TRITON_PTX}) is not this Triton's")
+ sparse.TRITON_PTX = real_ptx
+ for case, ptx, want_tries in (("a failed build", real_ptx, 1), ("another Triton release", "0.0", 0)):
+ tries, out = [], io.StringIO()
+
+ def broken(*a, **k):
+ tries.append(1)
+ raise RuntimeError("Error building extension 'tensorfold_glm_scores_v1': nvcc not found")
+
+ build.load, sparse.TRITON_PTX, sparse._SCORES_EXT, sparse._SCORES_FAILED = broken, ptx, None, None
+ raised = first = second = tok = cnt = None
+ on = True
+ try:
+ with contextlib.redirect_stdout(out):
+ first, second = sparse._scores_ext(), sparse._scores_ext()
+ on = sparse.prompt_scores_cuda()
+ tok, cnt = sparse._select_prompt(qi, ikr[:, KEY:], pk, P, R, pk.shape[0] - 2, pos_dev)
+ torch.cuda.synchronize()
+ except Exception as exc:
+ raised = exc
+ finally:
+ build.load, sparse.TRITON_PTX, sparse._SCORES_EXT, sparse._SCORES_FAILED = real_load, real_ptx, ext, None
+ logged = out.getvalue().count("prompt_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(tok is not None and torch.equal(tok, got["0"][0]) and torch.equal(cnt, got["0"][1]),
+ f"{case}: _select_prompt gives the Triton kernel's tokens and counts")
+ print("ALL PASS" if fails == 0 else f"{fails} FAIL", flush=True)
+ sys.exit(1 if fails else 0)
+
+
+if __name__ == "__main__":
+ main()