Skip to content

Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.

C++

QSA select: block scores on tensor cores, top-k keys in registers (+14.6% prompt at 128K)

Niko12212f9c38f0fe55
diff --git a/include/strata/kernels/qsa_select.hpp b/include/strata/kernels/qsa_select.hpp
index 962c76916..e31d3f3bc 100644
--- a/include/strata/kernels/qsa_select.hpp
+++ b/include/strata/kernels/qsa_select.hpp
@@ -28,8 +28,16 @@ void qsa_block_scores(const float* pooled, const float* dead, const float* q_idx
int64_t active_blocks = -1); ///< perf-review C-1: > 0 launches only this many blocks (the
///< batch's largest n_bid + 1; not for a captured graph)
+/// The same scores on tensor cores (3xTF32, FP32-level accuracy but another summation order: not bitwise; the tail
+/// block n_bid is the warp kernel's arithmetic). For the prompt path; false (nothing launched) on another geometry.
+bool qsa_block_scores_tc(const float* pooled, const float* dead, const float* q_idx, const int32_t* steps, int64_t nq,
+ int64_t max_blocks, const QsaShapes& s, float* scores, void* stream, int64_t active_blocks);
+
/// ids [nq, cap] (cells, ascending); `cap` >= the largest selection width.
void qsa_block_topk(const float* scores, const int32_t* steps, int64_t nq, int64_t max_blocks, int64_t cap,
const QsaShapes& s, int32_t* ids, void* stream);
+/// The original kernel (keys read from memory on every radix pass), for tests: the same ids.
+void qsa_block_topk_ref(const float* scores, const int32_t* steps, int64_t nq, int64_t max_blocks, int64_t cap,
+ const QsaShapes& s, int32_t* ids, void* stream);
} // namespace strata::kernels
diff --git a/src/kernels/cuda/qsa_select.cu b/src/kernels/cuda/qsa_select.cu
index 468d21e71..10eed5587 100644
--- a/src/kernels/cuda/qsa_select.cu
+++ b/src/kernels/cuda/qsa_select.cu
@@ -148,6 +148,285 @@ __global__ void __launch_bounds__(TOPK_T) block_topk_kernel(const float* __restr
}
}
+
+// ---- QSA select on tensor cores (perf-review, after D-1): the block scores of many queries are one GEMM,
+// rows (query, indexer head) x columns (blocks), K = 128, with relu per head summed. 3xTF32 (each operand split
+// into a TF32 hi and lo part, hi*hi + hi*lo + lo*hi) keeps FP32-level accuracy; the summation order differs from
+// the warp kernel, so a score can move in its last bits and a near-tie can select differently (not bitwise).
+// Blocks < n_bid only; the tail block n_bid (the `dead` key, +1e9) is scored by the warp kernel's own code.
+constexpr int TC_QT = 16; // queries per CTA (one m16 tile per indexer head)
+constexpr int TC_NB = 32; // blocks per tile (4 warps x n8)
+constexpr int TC_ITER = 4; // tiles per CTA (the query tile is loaded once)
+constexpr int TC_QS = IDX_HEADS * IDX_DIM + 4; // query row stride in floats
+constexpr int TC_KS = IDX_DIM + 4; // key row stride
+
+// TF32 conversion and MMA need sm_80: below it they compile to a trap and qsa_block_scores_tc refuses the device
+#if !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 800
+#define STRATA_SEL_SM80 1
+#else
+#define STRATA_SEL_SM80 0
+#endif
+__device__ __forceinline__ uint32_t tf32_hi(float x) {
+#if STRATA_SEL_SM80
+ uint32_t r;
+ asm("cvt.rna.tf32.f32 %0, %1;" : "=r"(r) : "f"(x));
+ return r;
+#else
+ return __float_as_uint(x);
+#endif
+}
+__device__ __forceinline__ void mma_tf32(float* c, const uint32_t* a, const uint32_t* b) {
+#if !STRATA_SEL_SM80
+ __trap();
+#else
+ asm volatile("mma.sync.aligned.m16n8k8.row.col.f32.tf32.tf32.f32 {%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, "
+ "{%0,%1,%2,%3};\n"
+ : "+f"(c[0]), "+f"(c[1]), "+f"(c[2]), "+f"(c[3])
+ : "r"(a[0]), "r"(a[1]), "r"(a[2]), "r"(a[3]), "r"(b[0]), "r"(b[1]));
+#endif
+}
+
+__global__ void __launch_bounds__(128) block_scores_tc_kernel(const float* __restrict__ pooled,
+ const float* __restrict__ q_idx,
+ const int32_t* __restrict__ steps, int64_t nq,
+ int64_t max_blocks, int64_t reach,
+ float* __restrict__ out) {
+ extern __shared__ __align__(16) float sm[];
+ float* sQ = sm; // [TC_QT][TC_QS]
+ float* sK = sm + TC_QT * TC_QS; // [TC_NB][TC_KS]
+ __shared__ int s_nbid[TC_QT];
+ const int t = threadIdx.x, lane = t & 31, warp = t >> 5, gid = lane >> 2, tig = lane & 3;
+ const int64_t q0 = (int64_t) blockIdx.y * TC_QT;
+ for (int i = t; i < TC_QT * IDX_HEADS * IDX_DIM / 4; i += 128) {
+ const int r = i / (IDX_HEADS * IDX_DIM / 4), c = i % (IDX_HEADS * IDX_DIM / 4);
+ float4 v = make_float4(0.f, 0.f, 0.f, 0.f);
+ if (q0 + r < nq) v = reinterpret_cast<const float4*>(q_idx + (q0 + r) * IDX_HEADS * IDX_DIM)[c];
+ *reinterpret_cast<float4*>(sQ + r * TC_QS + c * 4) = v;
+ }
+ if (t < TC_QT) s_nbid[t] = q0 + t < nq ? steps[(q0 + t) * kStepCount + kStepNBid] : 0;
+ int lo_nbid = 0x7fffffff, hi_nbid = 0;
+ __syncthreads();
+ for (int i = 0; i < TC_QT; ++i) {
+ if (q0 + i >= nq) break;
+ lo_nbid = min(lo_nbid, s_nbid[i]);
+ hi_nbid = max(hi_nbid, s_nbid[i]);
+ }
+ for (int it = 0; it < TC_ITER; ++it) {
+ const int64_t b0 = ((int64_t) blockIdx.x * TC_ITER + it) * TC_NB;
+ if (b0 >= reach || b0 >= hi_nbid) break; // blocks >= every query's n_bid: nothing to score
+ __syncthreads(); // the previous tile's reads are done
+ for (int i = t; i < TC_NB * IDX_DIM / 4; i += 128) {
+ const int r = i / (IDX_DIM / 4), c = i % (IDX_DIM / 4);
+ float4 v = make_float4(0.f, 0.f, 0.f, 0.f);
+ if (b0 + r < hi_nbid) v = reinterpret_cast<const float4*>(pooled + (b0 + r) * IDX_DIM)[c];
+ *reinterpret_cast<float4*>(sK + r * TC_KS + c * 4) = v;
+ }
+ __syncthreads();
+ float acc[IDX_HEADS][4];
+#pragma unroll
+ for (int h = 0; h < IDX_HEADS; ++h) acc[h][0] = acc[h][1] = acc[h][2] = acc[h][3] = 0.f;
+ const float* kr = sK + (warp * 8 + gid) * TC_KS;
+#pragma unroll 4
+ for (int k0 = 0; k0 < IDX_DIM; k0 += 8) {
+ const float kx0 = kr[k0 + tig], kx1 = kr[k0 + tig + 4];
+ uint32_t bh[2], bl[2];
+ bh[0] = tf32_hi(kx0);
+ bh[1] = tf32_hi(kx1);
+ bl[0] = tf32_hi(kx0 - __uint_as_float(bh[0]));
+ bl[1] = tf32_hi(kx1 - __uint_as_float(bh[1]));
+#pragma unroll
+ for (int h = 0; h < IDX_HEADS; ++h) {
+ const float* qa = sQ + h * IDX_DIM + k0 + tig;
+ const float x0 = qa[gid * TC_QS], x1 = qa[(gid + 8) * TC_QS];
+ const float x2 = qa[gid * TC_QS + 4], x3 = qa[(gid + 8) * TC_QS + 4];
+ uint32_t ah[4], al[4];
+ ah[0] = tf32_hi(x0); ah[1] = tf32_hi(x1); ah[2] = tf32_hi(x2); ah[3] = tf32_hi(x3);
+ al[0] = tf32_hi(x0 - __uint_as_float(ah[0]));
+ al[1] = tf32_hi(x1 - __uint_as_float(ah[1]));
+ al[2] = tf32_hi(x2 - __uint_as_float(ah[2]));
+ al[3] = tf32_hi(x3 - __uint_as_float(ah[3]));
+ mma_tf32(acc[h], al, bh);
+ mma_tf32(acc[h], ah, bl);
+ mma_tf32(acc[h], ah, bh);
+ }
+ }
+ // relu per head, heads added in order (as the warp kernel), written where the block completed for the query
+ const int64_t bc = b0 + warp * 8 + 2 * tig;
+#pragma unroll
+ for (int half = 0; half < 2; ++half) {
+ const int qr = gid + half * 8;
+ const int64_t qi = q0 + qr;
+ if (qi >= nq) continue;
+ const int nb = s_nbid[qr];
+#pragma unroll
+ for (int j = 0; j < 2; ++j) {
+ const int64_t b = bc + j;
+ if (b >= nb || b >= max_blocks) continue;
+ float score = 0.0f;
+#pragma unroll
+ for (int h = 0; h < IDX_HEADS; ++h) {
+ const float d = acc[h][half * 2 + j];
+ score += d > 0.0f ? d : 0.0f;
+ }
+ out[qi * max_blocks + b] = score;
+ }
+ }
+ }
+}
+
+// the tail block n_bid of each query: exactly block_scores_kernel's arithmetic for that block
+__global__ void __launch_bounds__(32) block_scores_tail_kernel(const float* __restrict__ dead,
+ const float* __restrict__ q_idx,
+ const int32_t* __restrict__ steps,
+ int64_t max_blocks, float* __restrict__ out) {
+ const int64_t qi = blockIdx.x;
+ const int32_t* st = steps + qi * kStepCount;
+ const int64_t n_kv = st[kStepNKv], n_bid = st[kStepNBid];
+ if (n_bid >= max_blocks) return;
+ const int lane = threadIdx.x & 31;
+ const float4 k4 = *reinterpret_cast<const float4*>(dead + lane * 4);
+ const float* q = q_idx + qi * IDX_HEADS * IDX_DIM + lane * 4;
+ float score = 0.0f;
+#pragma unroll
+ for (int h = 0; h < IDX_HEADS; ++h) {
+ const float4 q4 = *reinterpret_cast<const float4*>(q + h * IDX_DIM);
+ float d = k4.x * q4.x + k4.y * q4.y + k4.z * q4.z + k4.w * q4.w;
+#pragma unroll
+ for (int o = 16; o > 0; o >>= 1) d += __shfl_xor_sync(0xffffffffu, d, o);
+ score += d > 0.0f ? d : 0.0f;
+ }
+ if (lane == 0) {
+ if (n_kv % R != 0) score += 1e9f;
+ out[qi * max_blocks + n_bid] = score;
+ }
+}
+
+// ---- the same top-k with each query's keys read once: 1,024 threads hold up to TK_PER consecutive blocks' keys in
+// registers (contexts up to 4 * 1024 * TK_PER cells), per-warp histograms, block-wide scans. The selection rule is
+// block_topk_kernel's (radix threshold, ties to the lowest index, cells ascending): identical ids.
+constexpr int TK_T = 1024;
+constexpr int TK_PER = 33;
+
+__device__ __forceinline__ int block_excl_scan(int v, int* s_warp, int& total) {
+ const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5;
+ int x = v;
+#pragma unroll
+ for (int o = 1; o < 32; o <<= 1) {
+ const int y = __shfl_up_sync(0xffffffffu, x, o);
+ if (lane >= o) x += y;
+ }
+ if (lane == 31) s_warp[warp] = x;
+ __syncthreads();
+ if (warp == 0) {
+ int w = s_warp[lane];
+ int z = w;
+#pragma unroll
+ for (int o = 1; o < 32; o <<= 1) {
+ const int y = __shfl_up_sync(0xffffffffu, z, o);
+ if (lane >= o) z += y;
+ }
+ s_warp[lane] = z - w; // exclusive per warp
+ if (lane == 31) s_warp[32] = z; // total
+ }
+ __syncthreads();
+ const int r = s_warp[warp] + x - v;
+ total = s_warp[32];
+ __syncthreads();
+ return r;
+}
+
+__global__ void __launch_bounds__(TK_T) block_topk_reg_kernel(const float* __restrict__ scores,
+ const int32_t* __restrict__ steps, int64_t max_blocks,
+ int64_t cap, int32_t* __restrict__ ids) {
+ __shared__ int hist[TK_T / 32][256];
+ __shared__ int s_warp[33];
+ __shared__ int s_digit, s_above;
+ const int64_t qi = blockIdx.x;
+ const int32_t* st = steps + qi * kStepCount;
+ const int64_t n_kv = st[kStepNKv], n_bid = st[kStepNBid], width = st[kStepWidth];
+ int32_t* out = ids + qi * cap;
+ const int t = threadIdx.x, lane = t & 31, warp = t >> 5;
+ if (n_kv <= width) {
+ for (int64_t j = t; j < n_kv; j += TK_T) out[j] = (int32_t) j;
+ return;
+ }
+ const float* sc = scores + qi * max_blocks;
+ const int64_t nb = n_bid + 1;
+ const int64_t per = (nb + TK_T - 1) / TK_T; // <= TK_PER (the caller checks)
+ const int64_t b0 = (int64_t) t * per, b1 = (b0 + per < nb) ? b0 + per : nb;
+ uint32_t key[TK_PER];
+#pragma unroll
+ for (int j = 0; j < TK_PER; ++j) key[j] = (b0 + j < b1) ? order_key(sc[b0 + j]) : 0u;
+ auto weight = [&](int64_t b) -> int { return b < n_bid ? R : (int) (n_kv - n_bid * R); };
+ uint32_t prefix = 0;
+ int above = 0;
+ for (int shift = 24; shift >= 0; shift -= 8) {
+ for (int i = lane; i < 256; i += 32) hist[warp][i] = 0;
+ __syncwarp();
+ const uint32_t hi_mask = shift == 24 ? 0u : (0xffffffffu << (shift + 8));
+#pragma unroll
+ for (int j = 0; j < TK_PER; ++j) {
+ const int64_t b = b0 + j;
+ if (b >= b1) break;
+ const int w = weight(b);
+ if (w == 0) continue;
+ if ((key[j] & hi_mask) == (prefix & hi_mask)) atomicAdd(&hist[warp][(key[j] >> shift) & 255], w);
+ }
+ __syncthreads();
+ if (t < 256) { // fold the warps' histograms into warp 0's
+ int s = 0;
+ for (int w2 = 0; w2 < TK_T / 32; ++w2) s += hist[w2][t];
+ hist[0][t] = s;
+ }
+ __syncthreads();
+ if (t == 0) {
+ int cum = above, d = 255;
+ for (; d > 0; --d) {
+ if (cum + hist[0][d] >= width) break;
+ cum += hist[0][d];
+ }
+ s_digit = d;
+ s_above = cum;
+ }
+ __syncthreads();
+ prefix |= (uint32_t) s_digit << shift;
+ above = s_above;
+ __syncthreads();
+ }
+ const uint32_t thr = prefix;
+ const int64_t eq_budget = width - above;
+ int gt = 0, eq = 0;
+#pragma unroll
+ for (int j = 0; j < TK_PER; ++j) {
+ const int64_t b = b0 + j;
+ if (b >= b1) break;
+ const int w = weight(b);
+ if (w == 0) continue;
+ if (key[j] > thr) gt += w;
+ else if (key[j] == thr) eq += w;
+ }
+ int tot;
+ const int eq_before = block_excl_scan(eq, s_warp, tot);
+ int64_t my_eq = eq_budget - eq_before;
+ if (my_eq < 0) my_eq = 0;
+ if (my_eq > eq) my_eq = eq;
+ const int sel = gt + (int) my_eq;
+ int64_t wpos = block_excl_scan(sel, s_warp, tot);
+ int64_t eq_left = my_eq;
+#pragma unroll
+ for (int j = 0; j < TK_PER; ++j) {
+ const int64_t b = b0 + j;
+ if (b >= b1) break;
+ const int w = weight(b);
+ if (w == 0) continue;
+ if (key[j] > thr) {
+ for (int c = 0; c < w; ++c) out[wpos++] = (int32_t) (b * R + c);
+ } else if (key[j] == thr) {
+ for (int c = 0; c < w && eq_left > 0; ++c, --eq_left) out[wpos++] = (int32_t) (b * R + c);
+ }
+ }
+}
+
} // namespace
void qsa_block_scores(const float* pooled, const float* dead, const float* q_idx, const int32_t* steps, int64_t nq,
@@ -166,14 +445,74 @@ void qsa_block_scores(const float* pooled, const float* dead, const float* q_idx
if (e != cudaSuccess) { std::fprintf(stderr, "qsa_block_scores: %s\n", cudaGetErrorString(e)); std::exit(1); }
}
+bool qsa_block_scores_tc(const float* pooled, const float* dead, const float* q_idx, const int32_t* steps, int64_t nq,
+ int64_t max_blocks, const QsaShapes& s, float* scores, void* stream, int64_t active_blocks) {
+ if (nq <= 0) return true;
+ if (s.idx_dim != IDX_DIM || s.idx_n_head != IDX_HEADS || s.idx_block != R || nq > 65535 * TC_QT) return false;
+ { // sm_80 or newer (TF32 MMA); an older card keeps the warp kernel
+ static int cc_major[64] = {};
+ int dev = 0;
+ if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return false; }
+ if (cc_major[dev] == 0) {
+ int major = 0;
+ if (cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) != cudaSuccess) {
+ cudaGetLastError();
+ return false;
+ }
+ cc_major[dev] = major;
+ }
+ if (cc_major[dev] < 8) return false;
+ }
+ static bool attr[64] = {}; // the shared-memory opt-in is per device (a layer split runs it on several)
+ int adev = 0;
+ cudaGetDevice(&adev);
+ const int bytes = (TC_QT * TC_QS + TC_NB * TC_KS) * (int) sizeof(float);
+ if (!attr[adev]) {
+ if (cudaFuncSetAttribute(block_scores_tc_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, bytes) !=
+ cudaSuccess) {
+ cudaGetLastError();
+ return false;
+ }
+ attr[adev] = true;
+ }
+ const int64_t reach = active_blocks > 0 && active_blocks < max_blocks ? active_blocks : max_blocks;
+ const int64_t per = (int64_t) TC_NB * TC_ITER;
+ const dim3 grid((unsigned) ((reach + per - 1) / per), (unsigned) ((nq + TC_QT - 1) / TC_QT));
+ block_scores_tc_kernel<<<grid, 128, bytes, (cudaStream_t) stream>>>(pooled, q_idx, steps, nq, max_blocks, reach,
+ scores);
+ block_scores_tail_kernel<<<(unsigned) nq, 32, 0, (cudaStream_t) stream>>>(dead, q_idx, steps, max_blocks, scores);
+ const cudaError_t e = cudaGetLastError();
+ if (e != cudaSuccess) { std::fprintf(stderr, "qsa_block_scores_tc: %s\n", cudaGetErrorString(e)); std::exit(1); }
+ return true;
+}
+
+void qsa_block_topk_ref(const float* scores, const int32_t* steps, int64_t nq, int64_t max_blocks, int64_t cap,
+ const QsaShapes& s, int32_t* ids, void* stream) {
+ if (nq <= 0) return;
+ if (s.idx_block != R || cap < qsa_selection_width(kTopkMaxCells, s)) {
+ std::fprintf(stderr, "qsa_block_topk: unsupported geometry or cap\n");
+ std::exit(1);
+ }
+ block_topk_kernel<<<(unsigned) nq, TOPK_T, 0, (cudaStream_t) stream>>>(scores, steps, max_blocks, cap, ids);
+ const cudaError_t e = cudaGetLastError();
+ if (e != cudaSuccess) { std::fprintf(stderr, "qsa_block_topk: %s\n", cudaGetErrorString(e)); std::exit(1); }
+}
+
void qsa_block_topk(const float* scores, const int32_t* steps, int64_t nq, int64_t max_blocks, int64_t cap,
const QsaShapes& s, int32_t* ids, void* stream) {
+ // keys in registers when every query's blocks fit (contexts up to ~135K cells); the same ids. STRATA_TOPK_OLD=1:
+ // the kernel that reads them from memory on every pass
+ static const bool old = std::getenv("STRATA_TOPK_OLD") != nullptr;
if (nq <= 0) return;
+ if (old || max_blocks > (int64_t) TK_T * TK_PER) {
+ qsa_block_topk_ref(scores, steps, nq, max_blocks, cap, s, ids, stream);
+ return;
+ }
if (s.idx_block != R || cap < qsa_selection_width(kTopkMaxCells, s)) {
std::fprintf(stderr, "qsa_block_topk: unsupported geometry or cap\n");
std::exit(1);
}
- block_topk_kernel<<<(unsigned) nq, TOPK_T, 0, (cudaStream_t) stream>>>(scores, steps, max_blocks, cap, ids);
+ block_topk_reg_kernel<<<(unsigned) nq, TK_T, 0, (cudaStream_t) stream>>>(scores, steps, max_blocks, cap, ids);
const cudaError_t e = cudaGetLastError();
if (e != cudaSuccess) { std::fprintf(stderr, "qsa_block_topk: %s\n", cudaGetErrorString(e)); std::exit(1); }
}
diff --git a/src/kernels/qsa_select_bench.cpp b/src/kernels/qsa_select_bench.cpp
new file mode 100644
index 000000000..342a504a9
--- /dev/null
+++ b/src/kernels/qsa_select_bench.cpp
@@ -0,0 +1,139 @@
+// src/kernels/qsa_select_bench.cpp - the prompt path's QSA selection (qsa_select.hpp) timed per stage, block scores
+// (the warp kernel and the tensor-core one) and top-k, for a batch of consecutive queries at a given context, and
+// the two scorers compared: score difference and how many selections differ (GPU, synthetic, no model).
+// Usage: qsa_select_bench [context=131072] [queries=256] [reps=10]
+#include "strata/kernels/qsa.hpp"
+#include "strata/kernels/qsa_select.hpp"
+
+#include <cuda_runtime.h>
+
+#include <algorithm>
+#include <cmath>
+#include <cstdio>
+#include <cstdlib>
+#include <random>
+#include <vector>
+
+namespace k = strata::kernels;
+
+namespace {
+void ck(cudaError_t e, const char* w) {
+ if (e != cudaSuccess) { std::fprintf(stderr, "%s: %s\n", w, cudaGetErrorString(e)); std::exit(2); }
+}
+template <typename T> T* up(const std::vector<T>& h) {
+ T* d = nullptr;
+ ck(cudaMalloc(&d, h.size() * sizeof(T) + 64), "malloc");
+ ck(cudaMemcpy(d, h.data(), h.size() * sizeof(T), cudaMemcpyHostToDevice), "upload");
+ return d;
+}
+} // namespace
+
+int main(int argc, char** argv) {
+ const int64_t ctx = argc > 1 ? std::atoll(argv[1]) : 131072;
+ const int64_t nq = argc > 2 ? std::atoll(argv[2]) : 256;
+ const int reps = argc > 3 ? std::atoi(argv[3]) : 10;
+ const k::QsaShapes s = k::qsa_real_shapes();
+ const int64_t max_blocks = ctx / 4 + 1, cap = k::qsa_selection_width(k::kTopkMaxCells, s);
+ std::mt19937 rng(7);
+ std::normal_distribution<float> nd(0.f, 1.f);
+ // keys with a shared direction plus noise, so the scores have a spread like a real indexer's
+ std::vector<float> dir(128), pooled((size_t) (max_blocks * 128)), dead(128), q((size_t) (nq * 512));
+ for (auto& x : dir) x = nd(rng);
+ for (int64_t b = 0; b < max_blocks; ++b) {
+ const float a = nd(rng);
+ for (int d = 0; d < 128; ++d) pooled[(size_t) (b * 128 + d)] = 0.5f * a * dir[d] + nd(rng);
+ }
+ for (auto& x : dead) x = nd(rng);
+ for (int64_t i = 0; i < nq; ++i)
+ for (int d = 0; d < 512; ++d) q[(size_t) (i * 512 + d)] = 0.2f * dir[d % 128] + 0.1f * nd(rng);
+ std::vector<int32_t> steps((size_t) (nq * k::kStepCount));
+ for (int64_t i = 0; i < nq; ++i) { // qsa_step_fill's arithmetic (kept here so the bench links only qsa_select)
+ int32_t* st = steps.data() + i * k::kStepCount;
+ const int64_t pos = ctx - nq + i;
+ st[k::kStepPos] = (int32_t) pos;
+ st[k::kStepNKv] = (int32_t) (pos + 1);
+ st[k::kStepNBid] = (int32_t) ((pos + 1) / s.idx_block);
+ st[k::kStepWidth] = (int32_t) k::qsa_selection_width(pos + 1, s);
+ }
+ const float* d_pooled = up(pooled);
+ const float* d_dead = up(dead);
+ const float* d_q = up(q);
+ const int32_t* d_steps = up(steps);
+ float *sc_old = nullptr, *sc_new = nullptr;
+ int32_t *ids_old = nullptr, *ids_new = nullptr;
+ ck(cudaMalloc(&sc_old, (size_t) (nq * max_blocks) * 4), "malloc");
+ ck(cudaMalloc(&sc_new, (size_t) (nq * max_blocks) * 4), "malloc");
+ ck(cudaMalloc(&ids_old, (size_t) (nq * cap) * 4), "malloc");
+ ck(cudaMalloc(&ids_new, (size_t) (nq * cap) * 4), "malloc");
+ const int64_t active = steps[(size_t) ((nq - 1) * k::kStepCount + k::kStepNBid)] + 1;
+ auto run_old = [&] { k::qsa_block_scores(d_pooled, d_dead, d_q, d_steps, nq, max_blocks, s, sc_old, nullptr, active); };
+ auto run_new = [&] {
+ if (!k::qsa_block_scores_tc(d_pooled, d_dead, d_q, d_steps, nq, max_blocks, s, sc_new, nullptr, active)) {
+ std::fprintf(stderr, "tc scorer refused\n");
+ std::exit(2);
+ }
+ };
+ run_old();
+ run_new();
+ k::qsa_block_topk_ref(sc_old, d_steps, nq, max_blocks, cap, s, ids_old, nullptr);
+ k::qsa_block_topk(sc_new, d_steps, nq, max_blocks, cap, s, ids_new, nullptr);
+ int32_t* ids_reg = nullptr; // the register top-k on the OLD scores: must equal the reference exactly
+ ck(cudaMalloc(&ids_reg, (size_t) (nq * cap) * 4), "malloc");
+ k::qsa_block_topk(sc_old, d_steps, nq, max_blocks, cap, s, ids_reg, nullptr);
+ ck(cudaDeviceSynchronize(), "warm");
+ // compare
+ std::vector<float> a((size_t) (nq * max_blocks)), b(a.size());
+ std::vector<int32_t> ia((size_t) (nq * cap)), ib(ia.size());
+ ck(cudaMemcpy(a.data(), sc_old, a.size() * 4, cudaMemcpyDeviceToHost), "down");
+ ck(cudaMemcpy(b.data(), sc_new, b.size() * 4, cudaMemcpyDeviceToHost), "down");
+ ck(cudaMemcpy(ia.data(), ids_old, ia.size() * 4, cudaMemcpyDeviceToHost), "down");
+ ck(cudaMemcpy(ib.data(), ids_new, ib.size() * 4, cudaMemcpyDeviceToHost), "down");
+ std::vector<int32_t> ir(ia.size());
+ ck(cudaMemcpy(ir.data(), ids_reg, ir.size() * 4, cudaMemcpyDeviceToHost), "down");
+ int64_t reg_same = 0;
+ for (int64_t i = 0; i < nq; ++i) {
+ const int64_t w = steps[(size_t) (i * k::kStepCount + k::kStepWidth)];
+ reg_same += std::equal(ia.begin() + i * cap, ia.begin() + i * cap + w, ir.begin() + i * cap);
+ }
+ double max_rel = 0, sum_rel = 0, n_rel = 0;
+ int64_t same_sel = 0, cells_diff = 0, cells_all = 0;
+ for (int64_t i = 0; i < nq; ++i) {
+ const int32_t* st = steps.data() + i * k::kStepCount;
+ for (int64_t j = 0; j <= st[k::kStepNBid]; ++j) {
+ const double x = a[(size_t) (i * max_blocks + j)], y = b[(size_t) (i * max_blocks + j)];
+ const double r = std::fabs(x - y) / std::max(1e-6, std::fabs(x));
+ max_rel = std::max(max_rel, r);
+ sum_rel += r;
+ n_rel += 1;
+ }
+ const int64_t w = st[k::kStepWidth];
+ std::vector<int32_t> x(ia.begin() + i * cap, ia.begin() + i * cap + w), y(ib.begin() + i * cap, ib.begin() + i * cap + w);
+ same_sel += x == y;
+ std::vector<int32_t> d;
+ std::set_symmetric_difference(x.begin(), x.end(), y.begin(), y.end(), std::back_inserter(d));
+ cells_diff += (int64_t) d.size() / 2;
+ cells_all += w;
+ }
+ // time
+ cudaEvent_t e0, e1;
+ cudaEventCreate(&e0); cudaEventCreate(&e1);
+ auto timed = [&](auto f) {
+ cudaEventRecord(e0);
+ for (int r = 0; r < reps; ++r) f();
+ cudaEventRecord(e1);
+ ck(cudaEventSynchronize(e1), "time");
+ float ms = 0;
+ cudaEventElapsedTime(&ms, e0, e1);
+ return ms / reps;
+ };
+ const float t_old = timed(run_old), t_new = timed(run_new);
+ const float t_tk = timed([&] { k::qsa_block_topk_ref(sc_old, d_steps, nq, max_blocks, cap, s, ids_old, nullptr); });
+ const float t_tk2 = timed([&] { k::qsa_block_topk(sc_old, d_steps, nq, max_blocks, cap, s, ids_reg, nullptr); });
+ std::printf("top-k %.3f -> %.3f ms (%.1fx), register top-k identical to the reference %lld/%lld\n", t_tk, t_tk2,
+ t_tk / t_tk2, (long long) reg_same, (long long) nq);
+ std::printf("ctx %lld, %lld queries x %lld blocks: scores %.3f -> %.3f ms (%.1fx), top-k %.3f ms; score rel diff "
+ "mean %.2g max %.2g; selections identical %lld/%lld, cells differing %.4f%%\n", (long long) ctx,
+ (long long) nq, (long long) active, t_old, t_new, t_old / t_new, t_tk, sum_rel / std::max(1.0, n_rel),
+ max_rel, (long long) same_sel, (long long) nq, cells_all ? 100.0 * (double) cells_diff / (double) cells_all : 0.0);
+ return 0;
+}
diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp
index a9ceabff4..15c9f1228 100644
--- a/src/prefill/prefill.cpp
+++ b/src/prefill/prefill.cpp
@@ -1168,8 +1168,13 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e
// C-1: the grid reaches the batch's last query's n_bid (they rise with the position)
const int64_t active = (int64_t) m.steps_host[(size_t) ((t0 + nb - 1) * strata::kernels::kStepCount +
strata::kernels::kStepNBid)] + 1;
- strata::kernels::qsa_block_scores(st.idx_pooled, st.idx_dead, m.q_idx + t0 * 512, steps0, nb,
- m.max_blocks, s, m.sel_scores, m.cs, active);
+ // the scores on tensor cores (3xTF32: FP32-level, not bitwise); STRATA_SELECT_OLD=1: the warp kernel
+ static const bool old_sel = std::getenv("STRATA_SELECT_OLD") != nullptr;
+ if (old_sel || !strata::kernels::qsa_block_scores_tc(st.idx_pooled, st.idx_dead, m.q_idx + t0 * 512,
+ steps0, nb, m.max_blocks, s, m.sel_scores,
+ m.cs, active))
+ strata::kernels::qsa_block_scores(st.idx_pooled, st.idx_dead, m.q_idx + t0 * 512, steps0, nb,
+ m.max_blocks, s, m.sel_scores, m.cs, active);
strata::kernels::qsa_block_topk(m.sel_scores, steps0, nb, m.max_blocks, m.cap, s,
m.sel_ids + t0 * m.cap, m.cs);
}