okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221qsa_select tp_select: no __match_any_sync below sm_70 (a plain add per thread there; integer atomics, the same sums): the CUDA 12 release engine (sm_60..89) builds again0fe4ae509

main
206.9 KiB3913 linesraw
1// src/kernels/cuda/qsa_select.cu - see include/strata/kernels/qsa_select.hpp.
2#include "strata/core/emulate.hpp"
3#include "strata/core/sm75_series.hpp"
4#include "strata/core/geometry.hpp"
5#include <cstdlib>
6#include <cstring>
7#include "strata/kernels/qsa_select.hpp"
8#include "strata/kernels/qsa_two_pass.hpp"
9#include "strata/kernels/qsa_two_pass_status.hpp"
10#include "strata/kernels/gfx_arch.hpp"
11#include "strata/core/amd_community.hpp"
12
13#include <cuda_runtime.h>
14
15#include <atomic>
16#include <cfloat>
17#include <cstdio>
18#include <cstdlib>
19#include <cstring>
20
21namespace strata::kernels {
22namespace {
23
24constexpr int IDX_DIM = 128, IDX_HEADS = 4, R = 4;
25static_assert(IDX_DIM == strata::core::kCompiledGeometry.idx_key_dim && IDX_HEADS == strata::core::kCompiledGeometry.idx_q_heads && R == strata::core::kCompiledGeometry.idx_block,
26              "qsa_select is compiled for core/geometry.hpp");
27constexpr int SCORE_WARPS = 8;
28constexpr int TOPK_T = 256;
29
30__device__ __forceinline__ uint32_t order_key(float s) {
31    const float v = s + 0.0f;
32    if (!(v == v)) return 0u;
33    const uint32_t b = __float_as_uint(v);
34    return (b & 0x80000000u) ? ~b : (b | 0x80000000u);
35}
36
37__global__ void __launch_bounds__(SCORE_WARPS * 32) block_scores_kernel(const float* __restrict__ pooled,
38                                                                        const float* __restrict__ dead,
39                                                                        const float* __restrict__ q_idx,
40                                                                        const int32_t* __restrict__ steps,
41                                                                        int64_t max_blocks, float* __restrict__ out) {
42    const int64_t qi = blockIdx.y;
43    const int32_t* st = steps + qi * kStepCount;
44    const int64_t n_kv = st[kStepNKv], n_bid = st[kStepNBid];
45    const int64_t b = (int64_t) blockIdx.x * SCORE_WARPS + (threadIdx.x >> 5);
46    if (b > n_bid || b >= max_blocks) return;
47    const int lane = threadIdx.x & 31;
48    const float* key = (b == n_bid) ? dead : pooled + b * IDX_DIM;
49    const float4 k4 = *reinterpret_cast<const float4*>(key + lane * 4);
50    const float* q = q_idx + qi * IDX_HEADS * IDX_DIM + lane * 4;
51    float score = 0.0f;
52#pragma unroll
53    for (int h = 0; h < IDX_HEADS; ++h) {
54        const float4 q4 = *reinterpret_cast<const float4*>(q + h * IDX_DIM);
55        float d = k4.x * q4.x + k4.y * q4.y + k4.z * q4.z + k4.w * q4.w;
56#pragma unroll
57        for (int o = 16; o > 0; o >>= 1) d += __shfl_xor_sync(0xffffffffu, d, o);
58        score += d > 0.0f ? d : 0.0f;
59    }
60    if (lane == 0) {
61        if (b == n_bid && n_kv % R != 0) score += 1e9f;
62        out[qi * max_blocks + b] = score;
63    }
64}
65
66__global__ void __launch_bounds__(TOPK_T) block_topk_kernel(const float* __restrict__ scores,
67                                                            const int32_t* __restrict__ steps, int64_t max_blocks,
68                                                            int64_t cap, int32_t* __restrict__ ids) {
69    __shared__ int hist[256];
70    __shared__ int s_a[TOPK_T], s_b[TOPK_T];
71    __shared__ int s_digit, s_above;
72    const int64_t qi = blockIdx.x;
73    const int32_t* st = steps + qi * kStepCount;
74    const int64_t n_kv = st[kStepNKv], n_bid = st[kStepNBid], width = st[kStepWidth];
75    int32_t* out = ids + qi * cap;
76    const int t = threadIdx.x;
77    if (n_kv <= width) {                               // everything is selected: the identity, ascending
78        for (int64_t j = t; j < n_kv; j += TOPK_T) out[j] = (int32_t) j;
79        return;
80    }
81    const float* sc = scores + qi * max_blocks;
82    const int64_t nb = n_bid + 1;                      // blocks 0..n_bid, the last possibly empty
83    const int64_t per = (nb + TOPK_T - 1) / TOPK_T;
84    const int64_t b0 = (int64_t) t * per, b1 = (b0 + per < nb) ? b0 + per : nb;
85    auto weight = [&](int64_t b) -> int { return b < n_bid ? R : (int) (n_kv - n_bid * R); };
86    // ---- radix select: the largest key thr with (cells with key >= thr) >= width, 8 bits at a time
87    uint32_t prefix = 0;
88    int above = 0;                                     // cells strictly above the digits fixed so far
89    for (int shift = 24; shift >= 0; shift -= 8) {
90        for (int i = t; i < 256; i += TOPK_T) hist[i] = 0;
91        __syncthreads();
92        const uint32_t hi_mask = shift == 24 ? 0u : (0xffffffffu << (shift + 8));
93        for (int64_t b = b0; b < b1; ++b) {
94            const int w = weight(b);
95            if (w == 0) continue;
96            const uint32_t k = order_key(sc[b]);
97            if ((k & hi_mask) == (prefix & hi_mask)) atomicAdd(&hist[(k >> shift) & 255], w);
98        }
99        __syncthreads();
100        if (t == 0) {
101            int cum = above, d = 255;
102            for (; d > 0; --d) {
103                if (cum + hist[d] >= width) break;
104                cum += hist[d];
105            }
106            s_digit = d;
107            s_above = cum;
108        }
109        __syncthreads();
110        prefix |= (uint32_t) s_digit << shift;
111        above = s_above;
112        __syncthreads();
113    }
114    const uint32_t thr = prefix;
115    const int64_t eq_budget = width - above;          // cells equal to thr that fit, lowest index first
116    // ---- per-thread counts of cells above and at the threshold, then their exclusive prefixes
117    int gt = 0, eq = 0;
118    for (int64_t b = b0; b < b1; ++b) {
119        const int w = weight(b);
120        if (w == 0) continue;
121        const uint32_t k = order_key(sc[b]);
122        if (k > thr) gt += w;
123        else if (k == thr) eq += w;
124    }
125    s_a[t] = gt;
126    s_b[t] = eq;
127    __syncthreads();
128    if (t == 0) {
129        int ag = 0, ae = 0;
130        for (int i = 0; i < TOPK_T; ++i) {
131            const int g = s_a[i], e = s_b[i];
132            s_a[i] = ag; s_b[i] = ae;
133            ag += g; ae += e;
134        }
135    }
136    __syncthreads();
137    const int64_t eq_before = s_b[t];
138    int64_t my_eq = eq_budget - eq_before;
139    if (my_eq < 0) my_eq = 0;
140    if (my_eq > eq) my_eq = eq;
141    const int sel = gt + (int) my_eq;
142    __syncthreads();
143    s_a[t] = sel;
144    __syncthreads();
145    if (t == 0) {
146        int a = 0;
147        for (int i = 0; i < TOPK_T; ++i) { const int c = s_a[i]; s_a[i] = a; a += c; }
148    }
149    __syncthreads();
150    int64_t wpos = s_a[t];
151    int64_t eq_left = my_eq;
152    for (int64_t b = b0; b < b1; ++b) {
153        const int w = weight(b);
154        if (w == 0) continue;
155        const uint32_t k = order_key(sc[b]);
156        if (k > thr) {
157            for (int c = 0; c < w; ++c) out[wpos++] = (int32_t) (b * R + c);
158        } else if (k == thr) {
159            for (int c = 0; c < w && eq_left > 0; ++c, --eq_left) out[wpos++] = (int32_t) (b * R + c);
160        }
161    }
162}
163
164
165// ---- QSA select on tensor cores (perf-review, after D-1): the block scores of many queries are one GEMM,
166// rows (query, indexer head) x columns (blocks), K = 128, with relu per head summed. 3xTF32 (each operand split
167// into a TF32 hi and lo part, hi*hi + hi*lo + lo*hi) keeps FP32-level accuracy; the summation order differs from
168// the warp kernel, so a score can move in its last bits and a near-tie can select differently (not bitwise).
169// Blocks < n_bid only; the tail block n_bid (the `dead` key, +1e9) is scored by the warp kernel's own code.
170constexpr int TC_QT = 16;                 // queries per CTA (one m16 tile per indexer head)
171constexpr int TC_NB = 32;                 // blocks per tile (4 warps x n8)
172constexpr int TC_ITER = 4;                // tiles per CTA (the query tile is loaded once)
173constexpr int TC_QS = IDX_HEADS * IDX_DIM + 4;   // query row stride in floats
174constexpr int TC_KS = IDX_DIM + 4;               // key row stride
175
176// TF32 conversion and MMA need sm_80: below it they compile to a trap and qsa_block_scores_tc refuses the device
177#if defined(__HIPCC__)          // AMD: no mma.sync / cp.async; the host keeps the warp kernel (below)
178#define STRATA_SEL_SM80 0
179#elif !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 800
180#define STRATA_SEL_SM80 1
181#else
182#define STRATA_SEL_SM80 0
183#endif
184__device__ __forceinline__ uint32_t tf32_hi(float x) {
185#if STRATA_SEL_SM80
186    uint32_t r;
187    asm("cvt.rna.tf32.f32 %0, %1;" : "=r"(r) : "f"(x));
188    return r;
189#else
190    return __float_as_uint(x);
191#endif
192}
193__device__ __forceinline__ void mma_tf32(float* c, const uint32_t* a, const uint32_t* b) {
194#if !STRATA_SEL_SM80
195    __trap();
196#else
197    asm volatile("mma.sync.aligned.m16n8k8.row.col.f32.tf32.tf32.f32 {%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, "
198                 "{%0,%1,%2,%3};\n"
199                 : "+f"(c[0]), "+f"(c[1]), "+f"(c[2]), "+f"(c[3])
200                 : "r"(a[0]), "r"(a[1]), "r"(a[2]), "r"(a[3]), "r"(b[0]), "r"(b[1]));
201#endif
202}
203
204__global__ void __launch_bounds__(128) block_scores_tc_kernel(const float* __restrict__ pooled,
205                                                              const float* __restrict__ q_idx,
206                                                              const int32_t* __restrict__ steps, int64_t nq,
207                                                              int64_t max_blocks, int64_t reach,
208                                                              float* __restrict__ out) {
209    extern __shared__ __align__(16) float sm[];
210    float* sQ = sm;                                   // [TC_QT][TC_QS]
211    float* sK = sm + TC_QT * TC_QS;                   // [TC_NB][TC_KS]
212    __shared__ int s_nbid[TC_QT];
213    const int t = threadIdx.x, lane = t & 31, warp = t >> 5, gid = lane >> 2, tig = lane & 3;
214    const int64_t q0 = (int64_t) blockIdx.y * TC_QT;
215    for (int i = t; i < TC_QT * IDX_HEADS * IDX_DIM / 4; i += 128) {
216        const int r = i / (IDX_HEADS * IDX_DIM / 4), c = i % (IDX_HEADS * IDX_DIM / 4);
217        float4 v = make_float4(0.f, 0.f, 0.f, 0.f);
218        if (q0 + r < nq) v = reinterpret_cast<const float4*>(q_idx + (q0 + r) * IDX_HEADS * IDX_DIM)[c];
219        *reinterpret_cast<float4*>(sQ + r * TC_QS + c * 4) = v;
220    }
221    if (t < TC_QT) s_nbid[t] = q0 + t < nq ? steps[(q0 + t) * kStepCount + kStepNBid] : 0;
222    int lo_nbid = 0x7fffffff, hi_nbid = 0;
223    __syncthreads();
224    for (int i = 0; i < TC_QT; ++i) {
225        if (q0 + i >= nq) break;
226        lo_nbid = min(lo_nbid, s_nbid[i]);
227        hi_nbid = max(hi_nbid, s_nbid[i]);
228    }
229    for (int it = 0; it < TC_ITER; ++it) {
230        const int64_t b0 = ((int64_t) blockIdx.x * TC_ITER + it) * TC_NB;
231        if (b0 >= reach || b0 >= hi_nbid) break;      // blocks >= every query's n_bid: nothing to score
232        __syncthreads();                              // the previous tile's reads are done
233        for (int i = t; i < TC_NB * IDX_DIM / 4; i += 128) {
234            const int r = i / (IDX_DIM / 4), c = i % (IDX_DIM / 4);
235            float4 v = make_float4(0.f, 0.f, 0.f, 0.f);
236            if (b0 + r < hi_nbid) v = reinterpret_cast<const float4*>(pooled + (b0 + r) * IDX_DIM)[c];
237            *reinterpret_cast<float4*>(sK + r * TC_KS + c * 4) = v;
238        }
239        __syncthreads();
240        float acc[IDX_HEADS][4];
241#pragma unroll
242        for (int h = 0; h < IDX_HEADS; ++h) acc[h][0] = acc[h][1] = acc[h][2] = acc[h][3] = 0.f;
243        const float* kr = sK + (warp * 8 + gid) * TC_KS;
244#pragma unroll 4
245        for (int k0 = 0; k0 < IDX_DIM; k0 += 8) {
246            const float kx0 = kr[k0 + tig], kx1 = kr[k0 + tig + 4];
247            uint32_t bh[2], bl[2];
248            bh[0] = tf32_hi(kx0);
249            bh[1] = tf32_hi(kx1);
250            bl[0] = tf32_hi(kx0 - __uint_as_float(bh[0]));
251            bl[1] = tf32_hi(kx1 - __uint_as_float(bh[1]));
252#pragma unroll
253            for (int h = 0; h < IDX_HEADS; ++h) {
254                const float* qa = sQ + h * IDX_DIM + k0 + tig;
255                const float x0 = qa[gid * TC_QS], x1 = qa[(gid + 8) * TC_QS];
256                const float x2 = qa[gid * TC_QS + 4], x3 = qa[(gid + 8) * TC_QS + 4];
257                uint32_t ah[4], al[4];
258                ah[0] = tf32_hi(x0); ah[1] = tf32_hi(x1); ah[2] = tf32_hi(x2); ah[3] = tf32_hi(x3);
259                al[0] = tf32_hi(x0 - __uint_as_float(ah[0]));
260                al[1] = tf32_hi(x1 - __uint_as_float(ah[1]));
261                al[2] = tf32_hi(x2 - __uint_as_float(ah[2]));
262                al[3] = tf32_hi(x3 - __uint_as_float(ah[3]));
263                mma_tf32(acc[h], al, bh);
264                mma_tf32(acc[h], ah, bl);
265                mma_tf32(acc[h], ah, bh);
266            }
267        }
268        // relu per head, heads added in order (as the warp kernel), written where the block completed for the query
269        const int64_t bc = b0 + warp * 8 + 2 * tig;
270#pragma unroll
271        for (int half = 0; half < 2; ++half) {
272            const int qr = gid + half * 8;
273            const int64_t qi = q0 + qr;
274            if (qi >= nq) continue;
275            const int nb = s_nbid[qr];
276#pragma unroll
277            for (int j = 0; j < 2; ++j) {
278                const int64_t b = bc + j;
279                if (b >= nb || b >= max_blocks) continue;
280                float score = 0.0f;
281#pragma unroll
282                for (int h = 0; h < IDX_HEADS; ++h) {
283                    const float d = acc[h][half * 2 + j];
284                    score += d > 0.0f ? d : 0.0f;
285                }
286                out[qi * max_blocks + b] = score;
287            }
288        }
289    }
290}
291
292#if defined(__HIPCC__)
293// ---- gfx12 (RDNA4: gfx1200 / gfx1201) scorer on v_wmma_f32_16x16x16_bf16 (wave32).  Same GEMM as above: for a tile of 16
294// queries, every block's score is sum over the 4 indexer heads of relu(q_h . k), K = 128.  FP32-level accuracy from a
295// three-way bf16 split of both operands (x = hi + mid + lo EXACTLY - the top 8, next 8 and last 8 bits of the fp32
296// mantissa, so bf16's fp32-sized exponent range needs no scaling) and the six products of order <= 2, smallest first;
297// like the TF32 kernel it sums in another order than the warp kernel (not bitwise).  The tail block n_bid is the warp
298// kernel's arithmetic (block_scores_tail_kernel).
299//   D = A x B with A = 16 key blocks (row l%16 of a lane, k = 8*(l/16)+i), B = 16 queries (column l%16, same k):
300//   a lane ends up with 8 consecutive blocks of ONE query, written as one run.  No LDS for keys: a lane reads its
301//   32-byte slice of the key row from global (the 16 query tiles of a launch re-read them from L2); the queries are
302//   split once per CTA into LDS.
303// gfx11 (RDNA3 / RDNA3.5) has the same instruction with another fragment layout: a lane holds all 16 k of its row
304// (A) or column (B) - lanes 16..31 repeat lanes 0..15 - and D[2i + l/16][l%16]; SEL_KL is the k per lane, SEL_KOFF(g)
305// the first, SEL_ROW(i, g) the D row of element i.  Same products, same order per element as on gfx12.
306#if defined(__gfx1200__) || defined(__gfx1201__)
307#define STRATA_SEL_GFX12 1
308#define STRATA_SEL_GFX11 0
309#elif defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1103__) || defined(__gfx1150__) || \
310    defined(__gfx1151__)
311#define STRATA_SEL_GFX12 0
312#define STRATA_SEL_GFX11 1
313#else
314#define STRATA_SEL_GFX12 0
315#define STRATA_SEL_GFX11 0
316#endif
317#if STRATA_SEL_GFX11
318constexpr int SEL_KL = 16;
319#define SEL_KOFF(g) 0
320#define SEL_ROW(i, g) (2 * (i) + (g))
321#else
322constexpr int SEL_KL = 8;
323#define SEL_KOFF(g) ((g) * 8)
324#define SEL_ROW(i, g) ((g) * 8 + (i))
325#endif
326typedef short sel_s8 __attribute__((ext_vector_type(SEL_KL)));
327typedef float sel_f8 __attribute__((ext_vector_type(8)));
328typedef uint32_t sel_u4 __attribute__((ext_vector_type(SEL_KL / 2)));
329constexpr int WQT = 16;                    // queries per CTA (the N of one WMMA)
330constexpr int WITER = 4;                   // key tiles per warp (the CTA covers 4 warps * WITER * 16 blocks)
331constexpr int WQS = IDX_DIM + 8;           // bf16 elements per LDS row: 272 bytes, conflict-free 16-byte reads
332
333__device__ __forceinline__ sel_f8 wmma_bf16(const sel_s8& a, const sel_s8& b, const sel_f8& c) {
334#if STRATA_SEL_GFX12
335    return __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32_gfx12(a, b, c);
336#elif STRATA_SEL_GFX11
337    return __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32(a, b, c);
338#else
339    __trap();
340    return c;
341#endif
342}
343// the bf16 pieces of x as fp32 bit patterns whose upper 16 bits are the bf16 (lower 16 are zero)
344__device__ __forceinline__ void split3(float x, uint32_t& hi, uint32_t& mid, uint32_t& lo) {
345    hi = __float_as_uint(x) & 0xffff0000u;
346    const float r1 = x - __uint_as_float(hi);                   // exact
347    mid = __float_as_uint(r1) & 0xffff0000u;
348    lo = __float_as_uint(r1 - __uint_as_float(mid)) & 0xffff0000u;   // exact: at most 8 significant bits left
349}
350__device__ __forceinline__ uint32_t pack_bf16x2(uint32_t a, uint32_t b) {   // low half = a's bf16, high half = b's
351#if STRATA_SEL_GFX12 || STRATA_SEL_GFX11
352    return __builtin_amdgcn_perm(b, a, 0x07060302u);
353#else
354    return (a >> 16) | (b & 0xffff0000u);
355#endif
356}
357
358__global__ void __launch_bounds__(128) block_scores_wmma_kernel(const float* __restrict__ pooled,
359                                                                const float* __restrict__ q_idx,
360                                                                const int32_t* __restrict__ steps, int64_t nq,
361                                                                int64_t max_blocks, int64_t reach,
362                                                                float* __restrict__ out) {
363    __shared__ __align__(16) uint16_t sq[3][IDX_HEADS][WQT][WQS];   // hi / mid / lo, [head][query][dim]
364    __shared__ int s_nbid[WQT];
365    const int t = threadIdx.x, lane = t & 31, warp = t >> 5, l16 = lane & 15, g = lane >> 4;
366    const int64_t q0 = (int64_t) blockIdx.y * WQT;
367    for (int i = t; i < WQT * IDX_HEADS * IDX_DIM / 4; i += 128) {
368        const int row = i / (IDX_DIM / 4), c = i % (IDX_DIM / 4);
369        const int qr = row / IDX_HEADS, h = row % IDX_HEADS;
370        float4 v = make_float4(0.f, 0.f, 0.f, 0.f);
371        if (q0 + qr < nq) v = reinterpret_cast<const float4*>(q_idx + (q0 + qr) * IDX_HEADS * IDX_DIM)[h * (IDX_DIM / 4) + c];
372        const float x[4] = {v.x, v.y, v.z, v.w};
373        uint32_t hb[4], mb[4], lb[4];
374#pragma unroll
375        for (int j = 0; j < 4; ++j) split3(x[j], hb[j], mb[j], lb[j]);
376        *reinterpret_cast<uint2*>(&sq[0][h][qr][c * 4]) = make_uint2(pack_bf16x2(hb[0], hb[1]), pack_bf16x2(hb[2], hb[3]));
377        *reinterpret_cast<uint2*>(&sq[1][h][qr][c * 4]) = make_uint2(pack_bf16x2(mb[0], mb[1]), pack_bf16x2(mb[2], mb[3]));
378        *reinterpret_cast<uint2*>(&sq[2][h][qr][c * 4]) = make_uint2(pack_bf16x2(lb[0], lb[1]), pack_bf16x2(lb[2], lb[3]));
379    }
380    if (t < WQT) s_nbid[t] = q0 + t < nq ? steps[(q0 + t) * kStepCount + kStepNBid] : 0;
381    __syncthreads();
382    int hi_nbid = 0;
383#pragma unroll
384    for (int i = 0; i < WQT; ++i) hi_nbid = max(hi_nbid, s_nbid[i]);
385    const int64_t qi = q0 + l16;
386    const int nb_q = s_nbid[l16];
387    for (int it = 0; it < WITER; ++it) {
388        const int64_t b0 = (((int64_t) blockIdx.x * WITER + it) * 4 + warp) * 16;
389        if (b0 >= reach || b0 >= hi_nbid) break;          // warp-uniform; later tiles start higher
390        const int64_t row = b0 + l16;
391        const bool rv = row < hi_nbid && row < max_blocks;
392        const float* kp = pooled + (rv ? row : 0) * IDX_DIM + SEL_KOFF(g);
393        // acc: the hi*hi products; cor: the five smaller ones (<= 2^-8 of it). Kept apart and added once at the end: a
394        // correction summed into the big accumulator is rounded to ITS ulp at every one of the 48 steps (measured: 8e-7
395        // of the score scale; apart, near the warp kernel's)
396        sel_f8 acc[IDX_HEADS], cor[IDX_HEADS];
397#pragma unroll
398        for (int h = 0; h < IDX_HEADS; ++h) acc[h] = cor[h] = sel_f8{0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f};
399#pragma unroll 2
400        for (int kk = 0; kk < IDX_DIM / 16; ++kk) {
401            float x[SEL_KL];
402#pragma unroll
403            for (int j = 0; j < SEL_KL / 4; ++j) {
404                float4 kv = make_float4(0.f, 0.f, 0.f, 0.f);
405                if (rv) kv = *reinterpret_cast<const float4*>(kp + kk * 16 + 4 * j);
406                x[4 * j] = kv.x; x[4 * j + 1] = kv.y; x[4 * j + 2] = kv.z; x[4 * j + 3] = kv.w;
407            }
408            uint32_t hb[SEL_KL], mb[SEL_KL], lb[SEL_KL];
409#pragma unroll
410            for (int j = 0; j < SEL_KL; ++j) split3(x[j], hb[j], mb[j], lb[j]);
411            sel_u4 ah, am, al;
412#pragma unroll
413            for (int j = 0; j < SEL_KL / 2; ++j) {
414                ah[j] = pack_bf16x2(hb[2 * j], hb[2 * j + 1]);
415                am[j] = pack_bf16x2(mb[2 * j], mb[2 * j + 1]);
416                al[j] = pack_bf16x2(lb[2 * j], lb[2 * j + 1]);
417            }
418            const sel_s8 Ah = __builtin_bit_cast(sel_s8, ah), Am = __builtin_bit_cast(sel_s8, am),
419                         Al = __builtin_bit_cast(sel_s8, al);
420#pragma unroll
421            for (int h = 0; h < IDX_HEADS; ++h) {
422                const sel_s8 Bh = *reinterpret_cast<const sel_s8*>(&sq[0][h][l16][kk * 16 + SEL_KOFF(g)]);
423                const sel_s8 Bm = *reinterpret_cast<const sel_s8*>(&sq[1][h][l16][kk * 16 + SEL_KOFF(g)]);
424                const sel_s8 Bl = *reinterpret_cast<const sel_s8*>(&sq[2][h][l16][kk * 16 + SEL_KOFF(g)]);
425                cor[h] = wmma_bf16(Al, Bh, cor[h]);
426                cor[h] = wmma_bf16(Ah, Bl, cor[h]);
427                cor[h] = wmma_bf16(Am, Bm, cor[h]);
428                cor[h] = wmma_bf16(Ah, Bm, cor[h]);
429                cor[h] = wmma_bf16(Am, Bh, cor[h]);
430                acc[h] = wmma_bf16(Ah, Bh, acc[h]);
431            }
432        }
433        // relu per head, heads added in order (as the warp kernel); this lane: query qi, blocks b0 + SEL_ROW(i, g)
434        if (qi < nq) {
435#pragma unroll
436            for (int i = 0; i < 8; ++i) {
437                const int64_t b = b0 + SEL_ROW(i, g);
438                if (b >= nb_q || b >= max_blocks) continue;
439                float score = 0.0f;
440#pragma unroll
441                for (int h = 0; h < IDX_HEADS; ++h) {
442                    const float d = acc[h][i] + cor[h][i];
443                    score += d > 0.0f ? d : 0.0f;
444                }
445                out[qi * max_blocks + b] = score;
446            }
447        }
448    }
449}
450
451// the WMMA kernel needs gfx12 (gfx1200/gfx1201) or gfx11 (gfx110x/gfx115x: the other fragment layout) code objects
452bool sel_gfx12_device() {
453    static int ok[64] = {};   // per device: 0 unknown, 1 yes, 2 no
454    int dev = 0;
455    if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return false; }
456    if (ok[dev] == 0) {
457        cudaDeviceProp prop;
458        ok[dev] = (cudaGetDeviceProperties(&prop, dev) == cudaSuccess &&
459                   (std::strncmp(prop.gcnArchName, "gfx1200", 7) == 0 || std::strncmp(prop.gcnArchName, "gfx1201", 7) == 0 ||
460                    strata::kernels::gfx_arch_is_gfx11_wmma(prop.gcnArchName)))
461                      ? 1 : 2;
462        cudaGetLastError();
463    }
464    return ok[dev] == 1;
465}
466
467// RDNA2 (gfx1030-gfx1036): the FP32 tiled scorer's tiling measured there
468bool sel_gfx103_device() {
469    static int ok[64] = {};   // per device: 0 unknown, 1 yes, 2 no
470    int dev = 0;
471    if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return false; }
472    if (ok[dev] == 0) {
473        cudaDeviceProp prop;
474        ok[dev] = (cudaGetDeviceProperties(&prop, dev) == cudaSuccess && std::strncmp(prop.gcnArchName, "gfx103", 6) == 0) ? 1 : 2;
475        cudaGetLastError();
476    }
477    return ok[dev] == 1;
478}
479#endif  // __HIPCC__
480
481// the tail block n_bid of each query: exactly block_scores_kernel's arithmetic for that block
482__global__ void __launch_bounds__(32) block_scores_tail_kernel(const float* __restrict__ dead,
483                                                               const float* __restrict__ q_idx,
484                                                               const int32_t* __restrict__ steps,
485                                                               int64_t max_blocks, float* __restrict__ out) {
486    const int64_t qi = blockIdx.x;
487    const int32_t* st = steps + qi * kStepCount;
488    const int64_t n_kv = st[kStepNKv], n_bid = st[kStepNBid];
489    if (n_bid >= max_blocks) return;
490    const int lane = threadIdx.x & 31;
491    const float4 k4 = *reinterpret_cast<const float4*>(dead + lane * 4);
492    const float* q = q_idx + qi * IDX_HEADS * IDX_DIM + lane * 4;
493    float score = 0.0f;
494#pragma unroll
495    for (int h = 0; h < IDX_HEADS; ++h) {
496        const float4 q4 = *reinterpret_cast<const float4*>(q + h * IDX_DIM);
497        float d = k4.x * q4.x + k4.y * q4.y + k4.z * q4.z + k4.w * q4.w;
498#pragma unroll
499        for (int o = 16; o > 0; o >>= 1) d += __shfl_xor_sync(0xffffffffu, d, o);
500        score += d > 0.0f ? d : 0.0f;
501    }
502    if (lane == 0) {
503        if (n_kv % R != 0) score += 1e9f;
504        out[qi * max_blocks + n_bid] = score;
505    }
506}
507
508// ---- the block scores as an FP32 tiled GEMM for cards without a matrix-core scorer (CUDA below sm_80; HIP, opt-in):
509// rows (query, indexer head) x columns (blocks), K = 128 through shared memory, 2 queries x 4 heads x TN blocks per
510// thread, relu per head summed in registers.  The warp kernel spends 5 shuffles per 4 products and reached ~1 TFLOPS
511// on an RTX 2080 Ti; this one ~6.9 (256 queries: 4.5x at 4K, 6.8x at 120K-250K).  FP32 like the warp kernel in another
512// summation order, so not bitwise (as the tensor-core scorer).  Blocks < n_bid only; the tail block is
513// block_scores_tail_kernel's.
514//
515// The tiling (QT queries and NB blocks per CTA, KC of K per shared-memory pass, TN blocks per thread) only decides
516// which thread computes which score: every score is still the fmaf chain over k = 0..127 in order and the same relu sum
517// over the heads, so every tiling gives the same bytes (an RX 6900 XT, qsa_select_bench at 32K and 128K, 14 tilings,
518// also with 60 and 72 of its 80 CUs: all byte-identical).  CUDA keeps the tiling it was written with (32/64/32/4);
519// gfx103x runs 32/128/16/8, 15% faster there at 128K (0.695 -> 0.587 ms per 256 queries).
520template <int QT, int NB, int KC, int TN>
521__global__ void __launch_bounds__(256) block_scores_simt_kernel(const float* __restrict__ pooled,
522                                                                const float* __restrict__ q_idx,
523                                                                const int32_t* __restrict__ steps, int64_t nq,
524                                                                int64_t max_blocks, int64_t reach,
525                                                                float* __restrict__ out) {
526    constexpr int ROWS = QT * IDX_HEADS, QS = ROWS + 4, KS = NB + 4, CX = NB / TN;
527    static_assert((ROWS / 8) * CX == 256, "256 threads, 8 rows (2 queries x 4 heads) each");
528    static_assert(TN % 4 == 0 && KC % 4 == 0 && IDX_DIM % KC == 0, "float4 loads");
529    __shared__ __align__(16) float Qs[KC][QS];
530    __shared__ __align__(16) float Ks[KC][KS];
531    const int64_t q0 = (int64_t) blockIdx.y * QT, b0 = (int64_t) blockIdx.x * NB;
532    const int64_t qlast = (q0 + QT < nq ? q0 + QT : nq) - 1;
533    if (b0 >= steps[qlast * kStepCount + kStepNBid]) return;   // n_bid rises with the position
534    const int tid = threadIdx.x, tx = tid % CX, ty = tid / CX;
535    float acc[8][TN] = {};
536    for (int kc = 0; kc < IDX_DIM; kc += KC) {
537        for (int idx = tid; idx < ROWS * (KC / 4); idx += 256) {   // the query rows: ROWS x KC/4 float4
538            const int r = idx / (KC / 4), k4 = idx % (KC / 4);
539            float4 v = make_float4(0.f, 0.f, 0.f, 0.f);
540            if (q0 + (r >> 2) < nq)
541                v = *reinterpret_cast<const float4*>(q_idx + (q0 * IDX_HEADS + r) * IDX_DIM + kc + k4 * 4);
542            Qs[k4 * 4 + 0][r] = v.x; Qs[k4 * 4 + 1][r] = v.y; Qs[k4 * 4 + 2][r] = v.z; Qs[k4 * 4 + 3][r] = v.w;
543        }
544        for (int idx = tid; idx < NB * (KC / 4); idx += 256) {   // the pooled keys: NB x KC/4 float4
545            const int c = idx / (KC / 4), k4 = idx % (KC / 4);
546            float4 v = make_float4(0.f, 0.f, 0.f, 0.f);
547            if (b0 + c < reach) v = *reinterpret_cast<const float4*>(pooled + (b0 + c) * IDX_DIM + kc + k4 * 4);
548            Ks[k4 * 4 + 0][c] = v.x; Ks[k4 * 4 + 1][c] = v.y; Ks[k4 * 4 + 2][c] = v.z; Ks[k4 * 4 + 3][c] = v.w;
549        }
550        __syncthreads();
551#pragma unroll 8
552        for (int k = 0; k < KC; ++k) {
553            float qr[8], kr[TN];
554            *reinterpret_cast<float4*>(&qr[0]) = *reinterpret_cast<const float4*>(&Qs[k][ty * 8]);
555            *reinterpret_cast<float4*>(&qr[4]) = *reinterpret_cast<const float4*>(&Qs[k][ty * 8 + 4]);
556#pragma unroll
557            for (int t = 0; t < TN; t += 4)
558                *reinterpret_cast<float4*>(&kr[t]) = *reinterpret_cast<const float4*>(&Ks[k][tx * TN + t]);
559#pragma unroll
560            for (int i = 0; i < 8; ++i)
561#pragma unroll
562                for (int j = 0; j < TN; ++j) acc[i][j] = fmaf(qr[i], kr[j], acc[i][j]);
563        }
564        __syncthreads();
565    }
566#pragma unroll
567    for (int i = 0; i < 2; ++i) {
568        const int64_t q = q0 + ty * 2 + i;
569        if (q >= nq) continue;
570        const int64_t n_bid = steps[q * kStepCount + kStepNBid];
571#pragma unroll
572        for (int j = 0; j < TN; ++j) {
573            const int64_t b = b0 + tx * TN + j;
574            if (b >= n_bid || b >= max_blocks) continue;
575            float sc = 0.0f;
576#pragma unroll
577            for (int h = 0; h < IDX_HEADS; ++h) {
578                const float d = acc[i * 4 + h][j];
579                sc += d > 0.0f ? d : 0.0f;
580            }
581            out[q * max_blocks + b] = sc;
582        }
583    }
584}
585
586// The FP32 tiled scores and the tail block; false when the grid does not fit.  `rdna2_tiles`: gfx103x's tiling.
587static bool block_scores_simt(const float* pooled, const float* dead, const float* q_idx, const int32_t* steps,
588                              int64_t nq, int64_t max_blocks, int64_t reach, float* scores, cudaStream_t stream,
589                              bool rdna2_tiles) {
590    const int64_t qt = 32, nb = rdna2_tiles ? 128 : 64;
591    const dim3 grid((unsigned) ((reach + nb - 1) / nb), (unsigned) ((nq + qt - 1) / qt));
592    if (grid.y > 65535) return false;
593    if (rdna2_tiles)
594        block_scores_simt_kernel<32, 128, 16, 8><<<grid, 256, 0, stream>>>(pooled, q_idx, steps, nq, max_blocks, reach, scores);
595    else
596        block_scores_simt_kernel<32, 64, 32, 4><<<grid, 256, 0, stream>>>(pooled, q_idx, steps, nq, max_blocks, reach, scores);
597    block_scores_tail_kernel<<<(unsigned) nq, 32, 0, stream>>>(dead, q_idx, steps, max_blocks, scores);
598    const cudaError_t e = cudaGetLastError();
599    if (e != cudaSuccess) { std::fprintf(stderr, "qsa_block_scores (simt): %s\n", cudaGetErrorString(e)); std::exit(1); }
600    return true;
601}
602
603// block_scores_simt_kernel with larger tiles (QT queries x NB blocks, RI x CJ products per thread) and the next K
604// chunk's loads in registers while the current one is used.  Every (row, block) dot is the same fmaf chain over
605// k = 0..127 from 0, and the relu sum over the heads in the same order: the same bits as block_scores_simt_kernel.
606// STRATA_SELECT_SIMT=2.
607constexpr int S2_KC = 32;
608template <int QT, int NB>
609__global__ void __launch_bounds__(256, 1) block_scores_simt2_kernel(const float* __restrict__ pooled,
610                                                                    const float* __restrict__ q_idx,
611                                                                    const int32_t* __restrict__ steps, int64_t nq,
612                                                                    int64_t max_blocks, int64_t reach,
613                                                                    float* __restrict__ out) {
614    constexpr int ROWS = QT * IDX_HEADS, RI = ROWS / 16, CJ = NB / 16, QS = ROWS + 4, KS = NB + 4;
615    constexpr int QL = ROWS * S2_KC / 4 / 256, KL = NB * S2_KC / 4 / 256;   // float4 loads per thread
616    static_assert(RI % 4 == 0 && CJ % 4 == 0 && QL >= 1 && KL >= 1, "tile");
617    __shared__ __align__(16) float Qs[S2_KC][QS];
618    __shared__ __align__(16) float Ks[S2_KC][KS];
619    const int64_t q0 = (int64_t) blockIdx.y * QT, b0 = (int64_t) blockIdx.x * NB;
620    const int64_t qlast = (q0 + QT < nq ? q0 + QT : nq) - 1;
621    if (b0 >= steps[qlast * kStepCount + kStepNBid]) return;   // n_bid rises with the position
622    const int tid = threadIdx.x, tx = tid & 15, ty = tid >> 4;
623    float acc[RI][CJ];
624#pragma unroll
625    for (int i = 0; i < RI; ++i)
626#pragma unroll
627        for (int j = 0; j < CJ; ++j) acc[i][j] = 0.0f;
628    float4 qv[QL], kv[KL];
629    auto load = [&](int kc) {
630#pragma unroll
631        for (int i = 0; i < QL; ++i) {
632            const int idx = tid + i * 256, r = idx >> 3, k4 = idx & 7;
633            qv[i] = make_float4(0.f, 0.f, 0.f, 0.f);
634            if (q0 + (r >> 2) < nq)
635                qv[i] = *reinterpret_cast<const float4*>(q_idx + (q0 * IDX_HEADS + r) * IDX_DIM + kc + k4 * 4);
636        }
637#pragma unroll
638        for (int i = 0; i < KL; ++i) {
639            const int idx = tid + i * 256, c = idx >> 3, k4 = idx & 7;
640            kv[i] = make_float4(0.f, 0.f, 0.f, 0.f);
641            if (b0 + c < reach) kv[i] = *reinterpret_cast<const float4*>(pooled + (b0 + c) * IDX_DIM + kc + k4 * 4);
642        }
643    };
644    load(0);
645#pragma unroll 1
646    for (int kc = 0; kc < IDX_DIM; kc += S2_KC) {
647#pragma unroll
648        for (int i = 0; i < QL; ++i) {
649            const int idx = tid + i * 256, r = idx >> 3, k4 = idx & 7;
650            Qs[k4 * 4 + 0][r] = qv[i].x; Qs[k4 * 4 + 1][r] = qv[i].y; Qs[k4 * 4 + 2][r] = qv[i].z; Qs[k4 * 4 + 3][r] = qv[i].w;
651        }
652#pragma unroll
653        for (int i = 0; i < KL; ++i) {
654            const int idx = tid + i * 256, c = idx >> 3, k4 = idx & 7;
655            Ks[k4 * 4 + 0][c] = kv[i].x; Ks[k4 * 4 + 1][c] = kv[i].y; Ks[k4 * 4 + 2][c] = kv[i].z; Ks[k4 * 4 + 3][c] = kv[i].w;
656        }
657        __syncthreads();
658        if (kc + S2_KC < IDX_DIM) load(kc + S2_KC);   // in flight during this chunk's products
659#pragma unroll 4
660        for (int k = 0; k < S2_KC; ++k) {
661            float qr[RI], kr[CJ];
662#pragma unroll
663            for (int m = 0; m < RI / 4; ++m) {
664                const float4 a = *reinterpret_cast<const float4*>(&Qs[k][ty * RI + 4 * m]);
665                qr[4 * m] = a.x; qr[4 * m + 1] = a.y; qr[4 * m + 2] = a.z; qr[4 * m + 3] = a.w;
666            }
667#pragma unroll
668            for (int g = 0; g < CJ / 4; ++g) {
669                const float4 b = *reinterpret_cast<const float4*>(&Ks[k][g * 64 + tx * 4]);
670                kr[4 * g] = b.x; kr[4 * g + 1] = b.y; kr[4 * g + 2] = b.z; kr[4 * g + 3] = b.w;
671            }
672#pragma unroll
673            for (int i = 0; i < RI; ++i)
674#pragma unroll
675                for (int j = 0; j < CJ; ++j) acc[i][j] = fmaf(qr[i], kr[j], acc[i][j]);
676        }
677        __syncthreads();
678    }
679#pragma unroll
680    for (int qi = 0; qi < RI / 4; ++qi) {
681        const int64_t q = q0 + ty * (RI / 4) + qi;
682        if (q >= nq) continue;
683        const int64_t n_bid = steps[q * kStepCount + kStepNBid];
684#pragma unroll
685        for (int j = 0; j < CJ; ++j) {
686            const int64_t b = b0 + (j >> 2) * 64 + tx * 4 + (j & 3);
687            if (b >= n_bid || b >= max_blocks) continue;
688            float sc = 0.0f;
689#pragma unroll
690            for (int h = 0; h < IDX_HEADS; ++h) {
691                const float d = acc[qi * 4 + h][j];
692                sc += d > 0.0f ? d : 0.0f;
693            }
694            out[q * max_blocks + b] = sc;
695        }
696    }
697}
698
699// ---- the same top-k with each query's keys read once: 1,024 threads hold up to TK_PER consecutive blocks' keys in
700// registers (contexts up to 4 * 1024 * TK_PER cells), per-warp histograms, block-wide scans. The selection rule is
701// block_topk_kernel's (radix threshold, ties to the lowest index, cells ascending): identical ids.
702constexpr int TK_T = 1024;
703constexpr int TK_PER = 33;
704#if defined(__HIPCC__)
705// AMD (RDNA, wave32): a 1,024-thread block may use 192 VGPRs per lane, so the keys of 66 blocks per thread fit - contexts
706// up to 4 * 1024 * 66 = 270,336 cells (the 262,144 --max-context) keep the register kernel. NVIDIA's 64 registers per
707// thread at 1,024 threads allow only TK_PER.
708constexpr int TK_PER_MAX = 66;
709#else
710constexpr int TK_PER_MAX = TK_PER;
711#endif
712
713__device__ __forceinline__ int block_excl_scan(int v, int* s_warp, int& total) {
714    const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5;
715    int x = v;
716#pragma unroll
717    for (int o = 1; o < 32; o <<= 1) {
718        const int y = __shfl_up_sync(0xffffffffu, x, o);
719        if (lane >= o) x += y;
720    }
721    if (lane == 31) s_warp[warp] = x;
722    __syncthreads();
723    if (warp == 0) {
724        int w = s_warp[lane];
725        int z = w;
726#pragma unroll
727        for (int o = 1; o < 32; o <<= 1) {
728            const int y = __shfl_up_sync(0xffffffffu, z, o);
729            if (lane >= o) z += y;
730        }
731        s_warp[lane] = z - w;               // exclusive per warp
732        if (lane == 31) s_warp[32] = z;     // total
733    }
734    __syncthreads();
735    const int r = s_warp[warp] + x - v;
736    total = s_warp[32];
737    __syncthreads();
738    return r;
739}
740
741template <int PER>
742__global__ void __launch_bounds__(TK_T) block_topk_reg_kernel(const float* __restrict__ scores,
743                                                              const int32_t* __restrict__ steps, int64_t max_blocks,
744                                                              int64_t cap, int32_t* __restrict__ ids) {
745    __shared__ int hist[TK_T / 32][256];
746    __shared__ int s_warp[33];
747    __shared__ int s_digit, s_above;
748    const int64_t qi = blockIdx.x;
749    const int32_t* st = steps + qi * kStepCount;
750    const int64_t n_kv = st[kStepNKv], n_bid = st[kStepNBid], width = st[kStepWidth];
751    int32_t* out = ids + qi * cap;
752    const int t = threadIdx.x, lane = t & 31, warp = t >> 5;
753    if (n_kv <= width) {
754        for (int64_t j = t; j < n_kv; j += TK_T) out[j] = (int32_t) j;
755        return;
756    }
757    const float* sc = scores + qi * max_blocks;
758    const int64_t nb = n_bid + 1;
759    const int64_t per = (nb + TK_T - 1) / TK_T;       // <= PER (the caller checks)
760    const int64_t b0 = (int64_t) t * per, b1 = (b0 + per < nb) ? b0 + per : nb;
761    uint32_t key[PER];
762#pragma unroll
763    for (int j = 0; j < PER; ++j) key[j] = (b0 + j < b1) ? order_key(sc[b0 + j]) : 0u;
764    auto weight = [&](int64_t b) -> int { return b < n_bid ? R : (int) (n_kv - n_bid * R); };
765    uint32_t prefix = 0;
766    int above = 0;
767    for (int shift = 24; shift >= 0; shift -= 8) {
768        for (int i = lane; i < 256; i += 32) hist[warp][i] = 0;
769        __syncwarp();
770        const uint32_t hi_mask = shift == 24 ? 0u : (0xffffffffu << (shift + 8));
771#pragma unroll
772        for (int j = 0; j < PER; ++j) {
773            const int64_t b = b0 + j;
774            if (b >= b1) break;
775            const int w = weight(b);
776            if (w == 0) continue;
777            if ((key[j] & hi_mask) == (prefix & hi_mask)) atomicAdd(&hist[warp][(key[j] >> shift) & 255], w);
778        }
779        __syncthreads();
780        if (t < 256) {                                // fold the warps' histograms into warp 0's
781            int s = 0;
782            for (int w2 = 0; w2 < TK_T / 32; ++w2) s += hist[w2][t];
783            hist[0][t] = s;
784        }
785        __syncthreads();
786        // the digit: the first bin from the top where the count above reaches `width` (bin 0 when none of 255..1
787        // does).  Threads 0-255 (warps 0-7) prefix-sum the 256 bins in descending order instead of one thread
788        // walking them: the same digit and count above.
789        int v = 0, x = 0;
790        if (t < 256) {
791            v = hist[0][255 - t];
792            x = v;
793#pragma unroll
794            for (int o = 1; o < 32; o <<= 1) {
795                const int y = __shfl_up_sync(0xffffffffu, x, o);
796                if (lane >= o) x += y;
797            }
798            if (lane == 31) s_warp[warp] = x;
799        }
800        __syncthreads();
801        if (t < 256) {
802            int inc = x;
803            for (int w2 = 0; w2 < warp; ++w2) inc += s_warp[w2];
804            const int before = above + inc - v;
805            if (before < width && (above + inc >= width || t == 255)) {
806                s_digit = 255 - t;
807                s_above = before;
808            }
809        }
810        __syncthreads();
811        prefix |= (uint32_t) s_digit << shift;
812        above = s_above;
813        __syncthreads();
814    }
815    const uint32_t thr = prefix;
816    const int64_t eq_budget = width - above;
817    int gt = 0, eq = 0;
818#pragma unroll
819    for (int j = 0; j < PER; ++j) {
820        const int64_t b = b0 + j;
821        if (b >= b1) break;
822        const int w = weight(b);
823        if (w == 0) continue;
824        if (key[j] > thr) gt += w;
825        else if (key[j] == thr) eq += w;
826    }
827    int tot;
828    const int eq_before = block_excl_scan(eq, s_warp, tot);
829    int64_t my_eq = eq_budget - eq_before;
830    if (my_eq < 0) my_eq = 0;
831    if (my_eq > eq) my_eq = eq;
832    const int sel = gt + (int) my_eq;
833    int64_t wpos = block_excl_scan(sel, s_warp, tot);
834    int64_t eq_left = my_eq;
835#pragma unroll
836    for (int j = 0; j < PER; ++j) {
837        const int64_t b = b0 + j;
838        if (b >= b1) break;
839        const int w = weight(b);
840        if (w == 0) continue;
841        if (key[j] > thr) {
842            for (int c = 0; c < w; ++c) out[wpos++] = (int32_t) (b * R + c);
843        } else if (key[j] == thr) {
844            for (int c = 0; c < w && eq_left > 0; ++c, --eq_left) out[wpos++] = (int32_t) (b * R + c);
845        }
846    }
847}
848
849// ---- a query with more blocks than the register kernel holds (contexts past 4 * 1024 * TK_PER cells): the register
850// kernel's threads, per-warp histograms and warp scans, with each key read from memory again on every pass.  A
851// histogram has no order, so on the four radix passes thread t reads blocks t, t + 1024, ...: a warp reads 32
852// neighbours at a time.  The cells are emitted ascending in the order (warp, row, lane): warp w holds the `per` rows
853// of 32 consecutive blocks from block w * 32 * per.  block_topk_kernel's selection rule (radix threshold, ties to the
854// lowest index): identical ids.
855// campaign3: also compiled on HIP (gfx11: plain shared/atomic code, no sm_90 features; the dispatch still needs
856// reach > fit, i.e. the deep contexts where the ref radix was the only option on AMD).
857constexpr int TS_MAXQ = 4096;
858__device__ int g_tk_fail[TS_MAXQ];   // block_topk_sample_kernel: 1 = the query is block_topk_wide_kernel<true>'s
859template <bool ONLY_FAILED = false>
860__global__ void __launch_bounds__(TK_T) block_topk_wide_kernel(const float* __restrict__ scores,
861                                                               const int32_t* __restrict__ steps, int64_t max_blocks,
862                                                               int64_t cap, int32_t* __restrict__ ids) {
863    if (ONLY_FAILED && !g_tk_fail[blockIdx.x]) return;
864    __shared__ int hist[TK_T / 32][256];
865    __shared__ int s_gt[TK_T / 32], s_eq[TK_T / 32];
866    __shared__ int s_digit, s_above;
867    const int64_t qi = blockIdx.x;
868    const int32_t* st = steps + qi * kStepCount;
869    const int64_t n_kv = st[kStepNKv], n_bid = st[kStepNBid], width = st[kStepWidth];
870    int32_t* out = ids + qi * cap;
871    const int t = threadIdx.x, lane = t & 31, warp = t >> 5;
872    if (n_kv <= width) {
873        for (int64_t j = t; j < n_kv; j += TK_T) out[j] = (int32_t) j;
874        return;
875    }
876    const float* sc = scores + qi * max_blocks;
877    const int64_t nb = n_bid + 1;
878    const int64_t per = (nb + TK_T - 1) / TK_T;       // rows of 32 blocks per warp
879    auto weight = [&](int64_t b) -> int { return b < n_bid ? R : (int) (n_kv - n_bid * R); };
880    uint32_t prefix = 0;
881    int above = 0;
882    for (int shift = 24; shift >= 0; shift -= 8) {
883        for (int i = lane; i < 256; i += 32) hist[warp][i] = 0;
884        __syncwarp();
885        const uint32_t hi_mask = shift == 24 ? 0u : (0xffffffffu << (shift + 8));
886        for (int64_t b = t; b < nb; b += TK_T) {
887            const int w = weight(b);
888            if (w == 0) continue;
889            const uint32_t k = order_key(sc[b]);
890            if ((k & hi_mask) == (prefix & hi_mask)) atomicAdd(&hist[warp][(k >> shift) & 255], w);
891        }
892        __syncthreads();
893        if (t < 256) {                                // fold the warps' histograms into warp 0's
894            int sum = 0;
895            for (int w2 = 0; w2 < TK_T / 32; ++w2) sum += hist[w2][t];
896            hist[0][t] = sum;
897        }
898        __syncthreads();
899        if (t == 0) {
900            int cum = above, d = 255;
901            for (; d > 0; --d) {
902                if (cum + hist[0][d] >= width) break;
903                cum += hist[0][d];
904            }
905            s_digit = d;
906            s_above = cum;
907        }
908        __syncthreads();
909        prefix |= (uint32_t) s_digit << shift;
910        above = s_above;
911        __syncthreads();
912    }
913    const uint32_t thr = prefix;
914    const int eq_budget = (int) (width - above);      // cells equal to thr that fit, lowest index first
915    const int64_t w0 = (int64_t) warp * 32 * per;
916    int gt = 0, eq = 0;
917    for (int64_t b = w0 + lane; b < nb && b < w0 + 32 * per; b += 32) {
918        const int w = weight(b);
919        if (w == 0) continue;
920        const uint32_t k = order_key(sc[b]);
921        if (k > thr) gt += w;
922        else if (k == thr) eq += w;
923    }
924#pragma unroll
925    for (int o = 16; o > 0; o >>= 1) {
926        gt += __shfl_xor_sync(0xffffffffu, gt, o);
927        eq += __shfl_xor_sync(0xffffffffu, eq, o);
928    }
929    if (lane == 0) { s_gt[warp] = gt; s_eq[warp] = eq; }
930    __syncthreads();
931    if (t == 0) {                                     // per warp: the selected cells and the tied cells before it
932        int eb = 0, sb = 0;
933        for (int w2 = 0; w2 < TK_T / 32; ++w2) {
934            const int g2 = s_gt[w2], e2 = s_eq[w2];
935            const int take = eq_budget - eb < 0 ? 0 : (eq_budget - eb > e2 ? e2 : eq_budget - eb);
936            s_gt[w2] = sb;
937            s_eq[w2] = eb;
938            sb += g2 + take;
939            eb += e2;
940        }
941    }
942    __syncthreads();
943    int run_sel = s_gt[warp], run_eq = s_eq[warp];
944    for (int64_t r0 = w0; r0 < nb && r0 < w0 + 32 * per; r0 += 32) {
945        const int64_t b = r0 + lane;
946        const int w = b < nb ? weight(b) : 0;
947        const uint32_t k = w ? order_key(sc[b]) : 0u;
948        const int my_gt = (w && k > thr) ? w : 0, my_eq = (w && k == thr) ? w : 0;
949        if (__ballot_sync(0xffffffffu, (my_gt | my_eq) != 0) == 0u) continue;   // a row without a selected block
950        int pe = my_eq;                               // tied cells up to and with this lane
951#pragma unroll
952        for (int o = 1; o < 32; o <<= 1) {
953            const int y = __shfl_up_sync(0xffffffffu, pe, o);
954            if (lane >= o) pe += y;
955        }
956        const int left = eq_budget - (run_eq + pe - my_eq);
957        const int take = left < 0 ? 0 : (left > my_eq ? my_eq : left);
958        const int my_sel = my_gt + take;
959        int ps = my_sel;
960#pragma unroll
961        for (int o = 1; o < 32; o <<= 1) {
962            const int y = __shfl_up_sync(0xffffffffu, ps, o);
963            if (lane >= o) ps += y;
964        }
965        int32_t* dst = out + run_sel + ps - my_sel;
966        for (int c = 0; c < my_sel; ++c) dst[c] = (int32_t) (b * R + c);
967        run_eq += __shfl_sync(0xffffffffu, pe, 31);
968        run_sel += __shfl_sync(0xffffffffu, ps, 31);
969    }
970}
971
972
973// Block scores with every key block read ONCE for all of a call's queries (block_scores_kernel's grid is
974// (max_blocks / 8) x nq: ~24,600 mostly-idle blocks per layer at a decode window, each key re-read per query).  A fixed
975// grid strides over the blocks; per (block, query) the same arithmetic in the same order as block_scores_kernel.
976// qsa_block_scores takes it for every call without an active-block count and at most MQ queries: the captured decode
977// window, the uncaptured decode, and prefill's pooled16 call.
978constexpr int MQ = 8;
979__device__ __forceinline__ void block_scores_multi_body(const float* __restrict__ pooled,
980                                                        const float* __restrict__ dead,
981                                                        const float* __restrict__ q_idx,
982                                                        const int32_t* __restrict__ steps, int nq, int64_t max_blocks,
983                                                        float* __restrict__ out, bool early_exit,
984                                                        const QsaScoreRows& srow) {
985    __shared__ __align__(16) float qs[MQ * IDX_HEADS * IDX_DIM];
986    __shared__ int64_t s_nkv[MQ], s_nbid[MQ];
987    if (!early_exit)
988        for (int i = threadIdx.x; i < nq * IDX_HEADS * IDX_DIM; i += blockDim.x) qs[i] = q_idx[i];
989    if (threadIdx.x < nq) {
990        s_nkv[threadIdx.x] = steps[threadIdx.x * kStepCount + kStepNKv];
991        s_nbid[threadIdx.x] = steps[threadIdx.x * kStepCount + kStepNBid];
992    }
993    __syncthreads();
994    int64_t top = 0;
995    for (int q = 0; q < nq; ++q) top = s_nbid[q] > top ? s_nbid[q] : top;
996    if (early_exit) {
997        // (#783, stuchapin909) a CTA whose first block is past the batch's largest n_bid has no work: the grid is a
998        // fixed 256 CTAs and a decode window reaches only a few of them, so those return before staging the queries.
999        // Every thread of the CTA takes the same branch (top and blockIdx are CTA-uniform), so the barrier is safe.
1000        if ((int64_t) blockIdx.x * SCORE_WARPS > top) return;
1001        for (int i = threadIdx.x; i < nq * IDX_HEADS * IDX_DIM; i += blockDim.x) qs[i] = q_idx[i];
1002        __syncthreads();
1003    }
1004    const int lane = threadIdx.x & 31;
1005    const int64_t wstride = (int64_t) gridDim.x * SCORE_WARPS;
1006    for (int64_t b = (int64_t) blockIdx.x * SCORE_WARPS + (threadIdx.x >> 5); b <= top && b < max_blocks; b += wstride) {
1007        // srow.n > 0: each query reads its own sequence's keys; else one set of keys for every query
1008        const bool own = srow.n > 0;
1009        const float4 kp = own ? float4{} : *reinterpret_cast<const float4*>(pooled + b * IDX_DIM + lane * 4);
1010        const float4 kd = own ? float4{} : *reinterpret_cast<const float4*>(dead + lane * 4);
1011        for (int qi = 0; qi < nq; ++qi) {
1012            const int64_t n_bid = s_nbid[qi];
1013            if (b > n_bid) continue;
1014            const float4 k4 = !own ? ((b == n_bid) ? kd : kp)
1015                            : (b == n_bid) ? *reinterpret_cast<const float4*>(srow.dead[qi] + lane * 4)
1016                                           : *reinterpret_cast<const float4*>(srow.pooled[qi] + b * IDX_DIM + lane * 4);
1017            const float* q = qs + qi * IDX_HEADS * IDX_DIM + lane * 4;
1018            float score = 0.0f;
1019#pragma unroll
1020            for (int h = 0; h < IDX_HEADS; ++h) {
1021                const float4 q4 = *reinterpret_cast<const float4*>(q + h * IDX_DIM);
1022                float d = k4.x * q4.x + k4.y * q4.y + k4.z * q4.z + k4.w * q4.w;
1023#pragma unroll
1024                for (int o = 16; o > 0; o >>= 1) d += __shfl_xor_sync(0xffffffffu, d, o);
1025                score += d > 0.0f ? d : 0.0f;
1026            }
1027            if (lane == 0) {
1028                if (b == n_bid && s_nkv[qi] % R != 0) score += 1e9f;
1029                out[qi * max_blocks + b] = score;
1030            }
1031        }
1032    }
1033}
1034
1035__global__ void __launch_bounds__(SCORE_WARPS * 32) block_scores_multi_kernel(const float* __restrict__ pooled,
1036                                                                              const float* __restrict__ dead,
1037                                                                              const float* __restrict__ q_idx,
1038                                                                              const int32_t* __restrict__ steps, int nq,
1039                                                                              int64_t max_blocks, float* __restrict__ out,
1040                                                                              bool early_exit, QsaScoreRows srow = {}) {
1041    block_scores_multi_body(pooled, dead, q_idx, steps, nq, max_blocks, out, early_exit, srow);
1042}
1043
1044// Queries of different slots, each with its own indexer keys: blockIdx.y is the query, and its CTAs run exactly the
1045// single-query call of block_scores_multi_kernel (qsa_block_scores_slots).
1046struct ScoreSlotKeys {
1047    const float* pooled[MQ];
1048    const float* dead[MQ];
1049};
1050__global__ void __launch_bounds__(SCORE_WARPS * 32) block_scores_slots_kernel(ScoreSlotKeys keys,
1051                                                                              const float* __restrict__ q_idx,
1052                                                                              const int32_t* __restrict__ steps,
1053                                                                              int64_t max_blocks, float* __restrict__ out,
1054                                                                              bool early_exit) {
1055    const unsigned z = blockIdx.y;
1056    // the slot's pointers picked by unrolled selects: indexing the argument array by z would copy it to local memory
1057    const float* pooled = keys.pooled[0];
1058    const float* dead = keys.dead[0];
1059#pragma unroll
1060    for (unsigned i = 1; i < MQ; ++i)
1061        if (z == i) { pooled = keys.pooled[i]; dead = keys.dead[i]; }
1062    block_scores_multi_body(pooled, dead, q_idx + (size_t) z * IDX_HEADS * IDX_DIM,
1063                            steps + (size_t) z * kStepCount, 1, max_blocks, out + (size_t) z * max_blocks, early_exit,
1064                            QsaScoreRows{});
1065}
1066
1067// QSAROWS (docs/QSAROWS.md, STRATA_QSA_ROWS=1): block_scores_multi_kernel's work for NQ <= 4 queries with less issue
1068// pressure per (block, query).  nsys of a 131k decode window (RTX 2080 Ti + RTX 3060): the multi kernel costs ~20 us more a
1069// call for every row of the window on both cards - per (block, query) it reads the four query slices from shared memory
1070// (4 x LDS.128) and reduces each head's lane products with its own five shuffles (20 a block and query), and those two
1071// pipes bound it, not the key reads (the keys are read once for all the queries, as there).  Here (1) the lane's slices
1072// of the NQ queries (4 heads x 4 floats each) live in registers for the whole kernel, (2) the four heads' lane products
1073// are reduce-scattered with warp_sum's pairing (xor 16, 8, then 4, 2, 1: six shuffles for the four heads) and gathered
1074// to lane 0 in head order (three more).  Every sum adds the same two operands as block_scores_kernel's warp_sum at the
1075// same level (float add commutes), the dot expression is the same text in the same file, the relu-and-add runs over the
1076// heads in the same order: the same score bits.  The tail block and the +1e9 are as in the multi kernel.
1077template <int NQ>
1078__global__ void __launch_bounds__(SCORE_WARPS * 32) block_scores_rows_kernel(const float* __restrict__ pooled,
1079                                                                             const float* __restrict__ dead,
1080                                                                             const float* __restrict__ q_idx,
1081                                                                             const int32_t* __restrict__ steps, int nq,
1082                                                                             int64_t max_blocks, float* __restrict__ out) {
1083    __shared__ int64_t s_nkv[NQ], s_nbid[NQ];
1084    if (threadIdx.x < nq) {
1085        s_nkv[threadIdx.x] = steps[threadIdx.x * kStepCount + kStepNKv];
1086        s_nbid[threadIdx.x] = steps[threadIdx.x * kStepCount + kStepNBid];
1087    }
1088    __syncthreads();
1089    int64_t top = 0;
1090    for (int q = 0; q < nq; ++q) top = s_nbid[q] > top ? s_nbid[q] : top;
1091    if ((int64_t) blockIdx.x * SCORE_WARPS > top) return;   // the multi kernel's early exit (CTA-uniform)
1092    const int lane = threadIdx.x & 31;
1093    float4 qr[NQ][IDX_HEADS];
1094#pragma unroll
1095    for (int qi = 0; qi < NQ; ++qi)
1096#pragma unroll
1097        for (int h = 0; h < IDX_HEADS; ++h)
1098            qr[qi][h] = qi < nq ? *reinterpret_cast<const float4*>(q_idx + qi * IDX_HEADS * IDX_DIM + h * IDX_DIM + lane * 4)
1099                                : make_float4(0.f, 0.f, 0.f, 0.f);
1100    const float4 kd = *reinterpret_cast<const float4*>(dead + lane * 4);
1101    const bool hi16 = (lane & 16) != 0, hi8 = (lane & 8) != 0;
1102    const int64_t wstride = (int64_t) gridDim.x * SCORE_WARPS;
1103    for (int64_t b = (int64_t) blockIdx.x * SCORE_WARPS + (threadIdx.x >> 5); b <= top && b < max_blocks; b += wstride) {
1104        const float4 kp = *reinterpret_cast<const float4*>(pooled + b * IDX_DIM + lane * 4);
1105#pragma unroll
1106        for (int qi = 0; qi < NQ; ++qi) {
1107            if (qi >= nq) break;
1108            const int64_t n_bid = s_nbid[qi];
1109            if (b > n_bid) continue;
1110            const float4 k4 = (b == n_bid) ? kd : kp;
1111            float d[IDX_HEADS];
1112#pragma unroll
1113            for (int h = 0; h < IDX_HEADS; ++h) {
1114                const float4 q4 = qr[qi][h];
1115                d[h] = k4.x * q4.x + k4.y * q4.y + k4.z * q4.z + k4.w * q4.w;
1116            }
1117            // reduce-scatter: after xor 16 the lane keeps heads {0,1} (bit 4 clear) or {2,3}; after xor 8 one head
1118            float r2[2];
1119#pragma unroll
1120            for (int i = 0; i < 2; ++i)
1121                r2[i] = (hi16 ? d[i + 2] : d[i]) + __shfl_xor_sync(0xffffffffu, hi16 ? d[i] : d[i + 2], 16);
1122            float r = (hi8 ? r2[1] : r2[0]) + __shfl_xor_sync(0xffffffffu, hi8 ? r2[0] : r2[1], 8);
1123            r += __shfl_xor_sync(0xffffffffu, r, 4);
1124            r += __shfl_xor_sync(0xffffffffu, r, 2);
1125            r += __shfl_xor_sync(0xffffffffu, r, 1);
1126            // lane 8h holds head h's full sum: gather to lane 0 and add the relus in head order, as the warp kernel
1127            const float s1 = __shfl_sync(0xffffffffu, r, 8);
1128            const float s2 = __shfl_sync(0xffffffffu, r, 16);
1129            const float s3 = __shfl_sync(0xffffffffu, r, 24);
1130            if (lane == 0) {
1131                float score = 0.0f;
1132                score += r > 0.0f ? r : 0.0f;
1133                score += s1 > 0.0f ? s1 : 0.0f;
1134                score += s2 > 0.0f ? s2 : 0.0f;
1135                score += s3 > 0.0f ? s3 : 0.0f;
1136                if (b == n_bid && s_nkv[qi] % R != 0) score += 1e9f;
1137                out[qi * max_blocks + b] = score;
1138            }
1139        }
1140    }
1141}
1142
1143#if defined(__HIPCC__)
1144// Optional gfx1100 port of PR1825 (14bf3215): same FP32 expression and reduction tree.
1145// Decode and the original top-k stay unchanged. No additional persistent weight/state allocation.
1146constexpr int TS_Q = 64;     // queries per CTA (8 per wave, four lanes per query)
1147constexpr int TS_KB = 32;    // key blocks per shared-memory tile
1148constexpr int TS_BR = 512;   // key blocks per CTA
1149
1150__device__ __forceinline__ float ts_part(const float4 k4, const float4 q4) {
1151    return k4.x * q4.x + k4.y * q4.y + k4.z * q4.z + k4.w * q4.w;   // block_scores_kernel's per-lane expression
1152}
1153
1154__global__ void __launch_bounds__(256, 1) block_scores_thread_kernel(const float* __restrict__ pooled,
1155                                                                    const float* __restrict__ q_idx,
1156                                                                    const int32_t* __restrict__ steps, int64_t nq,
1157                                                                    int64_t max_blocks, int64_t reach,
1158                                                                    float* __restrict__ out) {
1159    __shared__ __align__(16) float4 ks[TS_KB][IDX_DIM / 4];
1160    __shared__ float so[TS_Q][TS_KB + 1];
1161    __shared__ int64_t s_nbid[TS_Q];
1162    // Four lanes per query, lane j (0..3) one quarter of the tree for all four heads: the partials c[j] of lane 0's
1163    // xor-shuffle sum combine groups j, j+16, j+8, j+24, j+4, j+20, j+12, j+28, and only then do the quarters meet
1164    // (c0 + c2, c1 + c3, then their sum) - two shuffles here.  A key load now feeds four heads: four times fewer
1165    // shared-memory loads per FMA. The MIO-pipe motivation was measured by PR1825 on NVIDIA.
1166    constexpr int QG[8] = {0, 16, 8, 24, 4, 20, 12, 28};
1167    const int t = threadIdx.x, lane = t & 31;
1168    const int ql = (t >> 5) * 8 + (lane >> 2), j4 = lane & 3;   // this lane's query (in the CTA) and quarter
1169    const int64_t q0 = (int64_t) blockIdx.y * TS_Q, qi = q0 + ql;
1170    if (t < TS_Q) s_nbid[t] = q0 + t < nq ? steps[(q0 + t) * kStepCount + kStepNBid] : -1;
1171    float4 qv[IDX_HEADS][8];
1172    {
1173        const float4* src = reinterpret_cast<const float4*>(q_idx + (qi < nq ? qi : 0) * IDX_HEADS * IDX_DIM);
1174#pragma unroll
1175        for (int h = 0; h < IDX_HEADS; ++h)
1176#pragma unroll
1177            for (int m = 0; m < 8; ++m) qv[h][m] = src[h * (IDX_DIM / 4) + j4 + QG[m]];
1178    }
1179    __syncthreads();
1180    int64_t top = -1;   // the largest n_bid of the CTA's queries: blocks at or past it are never written here
1181    for (int i = 0; i < TS_Q; ++i) top = s_nbid[i] > top ? s_nbid[i] : top;
1182    const int64_t b_lo = (int64_t) blockIdx.x * TS_BR;
1183    int64_t b_hi = b_lo + TS_BR;
1184    if (b_hi > reach) b_hi = reach;
1185    if (b_hi > top) b_hi = top;
1186    if (b_hi > max_blocks) b_hi = max_blocks;
1187    for (int64_t b0 = b_lo; b0 < b_hi; b0 += TS_KB) {
1188        const int nb = (int) (b_hi - b0 < TS_KB ? b_hi - b0 : TS_KB);
1189        __syncthreads();   // the previous tile's reads of ks and so are done
1190        for (int i = t; i < nb * (IDX_DIM / 4); i += blockDim.x)
1191            ks[i / (IDX_DIM / 4)][i % (IDX_DIM / 4)] = reinterpret_cast<const float4*>(pooled + (b0 + i / (IDX_DIM / 4)) * IDX_DIM)[i % (IDX_DIM / 4)];
1192        __syncthreads();
1193        for (int j = 0; j < nb; ++j) {
1194            float4 kk[8];
1195#pragma unroll
1196            for (int m = 0; m < 8; ++m) kk[m] = ks[j][j4 + QG[m]];
1197            float e[IDX_HEADS];
1198#pragma unroll
1199            for (int h = 0; h < IDX_HEADS; ++h) {
1200                const float c = ((ts_part(kk[0], qv[h][0]) + ts_part(kk[1], qv[h][1])) +
1201                                 (ts_part(kk[2], qv[h][2]) + ts_part(kk[3], qv[h][3]))) +
1202                                ((ts_part(kk[4], qv[h][4]) + ts_part(kk[5], qv[h][5])) +
1203                                 (ts_part(kk[6], qv[h][6]) + ts_part(kk[7], qv[h][7])));
1204                const float d = c + __shfl_xor_sync(0xffffffffu, c, 2);   // lane 0: c0 + c2, lane 1: c1 + c3
1205                e[h] = d + __shfl_xor_sync(0xffffffffu, d, 1);           // lane 0: (c0 + c2) + (c1 + c3)
1206            }
1207            if (j4 == 0) {
1208                float score = 0.0f;
1209#pragma unroll
1210                for (int h = 0; h < IDX_HEADS; ++h) score += e[h] > 0.0f ? e[h] : 0.0f;
1211                so[ql][j] = score;
1212            }
1213        }
1214        __syncthreads();
1215        for (int i = t; i < TS_Q * nb; i += blockDim.x) {
1216            const int q = i / nb, j = i % nb;
1217            if (b0 + j < s_nbid[q]) out[(q0 + q) * max_blocks + b0 + j] = so[q][j];
1218        }
1219    }
1220}
1221
1222// The exact scorer runs on gfx1100 (the PR's own card) when STRATA_SCORES_THREAD=1, and on gfx12 (RDNA4) unless STRATA_SCORES_THREAD=0:
1223// there it is bitwise equal to the warp scorer on an R9700 (qsa_scores_gfx1100_parity --full, 35 cases; exact_pp residual dumps at 70K and
1224// 131K tokens) and 3.6-4.4x faster in the scorer stage, +8% (131K) to +15% (230K) on a prompt read.  Other wave32 parts have no measurement.
1225// Returns 0 (not offered), 1 (gfx1100: only on request), 2 (gfx12: the default).
1226int scores_thread_arch() {
1227    int device = -1;
1228    if (cudaGetDevice(&device) != cudaSuccess) { cudaGetLastError(); return 0; }
1229    static thread_local int cached_device = -1;
1230    static thread_local int arch = 0;
1231    if (device != cached_device) {
1232        cudaDeviceProp properties{};
1233        arch = 0;
1234        if (cudaGetDeviceProperties(&properties, device) == cudaSuccess)
1235            arch = gfx_arch_is_gfx12(properties.gcnArchName) ? 2 : gfx_arch_is(properties.gcnArchName, "gfx1100") ? 1 : 0;
1236        cached_device = device;
1237        cudaGetLastError();
1238    }
1239    return arch;
1240}
1241#endif
1242
1243#if !defined(__HIPCC__)
1244// ---- prompt calls on cards without the tensor-core scorer (Turing): block_scores_kernel's scores, BITWISE, with a
1245// thread per (query, head) instead of a warp per (query, block).  There a warp spends 20 shuffles and five 512-byte
1246// loads per score; here a lane holds its query head (128 floats) in registers, every lane of the warp reads the same
1247// key from shared memory (a broadcast), and the 4-value partials are added in the tree lane 0 of the xor-shuffle sum
1248// computes: partial g covers values 4g..4g+3, level o adds g and g + o.  Float addition is commutative, so the same
1249// pairs in the same tree give the same bits.  The heads are then summed 0..3 from 0.0f as there.  Blocks < n_bid only:
1250// the tail block n_bid (the `dead` key, +1e9) is block_scores_tail_kernel's.
1251constexpr int TS_Q = 64;     // queries per CTA (8 per warp, a lane per query head)
1252constexpr int TS_KB = 32;    // key blocks per shared-memory tile
1253constexpr int TS_BR = 512;   // key blocks per CTA
1254
1255__device__ __forceinline__ float ts_part(const float4 k4, const float4 q4) {
1256    return k4.x * q4.x + k4.y * q4.y + k4.z * q4.z + k4.w * q4.w;   // block_scores_kernel's per-lane expression
1257}
1258
1259__global__ void __launch_bounds__(256, 1) block_scores_thread_kernel(const float* __restrict__ pooled,
1260                                                                    const float* __restrict__ q_idx,
1261                                                                    const int32_t* __restrict__ steps, int64_t nq,
1262                                                                    int64_t max_blocks, int64_t reach,
1263                                                                    float* __restrict__ out) {
1264    __shared__ __align__(16) float4 ks[TS_KB][IDX_DIM / 4];
1265    __shared__ float so[TS_Q][TS_KB + 1];
1266    __shared__ int64_t s_nbid[TS_Q];
1267    // Four lanes per query, lane j (0..3) one quarter of the tree for all four heads: the partials c[j] of lane 0's
1268    // xor-shuffle sum combine groups j, j+16, j+8, j+24, j+4, j+20, j+12, j+28, and only then do the quarters meet
1269    // (c0 + c2, c1 + c3, then their sum) - two shuffles here.  A key load now feeds four heads: four times fewer
1270    // shared-memory loads per FMA (the kernel was bound by the MIO pipe, ncu: mio_throttle first).
1271    constexpr int QG[8] = {0, 16, 8, 24, 4, 20, 12, 28};
1272    const int t = threadIdx.x, lane = t & 31;
1273    const int ql = (t >> 5) * 8 + (lane >> 2), j4 = lane & 3;   // this lane's query (in the CTA) and quarter
1274    const int64_t q0 = (int64_t) blockIdx.y * TS_Q, qi = q0 + ql;
1275    if (t < TS_Q) s_nbid[t] = q0 + t < nq ? steps[(q0 + t) * kStepCount + kStepNBid] : -1;
1276    float4 qv[IDX_HEADS][8];
1277    {
1278        const float4* src = reinterpret_cast<const float4*>(q_idx + (qi < nq ? qi : 0) * IDX_HEADS * IDX_DIM);
1279#pragma unroll
1280        for (int h = 0; h < IDX_HEADS; ++h)
1281#pragma unroll
1282            for (int m = 0; m < 8; ++m) qv[h][m] = src[h * (IDX_DIM / 4) + j4 + QG[m]];
1283    }
1284    __syncthreads();
1285    int64_t top = -1;   // the largest n_bid of the CTA's queries: blocks at or past it are never written here
1286    for (int i = 0; i < TS_Q; ++i) top = s_nbid[i] > top ? s_nbid[i] : top;
1287    const int64_t b_lo = (int64_t) blockIdx.x * TS_BR;
1288    int64_t b_hi = b_lo + TS_BR;
1289    if (b_hi > reach) b_hi = reach;
1290    if (b_hi > top) b_hi = top;
1291    if (b_hi > max_blocks) b_hi = max_blocks;
1292    for (int64_t b0 = b_lo; b0 < b_hi; b0 += TS_KB) {
1293        const int nb = (int) (b_hi - b0 < TS_KB ? b_hi - b0 : TS_KB);
1294        __syncthreads();   // the previous tile's reads of ks and so are done
1295        for (int i = t; i < nb * (IDX_DIM / 4); i += blockDim.x)
1296            ks[i / (IDX_DIM / 4)][i % (IDX_DIM / 4)] = reinterpret_cast<const float4*>(pooled + (b0 + i / (IDX_DIM / 4)) * IDX_DIM)[i % (IDX_DIM / 4)];
1297        __syncthreads();
1298        for (int j = 0; j < nb; ++j) {
1299            float4 kk[8];
1300#pragma unroll
1301            for (int m = 0; m < 8; ++m) kk[m] = ks[j][j4 + QG[m]];
1302            float e[IDX_HEADS];
1303#pragma unroll
1304            for (int h = 0; h < IDX_HEADS; ++h) {
1305                const float c = ((ts_part(kk[0], qv[h][0]) + ts_part(kk[1], qv[h][1])) +
1306                                 (ts_part(kk[2], qv[h][2]) + ts_part(kk[3], qv[h][3]))) +
1307                                ((ts_part(kk[4], qv[h][4]) + ts_part(kk[5], qv[h][5])) +
1308                                 (ts_part(kk[6], qv[h][6]) + ts_part(kk[7], qv[h][7])));
1309                const float d = c + __shfl_xor_sync(0xffffffffu, c, 2);   // lane 0: c0 + c2, lane 1: c1 + c3
1310                e[h] = d + __shfl_xor_sync(0xffffffffu, d, 1);           // lane 0: (c0 + c2) + (c1 + c3)
1311            }
1312            if (j4 == 0) {
1313                float score = 0.0f;
1314#pragma unroll
1315                for (int h = 0; h < IDX_HEADS; ++h) score += e[h] > 0.0f ? e[h] : 0.0f;
1316                so[ql][j] = score;
1317            }
1318        }
1319        __syncthreads();
1320        for (int i = t; i < TS_Q * nb; i += blockDim.x) {
1321            const int q = i / nb, j = i % nb;
1322            if (b0 + j < s_nbid[q]) out[(q0 + q) * max_blocks + b0 + j] = so[q][j];
1323        }
1324    }
1325}
1326#endif
1327
1328#if !defined(__HIPCC__)
1329// ---- the decode top-k on a thread-block cluster (sm_90+; S19).  One CTA per query (block_topk_reg_kernel, or
1330// block_topk_kernel above 33,792 blocks: a --max-context over ~135K) makes four radix passes and two scans over up to
1331// 65,538 blocks on ONE SM while the rest of the GPU idles - a decode window has 1-5 queries.  Here a cluster of CL_N
1332// CTAs shares a query: CTA r holds the keys of blocks [r * per, (r + 1) * per) in shared memory, builds the digit
1333// histogram of its keys, and PUSHES it into slot r of every CTA's `hin` (distributed shared memory); after one cluster
1334// barrier each CTA sums the CL_N slots itself, so all of them take the same digit.  The emit pass needs each CTA's
1335// cells above / at the threshold: pushed the same way, then each CTA offsets its own by the ranks before it.
1336// RTX 5070, per call at capacity = context (decode_cluster_parity --bench): 21.9 -> 15.6 us at 32K, 58 -> 18 at 128K,
1337// 200 -> 22 at 262K (the one-CTA kernels' digit search was serial, too: one thread over 256 bins per pass).
1338//
1339// IDENTICAL IDS, by construction rather than by luck: the threshold thr (the width-th largest key, cells counted with
1340// their weights) and `above` (cells with a larger key) are pure functions of the multiset of (key, weight) - integer
1341// histograms, summed in any order - and the digit rule is block_topk_kernel's, written as a scan (the largest digit d
1342// whose cells at or above it reach `need`; 0 when none). The cells emitted are then fixed: every cell of a block with
1343// key > thr, and the first eq_budget = width - above cells at thr in ascending order (a block at thr may be cut),
1344// written in ascending cell order. Position of a thread's first cell = (cells above thr before it) + min(cells at thr
1345// before it, eq_budget): the telescoped sum of the reference's per-thread clamp. NaN keys are 0 (order_key) as there.
1346//
1347// Barriers: barrier.cluster arrive / wait (each CTA's threads all take part; it also orders the CTA's own shared
1348// memory, so it doubles as __syncthreads). Phase 0 is a relaxed arrive at entry, waited before the first remote store
1349// (a CTA's shared memory exists once it runs). Pushes go out before the arrive that releases them, and nothing reads
1350// another CTA's memory after the last wait - so a CTA may exit without a closing barrier (a wait counts the threads
1351// that have not exited). `hin` alternates by pass parity: CTA x reads slot buffer p&1 in pass p before arriving at
1352// pass p+1's barrier, and nobody writes buffer p&1 again (pass p+2) before waiting on that barrier.
1353constexpr int CL_N = 8;        // CTAs per query (the portable cluster size)
1354constexpr int CL_T = 1024;     // threads per CTA
1355constexpr int CL_MAXQ = 16;    // larger calls (prefill sub-batches) fill the GPU with one CTA per query already
1356#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 900
1357#define STRATA_SEL_CLUSTER 1
1358#else
1359#define STRATA_SEL_CLUSTER 0   // an older target's code is a trap; qsa_block_topk_cluster never launches it there
1360#endif
1361
1362#if STRATA_SEL_CLUSTER
1363__device__ __forceinline__ void cl_arrive_relaxed() {
1364    asm volatile("barrier.cluster.arrive.relaxed.aligned;\n" ::: "memory");
1365}
1366__device__ __forceinline__ void cl_arrive() { asm volatile("barrier.cluster.arrive.release.aligned;\n" ::: "memory"); }
1367__device__ __forceinline__ void cl_wait() { asm volatile("barrier.cluster.wait.acquire.aligned;\n" ::: "memory"); }
1368__device__ __forceinline__ unsigned cl_rank() {
1369    unsigned r;
1370    asm volatile("mov.u32 %0, %%cluster_ctarank;\n" : "=r"(r));
1371    return r;
1372}
1373template <typename T> __device__ __forceinline__ T* cl_map(T* p, unsigned rank) {   // p in CTA `rank`'s shared memory
1374    uint64_t o;
1375    asm volatile("mapa.u64 %0, %1, %2;\n" : "=l"(o) : "l"((uint64_t) p), "r"(rank));
1376    return reinterpret_cast<T*>(o);
1377}
1378// exclusive block scan of a 64-bit value over CL_T threads; `total` = the CTA's sum
1379__device__ __forceinline__ unsigned long long cl_excl_scan64(unsigned long long v, unsigned long long* s_warp,
1380                                                             unsigned long long& total) {
1381    const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5;
1382    unsigned long long x = v;
1383#pragma unroll
1384    for (int o = 1; o < 32; o <<= 1) {
1385        const unsigned long long y = __shfl_up_sync(0xffffffffu, x, o);
1386        if (lane >= o) x += y;
1387    }
1388    if (lane == 31) s_warp[warp] = x;
1389    __syncthreads();
1390    if (warp == 0) {
1391        const unsigned long long w = s_warp[lane];
1392        unsigned long long z = w;
1393#pragma unroll
1394        for (int o = 1; o < 32; o <<= 1) {
1395            const unsigned long long y = __shfl_up_sync(0xffffffffu, z, o);
1396            if (lane >= o) z += y;
1397        }
1398        s_warp[lane] = z - w;
1399        if (lane == 31) s_warp[32] = z;
1400    }
1401    __syncthreads();
1402    total = s_warp[32];
1403    return s_warp[warp] + x - v;
1404}
1405#endif
1406
1407// grid (CL_N, nq), cluster (CL_N, 1, 1), CL_T threads, dynamic shared memory: ceil(max_blocks / CL_N) keys
1408__global__ void __launch_bounds__(CL_T) block_topk_cluster_kernel(const float* __restrict__ scores,
1409                                                                  const int32_t* __restrict__ steps, int64_t max_blocks,
1410                                                                  int64_t cap, int32_t* __restrict__ ids) {
1411#if STRATA_SEL_CLUSTER
1412    extern __shared__ uint32_t keys[];                  // this CTA's blocks' keys
1413    __shared__ __align__(16) int hin[2][CL_N][256];     // the cluster's histograms, slot = the pushing rank
1414    __shared__ __align__(16) int hloc[2][256];          // this CTA's histogram
1415    __shared__ unsigned long long cnt[CL_N];            // per rank: its cells above thr (low 32 bits) and at it (high)
1416    __shared__ unsigned long long s_warp[33];
1417    __shared__ uint32_t s_prefix;
1418    __shared__ int s_above;
1419    const unsigned rank = cl_rank();
1420    const int t = threadIdx.x, lane = t & 31, warp = t >> 5;
1421    cl_arrive_relaxed();                                // phase 0: this CTA runs
1422    const int64_t qi = blockIdx.y;
1423    const int32_t* st = steps + qi * kStepCount;
1424    const int64_t n_kv = st[kStepNKv], n_bid = st[kStepNBid], width = st[kStepWidth];
1425    int32_t* out = ids + qi * cap;
1426    if (n_kv <= width) {                                // the identity, split over the cluster; no remote access
1427        for (int64_t j = (int64_t) rank * CL_T + t; j < n_kv; j += (int64_t) CL_N * CL_T) out[j] = (int32_t) j;
1428        return;
1429    }
1430    // the tail block n_bid weighs its cells (0..3); with none it is not a candidate (the reference skips w == 0)
1431    const int wtail = (int) (n_kv - n_bid * R);
1432    const int64_t nbe = n_bid + (wtail > 0 ? 1 : 0);
1433    const int64_t per = (nbe + CL_N - 1) / CL_N;       // <= ceil(max_blocks / CL_N), the keys the host sized
1434    const int64_t lo = (int64_t) rank * per < nbe ? (int64_t) rank * per : nbe;
1435    const int64_t hi = lo + per < nbe ? lo + per : nbe;
1436    const int n = (int) (hi - lo);
1437    const int tail_i = (wtail > 0 && n_bid >= lo && n_bid < hi) ? (int) (n_bid - lo) : -1;
1438    const float* sc = scores + qi * max_blocks + lo;
1439    for (int i = t; i < n; i += CL_T) keys[i] = order_key(sc[i]);
1440    for (int i = t; i < 2 * 256; i += CL_T) (&hloc[0][0])[i] = 0;
1441    __syncthreads();
1442    uint32_t prefix = 0;
1443    int above = 0;                                      // cells strictly above the digits fixed so far
1444    for (int pass = 0; pass < 4; ++pass) {
1445        const int shift = 24 - 8 * pass;
1446        const uint32_t hmask = pass == 0 ? 0u : (0xffffffffu << (shift + 8));
1447        int* hl = hloc[pass & 1];
1448        // warp-aggregated: the scores share their top bits, so plain atomics would queue on a few bins
1449        for (int i0 = 0; i0 < n; i0 += CL_T) {
1450            const int i = i0 + t;
1451            int bin = -1;
1452            if (i < n) {
1453                const uint32_t k = keys[i];
1454                if ((k & hmask) == prefix) bin = (int) ((k >> shift) & 255);
1455            }
1456            const unsigned same = __match_any_sync(0xffffffffu, bin);
1457            if (bin >= 0 && lane == __ffs(same) - 1) atomicAdd(&hl[bin], __popc(same) * R);
1458            if (bin >= 0 && i == tail_i) atomicAdd(&hl[bin], wtail - R);
1459        }
1460        __syncthreads();
1461        if (pass == 0) cl_wait();                       // phase 0 done: every CTA's shared memory is there
1462        for (int i = t; i < CL_N * 64; i += CL_T) {     // the histogram into slot `rank` of every CTA, as int4
1463            const int dst = i >> 6, c = i & 63;
1464            *cl_map(reinterpret_cast<int4*>(&hin[pass & 1][rank][0]) + c, (unsigned) dst) =
1465                reinterpret_cast<const int4*>(hl)[c];
1466        }
1467        for (int i = t; i < 256; i += CL_T) hloc[(pass + 1) & 1][i] = 0;
1468        cl_arrive();
1469        cl_wait();
1470        if (warp == 0) {
1471            // lane L owns digits 255 - 8L down to 248 - 8L; the digit holding the need-th cell from the top
1472            const int need = (int) width - above;
1473            int tot[8], part = 0;
1474#pragma unroll
1475            for (int k = 0; k < 8; ++k) {
1476                const int d = 255 - 8 * lane - k;
1477                int v = 0;
1478#pragma unroll
1479                for (int r = 0; r < CL_N; ++r) v += hin[pass & 1][r][d];
1480                tot[k] = v;
1481                part += v;
1482            }
1483            int incl = part;
1484#pragma unroll
1485            for (int o = 1; o < 32; o <<= 1) {
1486                const int y = __shfl_up_sync(0xffffffffu, incl, o);
1487                if (lane >= o) incl += y;
1488            }
1489            const int excl = incl - part;
1490            const unsigned hit = __ballot_sync(0xffffffffu, excl < need && incl >= need);
1491            // no hit cannot happen (the cells total n_kv > width); the reference would then take digit 0
1492            const int who = hit ? __ffs(hit) - 1 : 31;
1493            if (lane == who) {
1494                int acc = excl, k = 0;
1495                for (; k < 7; ++k) {
1496                    if (acc + tot[k] >= need) break;
1497                    acc += tot[k];
1498                }
1499                s_prefix = prefix | ((uint32_t) (255 - 8 * lane - k) << shift);
1500                s_above = above + acc;
1501            }
1502        }
1503        __syncthreads();
1504        prefix = s_prefix;
1505        above = s_above;
1506    }
1507    const uint32_t thr = prefix;
1508    const int64_t eq_budget = width - above;           // cells at thr that fit, lowest index first
1509    // each thread a contiguous run of the CTA's keys; an odd run length keeps the shared reads conflict-free
1510    int seg = (n + CL_T - 1) / CL_T;
1511    if ((seg & 1) == 0 && seg > 0) ++seg;
1512    const int s0 = t * seg < n ? t * seg : n, s1 = s0 + seg < n ? s0 + seg : n;
1513    uint32_t gt = 0, eq = 0;
1514    for (int i = s0; i < s1; ++i) {
1515        const uint32_t k = keys[i], w = i == tail_i ? (uint32_t) wtail : (uint32_t) R;
1516        if (k > thr) gt += w;
1517        else if (k == thr) eq += w;
1518    }
1519    unsigned long long cta;
1520    const unsigned long long before =
1521        cl_excl_scan64((unsigned long long) gt | ((unsigned long long) eq << 32), s_warp, cta);
1522    if (t < CL_N) *cl_map(&cnt[rank], (unsigned) t) = cta;
1523    cl_arrive();
1524    cl_wait();
1525    int64_t gt_off = 0, eq_off = 0;
1526    for (unsigned r = 0; r < rank; ++r) {
1527        gt_off += (int64_t) (cnt[r] & 0xffffffffu);
1528        eq_off += (int64_t) (cnt[r] >> 32);
1529    }
1530    const int64_t eq_before = eq_off + (int64_t) (before >> 32);
1531    int64_t wpos = gt_off + (int64_t) (before & 0xffffffffu) + (eq_before < eq_budget ? eq_before : eq_budget);
1532    int64_t eq_left = eq_budget - eq_before;
1533    if (eq_left < 0) eq_left = 0;
1534    for (int i = s0; i < s1; ++i) {
1535        const uint32_t k = keys[i];
1536        const int w = i == tail_i ? wtail : R;
1537        const int64_t b = lo + i;
1538        if (k > thr) {
1539            for (int c = 0; c < w; ++c) out[wpos++] = (int32_t) (b * R + c);
1540        } else if (k == thr) {
1541            for (int c = 0; c < w && eq_left > 0; ++c, --eq_left) out[wpos++] = (int32_t) (b * R + c);
1542        }
1543    }
1544#else
1545    (void) scores; (void) steps; (void) max_blocks; (void) cap; (void) ids;
1546    __trap();
1547#endif
1548}
1549#endif  // !__HIPCC__
1550bool scores_multi_on() {
1551    static const bool on = [] { const char* v = std::getenv("STRATA_SCORES_MULTI"); return v == nullptr || std::atoi(v) != 0; }();
1552    return on;
1553}
1554// STRATA_QSA_EARLY_EXIT=0 keeps the old staging (every CTA loads the queries first); the scores are the same bits
1555bool scores_early_exit() {
1556    static const bool on = [] { const char* v = std::getenv("STRATA_QSA_EARLY_EXIT"); return v == nullptr || std::atoi(v) != 0; }();
1557    return on;
1558}
1559
1560#if !defined(__HIPCC__) && defined(STRATA_EXPERIMENTAL_SM60)
1561// STRATA_SELECT_LONG (verify.cpp): the long-context decode select, qsa_block_scores_long / qsa_block_topk_long.
1562// ---- decode block scores bit for bit block_scores_multi_kernel's, without its shuffles (STRATA_SCORES_DX, default on
1563// 6.x, under STRATA_SELECT_LONG).  The multi kernel gives a block to a warp and pays 5 shuffles per head per (block, query) for 4 products per
1564// lane: on GP100 a decode window's call costs ~88 us more per query at 300K cells.  Here lane i of warp h builds, for
1565// block i of a 32-block tile and indexer head h, the same 32-leaf tree as block_scores_multi_kernel's xor butterfly (lanes visited in
1566// 5-bit-reversed order, depth-first: the xor butterfly's association) for every query of the call at once, the key
1567// staged once per tile in shared memory and read by all of the queries; the relu sum over the heads then runs in the
1568// warp kernel's order (0 + r0 + r1 + r2 + r3) from shared memory.  Blocks < n_bid; the tail block n_bid is
1569// block_scores_tail_kernel's (the multi kernel's arithmetic for it).  A fixed grid strides over the tiles below the
1570// call's largest n_bid (capturable).
1571__device__ __forceinline__ int dx_lane(int j) { return (int) (__brev((unsigned) j) >> 27); }   // 5-bit reversal
1572constexpr int DX_NB = 32;                   // blocks per tile: one per lane
1573constexpr int DX_T = 32 * IDX_HEADS;        // warp h: indexer head h
1574constexpr int DX_KS = IDX_DIM + 4;          // a key row in shared memory (a quarter warp's 16-byte reads: 32 banks)
1575
1576template <int NQ>
1577__global__ void __launch_bounds__(DX_T) block_scores_dx_kernel(const float* __restrict__ pooled,
1578                                                               const float* __restrict__ q_idx,
1579                                                               const int32_t* __restrict__ steps, int64_t max_blocks,
1580                                                               float* __restrict__ out) {
1581    extern __shared__ __align__(16) float dx_smem[];
1582    float* Ks = dx_smem;                                 // [DX_NB][DX_KS]
1583    float* Qs = Ks + DX_NB * DX_KS;                      // [NQ][IDX_HEADS][IDX_DIM]
1584    float* Ds = Qs + NQ * IDX_HEADS * IDX_DIM;           // [NQ][IDX_HEADS][DX_NB]: each head's sum, for the relu pass
1585    __shared__ int64_t s_nbid[NQ];
1586    const int t = threadIdx.x, lane = t & 31, h = t >> 5;
1587    if (t < NQ) s_nbid[t] = steps[t * kStepCount + kStepNBid];
1588    __syncthreads();
1589    int64_t top = 0;
1590#pragma unroll
1591    for (int q = 0; q < NQ; ++q) top = s_nbid[q] > top ? s_nbid[q] : top;
1592    if (top > max_blocks) top = max_blocks;
1593    if ((int64_t) blockIdx.x * DX_NB >= top) return;     // CTA-uniform
1594    for (int i = t; i < NQ * IDX_HEADS * IDX_DIM / 4; i += DX_T)
1595        reinterpret_cast<float4*>(Qs)[i] = reinterpret_cast<const float4*>(q_idx)[i];
1596    const float* krow = Ks + lane * DX_KS;
1597    // the next tile's keys in registers while this one is scored (coalesced: thread t row (t + 128 i) / 32, float4 t % 32)
1598    constexpr int PF = DX_NB * (IDX_DIM / 4) / DX_T;
1599    float4 pre[PF];
1600    const int64_t stride = (int64_t) gridDim.x * DX_NB;
1601    auto fetch = [&](int64_t tb) {
1602#pragma unroll
1603        for (int i = 0; i < PF; ++i) {
1604            const int idx = t + i * DX_T, row = idx / (IDX_DIM / 4), c4 = idx % (IDX_DIM / 4);
1605            pre[i] = tb + row < top ? __ldg(reinterpret_cast<const float4*>(pooled + (tb + row) * IDX_DIM) + c4)
1606                                    : make_float4(0.f, 0.f, 0.f, 0.f);
1607        }
1608    };
1609    fetch((int64_t) blockIdx.x * DX_NB);
1610    for (int64_t b0 = (int64_t) blockIdx.x * DX_NB; b0 < top; b0 += stride) {
1611#pragma unroll
1612        for (int i = 0; i < PF; ++i) {
1613            const int idx = t + i * DX_T, row = idx / (IDX_DIM / 4), c4 = idx % (IDX_DIM / 4);
1614            *reinterpret_cast<float4*>(Ks + row * DX_KS + c4 * 4) = pre[i];
1615        }
1616        __syncthreads();
1617        if (b0 + stride < top) fetch(b0 + stride);
1618        float half0[NQ], half1[NQ];
1619#pragma unroll 1
1620        for (int c = 0; c < 4; ++c) {
1621            float l0[NQ], l1[NQ], l2[NQ];
1622#pragma unroll
1623            for (int jj = 0; jj < 8; ++jj) {
1624                const int L = dx_lane(8 * c + jj);
1625                const float4 k4 = *reinterpret_cast<const float4*>(krow + L * 4);
1626#pragma unroll
1627                for (int q = 0; q < NQ; ++q) {
1628                    const float4 q4 = *reinterpret_cast<const float4*>(Qs + (q * IDX_HEADS + h) * IDX_DIM + L * 4);
1629                    const float d = k4.x * q4.x + k4.y * q4.y + k4.z * q4.z + k4.w * q4.w;
1630                    // the depth-first tree over the slice's 8 leaves (pairs, quads, the octet), then the octets
1631                    if (jj == 0 || jj == 2 || jj == 4 || jj == 6) l0[q] = d;
1632                    else if (jj == 1 || jj == 5) l1[q] = l0[q] + d;
1633                    else if (jj == 3) l2[q] = l1[q] + (l0[q] + d);
1634                    else {
1635                        const float oct = l2[q] + (l1[q] + (l0[q] + d));
1636                        if (c == 0) half0[q] = oct;
1637                        else if (c == 1) half0[q] = half0[q] + oct;
1638                        else if (c == 2) half1[q] = oct;
1639                        else half1[q] = half1[q] + oct;
1640                    }
1641                }
1642            }
1643        }
1644#pragma unroll
1645        for (int q = 0; q < NQ; ++q) Ds[(q * IDX_HEADS + h) * DX_NB + lane] = half0[q] + half1[q];
1646        __syncthreads();                                 // also: every warp is done reading Ks before the next tile
1647        for (int q = h; q < NQ; q += IDX_HEADS) {
1648            const int64_t b = b0 + lane;
1649            if (b >= s_nbid[q]) continue;
1650            float score = 0.0f;
1651#pragma unroll
1652            for (int hh = 0; hh < IDX_HEADS; ++hh) {
1653                const float d = Ds[(q * IDX_HEADS + hh) * DX_NB + lane];
1654                score += d > 0.0f ? d : 0.0f;
1655            }
1656            out[q * max_blocks + b] = score;
1657        }
1658    }
1659}
1660
1661// ---- the decode top-k over several CTAs per query without clusters (any CUDA card; on sm_6x by default under
1662// STRATA_SELECT_LONG).  A decode
1663// window's 1-5 queries otherwise run one 1,024-thread CTA each (block_topk_wide_kernel past ~135K cells) on one SM
1664// apiece: on GP100 0.39 ms per call at 300K cells and 1.15 ms at 1M, x12 QSA layers per window.  Here each query gets
1665// n CTAs (a grid of n x nq), CTA r taking blocks [r * per, (r + 1) * per), and the four radix passes, the count and the
1666// emit are six kernels in a row on the caller's stream - capturable, no co-residency or spin waits: the kernel boundary
1667// is the barrier.  Exchange goes through the caller's scratch (qsa_topk_multi_scratch_ints): pass 0's histograms one
1668// row per CTA (plain stores), passes 1-3 summed with atomics into rows the pass-0 kernel zeroes, (prefix, above) after
1669// each digit, and each warp's cells above / at the threshold.  Nothing is carried from one call to the next.
1670// Warp w of a CTA takes the rows [w * rpw, (w + 1) * rpw) of 32 consecutive blocks (lane l block l of a row: coalesced),
1671// MT_U rows' loads in flight at a time; the loops stay rolled (GP100's instruction cache: a fully unrolled 33-row body
1672// doubled every kernel's time).
1673//
1674// IDENTICAL IDS, as block_topk_cluster_kernel's: thr (the width-th largest key, cells counted with their weights) and
1675// `above` are pure functions of the integer histograms whatever order they are summed in, and the digit rule is
1676// block_topk_kernel's (the largest digit d >= 1 whose cells at or above it reach `need`, else 0), here as a 256-thread
1677// scan.  The emit writes every cell of a block above thr and the first eq_budget = width - above cells at thr, ascending
1678// (block_topk_wide_kernel's row emit, offset by the cells of the warps and CTAs before).
1679constexpr int MT_T = 256;                   // threads per CTA
1680constexpr int MT_W = MT_T / 32;             // warps per CTA
1681constexpr int MT_U = 4;                     // rows of loads in flight per warp
1682constexpr int MT_NMAX = 32;                 // CTAs per query, at most
1683constexpr int MT_MAXQ = 16;                 // more queries per call fill the GPU with one CTA each already
1684// scratch per query (int32): pass 0's rows [MT_NMAX][256], passes 1-3 [3][256], state [5][2], counts [MT_NMAX][MT_W][2]
1685constexpr int MT_ACC = MT_NMAX * 256, MT_STATE = MT_ACC + 3 * 256, MT_CNT = MT_STATE + 16;
1686constexpr int MT_Q_INTS = MT_CNT + 2 * MT_NMAX * MT_W + 64;
1687static_assert(MT_NMAX * MT_W <= MT_T, "the emit sums the earlier CTAs' warp counts one per thread");
1688
1689struct MtQuery {
1690    int64_t n_kv, n_bid, width, lo, hi, row0;   // row0: the first block of this warp's first row
1691    int rpw, wtail;
1692    bool all;                                    // n_kv <= width: every cell, nothing to select
1693};
1694
1695__device__ __forceinline__ MtQuery mt_query(const int32_t* __restrict__ steps) {
1696    const int32_t* st = steps + (int64_t) blockIdx.y * kStepCount;
1697    MtQuery m;
1698    m.n_kv = st[kStepNKv];
1699    m.n_bid = st[kStepNBid];
1700    m.width = st[kStepWidth];
1701    m.all = m.n_kv <= m.width;
1702    // the tail block n_bid weighs its cells (0..3); with none it is not a candidate (the reference skips w == 0)
1703    m.wtail = (int) (m.n_kv - m.n_bid * R);
1704    const int64_t nbe = m.n_bid + (m.wtail > 0 ? 1 : 0);
1705    const int64_t per = (nbe + gridDim.x - 1) / gridDim.x;
1706    m.lo = (int64_t) blockIdx.x * per < nbe ? (int64_t) blockIdx.x * per : nbe;
1707    m.hi = m.lo + per < nbe ? m.lo + per : nbe;
1708    m.rpw = (int) (((m.hi - m.lo + 31) / 32 + MT_W - 1) / MT_W);
1709    m.row0 = m.lo + (int64_t) (threadIdx.x >> 5) * m.rpw * 32;
1710    return m;
1711}
1712
1713// rows j0 .. j0 + MT_U - 1 of this warp: key[u] for block row0 + 32 (j0 + u) + lane (0 past hi or the warp's rows)
1714__device__ __forceinline__ void mt_load(const MtQuery& m, const float* __restrict__ sc, int j0, uint32_t (&key)[MT_U]) {
1715    const int lane = threadIdx.x & 31;
1716#pragma unroll
1717    for (int u = 0; u < MT_U; ++u) {
1718        const int64_t b = m.row0 + 32 * (j0 + u) + lane;
1719        key[u] = (j0 + u < m.rpw && b < m.hi) ? order_key(__ldg(sc + b)) : 0u;
1720    }
1721}
1722
1723// inclusive scan of one value per thread over the MT_T threads
1724template <typename V> __device__ __forceinline__ V mt_incl_scan(V v, V* s_w) {
1725    const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5;
1726    V x = v;
1727#pragma unroll
1728    for (int o = 1; o < 32; o <<= 1) {
1729        const V y = __shfl_up_sync(0xffffffffu, x, o);
1730        if (lane >= o) x += y;
1731    }
1732    if (lane == 31) s_w[warp] = x;
1733    __syncthreads();
1734    V off = 0;
1735    for (int w = 0; w < warp; ++w) off += s_w[w];
1736    __syncthreads();
1737    return x + off;
1738}
1739
1740// The digit at `shift` from the 256 counts (thread t holds digit 255 - t's): block_topk_kernel's rule.
1741__device__ __forceinline__ void mt_choose(int v, int64_t width, int shift, uint32_t& prefix, int& above, int* s_w,
1742                                          int* s_ex, int* s_i) {
1743    const int t = threadIdx.x;
1744    if (t == 0) *s_i = 255;                              // no digit >= 1 reaches it: 0, all of 1..255 above
1745    const int incl = mt_incl_scan(v, s_w);
1746    s_ex[t] = incl - v;
1747    const int64_t need = width - above;
1748    if (t < 255 && incl >= need && incl - v < need) *s_i = t;   // the one t where the running count crosses `need`
1749    __syncthreads();
1750    const int i = *s_i;
1751    prefix |= (uint32_t) (255 - i) << shift;
1752    above += s_ex[i];
1753    __syncthreads();
1754}
1755
1756// pass PASS's histogram of the CTA's keys under the prefix so far (PASS >= 1 first takes digit PASS - 1)
1757template <int PASS>
1758__global__ void __launch_bounds__(MT_T) block_topk_multi_hist_kernel(const float* __restrict__ scores,
1759                                                                     const int32_t* __restrict__ steps,
1760                                                                     int64_t max_blocks, int32_t* __restrict__ scratch) {
1761    __shared__ int h[MT_W][256];
1762    __shared__ int s_w[MT_W], s_ex[256], s_i;
1763    const MtQuery m = mt_query(steps);
1764    if (m.all) return;
1765    const int t = threadIdx.x, lane = t & 31, warp = t >> 5;
1766    const float* sc = scores + (int64_t) blockIdx.y * max_blocks;
1767    uint32_t key[MT_U];
1768    mt_load(m, sc, 0, key);                              // in flight while the digit is taken
1769    for (int i = t; i < MT_W * 256; i += MT_T) (&h[0][0])[i] = 0;
1770    int32_t* qs = scratch + (int64_t) blockIdx.y * MT_Q_INTS;
1771    uint32_t prefix = 0;
1772    int above = 0;
1773    if (PASS == 0) {
1774        if (blockIdx.x == 0)                            // passes 1-3 sum into these: zero them for this call
1775            for (int i = t; i < 3 * 256; i += MT_T) qs[MT_ACC + i] = 0;
1776    } else {
1777        int v = 0;
1778        if (PASS == 1) {                                 // pass 0: one row per CTA
1779#pragma unroll 8
1780            for (unsigned r = 0; r < gridDim.x; ++r) v += qs[r * 256 + 255 - t];
1781        } else {
1782            prefix = (uint32_t) qs[MT_STATE + 2 * (PASS - 1)];
1783            above = qs[MT_STATE + 2 * (PASS - 1) + 1];
1784            v = qs[MT_ACC + (PASS - 2) * 256 + 255 - t];
1785        }
1786        mt_choose(v, m.width, 32 - 8 * PASS, prefix, above, s_w, s_ex, &s_i);
1787        if (blockIdx.x == 0 && t == 0) {
1788            qs[MT_STATE + 2 * PASS] = (int) prefix;
1789            qs[MT_STATE + 2 * PASS + 1] = above;
1790        }
1791    }
1792    __syncthreads();
1793    const int shift = 24 - 8 * PASS;
1794    const uint32_t hmask = PASS == 0 ? 0u : (0xffffffffu << (shift + 8));
1795#pragma unroll 1
1796    for (int j0 = 0; j0 < m.rpw; j0 += MT_U) {           // uniform over the warp: the ballots see all its lanes
1797      if (j0 > 0) mt_load(m, sc, j0, key);
1798#pragma unroll
1799      for (int u = 0; u < MT_U; ++u) {
1800        if (j0 + u >= m.rpw) break;
1801        const int64_t b = m.row0 + 32 * (j0 + u) + lane;
1802        const int bin = (b < m.hi && (key[u] & hmask) == prefix) ? (int) ((key[u] >> shift) & 255) : -1;
1803        // the scores share their top bits: the lanes on the first lane's bin in one atomic (no __match_any_sync on 6.x)
1804        const unsigned pend = __ballot_sync(0xffffffffu, bin >= 0);
1805        if (pend) {
1806            const int leader = __ffs(pend) - 1;
1807            const int lb = __shfl_sync(0xffffffffu, bin, leader);
1808            const unsigned same = __ballot_sync(0xffffffffu, bin == lb);
1809            if (lane == leader) atomicAdd(&h[warp][lb], __popc(same) * R);
1810            else if (bin >= 0 && bin != lb) atomicAdd(&h[warp][bin], R);
1811        }
1812        if (bin >= 0 && b == m.n_bid) atomicAdd(&h[warp][bin], m.wtail - R);
1813      }
1814    }
1815    __syncthreads();
1816    int sum = 0;
1817#pragma unroll
1818    for (int w = 0; w < MT_W; ++w) sum += h[w][t];
1819    if (PASS == 0) qs[blockIdx.x * 256 + t] = sum;
1820    else if (sum != 0) atomicAdd(&qs[MT_ACC + (PASS - 1) * 256 + t], sum);
1821}
1822
1823// digit 3 (the threshold), then each warp's cells above it and at it
1824__global__ void __launch_bounds__(MT_T) block_topk_multi_count_kernel(const float* __restrict__ scores,
1825                                                                      const int32_t* __restrict__ steps,
1826                                                                      int64_t max_blocks, int32_t* __restrict__ scratch) {
1827    __shared__ int s_w[MT_W], s_ex[256], s_i;
1828    const MtQuery m = mt_query(steps);
1829    if (m.all) return;
1830    const int t = threadIdx.x, lane = t & 31, warp = t >> 5;
1831    const float* sc = scores + (int64_t) blockIdx.y * max_blocks;
1832    uint32_t key[MT_U];
1833    mt_load(m, sc, 0, key);
1834    int32_t* qs = scratch + (int64_t) blockIdx.y * MT_Q_INTS;
1835    uint32_t prefix = (uint32_t) qs[MT_STATE + 6];
1836    int above = qs[MT_STATE + 7];
1837    mt_choose(qs[MT_ACC + 2 * 256 + 255 - t], m.width, 0, prefix, above, s_w, s_ex, &s_i);
1838    if (blockIdx.x == 0 && t == 0) {
1839        qs[MT_STATE + 8] = (int) prefix;
1840        qs[MT_STATE + 9] = above;
1841    }
1842    const uint32_t thr = prefix;
1843    int gt = 0, eq = 0;
1844#pragma unroll 1
1845    for (int j0 = 0; j0 < m.rpw; j0 += MT_U) {
1846        if (j0 > 0) mt_load(m, sc, j0, key);
1847#pragma unroll
1848        for (int u = 0; u < MT_U; ++u) {
1849            const int64_t b = m.row0 + 32 * (j0 + u) + lane;
1850            if (j0 + u >= m.rpw || b >= m.hi) continue;
1851            const int w = b == m.n_bid ? m.wtail : R;
1852            if (key[u] > thr) gt += w;
1853            else if (key[u] == thr) eq += w;
1854        }
1855    }
1856#pragma unroll
1857    for (int o = 16; o > 0; o >>= 1) {
1858        gt += __shfl_xor_sync(0xffffffffu, gt, o);
1859        eq += __shfl_xor_sync(0xffffffffu, eq, o);
1860    }
1861    if (lane == 0) {
1862        qs[MT_CNT + 2 * (blockIdx.x * MT_W + warp)] = gt;
1863        qs[MT_CNT + 2 * (blockIdx.x * MT_W + warp) + 1] = eq;
1864    }
1865}
1866
1867// the cells, ascending: a warp's first cell goes after the cells the CTAs and warps before it selected
1868__global__ void __launch_bounds__(MT_T) block_topk_multi_emit_kernel(const float* __restrict__ scores,
1869                                                                     const int32_t* __restrict__ steps,
1870                                                                     int64_t max_blocks, int64_t cap,
1871                                                                     int32_t* __restrict__ ids,
1872                                                                     const int32_t* __restrict__ scratch) {
1873    __shared__ unsigned long long s_w[MT_W];
1874    const MtQuery m = mt_query(steps);
1875    const int t = threadIdx.x, lane = t & 31, warp = t >> 5;
1876    int32_t* out = ids + (int64_t) blockIdx.y * cap;
1877    if (m.all) {                                         // the identity, split over the CTAs
1878        for (int64_t j = (int64_t) blockIdx.x * MT_T + t; j < m.n_kv; j += (int64_t) gridDim.x * MT_T) out[j] = (int32_t) j;
1879        return;
1880    }
1881    const float* sc = scores + (int64_t) blockIdx.y * max_blocks;
1882    uint32_t key[MT_U];
1883    mt_load(m, sc, 0, key);
1884    const int32_t* qs = scratch + (int64_t) blockIdx.y * MT_Q_INTS;
1885    const uint32_t thr = (uint32_t) qs[MT_STATE + 8];
1886    const int eq_budget = (int) (m.width - qs[MT_STATE + 9]);   // cells at thr that fit, lowest index first
1887    // the cells of the warps before this one: the earlier CTAs' (one warp count per thread), then this CTA's
1888    unsigned long long c = 0;
1889    if (t < (int) blockIdx.x * MT_W)
1890        c = (unsigned long long) (unsigned) qs[MT_CNT + 2 * t] | ((unsigned long long) (unsigned) qs[MT_CNT + 2 * t + 1] << 32);
1891#pragma unroll
1892    for (int o = 16; o > 0; o >>= 1) c += __shfl_xor_sync(0xffffffffu, c, o);
1893    if (lane == 0) s_w[warp] = c;
1894    __syncthreads();
1895    unsigned long long before = 0;
1896    for (int w = 0; w < MT_W; ++w) before += s_w[w];
1897    for (int w = 0; w < warp; ++w) {
1898        const int i = (int) blockIdx.x * MT_W + w;
1899        before += (unsigned long long) (unsigned) qs[MT_CNT + 2 * i] |
1900                  ((unsigned long long) (unsigned) qs[MT_CNT + 2 * i + 1] << 32);
1901    }
1902    const int gt_before = (int) (before & 0xffffffffu), eq_before = (int) (before >> 32);
1903    int run_sel = gt_before + (eq_before < eq_budget ? eq_before : eq_budget), run_eq = eq_before;
1904#pragma unroll 1
1905    for (int j0 = 0; j0 < m.rpw; j0 += MT_U) {
1906      if (j0 > 0) mt_load(m, sc, j0, key);
1907#pragma unroll
1908      for (int u = 0; u < MT_U; ++u) {
1909        if (j0 + u >= m.rpw) break;
1910        const int64_t b = m.row0 + 32 * (j0 + u) + lane;
1911        const int w = b < m.hi ? (b == m.n_bid ? m.wtail : R) : 0;
1912        const uint32_t k = key[u];
1913        const int my_gt = (w && k > thr) ? w : 0, my_eq = (w && k == thr) ? w : 0;
1914        if (__ballot_sync(0xffffffffu, (my_gt | my_eq) != 0) == 0u) continue;   // a row without a selected block
1915        int pe = my_eq;                                  // tied cells up to and with this lane
1916#pragma unroll
1917        for (int o = 1; o < 32; o <<= 1) {
1918            const int y = __shfl_up_sync(0xffffffffu, pe, o);
1919            if (lane >= o) pe += y;
1920        }
1921        const int left = eq_budget - (run_eq + pe - my_eq);
1922        const int take = left < 0 ? 0 : (left > my_eq ? my_eq : left);
1923        const int my_sel = my_gt + take;
1924        int ps = my_sel;
1925#pragma unroll
1926        for (int o = 1; o < 32; o <<= 1) {
1927            const int y = __shfl_up_sync(0xffffffffu, ps, o);
1928            if (lane >= o) ps += y;
1929        }
1930        int32_t* dst = out + run_sel + ps - my_sel;
1931        for (int cc = 0; cc < my_sel; ++cc) dst[cc] = (int32_t) (b * R + cc);
1932        run_eq += __shfl_sync(0xffffffffu, pe, 31);
1933        run_sel += __shfl_sync(0xffffffffu, ps, 31);
1934      }
1935    }
1936}
1937#endif  // !__HIPCC__ && STRATA_EXPERIMENTAL_SM60
1938}  // namespace
1939
1940bool qsa_block_scores_slots(const float* const* pooled, const float* const* dead, const float* q_idx,
1941                            const int32_t* steps, int64_t nq, int64_t max_blocks, const QsaShapes& s, float* scores,
1942                            void* stream) {
1943    if (nq <= 0) return true;
1944    if (s.idx_dim != IDX_DIM || s.idx_n_head != IDX_HEADS || s.idx_block != R) {
1945        std::fprintf(stderr, "qsa_block_scores_slots: unsupported indexer geometry\n");
1946        std::exit(1);
1947    }
1948    if (nq > MQ || !scores_multi_on()) return false;   // the single-query call would not run the multi kernel
1949    ScoreSlotKeys keys{};
1950    for (int64_t z = 0; z < nq; ++z) {
1951        keys.pooled[z] = pooled[z];
1952        keys.dead[z] = dead[z];
1953    }
1954    block_scores_slots_kernel<<<dim3(256, (unsigned) nq), SCORE_WARPS * 32, 0, (cudaStream_t) stream>>>(
1955        keys, q_idx, steps, max_blocks, scores, scores_early_exit());
1956    const cudaError_t e = cudaGetLastError();
1957    if (e != cudaSuccess) { std::fprintf(stderr, "qsa_block_scores_slots: %s\n", cudaGetErrorString(e)); std::exit(1); }
1958    return true;
1959}
1960
1961// block_scores_multi_kernel with the warp sums as one recursive-halving reduction.  A (query, head) dot is a lane's
1962// 4-term product summed over the 32 lanes by an xor butterfly (offsets 16, 8, 4, 2, 1): 5 shuffles per value, 20 per
1963// (block, query) - on Turing the decode scorer's time grew with the window's queries (420K cells: 117 / 265 / 509 us
1964// for 1 / 3 / 6 queries), the shuffles, not the keys.  Here the V = 4 x queries values (padded to a power of 2) are
1965// reduced together: at offset o each lane keeps half of its values and adds its partner's copy of them - the pair
1966// (lane l, lane l ^ o) the butterfly adds for that value at that offset, so every value's additions are the
1967// butterfly's, operand for operand (float addition commutes): the same bits, with V - 1 shuffles plus the plain
1968// butterfly's remaining stages instead of 5 V.  Lane l ends with value (l >> (5 - log2 V)); the query's 4 heads are
1969// then gathered by its head-0 lane and summed in block_scores_multi_kernel's order.  STRATA_SCORES_HALVE=0: the old kernel.
1970template <int V>
1971__global__ void __launch_bounds__(SCORE_WARPS * 32) block_scores_halve_kernel(const float* __restrict__ pooled,
1972                                                                              const float* __restrict__ dead,
1973                                                                              const float* __restrict__ q_idx,
1974                                                                              const int32_t* __restrict__ steps, int nq,
1975                                                                              int64_t max_blocks, float* __restrict__ out) {
1976    constexpr int NQ = V / IDX_HEADS;              // query slots (nq <= NQ)
1977    constexpr int LV = V == 4 ? 2 : V == 8 ? 3 : V == 16 ? 4 : 5, SH = 5 - LV;
1978    static_assert(V == 4 || V == 8 || V == 16 || V == 32, "V");
1979    __shared__ __align__(16) float qs[NQ * IDX_HEADS * IDX_DIM];
1980    __shared__ int64_t s_nkv[NQ], s_nbid[NQ];
1981    if (threadIdx.x < NQ) {
1982        s_nkv[threadIdx.x] = threadIdx.x < nq ? steps[threadIdx.x * kStepCount + kStepNKv] : 0;
1983        s_nbid[threadIdx.x] = threadIdx.x < nq ? steps[threadIdx.x * kStepCount + kStepNBid] : -1;
1984    }
1985    __syncthreads();
1986    int64_t top = 0;
1987    for (int q = 0; q < nq; ++q) top = s_nbid[q] > top ? s_nbid[q] : top;
1988    if ((int64_t) blockIdx.x * SCORE_WARPS > top) return;   // CTA-uniform (as block_scores_multi_kernel's early exit)
1989    for (int i = threadIdx.x; i < NQ * IDX_HEADS * IDX_DIM; i += blockDim.x)
1990        qs[i] = i < nq * IDX_HEADS * IDX_DIM ? q_idx[i] : 0.0f;
1991    __syncthreads();
1992    const int lane = threadIdx.x & 31;
1993    const int64_t wstride = (int64_t) gridDim.x * SCORE_WARPS;
1994    const float4 kd = *reinterpret_cast<const float4*>(dead + lane * 4);
1995    // up to 4 queries: the lane's query values in registers (read once, not once per block from shared memory: the
1996    // shared-memory reads were the kernel's limit, ncu mio_throttle)
1997    constexpr bool QREG = V <= 16;
1998    float4 qr[QREG ? V : 1];
1999    if constexpr (QREG) {
2000#pragma unroll
2001        for (int i = 0; i < V; ++i) qr[i] = *reinterpret_cast<const float4*>(qs + (i >> 2) * IDX_HEADS * IDX_DIM + (i & 3) * IDX_DIM + lane * 4);
2002    }
2003    int s_nbid_r[NQ];                               // n_bid < 2^31
2004#pragma unroll
2005    for (int qi = 0; qi < NQ; ++qi) s_nbid_r[qi] = (int) s_nbid[qi];
2006    for (int64_t b = (int64_t) blockIdx.x * SCORE_WARPS + (threadIdx.x >> 5); b <= top && b < max_blocks; b += wstride) {
2007        const float4 kp = *reinterpret_cast<const float4*>(pooled + b * IDX_DIM + lane * 4);
2008        float v[V];
2009#pragma unroll
2010        for (int qi = 0; qi < NQ; ++qi) {
2011            const float4 k4 = (b == s_nbid_r[qi]) ? kd : kp;
2012            const float* q = qs + qi * IDX_HEADS * IDX_DIM + lane * 4;
2013#pragma unroll
2014            for (int h = 0; h < IDX_HEADS; ++h) {
2015                float4 q4;
2016                if constexpr (QREG) q4 = qr[qi * IDX_HEADS + h];
2017                else q4 = *reinterpret_cast<const float4*>(q + h * IDX_DIM);
2018                v[qi * IDX_HEADS + h] = k4.x * q4.x + k4.y * q4.y + k4.z * q4.z + k4.w * q4.w;
2019            }
2020        }
2021        // recursive halving over offsets 16, 8, ... while more than one value is left, then the plain butterfly
2022        int cnt = V;
2023#pragma unroll
2024        for (int o = 16; o > 0; o >>= 1) {
2025            if (cnt > 1) {
2026                const int half = cnt >> 1;
2027                const bool hi = (lane & o) != 0;
2028#pragma unroll
2029                for (int i = 0; i < V / 2; ++i) {
2030                    if (i < half) {
2031                        const float send = hi ? v[i] : v[i + half];
2032                        const float keep = hi ? v[i + half] : v[i];
2033                        const float recv = __shfl_xor_sync(0xffffffffu, send, o);
2034                        v[i] = keep + recv;
2035                    }
2036                }
2037                cnt = half;
2038            } else {
2039                v[0] += __shfl_xor_sync(0xffffffffu, v[0], o);
2040            }
2041        }
2042        // lane l holds value j = l >> SH = qi * 4 + h; the head-0 lane of each query gathers heads 1-3
2043        const int j = lane >> SH, qi = j >> 2;
2044        const float d1 = __shfl_sync(0xffffffffu, v[0], (lane + (1 << SH)) & 31);
2045        const float d2 = __shfl_sync(0xffffffffu, v[0], (lane + (2 << SH)) & 31);
2046        const float d3 = __shfl_sync(0xffffffffu, v[0], (lane + (3 << SH)) & 31);
2047        if ((j & 3) == 0 && (lane & ((1 << SH) - 1)) == 0 && qi < nq && b <= s_nbid_r[qi & (NQ - 1)]) {
2048            const float d[4] = {v[0], d1, d2, d3};
2049            float score = 0.0f;
2050#pragma unroll
2051            for (int h = 0; h < IDX_HEADS; ++h) score += d[h] > 0.0f ? d[h] : 0.0f;
2052            if (b == s_nbid_r[qi & (NQ - 1)] && s_nkv[qi] % R != 0) score += 1e9f;
2053            out[qi * max_blocks + b] = score;
2054        }
2055    }
2056}
2057
2058// #1825: the prompt path's thread-per-head scorer (bitwise the warp kernel's scores).  Default: Turing with
2059// STRATA_SM75_PERF=1 (the P100 gain measured here is +1..3% at 30-60K tokens, under the 3% bar for a new default);
2060// STRATA_SCORES_THREAD=1 turns it on, =0 off, on any CUDA card
2061bool scores_thread_on() {
2062    static const int env = [] { const char* v = std::getenv("STRATA_SCORES_THREAD"); return v ? (std::atoi(v) != 0 ? 1 : 0) : -1; }();
2063    if (env >= 0) return env != 0;
2064    static int ok[64] = {};   // 0 unknown, 1 yes, 2 no
2065    int dev = 0;
2066    if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return false; }
2067    if (ok[dev] == 0) {
2068        int major = 0, minor = 0;
2069        cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev);
2070        cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev);
2071        ok[dev] = strata::sm75_default(major, minor) ? 1 : 2;   // Turing, STRATA_SM75_PERF=1
2072    }
2073    return ok[dev] == 1;
2074}
2075
2076bool scores_halve_on() {
2077    static const int env = [] { const char* v = std::getenv("STRATA_SCORES_HALVE"); return v ? (std::atoi(v) != 0 ? 1 : 0) : -1; }();
2078    if (env >= 0) return env != 0;
2079    static int ok[64] = {};   // 0 unknown, 1 yes, 2 no
2080    int dev = 0;
2081    if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return false; }
2082    if (ok[dev] == 0) {
2083        int major = 0, minor = 0;
2084        cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev);
2085        cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev);
2086        ok[dev] = strata::sm75_default(major, minor) ? 1 : 2;   // Turing, STRATA_SM75_PERF=1
2087    }
2088    return ok[dev] == 1;
2089}
2090
2091void qsa_block_scores(const float* pooled, const float* dead, const float* q_idx, const int32_t* steps, int64_t nq,
2092                      int64_t max_blocks, const QsaShapes& s, float* scores, void* stream, int64_t active_blocks) {
2093    if (nq <= 0) return;
2094    if (s.idx_dim != IDX_DIM || s.idx_n_head != IDX_HEADS || s.idx_block != R || nq > 65535) {
2095        std::fprintf(stderr, "qsa_block_scores: unsupported indexer geometry\n");
2096        std::exit(1);
2097    }
2098    // a block past a query's n_bid returns at once: the grid need only reach the batch's largest n_bid (C-1)
2099    if (scores_multi_on() && nq <= MQ && active_blocks <= 0) {   // no active count: decode (captured or not) and prefill's pooled16
2100        // QSAROWS: STRATA_QSA_ROWS=1 (exactly) takes block_scores_rows_kernel for calls of up to 4 queries - the same bits
2101        static const bool rows_env = [] { const char* v = std::getenv("STRATA_QSA_ROWS"); return v != nullptr && v[0] == '1' && v[1] == '\0'; }();
2102        if (rows_env && qsa_block_scores_rows(pooled, dead, q_idx, steps, nq, max_blocks, s, scores, stream)) return;
2103        if (scores_halve_on()) {   // Turing: block_scores_halve_kernel, the same bits
2104            const cudaStream_t st = (cudaStream_t) stream;
2105            if (nq <= 1) block_scores_halve_kernel<4><<<256, SCORE_WARPS * 32, 0, st>>>(pooled, dead, q_idx, steps, (int) nq, max_blocks, scores);
2106            else if (nq <= 2) block_scores_halve_kernel<8><<<256, SCORE_WARPS * 32, 0, st>>>(pooled, dead, q_idx, steps, (int) nq, max_blocks, scores);
2107            else if (nq <= 4) block_scores_halve_kernel<16><<<256, SCORE_WARPS * 32, 0, st>>>(pooled, dead, q_idx, steps, (int) nq, max_blocks, scores);
2108            else {   // 5-8 queries: two calls of up to 4 (the register form; each query's scores are its own)
2109                block_scores_halve_kernel<16><<<256, SCORE_WARPS * 32, 0, st>>>(pooled, dead, q_idx, steps, 4, max_blocks, scores);
2110                const int rest = (int) nq - 4;
2111                const float* q2 = q_idx + 4 * IDX_HEADS * IDX_DIM;
2112                const int32_t* st2 = steps + 4 * kStepCount;
2113                float* sc2 = scores + 4 * max_blocks;
2114                if (rest <= 1) block_scores_halve_kernel<4><<<256, SCORE_WARPS * 32, 0, st>>>(pooled, dead, q2, st2, rest, max_blocks, sc2);
2115                else if (rest <= 2) block_scores_halve_kernel<8><<<256, SCORE_WARPS * 32, 0, st>>>(pooled, dead, q2, st2, rest, max_blocks, sc2);
2116                else block_scores_halve_kernel<16><<<256, SCORE_WARPS * 32, 0, st>>>(pooled, dead, q2, st2, rest, max_blocks, sc2);
2117            }
2118            const cudaError_t e = cudaGetLastError();
2119            if (e != cudaSuccess) { std::fprintf(stderr, "qsa_block_scores halve: %s\n", cudaGetErrorString(e)); std::exit(1); }
2120            return;
2121        }
2122        block_scores_multi_kernel<<<256, SCORE_WARPS * 32, 0, (cudaStream_t) stream>>>(pooled, dead, q_idx, steps, (int) nq,
2123                                                                                     max_blocks, scores, scores_early_exit());
2124        const cudaError_t e = cudaGetLastError();
2125        if (e != cudaSuccess) { std::fprintf(stderr, "qsa_block_scores multi: %s\n", cudaGetErrorString(e)); std::exit(1); }
2126        return;
2127    }
2128    const int64_t reach = active_blocks > 0 && active_blocks < max_blocks ? active_blocks : max_blocks;
2129#if defined(__HIPCC__)
2130    // STRATA_SCORES_THREAD: 1 = on (gfx1100, gfx12), 0 = off, unset = on for gfx12 only (gfx1100: off, nothing measured here)
2131    static const int thread_env = [] {
2132        const char* value = std::getenv("STRATA_SCORES_THREAD");
2133        return value == nullptr ? -1 : (std::atoi(value) == 1 ? 1 : 0);
2134    }();
2135    // The bound is the ACTUAL live extent. A reserved 256K context never enables this by itself.
2136    if (thread_env != 0 && active_blocks >= 16385 && active_blocks <= max_blocks && nq >= 64 &&
2137        (scores_thread_arch() == 2 || (thread_env == 1 && scores_thread_arch() == 1))) {
2138        static thread_local bool logged = false;
2139        if (!logged && (thread_env == -1 || std::getenv("STRATA_SCORES_THREAD_TRACE"))) {
2140            std::fprintf(stderr, "qsa exact thread: the prompt's block scorer runs as the four-lanes-per-query kernel (nq=%lld active_blocks=%lld "
2141                                 "capacity=%lld; the same scores bit for bit; STRATA_SCORES_THREAD=0 turns it off)\n",
2142                         (long long)nq, (long long)active_blocks, (long long)max_blocks);
2143            logged = true;
2144        }
2145        const dim3 tgrid((unsigned)((reach + TS_BR - 1) / TS_BR), (unsigned)((nq + TS_Q - 1) / TS_Q));
2146        block_scores_thread_kernel<<<tgrid, 256, 0, (cudaStream_t)stream>>>(pooled, q_idx, steps, nq,
2147                                                                         max_blocks, reach, scores);
2148        block_scores_tail_kernel<<<(unsigned)nq, 32, 0, (cudaStream_t)stream>>>(dead, q_idx, steps,
2149                                                                            max_blocks, scores);
2150        const cudaError_t error = cudaGetLastError();
2151        if (error != cudaSuccess) {
2152            std::fprintf(stderr, "qsa exact thread: %s\n", cudaGetErrorString(error));
2153            std::exit(1);
2154        }
2155        return;
2156    }
2157#else
2158    // prompt calls (an active-block count): the thread-per-head kernel, the same bits (opt-in: scores_thread_on); else the
2159    // warp kernel below
2160    if (active_blocks > 0 && scores_thread_on()) {
2161        const dim3 tgrid((unsigned) ((reach + TS_BR - 1) / TS_BR), (unsigned) ((nq + TS_Q - 1) / TS_Q));
2162        block_scores_thread_kernel<<<tgrid, 256, 0, (cudaStream_t) stream>>>(pooled, q_idx, steps, nq, max_blocks, reach,
2163                                                                             scores);
2164        block_scores_tail_kernel<<<(unsigned) nq, 32, 0, (cudaStream_t) stream>>>(dead, q_idx, steps, max_blocks, scores);
2165        const cudaError_t e = cudaGetLastError();
2166        if (e != cudaSuccess) { std::fprintf(stderr, "qsa_block_scores thread: %s\n", cudaGetErrorString(e)); std::exit(1); }
2167        return;
2168    }
2169#endif
2170    const dim3 grid((unsigned) ((reach + SCORE_WARPS - 1) / SCORE_WARPS), (unsigned) nq);
2171    block_scores_kernel<<<grid, SCORE_WARPS * 32, 0, (cudaStream_t) stream>>>(pooled, dead, q_idx, steps, max_blocks,
2172                                                                              scores);
2173    const cudaError_t e = cudaGetLastError();
2174    if (e != cudaSuccess) { std::fprintf(stderr, "qsa_block_scores: %s\n", cudaGetErrorString(e)); std::exit(1); }
2175}
2176
2177bool qsa_block_scores_rows(const float* pooled, const float* dead, const float* q_idx, const int32_t* steps, int64_t nq,
2178                           int64_t max_blocks, const QsaShapes& s, float* scores, void* stream) {
2179    if (nq <= 0) return true;
2180    if (nq > 4 || s.idx_dim != IDX_DIM || s.idx_n_head != IDX_HEADS || s.idx_block != R) return false;
2181    cudaStream_t st = (cudaStream_t) stream;
2182    const int n = (int) nq;
2183    if (n == 1) block_scores_rows_kernel<1><<<256, SCORE_WARPS * 32, 0, st>>>(pooled, dead, q_idx, steps, n, max_blocks, scores);
2184    else if (n == 2) block_scores_rows_kernel<2><<<256, SCORE_WARPS * 32, 0, st>>>(pooled, dead, q_idx, steps, n, max_blocks, scores);
2185    else if (n == 3) block_scores_rows_kernel<3><<<256, SCORE_WARPS * 32, 0, st>>>(pooled, dead, q_idx, steps, n, max_blocks, scores);
2186    else block_scores_rows_kernel<4><<<256, SCORE_WARPS * 32, 0, st>>>(pooled, dead, q_idx, steps, n, max_blocks, scores);
2187    const cudaError_t e = cudaGetLastError();
2188    if (e != cudaSuccess) { std::fprintf(stderr, "qsa_block_scores rows: %s\n", cudaGetErrorString(e)); std::exit(1); }
2189    return true;
2190}
2191
2192void qsa_block_scores_rows(const QsaScoreRows& rows, const float* q_idx, const int32_t* steps, int64_t nq,
2193                           int64_t max_blocks, const QsaShapes& s, float* scores, void* stream) {
2194    if (nq <= 0) return;
2195    if (s.idx_dim != IDX_DIM || s.idx_n_head != IDX_HEADS || s.idx_block != R || nq > MQ || rows.n != nq) {
2196        std::fprintf(stderr, "qsa_block_scores_rows: unsupported geometry\n");
2197        std::exit(1);
2198    }
2199    static const bool early = [] { const char* v = std::getenv("STRATA_QSA_EARLY_EXIT"); return v == nullptr || std::atoi(v) != 0; }();
2200    block_scores_multi_kernel<<<256, SCORE_WARPS * 32, 0, (cudaStream_t) stream>>>(nullptr, nullptr, q_idx, steps, (int) nq,
2201                                                                                 max_blocks, scores, early, rows);
2202    const cudaError_t e = cudaGetLastError();
2203    if (e != cudaSuccess) { std::fprintf(stderr, "qsa_block_scores_rows: %s\n", cudaGetErrorString(e)); std::exit(1); }
2204}
2205
2206bool qsa_block_scores_tc(const float* pooled, const float* dead, const float* q_idx, const int32_t* steps, int64_t nq,
2207                         int64_t max_blocks, const QsaShapes& s, float* scores, void* stream, int64_t active_blocks) {
2208    if (nq <= 0) return true;
2209    if (s.idx_dim != IDX_DIM || s.idx_n_head != IDX_HEADS || s.idx_block != R || nq > 65535 * TC_QT) return false;
2210#if defined(__HIPCC__)
2211    // AMD: the gfx12 (RDNA4) WMMA scorer, opt-in (STRATA_SELECT_WMMA=1): it selects slightly differently from the warp
2212    // kernel (254/256 queries the same), so the default keeps the warp kernel; every other target keeps it too (false)
2213    static const bool wmma_on = [] {
2214        const char* v = std::getenv("STRATA_SELECT_WMMA");
2215        return v != nullptr && v[0] != '\0' && v[0] != '0';
2216    }();
2217    // any HIP card: the FP32 tiled scorer, opt-in as on CUDA (STRATA_SELECT_SIMT=1; another summation order than the
2218    // warp kernel, so the default keeps the warp kernel).  RX 6900 XT, 256 queries at 128K: 2.71 -> 0.587 ms
2219    // STRATA_SELECT_SIMT=2 (#2071): block_scores_simt2_kernel, 32 x 128 tiles with the next K chunk in registers (the same
2220    // bits as =1), as on CUDA.  RX 6900 XT, 2x, 32K / 128K prompt: +1% over =1 (E457)
2221    // unset: -1.  The community switch (strata/core/amd_community.hpp, STRATA_AMD_COMMUNITY_TUNING, on by default) makes mode 2
2222    // the default on gfx103x only (RX 6000, where #3073's contributor measured it: 119K prompt -6.5%); any value of the variable wins.
2223    static const int simt_env = [] {
2224        const char* v = std::getenv("STRATA_SELECT_SIMT");
2225        return v == nullptr ? -1 : v[0] == '1' ? 1 : v[0] == '2' ? 2 : 0;
2226    }();
2227    static const bool community_on = strata::amd_community::tuning_on();
2228    const int simt_v = simt_env >= 0 ? simt_env : (community_on && sel_gfx103_device() ? 2 : 0);
2229    // STRATA_SELECT_ALT_MIN_TOKENS=N: the simt / WMMA scorer acts only for a read whose reach is at least N tokens (blocks of R = 4);
2230    // a shorter one keeps the warp kernel.  On the R9700 (p620) neither scorer gains below ~24K tokens and simt2's values move more
2231    // there, so the gfx12 default sets it (arch_defaults.cpp); the community simt2 default of gfx103x starts at 28,672 tokens, just under the
2232    // 31K its contributor measured.  Unset: no limit for a scorer the user asked for.
2233    static const int64_t alt_min_env = [] {
2234        const char* v = std::getenv("STRATA_SELECT_ALT_MIN_TOKENS");
2235        return v != nullptr && v[0] != 0 ? (int64_t) std::atoll(v) : (int64_t) -1;
2236    }();
2237    if (simt_v != 0 || wmma_on) {
2238        const int64_t reach_all = active_blocks > 0 && active_blocks < max_blocks ? active_blocks : max_blocks;
2239        const int64_t min_tok = alt_min_env >= 0 ? alt_min_env : (simt_env < 0 && simt_v == 2 ? 28672 : 0);
2240        if (reach_all * R < min_tok) return false;
2241    }
2242    if (simt_v != 0 && !(wmma_on && sel_gfx12_device())) {
2243        const int64_t reach = active_blocks > 0 && active_blocks < max_blocks ? active_blocks : max_blocks;
2244        const bool rdna2 = sel_gfx103_device();
2245        static std::atomic<bool> said{false};
2246        if (!said.exchange(true))
2247            std::fprintf(stderr, "qsa select: FP32 tiled scorer (STRATA_SELECT_SIMT=%d), tiles %s\n", simt_v,
2248                         simt_v == 2 ? "simt2 32x128 (#2071)" : rdna2 ? "32/128/16/8 (gfx103x)" : "32/64/32/4");
2249        if (simt_v == 2) {
2250            const dim3 grid((unsigned) ((reach + 127) / 128), (unsigned) ((nq + 31) / 32));
2251            if (grid.y > 65535) return false;
2252            block_scores_simt2_kernel<32, 128><<<grid, 256, 0, (cudaStream_t) stream>>>(pooled, q_idx, steps, nq,
2253                                                                                       max_blocks, reach, scores);
2254            block_scores_tail_kernel<<<(unsigned) nq, 32, 0, (cudaStream_t) stream>>>(dead, q_idx, steps, max_blocks,
2255                                                                                    scores);
2256            const cudaError_t e = cudaGetLastError();
2257            if (e != cudaSuccess) { std::fprintf(stderr, "qsa_block_scores (simt2): %s\n", cudaGetErrorString(e)); std::exit(1); }
2258            return true;
2259        }
2260        return block_scores_simt(pooled, dead, q_idx, steps, nq, max_blocks, reach, scores, (cudaStream_t) stream, rdna2);
2261    }
2262    if (!wmma_on || !sel_gfx12_device()) return false;
2263    {
2264        const int64_t reach = active_blocks > 0 && active_blocks < max_blocks ? active_blocks : max_blocks;
2265        const int64_t per = (int64_t) 4 * WITER * 16;
2266        const dim3 grid((unsigned) ((reach + per - 1) / per), (unsigned) ((nq + WQT - 1) / WQT));
2267        block_scores_wmma_kernel<<<grid, 128, 0, (cudaStream_t) stream>>>(pooled, q_idx, steps, nq, max_blocks, reach, scores);
2268        block_scores_tail_kernel<<<(unsigned) nq, 32, 0, (cudaStream_t) stream>>>(dead, q_idx, steps, max_blocks, scores);
2269        const cudaError_t e = cudaGetLastError();
2270        if (e != cudaSuccess) { std::fprintf(stderr, "qsa_block_scores_tc: %s\n", cudaGetErrorString(e)); std::exit(1); }
2271        return true;
2272    }
2273#else
2274    {   // sm_80 or newer (TF32 MMA); an older card keeps the warp kernel
2275        static int cc_major[64] = {};
2276        int dev = 0;
2277        if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return false; }
2278        if (cc_major[dev] == 0) {
2279            int major = 0;
2280            if (cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) != cudaSuccess) {
2281                cudaGetLastError();
2282                return false;
2283            }
2284            // STRATA_QSA_WARP=1|select (an A/B arm): the pre-sm_80 kernels on any card, as RTX 20 runs them
2285            const char* w = std::getenv("STRATA_QSA_WARP");
2286            cc_major[dev] = w && (!std::strcmp(w, "1") || !std::strcmp(w, "select")) ? 7 : strata::cc_major_of(major);
2287        }
2288        if (cc_major[dev] < 8) {
2289            // no TF32 tensor cores: the FP32 tiled kernel, opt-in (STRATA_SELECT_SIMT=1): its sum order differs from the
2290            // warp kernel's, so the default stays the caller's warp kernel and the output bytes stay the same
2291            // STRATA_SELECT_SIMT=2: block_scores_simt2_kernel (the same bits as =1, larger tiles)
2292            static const int simt = [] {
2293                const char* v = std::getenv("STRATA_SELECT_SIMT");
2294                return v == nullptr ? 0 : v[0] == '1' ? 1 : v[0] == '2' ? 2 : 0;
2295            }();
2296            if (!simt) return false;
2297            const int64_t reach = active_blocks > 0 && active_blocks < max_blocks ? active_blocks : max_blocks;
2298            if (simt == 2) {
2299                // STRATA_SIMT2_TILE=2: 64 x 64 tiles (measured slower: 400K 3.00 vs 2.82 ms)
2300                static const int tile = [] { const char* v = std::getenv("STRATA_SIMT2_TILE"); return v ? std::atoi(v) : 1; }();
2301                if (tile != 2) {
2302                    const dim3 grid((unsigned) ((reach + 127) / 128), (unsigned) ((nq + 31) / 32));
2303                    if (grid.y > 65535) return false;
2304                    block_scores_simt2_kernel<32, 128><<<grid, 256, 0, (cudaStream_t) stream>>>(pooled, q_idx, steps, nq,
2305                                                                                               max_blocks, reach, scores);
2306                } else {
2307                    const dim3 grid((unsigned) ((reach + 63) / 64), (unsigned) ((nq + 63) / 64));
2308                    if (grid.y > 65535) return false;
2309                    block_scores_simt2_kernel<64, 64><<<grid, 256, 0, (cudaStream_t) stream>>>(pooled, q_idx, steps, nq,
2310                                                                                              max_blocks, reach, scores);
2311                }
2312                block_scores_tail_kernel<<<(unsigned) nq, 32, 0, (cudaStream_t) stream>>>(dead, q_idx, steps, max_blocks,
2313                                                                                        scores);
2314                const cudaError_t e = cudaGetLastError();
2315                if (e != cudaSuccess) { std::fprintf(stderr, "qsa_block_scores (simt): %s\n", cudaGetErrorString(e)); std::exit(1); }
2316                return true;
2317            }
2318            return block_scores_simt(pooled, dead, q_idx, steps, nq, max_blocks, reach, scores, (cudaStream_t) stream,
2319                                     false);
2320        }
2321    }
2322    static bool attr[64] = {};   // the shared-memory opt-in is per device (a layer split runs it on several)
2323    int adev = 0;
2324    cudaGetDevice(&adev);
2325    const int bytes = (TC_QT * TC_QS + TC_NB * TC_KS) * (int) sizeof(float);
2326    if (!attr[adev]) {
2327        if (cudaFuncSetAttribute(block_scores_tc_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, bytes) !=
2328            cudaSuccess) {
2329            cudaGetLastError();
2330            return false;
2331        }
2332        attr[adev] = true;
2333    }
2334    const int64_t reach = active_blocks > 0 && active_blocks < max_blocks ? active_blocks : max_blocks;
2335    const int64_t per = (int64_t) TC_NB * TC_ITER;
2336    const dim3 grid((unsigned) ((reach + per - 1) / per), (unsigned) ((nq + TC_QT - 1) / TC_QT));
2337    block_scores_tc_kernel<<<grid, 128, bytes, (cudaStream_t) stream>>>(pooled, q_idx, steps, nq, max_blocks, reach,
2338                                                                         scores);
2339    block_scores_tail_kernel<<<(unsigned) nq, 32, 0, (cudaStream_t) stream>>>(dead, q_idx, steps, max_blocks, scores);
2340    const cudaError_t e = cudaGetLastError();
2341    if (e != cudaSuccess) { std::fprintf(stderr, "qsa_block_scores_tc: %s\n", cudaGetErrorString(e)); std::exit(1); }
2342    return true;
2343#endif
2344}
2345
2346void qsa_block_topk_ref(const float* scores, const int32_t* steps, int64_t nq, int64_t max_blocks, int64_t cap,
2347                        const QsaShapes& s, int32_t* ids, void* stream) {
2348    if (nq <= 0) return;
2349    if (s.idx_block != R || cap < qsa_selection_width(kTopkMaxCells, s)) {
2350        std::fprintf(stderr, "qsa_block_topk: unsupported geometry or cap\n");
2351        std::exit(1);
2352    }
2353    block_topk_kernel<<<(unsigned) nq, TOPK_T, 0, (cudaStream_t) stream>>>(scores, steps, max_blocks, cap, ids);
2354    const cudaError_t e = cudaGetLastError();
2355    if (e != cudaSuccess) { std::fprintf(stderr, "qsa_block_topk: %s\n", cudaGetErrorString(e)); std::exit(1); }
2356}
2357
2358#if !defined(__HIPCC__)
2359// Only Turing has a retained model measurement for this CUDA dispatch. Other CUDA devices keep the capacity rule
2360// (the RTX 5070 regression below). Cache the properties per calling thread; layer-split device switches are checked.
2361static bool topk_active_turing_device() {
2362    int dev = 0;
2363    if (cudaGetDevice(&dev) != cudaSuccess) return false;
2364    static thread_local int cached_device = -1;
2365    static thread_local bool turing = false;
2366    if (dev != cached_device) {
2367        cudaDeviceProp prop{};
2368        if (cudaGetDeviceProperties(&prop, dev) != cudaSuccess) return false;
2369        turing = prop.major == 7 && prop.minor == 5;
2370        cached_device = dev;
2371    }
2372    return turing;
2373}
2374#endif
2375
2376bool qsa_block_topk_cluster(const float* scores, const int32_t* steps, int64_t nq, int64_t max_blocks, int64_t cap,
2377                            const QsaShapes& s, int32_t* ids, void* stream) {
2378#if defined(__HIPCC__)
2379    (void) scores; (void) steps; (void) nq; (void) max_blocks; (void) cap; (void) s; (void) ids; (void) stream;
2380    return false;
2381#else
2382    if (nq <= 0) return true;
2383    if (s.idx_block != R || cap < qsa_selection_width(kTopkMaxCells, s) || nq > 65535 || max_blocks <= 0) return false;
2384    const size_t smem = (size_t) ((max_blocks + CL_N - 1) / CL_N) * sizeof(uint32_t);
2385    // Per device (a layer split runs on several): 1 the cluster kernel runs here, 2 it does not. It needs sm_90+ (the
2386    // card's, or STRATA_EMULATE_CC's) AND code built for it: a build with only older code JIT-compiles their PTX, whose
2387    // copy of this kernel is a trap - the function's PTX version says which. `opt`: the dynamic shared memory opted in.
2388    static int ok[64] = {};
2389    static size_t opt[64] = {};
2390    int dev = 0;
2391    if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return false; }
2392    if (ok[dev] == 0) {
2393        int major = 0;
2394        cudaFuncAttributes fa{};
2395        const bool code = cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) == cudaSuccess &&
2396                          strata::cc_major_of(major) >= 9 &&
2397                          cudaFuncGetAttributes(&fa, block_topk_cluster_kernel) == cudaSuccess && fa.ptxVersion >= 90 &&
2398                          fa.binaryVersion >= 90;
2399        cudaGetLastError();
2400        ok[dev] = code ? 1 : 2;
2401    }
2402    if (ok[dev] != 1) return false;
2403    if (smem > opt[dev]) {   // a larger capacity: opt in, and check that a cluster of CL_N such CTAs can be resident
2404        int clusters = 0;
2405        cudaLaunchConfig_t q{};
2406        cudaLaunchAttribute qa[1];
2407        qa[0].id = cudaLaunchAttributeClusterDimension;
2408        qa[0].val.clusterDim.x = CL_N;
2409        qa[0].val.clusterDim.y = 1;
2410        qa[0].val.clusterDim.z = 1;
2411        q.gridDim = dim3(CL_N, 1, 1);
2412        q.blockDim = dim3(CL_T, 1, 1);
2413        q.dynamicSmemBytes = smem;
2414        q.attrs = qa;
2415        q.numAttrs = 1;
2416        if (cudaFuncSetAttribute(block_topk_cluster_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) smem) !=
2417                cudaSuccess ||
2418            cudaOccupancyMaxActiveClusters(&clusters, block_topk_cluster_kernel, &q) != cudaSuccess || clusters < 1) {
2419            cudaGetLastError();
2420            return false;    // this capacity takes the one-CTA kernels; a smaller one may still fit
2421        }
2422        opt[dev] = smem;
2423    }
2424    cudaLaunchConfig_t cfg{};
2425    cudaLaunchAttribute at[1];
2426    at[0].id = cudaLaunchAttributeClusterDimension;
2427    at[0].val.clusterDim.x = CL_N;
2428    at[0].val.clusterDim.y = 1;
2429    at[0].val.clusterDim.z = 1;
2430    cfg.gridDim = dim3(CL_N, (unsigned) nq, 1);
2431    cfg.blockDim = dim3(CL_T, 1, 1);
2432    cfg.dynamicSmemBytes = smem;
2433    cfg.stream = (cudaStream_t) stream;
2434    cfg.attrs = at;
2435    cfg.numAttrs = 1;
2436    const cudaError_t e = cudaLaunchKernelEx(&cfg, block_topk_cluster_kernel, scores, steps, max_blocks, cap, ids);
2437    if (e != cudaSuccess) { std::fprintf(stderr, "qsa_block_topk cluster: %s\n", cudaGetErrorString(e)); std::exit(1); }
2438    return true;
2439#endif
2440}
2441
2442#if !defined(__HIPCC__)
2443// ---- the decode top-k split over many CTAs, for cards without thread-block clusters (Turing: a decode window's 1-6
2444// queries ran block_topk_wide_kernel on 1-6 SMs, ~230 us a call at 420K cells, RTX 2080 Ti).  A query's blocks are
2445// cut into chunks of SP_CH; six launches: four radix passes (each chunk adds its 8-bit histogram to the query's global
2446// one), a count of each chunk's cells above / at the threshold, and the emit.  Each pass's CTAs take the previous
2447// digit from the complete histogram with block_topk_kernel's rule (the largest digit whose cells at or above it reach
2448// the width; 0 when none) - pure functions of integer counts, so every CTA finds the same digit, and the threshold,
2449// `above` and the emitted cells are block_topk_kernel's: identical ids.  STRATA_TOPK_SPLIT=0 keeps the wide kernel.
2450constexpr int SP_T = 256, SP_W = SP_T / 32, SP_CH = 2048, SP_MAXQ = 16, SP_MAXCH = 512;
2451__device__ int g_sp_hist[SP_MAXQ][4][256];
2452__device__ int g_sp_state[5][SP_MAXQ][2];          // after p digits: prefix, above
2453__device__ int g_sp_cnt[SP_MAXQ][SP_MAXCH][2];     // per chunk: cells above the threshold, cells at it
2454
2455// the digit of pass `p` from its complete histogram: block_topk_kernel's scan as a parallel suffix sum
2456__device__ void sp_digit(const int* __restrict__ h, int width, int above, int& digit, int& above_out, int* s_buf) {
2457    const int t = threadIdx.x;
2458    // s_buf[d] = sum of h[d'] for d' > d (exclusive suffix), d in 0..255
2459    const int v = h[t];
2460    int x = v;                                     // inclusive suffix scan over t = 255..0: reverse index r = 255 - t
2461    const int lane = t & 31, w = t >> 5;
2462    __shared__ int s_w[SP_W];
2463    // scan in reverse order: thread t holds element r = 255 - t
2464    int e = h[255 - t];
2465    for (int o = 1; o < 32; o <<= 1) { const int y = __shfl_up_sync(0xffffffffu, e, o); if (lane >= o) e += y; }
2466    if (lane == 31) s_w[w] = e;
2467    __syncthreads();
2468    int add = 0;
2469    for (int i = 0; i < w; ++i) add += s_w[i];
2470    e += add;                                      // inclusive suffix sum of h from 255 down to r = 255 - t
2471    (void) x; (void) v;
2472    s_buf[255 - t] = e;                            // s_buf[r] = sum_{d >= r} h[d]
2473    __syncthreads();
2474    // the scan picks the largest d in 1..255 with above + sum_{d' >= d} h >= width, else 0
2475    __shared__ int s_best;
2476    if (t == 0) s_best = 0;
2477    __syncthreads();
2478    if (t >= 1 && above + s_buf[t] >= width) atomicMax(&s_best, t);
2479    __syncthreads();
2480    const int d = s_best;
2481    digit = d;
2482    above_out = above + (d == 255 ? 0 : s_buf[d + 1]);   // cells strictly above digit d (the scan's cum)
2483    if (d == 0) above_out = above + s_buf[1];
2484    __syncthreads();
2485}
2486
2487template <int P>
2488__global__ void __launch_bounds__(SP_T) topk_split_hist_kernel(const float* __restrict__ scores,
2489                                                               const int32_t* __restrict__ steps, int64_t max_blocks) {
2490    __shared__ int hist[SP_W][256];
2491    __shared__ int s_buf[256];
2492    const int q = blockIdx.y, t = threadIdx.x, lane = t & 31, warp = t >> 5;
2493    const int32_t* st = steps + (int64_t) q * kStepCount;
2494    const int64_t n_kv = st[kStepNKv], n_bid = st[kStepNBid], width = st[kStepWidth];
2495    if (n_kv <= width) return;
2496    const int64_t nb = n_bid + 1, b0 = (int64_t) blockIdx.x * SP_CH;
2497    uint32_t prefix = 0;
2498    int above = 0;
2499    if (P > 0) {
2500        const int pa = g_sp_state[P - 1][q][0], ab = g_sp_state[P - 1][q][1];
2501        int d, ab2;
2502        sp_digit(g_sp_hist[q][P - 1], (int) width, ab, d, ab2, s_buf);
2503        prefix = (uint32_t) pa | ((uint32_t) d << (24 - 8 * (P - 1)));
2504        above = ab2;
2505        if (blockIdx.x == 0 && t == 0) { g_sp_state[P][q][0] = (int) prefix; g_sp_state[P][q][1] = above; }
2506    } else if (blockIdx.x == 0 && t == 0) {
2507        g_sp_state[0][q][0] = 0; g_sp_state[0][q][1] = 0;
2508    }
2509    if (P == 4 || b0 >= nb) return;
2510    constexpr int shift = 24 - 8 * (P < 4 ? P : 0);
2511    const uint32_t hi_mask = P == 0 ? 0u : (0xffffffffu << (shift + 8));
2512    for (int i = lane; i < 256; i += 32) hist[warp][i] = 0;
2513    __syncwarp();
2514    const float* sc = scores + (int64_t) q * max_blocks;
2515    const int64_t b1 = b0 + SP_CH < nb ? b0 + SP_CH : nb;
2516    for (int64_t b = b0 + t; b < b1; b += SP_T) {
2517        const int w = b < n_bid ? R : (int) (n_kv - n_bid * R);
2518        if (w == 0) continue;
2519        const uint32_t k = order_key(sc[b]);
2520        if ((k & hi_mask) == (prefix & hi_mask)) atomicAdd(&hist[warp][(k >> shift) & 255], w);
2521    }
2522    __syncthreads();
2523    int s = 0;
2524    for (int w2 = 0; w2 < SP_W; ++w2) s += hist[w2][t];
2525    if (s) atomicAdd(&g_sp_hist[q][P][t], s);
2526}
2527
2528// the threshold from pass 3's histogram, then each chunk's cells above / at it
2529__global__ void __launch_bounds__(SP_T) topk_split_count_kernel(const float* __restrict__ scores,
2530                                                                const int32_t* __restrict__ steps, int64_t max_blocks) {
2531    __shared__ int s_buf[256];
2532    __shared__ int s_r[2][SP_W];
2533    const int q = blockIdx.y, t = threadIdx.x, lane = t & 31, warp = t >> 5;
2534    const int32_t* st = steps + (int64_t) q * kStepCount;
2535    const int64_t n_kv = st[kStepNKv], n_bid = st[kStepNBid], width = st[kStepWidth];
2536    if (n_kv <= width) return;
2537    const int pa = g_sp_state[3][q][0], ab = g_sp_state[3][q][1];
2538    int d, ab2;
2539    sp_digit(g_sp_hist[q][3], (int) width, ab, d, ab2, s_buf);
2540    const uint32_t thr = (uint32_t) pa | (uint32_t) d;
2541    if (blockIdx.x == 0 && t == 0) { g_sp_state[4][q][0] = (int) thr; g_sp_state[4][q][1] = ab2; }
2542    const int64_t nb = n_bid + 1, b0 = (int64_t) blockIdx.x * SP_CH;
2543    const int64_t b1 = b0 + SP_CH < nb ? b0 + SP_CH : nb;
2544    const float* sc = scores + (int64_t) q * max_blocks;
2545    int gt = 0, eq = 0;
2546    for (int64_t b = b0 + t; b < b1; b += SP_T) {
2547        const int w = b < n_bid ? R : (int) (n_kv - n_bid * R);
2548        if (w == 0) continue;
2549        const uint32_t k = order_key(sc[b]);
2550        if (k > thr) gt += w;
2551        else if (k == thr) eq += w;
2552    }
2553    for (int o = 16; o > 0; o >>= 1) {
2554        gt += __shfl_xor_sync(0xffffffffu, gt, o);
2555        eq += __shfl_xor_sync(0xffffffffu, eq, o);
2556    }
2557    if (lane == 0) { s_r[0][warp] = gt; s_r[1][warp] = eq; }
2558    __syncthreads();
2559    if (t == 0) {
2560        int g2 = 0, e2 = 0;
2561        for (int w2 = 0; w2 < SP_W; ++w2) { g2 += s_r[0][w2]; e2 += s_r[1][w2]; }
2562        g_sp_cnt[q][blockIdx.x][0] = g2;
2563        g_sp_cnt[q][blockIdx.x][1] = e2;
2564    }
2565}
2566
2567// the emit: block_topk_wide_kernel's within a chunk, offset by the chunks before it
2568__global__ void __launch_bounds__(SP_T) topk_split_emit_kernel(const float* __restrict__ scores,
2569                                                               const int32_t* __restrict__ steps, int64_t max_blocks,
2570                                                               int64_t cap, int32_t* __restrict__ ids) {
2571    __shared__ int s_gt[SP_W], s_eq[SP_W];
2572    __shared__ int s_sel0, s_eqb0;
2573    const int q = blockIdx.y, t = threadIdx.x, lane = t & 31, warp = t >> 5;
2574    const int32_t* st = steps + (int64_t) q * kStepCount;
2575    const int64_t n_kv = st[kStepNKv], n_bid = st[kStepNBid], width = st[kStepWidth];
2576    int32_t* out = ids + (int64_t) q * cap;
2577    const int64_t nb = n_bid + 1, b0 = (int64_t) blockIdx.x * SP_CH;
2578    if (n_kv <= width) {                               // everything is selected: the identity, ascending
2579        const int64_t c0 = b0 * R, c1 = (b0 + SP_CH) * R < n_kv ? (b0 + SP_CH) * R : n_kv;
2580        for (int64_t j = c0 + t; j < c1; j += SP_T) out[j] = (int32_t) j;
2581        return;
2582    }
2583    if (b0 >= nb) return;
2584    const uint32_t thr = (uint32_t) g_sp_state[4][q][0];
2585    const int eq_budget = (int) (width - g_sp_state[4][q][1]);
2586    if (t == 0) {                                      // the cells the chunks before this one select / hold at thr
2587        int sel = 0, eqb = 0;
2588        for (int c = 0; c < (int) blockIdx.x; ++c) {
2589            const int g2 = g_sp_cnt[q][c][0], e2 = g_sp_cnt[q][c][1];
2590            const int take = eq_budget - eqb < 0 ? 0 : (eq_budget - eqb > e2 ? e2 : eq_budget - eqb);
2591            sel += g2 + take;
2592            eqb += e2;
2593        }
2594        s_sel0 = sel;
2595        s_eqb0 = eqb;
2596    }
2597    const int64_t b1 = b0 + SP_CH < nb ? b0 + SP_CH : nb;
2598    const int64_t per = (SP_CH / 32) / SP_W;           // rows of 32 blocks per warp
2599    const int64_t w0 = b0 + (int64_t) warp * 32 * per, w1 = w0 + 32 * per < b1 ? w0 + 32 * per : b1;
2600    const float* sc = scores + (int64_t) q * max_blocks;
2601    auto weight = [&](int64_t b) -> int { return b < n_bid ? R : (int) (n_kv - n_bid * R); };
2602    int gt = 0, eq = 0;
2603    for (int64_t b = w0 + lane; b < w1; b += 32) {
2604        const int w = weight(b);
2605        if (w == 0) continue;
2606        const uint32_t k = order_key(sc[b]);
2607        if (k > thr) gt += w;
2608        else if (k == thr) eq += w;
2609    }
2610#pragma unroll
2611    for (int o = 16; o > 0; o >>= 1) {
2612        gt += __shfl_xor_sync(0xffffffffu, gt, o);
2613        eq += __shfl_xor_sync(0xffffffffu, eq, o);
2614    }
2615    if (lane == 0) { s_gt[warp] = gt; s_eq[warp] = eq; }
2616    __syncthreads();
2617    if (t == 0) {
2618        int eb = s_eqb0, sb = s_sel0;
2619        for (int w2 = 0; w2 < SP_W; ++w2) {
2620            const int g2 = s_gt[w2], e2 = s_eq[w2];
2621            const int take = eq_budget - eb < 0 ? 0 : (eq_budget - eb > e2 ? e2 : eq_budget - eb);
2622            s_gt[w2] = sb;
2623            s_eq[w2] = eb;
2624            sb += g2 + take;
2625            eb += e2;
2626        }
2627    }
2628    __syncthreads();
2629    int run_sel = s_gt[warp], run_eq = s_eq[warp];
2630    for (int64_t r0 = w0; r0 < w1; r0 += 32) {
2631        const int64_t b = r0 + lane;
2632        const int w = b < w1 ? weight(b) : 0;
2633        const uint32_t k = w ? order_key(sc[b]) : 0u;
2634        const int my_gt = (w && k > thr) ? w : 0, my_eq = (w && k == thr) ? w : 0;
2635        if (__ballot_sync(0xffffffffu, (my_gt | my_eq) != 0) == 0u) continue;
2636        int pe = my_eq;
2637#pragma unroll
2638        for (int o = 1; o < 32; o <<= 1) {
2639            const int y = __shfl_up_sync(0xffffffffu, pe, o);
2640            if (lane >= o) pe += y;
2641        }
2642        const int left = eq_budget - (run_eq + pe - my_eq);
2643        const int take = left < 0 ? 0 : (left > my_eq ? my_eq : left);
2644        const int my_sel = my_gt + take;
2645        int ps = my_sel;
2646#pragma unroll
2647        for (int o = 1; o < 32; o <<= 1) {
2648            const int y = __shfl_up_sync(0xffffffffu, ps, o);
2649            if (lane >= o) ps += y;
2650        }
2651        int32_t* dst = out + run_sel + ps - my_sel;
2652        for (int c = 0; c < my_sel; ++c) dst[c] = (int32_t) (b * R + c);
2653        run_eq += __shfl_sync(0xffffffffu, pe, 31);
2654        run_sel += __shfl_sync(0xffffffffu, ps, 31);
2655    }
2656}
2657
2658bool topk_split_device() {
2659    static int ok[64] = {};   // 0 unknown, 1 yes, 2 no
2660    static const int env = [] { const char* v = std::getenv("STRATA_TOPK_SPLIT"); return v ? (std::atoi(v) != 0 ? 1 : 0) : -1; }();
2661    if (env == 0) return false;
2662    int dev = 0;
2663    if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return false; }
2664    if (ok[dev] == 0) {
2665        int major = 0, minor = 0;
2666        cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev);
2667        cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev);
2668        ok[dev] = (env == 1 || strata::sm75_default(major, minor)) ? 1 : 2;   // Turing, STRATA_SM75_PERF=1
2669    }
2670    return ok[dev] == 1;
2671}
2672
2673bool qsa_block_topk_split(const float* scores, const int32_t* steps, int64_t nq, int64_t max_blocks, int64_t cap,
2674                          int32_t* ids, cudaStream_t s) {
2675    const int64_t nch = (max_blocks + SP_CH - 1) / SP_CH;
2676    if (nq < 1 || nq > SP_MAXQ || nch > SP_MAXCH) return false;
2677    static void* hist_ptr[64] = {};
2678    int dev = 0;
2679    if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return false; }
2680    if (hist_ptr[dev] == nullptr && cudaGetSymbolAddress(&hist_ptr[dev], g_sp_hist) != cudaSuccess) {
2681        cudaGetLastError();
2682        hist_ptr[dev] = nullptr;
2683        return false;
2684    }
2685    if (cudaMemsetAsync(hist_ptr[dev], 0, (size_t) nq * 4 * 256 * sizeof(int), s) != cudaSuccess) return false;
2686    const dim3 grid((unsigned) nch, (unsigned) nq);
2687    topk_split_hist_kernel<0><<<grid, SP_T, 0, s>>>(scores, steps, max_blocks);
2688    topk_split_hist_kernel<1><<<grid, SP_T, 0, s>>>(scores, steps, max_blocks);
2689    topk_split_hist_kernel<2><<<grid, SP_T, 0, s>>>(scores, steps, max_blocks);
2690    topk_split_hist_kernel<3><<<grid, SP_T, 0, s>>>(scores, steps, max_blocks);
2691    topk_split_count_kernel<<<grid, SP_T, 0, s>>>(scores, steps, max_blocks);
2692    topk_split_emit_kernel<<<grid, SP_T, 0, s>>>(scores, steps, max_blocks, cap, ids);
2693    return true;
2694}
2695#endif
2696
2697#if !defined(__HIPCC__)
2698// ---- the prompt path's top-k with one full read of the scores (Turing).  block_topk_wide_kernel reads a query's scores
2699// six times (four radix passes, a count, the emit); past ~90K cells that is DRAM traffic (256 queries at 400K: 0.6 GB a
2700// layer, ~1.5 ms on an RTX 2080 Ti).  Here a CTA first reads every 32nd block and takes the KS-th largest of those keys
2701// as a bound LB, then reads all blocks once and keeps the ones with key >= LB in shared memory.  When those hold at
2702// least `width` cells, the width-th largest cell key (block_topk_kernel's threshold) is >= LB, so every block at or
2703// above the threshold is a candidate: the threshold, `above` and the tie budget computed over the candidates with
2704// block_topk_kernel's rule are the reference's, and the candidates sorted by block emit the reference's cells in its
2705// order.  Otherwise (too few cells above LB, or more than SM_CAP candidates) the query is flagged and
2706// block_topk_wide_kernel<true> runs it.  STRATA_TOPK_SAMPLE=0 keeps the wide kernel alone.
2707constexpr int TS_STRIDE = 32, TS_CAP = 4096;
2708
2709__device__ __forceinline__ int ts_block_scan(int v, int* s_w) {   // exclusive scan over the CTA's TK_T threads
2710    const int t = threadIdx.x, lane = t & 31, w = t >> 5;
2711    int x = v;
2712#pragma unroll
2713    for (int o = 1; o < 32; o <<= 1) { const int y = __shfl_up_sync(0xffffffffu, x, o); if (lane >= o) x += y; }
2714    if (lane == 31) s_w[w] = x;
2715    __syncthreads();
2716    if (w == 0) {
2717        int y = lane < TK_T / 32 ? s_w[lane] : 0;
2718#pragma unroll
2719        for (int o = 1; o < 32; o <<= 1) { const int z = __shfl_up_sync(0xffffffffu, y, o); if (lane >= o) y += z; }
2720        if (lane < TK_T / 32) s_w[lane] = y;   // inclusive warp totals
2721    }
2722    __syncthreads();
2723    const int base = w > 0 ? s_w[w - 1] : 0;
2724    const int r = base + x - v;
2725    __syncthreads();
2726    return r;
2727}
2728
2729__global__ void __launch_bounds__(TK_T) block_topk_sample_kernel(const float* __restrict__ scores,
2730                                                                 const int32_t* __restrict__ steps, int64_t max_blocks,
2731                                                                 int64_t cap, int32_t* __restrict__ ids) {
2732    __shared__ uint32_t s_key[TS_CAP];
2733    __shared__ int32_t s_idx[TS_CAP];
2734    __shared__ int hist[256];
2735    __shared__ int s_w[TK_T / 32];
2736    __shared__ int s_cnt, s_cells, s_digit, s_above;
2737    const int64_t qi = blockIdx.x;
2738    const int32_t* st = steps + qi * kStepCount;
2739    const int64_t n_kv = st[kStepNKv], n_bid = st[kStepNBid], width = st[kStepWidth];
2740    int32_t* out = ids + qi * cap;
2741    const int t = threadIdx.x;
2742    if (n_kv <= width) {
2743        if (t == 0) g_tk_fail[qi] = 0;
2744        for (int64_t j = t; j < n_kv; j += TK_T) out[j] = (int32_t) j;
2745        return;
2746    }
2747    const float* sc = scores + qi * max_blocks;
2748    const int64_t nb = n_bid + 1;
2749    auto weight = [&](int64_t b) -> int { return b < n_bid ? R : (int) (n_kv - n_bid * R); };
2750    const int ns = (int) ((nb + TS_STRIDE - 1) / TS_STRIDE);
2751    if (ns > TS_CAP) { if (t == 0) g_tk_fail[qi] = 1; return; }
2752    // 1. the bound: the KS-th largest of every 32nd block's key (a block without cells counts as the smallest key)
2753    for (int i = t; i < ns; i += TK_T) {
2754        const int64_t b = (int64_t) i * TS_STRIDE;
2755        s_key[i] = weight(b) ? order_key(sc[b]) : 0u;
2756    }
2757    const int ks_want = (int) (2 * ((width + R * TS_STRIDE - 1) / (R * TS_STRIDE)) + 16);
2758    int need = ks_want < ns ? ks_want : ns;
2759    uint32_t prefix = 0;
2760    for (int shift = 24; shift >= 0; shift -= 8) {
2761        for (int i = t; i < 256; i += TK_T) hist[i] = 0;
2762        __syncthreads();
2763        const uint32_t hi_mask = shift == 24 ? 0u : (0xffffffffu << (shift + 8));
2764        for (int i = t; i < ns; i += TK_T) {
2765            const uint32_t k = s_key[i];
2766            if ((k & hi_mask) == (prefix & hi_mask)) atomicAdd(&hist[(k >> shift) & 255], 1);
2767        }
2768        __syncthreads();
2769        if (t == 0) {
2770            int cum = 0, d = 255;
2771            for (; d > 0; --d) {
2772                if (cum + hist[d] >= need) break;
2773                cum += hist[d];
2774            }
2775            s_digit = d;
2776            s_above = need - cum;
2777        }
2778        __syncthreads();
2779        prefix |= (uint32_t) s_digit << shift;
2780        need = s_above;
2781        __syncthreads();
2782    }
2783    const uint32_t lb = prefix;
2784    // 2. one read of every block: the candidates (key >= LB) and their cells
2785    if (t == 0) { s_cnt = 0; s_cells = 0; }
2786    __syncthreads();
2787    for (int64_t b = t; b < nb; b += TK_T) {
2788        const int w = weight(b);
2789        if (w == 0) continue;
2790        const uint32_t k = order_key(sc[b]);
2791        if (k >= lb) {
2792            const int pos = atomicAdd(&s_cnt, 1);
2793            if (pos < TS_CAP) { s_key[pos] = k; s_idx[pos] = (int32_t) b; }
2794            atomicAdd(&s_cells, w);
2795        }
2796    }
2797    __syncthreads();
2798    const int n = s_cnt;
2799    if (n > TS_CAP || s_cells < width) {   // the bound was too low or too high: the wide kernel takes this query
2800        if (t == 0) g_tk_fail[qi] = 1;
2801        return;
2802    }
2803    if (t == 0) g_tk_fail[qi] = 0;
2804    // 3. block_topk_kernel's threshold over the candidates (weighted)
2805    prefix = 0;
2806    int above = 0;
2807    for (int shift = 24; shift >= 0; shift -= 8) {
2808        for (int i = t; i < 256; i += TK_T) hist[i] = 0;
2809        __syncthreads();
2810        const uint32_t hi_mask = shift == 24 ? 0u : (0xffffffffu << (shift + 8));
2811        for (int i = t; i < n; i += TK_T) {
2812            const uint32_t k = s_key[i];
2813            if ((k & hi_mask) == (prefix & hi_mask)) atomicAdd(&hist[(k >> shift) & 255], weight(s_idx[i]));
2814        }
2815        __syncthreads();
2816        if (t == 0) {
2817            int cum = above, d = 255;
2818            for (; d > 0; --d) {
2819                if (cum + hist[d] >= width) break;
2820                cum += hist[d];
2821            }
2822            s_digit = d;
2823            s_above = cum;
2824        }
2825        __syncthreads();
2826        prefix |= (uint32_t) s_digit << shift;
2827        above = s_above;
2828        __syncthreads();
2829    }
2830    const uint32_t thr = prefix;
2831    const int eq_budget = (int) (width - above);
2832    // 4. the candidates in block order (bitonic sort; padding sorts last)
2833    int n2 = 1;
2834    while (n2 < n) n2 <<= 1;
2835    for (int i = n + t; i < n2; i += TK_T) { s_idx[i] = 0x7fffffff; s_key[i] = 0u; }
2836    __syncthreads();
2837    for (int kk = 2; kk <= n2; kk <<= 1) {
2838        for (int j = kk >> 1; j > 0; j >>= 1) {
2839            for (int i = t; i < n2; i += TK_T) {
2840                const int p = i ^ j;
2841                if (p > i) {
2842                    const bool up = (i & kk) == 0;
2843                    const int a = s_idx[i], b = s_idx[p];
2844                    if ((a > b) == up) {
2845                        s_idx[i] = b; s_idx[p] = a;
2846                        const uint32_t ka = s_key[i]; s_key[i] = s_key[p]; s_key[p] = ka;
2847                    }
2848                }
2849            }
2850            __syncthreads();
2851        }
2852    }
2853    // 5. the emit: cells above thr, and the first eq_budget cells at thr, in block order
2854    constexpr int PER = TS_CAP / TK_T;              // candidates per thread, consecutive
2855    int eqc[PER], gtc[PER];
2856    int my_eq = 0;
2857#pragma unroll
2858    for (int r = 0; r < PER; ++r) {
2859        const int i = t * PER + r;
2860        const int w = i < n ? weight(s_idx[i]) : 0;
2861        const uint32_t k = s_key[i < n ? i : 0];
2862        gtc[r] = (i < n && k > thr) ? w : 0;
2863        eqc[r] = (i < n && k == thr) ? w : 0;
2864        my_eq += eqc[r];
2865    }
2866    int eq_before = ts_block_scan(my_eq, s_w);
2867    int sel[PER], my_sel = 0;
2868#pragma unroll
2869    for (int r = 0; r < PER; ++r) {
2870        const int left = eq_budget - eq_before;
2871        const int take = left < 0 ? 0 : (left > eqc[r] ? eqc[r] : left);
2872        sel[r] = gtc[r] + take;
2873        my_sel += sel[r];
2874        eq_before += eqc[r];
2875    }
2876    int pos = ts_block_scan(my_sel, s_w);
2877#pragma unroll
2878    for (int r = 0; r < PER; ++r) {
2879        const int i = t * PER + r;
2880        if (sel[r] > 0) {
2881            const int64_t b = s_idx[i];
2882            for (int c = 0; c < sel[r]; ++c) out[pos + c] = (int32_t) (b * R + c);
2883        }
2884        pos += sel[r];
2885    }
2886}
2887
2888// The prompt path's one-read top-k: STRATA_TOPK_SAMPLE=0 / 1 forces it off / on for any card; unset it is a Turing kernel
2889// of the series (STRATA_SM75_PERF=1).  (As submitted in #2093 it was on for every CUDA card; same ids, but only measured
2890// on an RTX 2080 Ti, so the other cards keep the wide kernel.)
2891bool topk_sample_on() {
2892    static const int env = [] { const char* v = std::getenv("STRATA_TOPK_SAMPLE"); return v ? (std::atoi(v) != 0 ? 1 : 0) : -1; }();
2893    if (env >= 0) return env != 0;
2894    static int ok[64] = {};   // 0 unknown, 1 yes, 2 no
2895    int dev = 0;
2896    if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return false; }
2897    if (ok[dev] == 0) {
2898        int major = 0, minor = 0;
2899        cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev);
2900        cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev);
2901        ok[dev] = strata::sm75_default(major, minor) ? 1 : 2;
2902    }
2903    return ok[dev] == 1;
2904}
2905#endif
2906
2907void qsa_block_topk(const float* scores, const int32_t* steps, int64_t nq, int64_t max_blocks, int64_t cap,
2908                    const QsaShapes& s, int32_t* ids, void* stream, int64_t active_blocks) {
2909    // keys in registers when every query's blocks fit (contexts up to ~135K cells), else (CUDA) the same threads
2910    // reading them from memory; the same ids. STRATA_TOPK_OLD=1: the original kernel
2911    static const bool old = std::getenv("STRATA_TOPK_OLD") != nullptr;
2912    if (nq <= 0) return;
2913#if !defined(__HIPCC__)
2914    // sm_90+: a cluster of CL_N CTAs per query for the calls of a few queries (decode windows); the same ids.
2915    // STRATA_QSA_CLUSTER=0: the one-CTA kernels below
2916    static const bool cluster = [] {
2917        const char* v = std::getenv("STRATA_QSA_CLUSTER");
2918        return !v || std::atoi(v) != 0;
2919    }();
2920    if (cluster && !old && nq <= CL_MAXQ && qsa_block_topk_cluster(scores, steps, nq, max_blocks, cap, s, ids, stream))
2921        return;
2922#endif
2923#if !defined(__HIPCC__)
2924    // Turing decode (a window's few queries, no block count): the split kernels above; the same ids
2925    if (!old && active_blocks <= 0 && max_blocks >= 16384 && s.idx_block == R &&
2926        cap >= qsa_selection_width(kTopkMaxCells, s) && topk_split_device() &&
2927        qsa_block_topk_split(scores, steps, nq, max_blocks, cap, ids, (cudaStream_t) stream)) {
2928        const cudaError_t e = cudaGetLastError();
2929        if (e != cudaSuccess) { std::fprintf(stderr, "qsa_block_topk (split): %s\n", cudaGetErrorString(e)); std::exit(1); }
2930        return;
2931    }
2932#endif
2933    // the blocks a query can have: the call's active count when the caller knows it (the prompt path), else the capacity.
2934    // Decode (no count) keeps the capacity rule and the original register width: nothing changes there.
2935#if defined(__HIPCC__)
2936    const bool counted = active_blocks > 0;
2937#else
2938    // Turing: --max-context 262144 makes the stride 65538, even while a 131K prompt's active blocks fit in
2939    // TK_T * TK_PER registers. Use the prefill bound on sm_75, keeping max_blocks as the score-row stride.
2940    // Other CUDA devices keep 0.1.32's capacity rule: #337 was measured on RDNA4, and RTX 5070 64K prompts were
2941    // 1-3% slower. Decode/captured graphs omit the bound and never query the device here.
2942    static const bool capacity_guard = std::getenv("STRATA_TOPK_CAPACITY_GUARD") != nullptr;
2943    // STRATA_TOPK_ACTIVE_ANY=1 (tests): the Turing dispatch on any CUDA card, so qsa_topk_active_parity checks it
2944    // on whatever card runs the tests (the kernels are the same on every architecture)
2945    static const bool any_card = [] { const char* v = std::getenv("STRATA_TOPK_ACTIVE_ANY"); return v && v[0] == '1'; }();
2946    const bool counted = !capacity_guard && active_blocks > 0 && active_blocks <= max_blocks &&
2947                         (any_card || topk_active_turing_device());
2948#endif
2949    const int64_t reach = counted && active_blocks < max_blocks ? active_blocks : max_blocks;
2950    const int64_t fit = (int64_t) TK_T * (counted ? TK_PER_MAX : TK_PER);
2951#if defined(__HIPCC__)
2952    // gfx1201: below ~28K cells (7,168 blocks) the 1,024-thread kernel's fixed cost loses to the ref.  STRATA_TOPK_REG_MIN_BLOCKS
2953    // moves the line (0: the register kernel always); gfx1151's table sets 4096, the crossover with the cooperative scan
2954    static const int64_t kRegMinBlocks = [] {
2955        const char* v = std::getenv("STRATA_TOPK_REG_MIN_BLOCKS");
2956        return v != nullptr ? (int64_t) std::atoll(v) : (int64_t) 7168;
2957    }();
2958    const bool too_small = counted && reach < kRegMinBlocks;
2959    // campaign3: `reach > fit` no longer forces the ref radix - the wide kernel below takes it (same ids).
2960    if (old || too_small) {
2961#else
2962    constexpr int64_t kWideMinBlocks = 4608;   // RTX 3060: a prompt batch below ~18K cells is faster on the ref
2963    const bool too_small = reach > fit && active_blocks > 0 && active_blocks < kWideMinBlocks;
2964    if (old || too_small) {
2965#endif
2966        qsa_block_topk_ref(scores, steps, nq, max_blocks, cap, s, ids, stream);
2967        return;
2968    }
2969    if (s.idx_block != R || cap < qsa_selection_width(kTopkMaxCells, s)) {
2970        std::fprintf(stderr, "qsa_block_topk: unsupported geometry or cap\n");
2971        std::exit(1);
2972    }
2973    // Turing prefill (the `counted` bound) above ~90K cells (22,528 blocks): the wide kernel, which reads the keys
2974    // coalesced, instead of the register kernel's uncoalesced per-thread runs (PR #743: 131K, 1.03 -> 0.75 ms); the
2975    // same ids.  STRATA_TOPK_STREAM=0 restores the register kernel there.
2976    // campaign3: on HIP too (was CUDA-only; gfx11 has no sm_90 cluster path and fell to the ref radix past the
2977    // register kernel's reach - the deep-decode top-k cost).  Same ids as the ref kernel.
2978    static const bool turing_wide = [] {
2979        const char* v = std::getenv("STRATA_TOPK_STREAM");
2980        return v == nullptr || v[0] != '0';
2981    }();
2982    if (reach > fit || (turing_wide && counted && reach > 22528)) {   // past the register kernel's reach, or Turing's band
2983#if !defined(__HIPCC__)
2984        if (counted && nq <= TS_MAXQ && reach > 28672 && topk_sample_on()) {   // one read of the scores (below ~115K cells the wide kernel is as fast)
2985            block_topk_sample_kernel<<<(unsigned) nq, TK_T, 0, (cudaStream_t) stream>>>(scores, steps, max_blocks, cap, ids);
2986            block_topk_wide_kernel<true><<<(unsigned) nq, TK_T, 0, (cudaStream_t) stream>>>(scores, steps, max_blocks, cap, ids);
2987        } else
2988#endif
2989        block_topk_wide_kernel<false><<<(unsigned) nq, TK_T, 0, (cudaStream_t) stream>>>(scores, steps, max_blocks, cap, ids);
2990    } else
2991    if (reach <= (int64_t) TK_T * TK_PER)
2992        block_topk_reg_kernel<TK_PER><<<(unsigned) nq, TK_T, 0, (cudaStream_t) stream>>>(scores, steps, max_blocks, cap, ids);
2993    else
2994        block_topk_reg_kernel<TK_PER_MAX><<<(unsigned) nq, TK_T, 0, (cudaStream_t) stream>>>(scores, steps, max_blocks, cap, ids);
2995    const cudaError_t e = cudaGetLastError();
2996    if (e != cudaSuccess) { std::fprintf(stderr, "qsa_block_topk: %s\n", cudaGetErrorString(e)); std::exit(1); }
2997}
2998
2999#if !defined(__HIPCC__) && defined(STRATA_EXPERIMENTAL_SM60)
3000// STRATA_SCORES_DX: 0 off, 1 on for any CUDA card; unset: on for compute capability 6.x (block_scores_dx_kernel).
3001// `sms`: the device's multiprocessors (the grid: as many CTAs as fit on each).
3002static bool scores_dx_device(int& sms) {
3003    static const int env = [] {
3004        const char* v = std::getenv("STRATA_SCORES_DX");
3005        return v == nullptr || *v == '\0' ? -1 : std::atoi(v);
3006    }();
3007    if (env == 0) return false;
3008    int dev = 0;
3009    if (cudaGetDevice(&dev) != cudaSuccess) { cudaGetLastError(); return false; }
3010    static thread_local int cached_device = -1, cached_sms = 0;
3011    static thread_local bool pascal = false;
3012    if (dev != cached_device) {
3013        int major = 0;
3014        pascal = cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) == cudaSuccess &&
3015                 strata::cc_major_of(major) == 6;
3016        if (cudaDeviceGetAttribute(&cached_sms, cudaDevAttrMultiProcessorCount, dev) != cudaSuccess) cached_sms = 0;
3017        cudaGetLastError();
3018        cached_device = dev;
3019    }
3020    sms = cached_sms;
3021    return sms > 0 && (env > 0 || pascal);
3022}
3023
3024template <int NQ>
3025static void scores_dx_launch(const float* pooled, const float* q_idx, const int32_t* steps, int64_t max_blocks,
3026                             float* scores, int sms, cudaStream_t st) {
3027    const size_t smem = (size_t) (DX_NB * DX_KS + NQ * IDX_HEADS * IDX_DIM + NQ * IDX_HEADS * DX_NB) * sizeof(float);
3028    static thread_local int per_sm[64][9] = {};          // CTAs per multiprocessor, by device and NQ
3029    int dev = 0;
3030    cudaGetDevice(&dev);
3031    int& occ = per_sm[dev & 63][NQ];
3032    if (occ == 0 && (cudaOccupancyMaxActiveBlocksPerMultiprocessor(&occ, block_scores_dx_kernel<NQ>, DX_T, smem) !=
3033                         cudaSuccess || occ < 1)) {
3034        cudaGetLastError();
3035        occ = 2;
3036    }
3037    const int64_t tiles = (max_blocks + DX_NB - 1) / DX_NB, want = (int64_t) occ * sms;
3038    const unsigned grid = (unsigned) (want < tiles ? want : tiles);
3039    block_scores_dx_kernel<NQ><<<grid, DX_T, smem, st>>>(pooled, q_idx, steps, max_blocks, scores);
3040}
3041
3042static bool qsa_block_scores_dx(const float* pooled, const float* dead, const float* q_idx, const int32_t* steps,
3043                                int64_t nq, int64_t max_blocks, float* scores, void* stream) {
3044    int sms = 0;
3045    if (nq < 1 || nq > MQ || !scores_dx_device(sms)) return false;
3046    const cudaStream_t st = (cudaStream_t) stream;
3047    switch (nq) {
3048        case 1: scores_dx_launch<1>(pooled, q_idx, steps, max_blocks, scores, sms, st); break;
3049        case 2: scores_dx_launch<2>(pooled, q_idx, steps, max_blocks, scores, sms, st); break;
3050        case 3: scores_dx_launch<3>(pooled, q_idx, steps, max_blocks, scores, sms, st); break;
3051        case 4: scores_dx_launch<4>(pooled, q_idx, steps, max_blocks, scores, sms, st); break;
3052        case 5: scores_dx_launch<5>(pooled, q_idx, steps, max_blocks, scores, sms, st); break;
3053        case 6: scores_dx_launch<6>(pooled, q_idx, steps, max_blocks, scores, sms, st); break;
3054        case 7: scores_dx_launch<7>(pooled, q_idx, steps, max_blocks, scores, sms, st); break;
3055        default: scores_dx_launch<8>(pooled, q_idx, steps, max_blocks, scores, sms, st); break;
3056    }
3057    block_scores_tail_kernel<<<(unsigned) nq, 32, 0, st>>>(dead, q_idx, steps, max_blocks, scores);
3058    const cudaError_t e = cudaGetLastError();
3059    if (e != cudaSuccess) { std::fprintf(stderr, "qsa_block_scores (dx): %s\n", cudaGetErrorString(e)); std::exit(1); }
3060    return true;
3061}
3062#endif
3063
3064#if !defined(__HIPCC__) && defined(STRATA_EXPERIMENTAL_SM60)
3065// STRATA_TOPK_MULTI: 0 off, 1 on for any CUDA card and capacity; unset: on for compute capability 6.x past the register
3066// kernel's reach (GP100: 0.39 -> 0.04 ms per call at 300K cells; see block_topk_multi_hist_kernel)
3067static int topk_multi_mode() {
3068    static const int env = [] {
3069        const char* v = std::getenv("STRATA_TOPK_MULTI");
3070        return v == nullptr || *v == '\0' ? -1 : std::atoi(v);
3071    }();
3072    if (env >= 0) return env != 0 ? 1 : 0;
3073    int dev = 0;
3074    if (cudaGetDevice(&dev) != cudaSuccess) { cudaGetLastError(); return 0; }
3075    static thread_local int cached_device = -1;
3076    static thread_local int mode = 0;
3077    if (dev != cached_device) {
3078        int major = 0;
3079        mode = cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) == cudaSuccess &&
3080                       strata::cc_major_of(major) == 6 ? 2 : 0;
3081        cudaGetLastError();
3082        cached_device = dev;
3083    }
3084    return mode;
3085}
3086
3087static bool qsa_block_topk_multi(const float* scores, const int32_t* steps, int64_t nq, int64_t max_blocks, int64_t cap,
3088                                 int32_t* ids, void* stream, int32_t* scratch) {
3089    // CTAs per query from the capacity (the grid is fixed in a captured graph; each CTA's share follows n_bid): one per
3090    // 2,048 blocks, at most MT_NMAX. STRATA_TOPK_MULTI_N: a fixed count (tests)
3091    static const int n_env = [] { const char* v = std::getenv("STRATA_TOPK_MULTI_N"); return v ? std::atoi(v) : 0; }();
3092    int64_t n = n_env > 0 ? n_env : (max_blocks + 2047) / 2048;
3093    n = n < 1 ? 1 : n > MT_NMAX ? MT_NMAX : n;
3094    const dim3 grid((unsigned) n, (unsigned) nq);
3095    const cudaStream_t st = (cudaStream_t) stream;
3096    block_topk_multi_hist_kernel<0><<<grid, MT_T, 0, st>>>(scores, steps, max_blocks, scratch);
3097    block_topk_multi_hist_kernel<1><<<grid, MT_T, 0, st>>>(scores, steps, max_blocks, scratch);
3098    block_topk_multi_hist_kernel<2><<<grid, MT_T, 0, st>>>(scores, steps, max_blocks, scratch);
3099    block_topk_multi_hist_kernel<3><<<grid, MT_T, 0, st>>>(scores, steps, max_blocks, scratch);
3100    block_topk_multi_count_kernel<<<grid, MT_T, 0, st>>>(scores, steps, max_blocks, scratch);
3101    block_topk_multi_emit_kernel<<<grid, MT_T, 0, st>>>(scores, steps, max_blocks, cap, ids, scratch);
3102    const cudaError_t e = cudaGetLastError();
3103    if (e != cudaSuccess) { std::fprintf(stderr, "qsa_block_topk multi: %s\n", cudaGetErrorString(e)); std::exit(1); }
3104    return true;
3105}
3106#endif
3107
3108// ---- STRATA_SELECT_LONG (verify.cpp, opt-in): the decode select past ~64K cells.  Outside the SM60 build (and on HIP)
3109// these are the plain calls; the scratch is never asked for.
3110int64_t qsa_topk_multi_scratch_ints(int64_t nq) {
3111#if !defined(__HIPCC__) && defined(STRATA_EXPERIMENTAL_SM60)
3112    return (nq < MT_MAXQ ? nq : MT_MAXQ) * (int64_t) MT_Q_INTS;
3113#else
3114    (void) nq;
3115    return 0;
3116#endif
3117}
3118
3119void qsa_block_topk_long(const float* scores, const int32_t* steps, int64_t nq, int64_t max_blocks, int64_t cap,
3120                         const QsaShapes& s, int32_t* ids, void* stream, int64_t active_blocks, int32_t* multi_scratch) {
3121#if !defined(__HIPCC__) && defined(STRATA_EXPERIMENTAL_SM60)
3122    // several CTAs per query through the caller's scratch (decode calls: no active count, a few queries)
3123    static const bool old = std::getenv("STRATA_TOPK_OLD") != nullptr;
3124    if (nq > 0 && multi_scratch != nullptr && !old && active_blocks <= 0 && nq <= MT_MAXQ && s.idx_block == R &&
3125        cap >= qsa_selection_width(kTopkMaxCells, s)) {
3126        const int mode = topk_multi_mode();
3127        if ((mode == 1 || (mode == 2 && max_blocks > (int64_t) TK_T * TK_PER)) &&
3128            qsa_block_topk_multi(scores, steps, nq, max_blocks, cap, ids, stream, multi_scratch))
3129            return;
3130    }
3131#else
3132    (void) multi_scratch;
3133#endif
3134    qsa_block_topk(scores, steps, nq, max_blocks, cap, s, ids, stream, active_blocks);
3135}
3136
3137void qsa_block_scores_long(const float* pooled, const float* dead, const float* q_idx, const int32_t* steps, int64_t nq,
3138                           int64_t max_blocks, const QsaShapes& s, float* scores, void* stream, int64_t active_blocks) {
3139#if !defined(__HIPCC__) && defined(STRATA_EXPERIMENTAL_SM60)
3140    if (nq > 0 && s.idx_dim == IDX_DIM && s.idx_n_head == IDX_HEADS && s.idx_block == R && scores_multi_on() &&
3141        nq <= MQ && active_blocks <= 0 &&
3142        qsa_block_scores_dx(pooled, dead, q_idx, steps, nq, max_blocks, scores, stream))
3143        return;
3144#endif
3145    qsa_block_scores(pooled, dead, q_idx, steps, nq, max_blocks, s, scores, stream, active_blocks);
3146}
3147
3148// ==== STRATA_SELECT_TWO_PASS (the prompt path's block scores in two precisions; qsa_two_pass.hpp has the bound) ====
3149// qsa_block_scores_tc computes every block score in 3xTF32.  Here every block is scored once in single-pass TF32
3150// (S1), a per-block bound eps encloses today's 3xTF32 score S3 in [S1 - eps, S1 + eps], and only the blocks whose
3151// interval reaches the query's top-k cut-off are scored again, with block_scores_tc_kernel's arithmetic, bit for bit.
3152// qsa_block_topk then reads a row whose every block lies on the same side of the threshold as in today's row and
3153// whose blocks at the threshold hold today's exact scores: the same threshold, the same ties, the same cells.  The row
3154// itself is not today's (kept blocks hold S1), so it is for qsa_block_topk only: nothing else reads m.sel_scores.
3155#if !defined(__HIPCC__)
3156__device__ unsigned long long g_tp_stats[two_pass::kStatCount];
3157
3158namespace {
3159namespace tp = strata::kernels::two_pass;
3160
3161constexpr int TP1_ITER = 8;      // 32-block tiles per single-pass CTA (its query fragments are loaded once)
3162constexpr int TPB_T = 512;       // the band kernel's threads (one query per CTA)
3163static_assert(TPB_T == IDX_HEADS * IDX_DIM, "the band kernel reads one query element per thread");
3164
3165__device__ __forceinline__ float tp_inf() { return __int_as_float(0x7f800000); }
3166__device__ __forceinline__ float tp_key_float(uint32_t k) {   // order_key's inverse (keys of non-NaN floats)
3167    return __uint_as_float((k & 0x80000000u) ? (k & 0x7fffffffu) : ~k);
3168}
3169
3170// The single-pass enclosure of block b's 3xTF32 score from its single-pass score s: [lo, hi], eps rounded up and the
3171// ends rounded outwards.  False: no bound (a non-finite score, norm or coefficient, or a bound past kMaxEps).
3172__device__ __forceinline__ bool tp_interval(float s, float2 kn, float P, float Q, float& lo, float& hi, float& e) {
3173    e = __fmaf_ru(P, kn.y, __fmaf_ru(Q, kn.x, tp::kAbs));
3174    if (!(e <= tp::kMaxEps) || !(fabsf(s) <= FLT_MAX)) return false;
3175    lo = __fsub_rd(s, e);
3176    hi = __fadd_ru(s, e);
3177    return true;
3178}
3179
3180// The key norms (upper bounds): per pooled block |tf32(k)| and |tf32(k - tf32(k))|, the split block_scores_tc_kernel
3181// makes, in double with every operation rounded up; a non-finite norm becomes +inf (its blocks are never bounded).
3182__global__ void __launch_bounds__(256) tp_keys_kernel(const float* __restrict__ pooled, int64_t n_blocks,
3183                                                      float2* __restrict__ kn) {
3184    const int64_t b = (int64_t) blockIdx.x * 8 + (threadIdx.x >> 5);
3185    if (b >= n_blocks) return;
3186    const int lane = threadIdx.x & 31;
3187    const float4 v = reinterpret_cast<const float4*>(pooled + b * IDX_DIM)[lane];
3188    const float x[4] = {v.x, v.y, v.z, v.w};
3189    double sh = 0.0, sl = 0.0;
3190#pragma unroll
3191    for (int j = 0; j < 4; ++j) {
3192        const float h = __uint_as_float(tf32_hi(x[j]));
3193        const float l = __uint_as_float(tf32_hi(x[j] - h));
3194        sh = __dadd_ru(sh, __dmul_ru((double) h, (double) h));
3195        sl = __dadd_ru(sl, __dmul_ru((double) l, (double) l));
3196    }
3197#pragma unroll
3198    for (int o = 16; o > 0; o >>= 1) {
3199        sh = __dadd_ru(sh, __shfl_xor_sync(0xffffffffu, sh, o));
3200        sl = __dadd_ru(sl, __shfl_xor_sync(0xffffffffu, sl, o));
3201    }
3202    if (lane == 0) {
3203        float kh = __double2float_ru(__dsqrt_ru(sh)), kl = __double2float_ru(__dsqrt_ru(sl));
3204        if (!(kh <= FLT_MAX)) kh = tp_inf();
3205        if (!(kl <= FLT_MAX)) kl = tp_inf();
3206        kn[b] = make_float2(kh, kl);
3207    }
3208}
3209
3210// Pass 1: S1 = sum over the heads of relu(tf32(q) . tf32(k)), one MMA per step (block_scores_tc_kernel makes three).
3211// Warp h is head h and keeps its 16 steps of A fragments in registers; a CTA is one 16-query tile (blockIdx.x, so the
3212// CTAs that run together read the same keys) and TP1_ITER tiles of 32 blocks.  Blocks < n_bid only, as today; the
3213// tail block is block_scores_tail_kernel's.  Also clears the tile flags the band kernel sets.
3214__global__ void __launch_bounds__(128) tp_score1_kernel(const float* __restrict__ pooled,
3215                                                        const float* __restrict__ q_idx,
3216                                                        const int32_t* __restrict__ steps, int64_t nq,
3217                                                        int64_t max_blocks, int64_t reach, float* __restrict__ out,
3218                                                        int* __restrict__ tiles) {
3219    __shared__ __align__(16) uint32_t sK[TC_NB * TC_KS];
3220    __shared__ float red[IDX_HEADS][TC_QT][TC_NB + 1];
3221    __shared__ int s_nbid[TC_QT];
3222    const int t = threadIdx.x, lane = t & 31, h = t >> 5, gid = lane >> 2, tig = lane & 3;
3223    const int64_t q0 = (int64_t) blockIdx.x * TC_QT;
3224    if (blockIdx.y == 0 && t == 0) tiles[blockIdx.x] = 0;
3225    if (t < TC_QT) s_nbid[t] = q0 + t < nq ? steps[(q0 + t) * kStepCount + kStepNBid] : 0;
3226    uint32_t a[16][4];   // rows gid and gid + 8, k = 8s + tig and 8s + tig + 4 (the m16n8k8 A fragment)
3227    {
3228        const bool r0 = q0 + gid < nq, r1 = q0 + gid + 8 < nq;
3229        const float* qa = q_idx + (r0 ? q0 + gid : 0) * (IDX_HEADS * IDX_DIM) + h * IDX_DIM + tig;
3230        const float* qb = q_idx + (r1 ? q0 + gid + 8 : 0) * (IDX_HEADS * IDX_DIM) + h * IDX_DIM + tig;
3231#pragma unroll
3232        for (int s = 0; s < 16; ++s) {
3233            a[s][0] = tf32_hi(r0 ? qa[8 * s] : 0.f);
3234            a[s][1] = tf32_hi(r1 ? qb[8 * s] : 0.f);
3235            a[s][2] = tf32_hi(r0 ? qa[8 * s + 4] : 0.f);
3236            a[s][3] = tf32_hi(r1 ? qb[8 * s + 4] : 0.f);
3237        }
3238    }
3239    __syncthreads();
3240    int hi_nbid = 0;
3241    for (int i = 0; i < TC_QT; ++i) hi_nbid = max(hi_nbid, s_nbid[i]);
3242    for (int it = 0; it < TP1_ITER; ++it) {
3243        const int64_t b0 = ((int64_t) blockIdx.y * TP1_ITER + it) * TC_NB;
3244        if (b0 >= reach || b0 >= hi_nbid) break;
3245        __syncthreads();                              // the previous tile's sK and red reads are done
3246        for (int i = t; i < TC_NB * IDX_DIM / 4; i += 128) {
3247            const int r = i / (IDX_DIM / 4), c = i % (IDX_DIM / 4);
3248            float4 v = make_float4(0.f, 0.f, 0.f, 0.f);
3249            if (b0 + r < hi_nbid) v = reinterpret_cast<const float4*>(pooled + (b0 + r) * IDX_DIM)[c];
3250            *reinterpret_cast<uint4*>(sK + r * TC_KS + c * 4) =
3251                make_uint4(tf32_hi(v.x), tf32_hi(v.y), tf32_hi(v.z), tf32_hi(v.w));
3252        }
3253        __syncthreads();
3254        float acc[4][4];
3255#pragma unroll
3256        for (int n = 0; n < 4; ++n) acc[n][0] = acc[n][1] = acc[n][2] = acc[n][3] = 0.f;
3257#pragma unroll
3258        for (int s = 0; s < 16; ++s) {
3259#pragma unroll
3260            for (int n = 0; n < 4; ++n) {
3261                const uint32_t* kr = sK + (n * 8 + gid) * TC_KS + 8 * s + tig;
3262                const uint32_t b[2] = {kr[0], kr[4]};
3263                mma_tf32(acc[n], a[s], b);
3264            }
3265        }
3266#pragma unroll
3267        for (int n = 0; n < 4; ++n) {
3268            const int c = n * 8 + 2 * tig;
3269            red[h][gid][c] = acc[n][0] > 0.0f ? acc[n][0] : 0.0f;
3270            red[h][gid][c + 1] = acc[n][1] > 0.0f ? acc[n][1] : 0.0f;
3271            red[h][gid + 8][c] = acc[n][2] > 0.0f ? acc[n][2] : 0.0f;
3272            red[h][gid + 8][c + 1] = acc[n][3] > 0.0f ? acc[n][3] : 0.0f;
3273        }
3274        __syncthreads();
3275        for (int e = t; e < TC_QT * TC_NB; e += 128) {
3276            const int r = e / TC_NB, c = e % TC_NB;
3277            const int64_t qi = q0 + r, b = b0 + c;
3278            if (qi >= nq || b >= s_nbid[r] || b >= max_blocks) continue;
3279            float score = 0.0f;
3280#pragma unroll
3281            for (int h2 = 0; h2 < IDX_HEADS; ++h2) score += red[h2][r][c];
3282            out[qi * max_blocks + b] = score;
3283        }
3284    }
3285}
3286
3287// block_topk_kernel's threshold over a list in shared memory: the largest key k such that the weighted entries with
3288// a key >= k reach `width`, 8 bits a pass with that kernel's digit rule (the largest digit whose cells at or above it
3289// reach the width, else 0).  unit: every entry weighs 1 (the sample); else a listed block weighs R and the tail block
3290// n_bid w_tail.  Every thread of the CTA calls it; it ends synchronized.
3291__device__ uint32_t tp_select(const uint32_t* __restrict__ key, const int32_t* __restrict__ blk, int n, int width,
3292                              bool unit, int64_t n_bid, int w_tail, int* hist, int* s_misc) {
3293    const int t = threadIdx.x, lane = t & 31, warp = t >> 5;
3294    uint32_t prefix = 0;
3295    int above = 0;
3296    for (int shift = 24; shift >= 0; shift -= 8) {
3297        for (int i = t; i < 256; i += TPB_T) hist[i] = 0;
3298        __syncthreads();
3299        const uint32_t hi_mask = shift == 24 ? 0u : (0xffffffffu << (shift + 8));
3300        for (int i0 = 0; i0 < n; i0 += TPB_T) {       // the same trip count in every thread: whole warps match
3301            const int i = i0 + t;
3302            const uint32_t k = i < n ? key[i] : 0u;
3303            const bool hit = i < n && (k & hi_mask) == (prefix & hi_mask);
3304            const bool tail = hit && !unit && blk[i] == n_bid;
3305            const int d = (int) ((k >> shift) & 255u);
3306            const int g = hit && !tail ? d : 256;
3307#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ < 700
3308            // no __match_any_sync on 6.x: one add per thread (integer atomics: the same sums, only more of them)
3309            if (g < 256) atomicAdd(&hist[d], unit ? 1 : R);
3310#else
3311            const unsigned grp = __match_any_sync(0xffffffffu, g);   // one add per digit and warp
3312            if (g < 256 && lane == __ffs(grp) - 1) atomicAdd(&hist[d], (unit ? 1 : R) * __popc(grp));
3313#endif
3314            if (tail) atomicAdd(&hist[d], w_tail);
3315        }
3316        __syncthreads();
3317        if (warp == 0) {                              // the digit: lane l holds digits 8l .. 8l + 7
3318            int v[8], local = 0;
3319#pragma unroll
3320            for (int j = 0; j < 8; ++j) { v[j] = hist[lane * 8 + j]; local += v[j]; }
3321            int suf = local;                          // cells in this lane's digits and every higher one
3322#pragma unroll
3323            for (int o = 1; o < 32; o <<= 1) {
3324                const int y = __shfl_down_sync(0xffffffffu, suf, o);
3325                if (lane + o < 32) suf += y;
3326            }
3327            int cum = above + suf - local, best = -1, best_cum = 0;
3328#pragma unroll
3329            for (int j = 7; j >= 0; --j) {
3330                const int dd = lane * 8 + j;
3331                if (best < 0 && dd >= 1 && cum + v[j] >= width) { best = dd; best_cum = cum; }
3332                cum += v[j];
3333            }
3334            const unsigned m = __ballot_sync(0xffffffffu, best >= 0);
3335            const int top = m ? 31 - __clz((int) m) : 0;
3336            const int dsel = __shfl_sync(0xffffffffu, best, top), csel = __shfl_sync(0xffffffffu, best_cum, top);
3337            const int all = __shfl_sync(0xffffffffu, suf, 0), h0 = __shfl_sync(0xffffffffu, v[0], 0);
3338            if (lane == 0) {
3339                s_misc[0] = m ? dsel : 0;
3340                s_misc[1] = m ? csel : above + all - h0;   // digit 0: every cell of digits 1..255 is above it
3341            }
3342        }
3343        __syncthreads();
3344        prefix |= (uint32_t) s_misc[0] << shift;
3345        above = s_misc[1];
3346        __syncthreads();
3347    }
3348    return prefix;
3349}
3350
3351// Per query: the blocks to score again.  1. the coefficients P, Q (qsa_two_pass.hpp) from the query's head norms;
3352// 2. a candidate threshold F from every 32nd block (only when the blocks outnumber the list): the ks-th largest
3353// sampled S1 - eps; 3. one read of every block: the candidates (S1 + eps >= F), the cells with S1 - eps >= F (at least
3354// `width` of them, so the threshold T of today's row and the single-pass one T1 are both >= F and every block that
3355// matters below is a candidate) and E = the largest candidate eps; 4. T1 over the candidates; 5. T lies in
3356// [max(T1 - E, F), T1 + E]: a candidate whose interval reaches it (and is not the exact tail block) is listed for a
3357// re-score, by its column residue b % 8.  A query that cannot be settled (no bound for some candidate, a list or a
3358// residue list full, too few cells above F) is flagged: its 16-query tile is scored again in full.
3359__global__ void __launch_bounds__(TPB_T) tp_band_kernel(const float* __restrict__ scores,
3360                                                        const float* __restrict__ q_idx,
3361                                                        const int32_t* __restrict__ steps, int64_t max_blocks,
3362                                                        const float2* __restrict__ kn, float2* __restrict__ qc,
3363                                                        int* __restrict__ mode, int* __restrict__ cnt,
3364                                                        int* __restrict__ ids, int* __restrict__ tiles) {
3365    extern __shared__ __align__(16) uint32_t tp_sm[];
3366    uint32_t* c_key = tp_sm;                                           // [kCandCap] S1 keys (first: the sample)
3367    int32_t* c_blk = reinterpret_cast<int32_t*>(tp_sm + tp::kCandCap);  // [kCandCap] their blocks
3368    __shared__ int hist[256];
3369    __shared__ int s_misc[2], s_n, s_bad, s_wf[TPB_T / 32], s_cnt[8];
3370    __shared__ float s_e[TPB_T / 32], s_P, s_Q, s_E;
3371    __shared__ double s_hn[TPB_T / 32][2];
3372    const int t = threadIdx.x, lane = t & 31, warp = t >> 5;
3373    const int64_t qi = blockIdx.x;
3374    const int32_t* st = steps + qi * kStepCount;
3375    const int64_t n_kv = st[kStepNKv], n_bid = st[kStepNBid], width = st[kStepWidth];
3376    if (qi == 0 && t == 0) atomicAdd(&g_tp_stats[tp::kStCalls], 1ull);
3377    if (n_kv <= width) {                              // every cell is selected: qsa_block_topk reads no score
3378        if (t == 0) { mode[qi] = 0; atomicAdd(&g_tp_stats[tp::kStIdentity], 1ull); }
3379        return;
3380    }
3381    {   // 1. a = sum_h |tf32(q_h)|, c = sum_h |tf32(q_h - tf32(q_h))|, rounded up; warps 4h .. 4h + 3 hold head h
3382        const float x = q_idx[qi * IDX_HEADS * IDX_DIM + t];
3383        const float hx = __uint_as_float(tf32_hi(x));
3384        const float lx = __uint_as_float(tf32_hi(x - hx));
3385        double sh = __dmul_ru((double) hx, (double) hx), sl = __dmul_ru((double) lx, (double) lx);
3386#pragma unroll
3387        for (int o = 16; o > 0; o >>= 1) {
3388            sh = __dadd_ru(sh, __shfl_xor_sync(0xffffffffu, sh, o));
3389            sl = __dadd_ru(sl, __shfl_xor_sync(0xffffffffu, sl, o));
3390        }
3391        if (lane == 0) { s_hn[warp][0] = sh; s_hn[warp][1] = sl; }
3392        if (t == 0) { s_n = 0; s_bad = 0; }
3393        if (t < 8) s_cnt[t] = 0;
3394        __syncthreads();
3395        if (t == 0) {
3396            double a = 0.0, c = 0.0;
3397            for (int hh = 0; hh < IDX_HEADS; ++hh) {
3398                double eh = 0.0, el = 0.0;
3399                for (int w = 0; w < 4; ++w) { eh = __dadd_ru(eh, s_hn[4 * hh + w][0]); el = __dadd_ru(el, s_hn[4 * hh + w][1]); }
3400                a = __dadd_ru(a, __dsqrt_ru(eh));
3401                c = __dadd_ru(c, __dsqrt_ru(el));
3402            }
3403            double P = 0.0, Q = 0.0;
3404            tp::coefficients(a, c, P, Q);             // RN in double: far inside kSlack
3405            s_P = __double2float_ru(P);
3406            s_Q = __double2float_ru(Q);
3407        }
3408        __syncthreads();
3409    }
3410    const float P = s_P, Q = s_Q;
3411    const int64_t nb = n_bid + 1;
3412    const int w_tail = (int) (n_kv - n_bid * R);
3413    const float* sc = scores + qi * max_blocks;
3414    bool full = !(P <= tp::kMaxEps && Q <= tp::kMaxEps);
3415    float F = -tp_inf();
3416    if (!full && nb > tp::kCandCap) {                 // 2. the sample
3417        int64_t stride = tp::kSampleStride;
3418        while ((nb + stride - 1) / stride > tp::kCandCap) stride *= 2;
3419        const int ns = (int) ((nb + stride - 1) / stride);
3420        for (int i = t; i < ns; i += TPB_T) {
3421            const int64_t b = (int64_t) i * stride;
3422            uint32_t k = 0u;                          // no bound, or no cells: the lowest key
3423            if (b < n_bid) {
3424                float lo, hi, e;
3425                if (tp_interval(sc[b], kn[b], P, Q, lo, hi, e)) k = order_key(lo);
3426            } else if (w_tail > 0) {
3427                k = order_key(sc[b]);
3428            }
3429            c_key[i] = k;
3430        }
3431        __syncthreads();
3432        const int ks = (int) (2 * ((width + R * stride - 1) / (R * stride)) + 16);
3433        const uint32_t fk = tp_select(c_key, c_blk, ns, ks < ns ? ks : ns, true, n_bid, w_tail, hist, s_misc);
3434        if (fk != 0u) F = tp_key_float(fk);
3435    }
3436    int wf = 0;
3437    float emax = 0.0f;
3438    bool bad = false;
3439    if (!full) {                                      // 3. one read of every block
3440        for (int64_t b = t; b < nb; b += TPB_T) {
3441            float lo, hi, e = 0.0f, s;
3442            int w;
3443            if (b < n_bid) {
3444                w = R;
3445                s = sc[b];
3446                if (!tp_interval(s, kn[b], P, Q, lo, hi, e)) { bad = true; continue; }
3447            } else {
3448                w = w_tail;
3449                if (w == 0) continue;
3450                s = lo = hi = sc[b];                  // the tail kernel's score: today's
3451            }
3452            if (lo >= F) wf += w;
3453            if (hi >= F) {
3454                const int pos = atomicAdd(&s_n, 1);
3455                if (pos < tp::kCandCap) { c_key[pos] = order_key(s); c_blk[pos] = (int32_t) b; }
3456                emax = fmaxf(emax, e);
3457            }
3458        }
3459    }
3460#pragma unroll
3461    for (int o = 16; o > 0; o >>= 1) {
3462        wf += __shfl_xor_sync(0xffffffffu, wf, o);
3463        emax = fmaxf(emax, __shfl_xor_sync(0xffffffffu, emax, o));
3464    }
3465    bad = __any_sync(0xffffffffu, bad);
3466    if (lane == 0) { s_wf[warp] = wf; s_e[warp] = emax; if (bad) s_bad = 1; }
3467    __syncthreads();
3468    if (t == 0) {
3469        int W = 0;
3470        float E = 0.0f;
3471        for (int w = 0; w < TPB_T / 32; ++w) { W += s_wf[w]; E = fmaxf(E, s_e[w]); }
3472        s_misc[0] = W;
3473        s_E = E;
3474    }
3475    __syncthreads();
3476    const int n = s_n;
3477    full = full || s_bad != 0 || n > tp::kCandCap || s_misc[0] < width;
3478    if (!full) {
3479        // 4. T1, then 5. the window [lo_b, hi_b] that holds today's threshold
3480        const uint32_t t1k = tp_select(c_key, c_blk, n, (int) width, false, n_bid, w_tail, hist, s_misc);
3481        const float T1 = tp_key_float(t1k), E = s_E;
3482        const float lo_b = fmaxf(__fsub_rd(T1, E), F), hi_b = __fadd_ru(T1, E);
3483        for (int i = t; i < n; i += TPB_T) {
3484            const int64_t b = c_blk[i];
3485            if (b >= n_bid) continue;                 // the tail block holds today's score already
3486            float lo, hi, e;
3487            tp_interval(tp_key_float(c_key[i]), kn[b], P, Q, lo, hi, e);   // bounded in 3: the same result
3488            if (hi >= lo_b && lo <= hi_b) {
3489                const int r = (int) (b & 7);
3490                const int p = atomicAdd(&s_cnt[r], 1);
3491                if (p < tp::kResCap) ids[(qi * 8 + r) * tp::kResCap + p] = (int32_t) b;
3492            }
3493        }
3494        __syncthreads();
3495    }
3496    if (t == 0) {
3497        int tot = 0, mx = 0;
3498        for (int r = 0; r < 8; ++r) { tot += s_cnt[r]; mx = max(mx, s_cnt[r]); }
3499        if (mx > tp::kResCap) full = true;
3500        atomicAdd(&g_tp_stats[tp::kStQueries], 1ull);
3501        atomicAdd(&g_tp_stats[tp::kStBlocks], (unsigned long long) n_bid);
3502        if (full) {
3503            mode[qi] = 2;
3504            if (atomicExch(&tiles[qi / TC_QT], 1) == 0) atomicAdd(&g_tp_stats[tp::kStFullTiles], 1ull);
3505            atomicAdd(&g_tp_stats[tp::kStFull], 1ull);
3506        } else {
3507            for (int r = 0; r < 8; ++r) cnt[qi * 8 + r] = s_cnt[r];
3508            qc[qi] = make_float2(P, Q);
3509            mode[qi] = 1;
3510            atomicAdd(&g_tp_stats[tp::kStBand], (unsigned long long) tot);
3511            atomicMax(&g_tp_stats[tp::kStBandMax], (unsigned long long) tot);
3512            atomicAdd(&g_tp_stats[tp::kStCand], (unsigned long long) n);
3513            atomicMax(&g_tp_stats[tp::kStCandMax], (unsigned long long) n);
3514        }
3515    }
3516}
3517
3518// The listed blocks scored again exactly as block_scores_tc_kernel scores them: the query in its row of the m16
3519// tile (qi % 16), each block in its column of the n8 tile (b % 8), the same TF32 splits, the same three MMAs per step
3520// in the same order into the same accumulator, the same relu sum.  The other rows and columns hold zeros where
3521// today's kernel holds other queries and blocks; an MMA output element depends only on its own row of A, column of B
3522// and accumulator, so the element is today's bit for bit (qsa_two_pass_parity and STRATA_SELECT_TWO_PASS_CHECK
3523// compare every one with today's kernel).  Warp w takes tiles w, w + 4, ...: tile j holds the j-th listed block of
3524// every residue.
3525__global__ void __launch_bounds__(128) tp_rescore_kernel(const float* __restrict__ pooled,
3526                                                         const float* __restrict__ q_idx, int64_t max_blocks,
3527                                                         const int* __restrict__ mode, const int* __restrict__ cnt,
3528                                                         const int* __restrict__ ids, const int* __restrict__ tiles,
3529                                                         float* __restrict__ out) {
3530    __shared__ __align__(16) float sq[IDX_HEADS * IDX_DIM];
3531    __shared__ int s_cnt[8];
3532    const int64_t qi = blockIdx.x;
3533    if (mode[qi] != 1 || tiles[qi / TC_QT] != 0) return;   // nothing listed, or the full kernel takes the tile
3534    const int t = threadIdx.x, lane = t & 31, warp = t >> 5, gid = lane >> 2, tig = lane & 3;
3535    for (int i = t; i < IDX_HEADS * IDX_DIM; i += 128) sq[i] = q_idx[qi * IDX_HEADS * IDX_DIM + i];
3536    if (t < 8) s_cnt[t] = cnt[qi * 8 + t];
3537    __syncthreads();
3538    int ntile = 0;
3539    for (int r = 0; r < 8; ++r) ntile = max(ntile, s_cnt[r]);
3540    const int row = (int) (qi % TC_QT);
3541    const bool mine0 = gid == (row & 7) && row < 8, mine1 = gid == (row & 7) && row >= 8;
3542    const int* lst = ids + qi * 8 * tp::kResCap;
3543    for (int j = warp; j < ntile; j += 4) {
3544        const int bcol = j < s_cnt[gid] ? lst[gid * tp::kResCap + j] : -1;   // this lane's column: gid
3545        const float* kr = pooled + (int64_t) (bcol >= 0 ? bcol : 0) * IDX_DIM;
3546        float acc[IDX_HEADS][4];
3547#pragma unroll
3548        for (int h = 0; h < IDX_HEADS; ++h) acc[h][0] = acc[h][1] = acc[h][2] = acc[h][3] = 0.f;
3549#pragma unroll 4
3550        for (int k0 = 0; k0 < IDX_DIM; k0 += 8) {
3551            const float kx0 = bcol >= 0 ? kr[k0 + tig] : 0.f, kx1 = bcol >= 0 ? kr[k0 + tig + 4] : 0.f;
3552            uint32_t bh[2], bl[2];
3553            bh[0] = tf32_hi(kx0);
3554            bh[1] = tf32_hi(kx1);
3555            bl[0] = tf32_hi(kx0 - __uint_as_float(bh[0]));
3556            bl[1] = tf32_hi(kx1 - __uint_as_float(bh[1]));
3557#pragma unroll
3558            for (int h = 0; h < IDX_HEADS; ++h) {
3559                const float* qa = sq + h * IDX_DIM + k0 + tig;
3560                const float x0 = mine0 ? qa[0] : 0.f, x1 = mine1 ? qa[0] : 0.f;
3561                const float x2 = mine0 ? qa[4] : 0.f, x3 = mine1 ? qa[4] : 0.f;
3562                uint32_t ah[4], al[4];
3563                ah[0] = tf32_hi(x0); ah[1] = tf32_hi(x1); ah[2] = tf32_hi(x2); ah[3] = tf32_hi(x3);
3564                al[0] = tf32_hi(x0 - __uint_as_float(ah[0]));
3565                al[1] = tf32_hi(x1 - __uint_as_float(ah[1]));
3566                al[2] = tf32_hi(x2 - __uint_as_float(ah[2]));
3567                al[3] = tf32_hi(x3 - __uint_as_float(ah[3]));
3568                mma_tf32(acc[h], al, bh);
3569                mma_tf32(acc[h], ah, bl);
3570                mma_tf32(acc[h], ah, bh);
3571            }
3572        }
3573        if (gid == (row & 7)) {                       // row `row`, columns 2 tig and 2 tig + 1
3574#pragma unroll
3575            for (int jj = 0; jj < 2; ++jj) {
3576                const int c = 2 * tig + jj;
3577                if (j >= s_cnt[c]) continue;
3578                const int64_t b = lst[c * tp::kResCap + j];
3579                float score = 0.0f;
3580#pragma unroll
3581                for (int h = 0; h < IDX_HEADS; ++h) {
3582                    const float d = row >= 8 ? (jj ? acc[h][3] : acc[h][2]) : (jj ? acc[h][1] : acc[h][0]);
3583                    score += d > 0.0f ? d : 0.0f;
3584                }
3585                out[qi * max_blocks + b] = score;
3586            }
3587        }
3588    }
3589}
3590
3591// A flagged 16-query tile scored again in full: block_scores_tc_kernel's body as it is above, the CTA taking the tile
3592// (blockIdx.y) only when the band kernel flagged it and striding over its 128-block ranges.  Each 32-block tile is
3593// computed exactly as today's kernel computes it (the same shared-memory tiles, warps, MMAs and sums), so every
3594// score of the tile is today's.
3595__global__ void __launch_bounds__(128) tp_full_kernel(const float* __restrict__ pooled,
3596                                                      const float* __restrict__ q_idx,
3597                                                      const int32_t* __restrict__ steps, int64_t nq,
3598                                                      int64_t max_blocks, int64_t reach,
3599                                                      const int* __restrict__ tiles, float* __restrict__ out) {
3600    if (tiles[blockIdx.y] == 0) return;
3601    extern __shared__ __align__(16) float sm[];
3602    float* sQ = sm;                                   // [TC_QT][TC_QS]
3603    float* sK = sm + TC_QT * TC_QS;                   // [TC_NB][TC_KS]
3604    __shared__ int s_nbid[TC_QT];
3605    const int t = threadIdx.x, lane = t & 31, warp = t >> 5, gid = lane >> 2, tig = lane & 3;
3606    const int64_t q0 = (int64_t) blockIdx.y * TC_QT;
3607    for (int i = t; i < TC_QT * IDX_HEADS * IDX_DIM / 4; i += 128) {
3608        const int r = i / (IDX_HEADS * IDX_DIM / 4), c = i % (IDX_HEADS * IDX_DIM / 4);
3609        float4 v = make_float4(0.f, 0.f, 0.f, 0.f);
3610        if (q0 + r < nq) v = reinterpret_cast<const float4*>(q_idx + (q0 + r) * IDX_HEADS * IDX_DIM)[c];
3611        *reinterpret_cast<float4*>(sQ + r * TC_QS + c * 4) = v;
3612    }
3613    if (t < TC_QT) s_nbid[t] = q0 + t < nq ? steps[(q0 + t) * kStepCount + kStepNBid] : 0;
3614    int lo_nbid = 0x7fffffff, hi_nbid = 0;
3615    __syncthreads();
3616    for (int i = 0; i < TC_QT; ++i) {
3617        if (q0 + i >= nq) break;
3618        lo_nbid = min(lo_nbid, s_nbid[i]);
3619        hi_nbid = max(hi_nbid, s_nbid[i]);
3620    }
3621    (void) lo_nbid;
3622    for (int64_t x = blockIdx.x; x * TC_NB * TC_ITER < reach; x += gridDim.x) {
3623        for (int it = 0; it < TC_ITER; ++it) {
3624            const int64_t b0 = (x * TC_ITER + it) * TC_NB;
3625            if (b0 >= reach || b0 >= hi_nbid) break;
3626            __syncthreads();
3627            for (int i = t; i < TC_NB * IDX_DIM / 4; i += 128) {
3628                const int r = i / (IDX_DIM / 4), c = i % (IDX_DIM / 4);
3629                float4 v = make_float4(0.f, 0.f, 0.f, 0.f);
3630                if (b0 + r < hi_nbid) v = reinterpret_cast<const float4*>(pooled + (b0 + r) * IDX_DIM)[c];
3631                *reinterpret_cast<float4*>(sK + r * TC_KS + c * 4) = v;
3632            }
3633            __syncthreads();
3634            float acc[IDX_HEADS][4];
3635#pragma unroll
3636            for (int h = 0; h < IDX_HEADS; ++h) acc[h][0] = acc[h][1] = acc[h][2] = acc[h][3] = 0.f;
3637            const float* kr = sK + (warp * 8 + gid) * TC_KS;
3638#pragma unroll 4
3639            for (int k0 = 0; k0 < IDX_DIM; k0 += 8) {
3640                const float kx0 = kr[k0 + tig], kx1 = kr[k0 + tig + 4];
3641                uint32_t bh[2], bl[2];
3642                bh[0] = tf32_hi(kx0);
3643                bh[1] = tf32_hi(kx1);
3644                bl[0] = tf32_hi(kx0 - __uint_as_float(bh[0]));
3645                bl[1] = tf32_hi(kx1 - __uint_as_float(bh[1]));
3646#pragma unroll
3647                for (int h = 0; h < IDX_HEADS; ++h) {
3648                    const float* qa = sQ + h * IDX_DIM + k0 + tig;
3649                    const float x0 = qa[gid * TC_QS], x1 = qa[(gid + 8) * TC_QS];
3650                    const float x2 = qa[gid * TC_QS + 4], x3 = qa[(gid + 8) * TC_QS + 4];
3651                    uint32_t ah[4], al[4];
3652                    ah[0] = tf32_hi(x0); ah[1] = tf32_hi(x1); ah[2] = tf32_hi(x2); ah[3] = tf32_hi(x3);
3653                    al[0] = tf32_hi(x0 - __uint_as_float(ah[0]));
3654                    al[1] = tf32_hi(x1 - __uint_as_float(ah[1]));
3655                    al[2] = tf32_hi(x2 - __uint_as_float(ah[2]));
3656                    al[3] = tf32_hi(x3 - __uint_as_float(ah[3]));
3657                    mma_tf32(acc[h], al, bh);
3658                    mma_tf32(acc[h], ah, bl);
3659                    mma_tf32(acc[h], ah, bh);
3660                }
3661            }
3662            const int64_t bc = b0 + warp * 8 + 2 * tig;
3663#pragma unroll
3664            for (int half = 0; half < 2; ++half) {
3665                const int qr = gid + half * 8;
3666                const int64_t qi = q0 + qr;
3667                if (qi >= nq) continue;
3668                const int nbq = s_nbid[qr];
3669#pragma unroll
3670                for (int j = 0; j < 2; ++j) {
3671                    const int64_t b = bc + j;
3672                    if (b >= nbq || b >= max_blocks) continue;
3673                    float score = 0.0f;
3674#pragma unroll
3675                    for (int h = 0; h < IDX_HEADS; ++h) {
3676                        const float d = acc[h][half * 2 + j];
3677                        score += d > 0.0f ? d : 0.0f;
3678                    }
3679                    out[qi * max_blocks + b] = score;
3680                }
3681            }
3682        }
3683    }
3684}
3685
3686// STRATA_SELECT_TWO_PASS_CHECK: one query against today's row and ids.  Ids: every entry qsa_block_topk wrote.  Scored-
3687// again blocks (listed, the tail, or every block of a full query): bitwise today's score.  Kept blocks: |S1 - S3| <= eps.
3688__global__ void __launch_bounds__(256) tp_check_kernel(const float* __restrict__ scores, const int32_t* __restrict__ ids,
3689                                                       const float* __restrict__ ref, const int32_t* __restrict__ ref_ids,
3690                                                       const int32_t* __restrict__ steps, int64_t max_blocks,
3691                                                       int64_t cap, const float2* __restrict__ kn,
3692                                                       const float2* __restrict__ qc, const int* __restrict__ mode,
3693                                                       const int* __restrict__ cnt, const int* __restrict__ lists,
3694                                                       const int* __restrict__ tiles) {
3695    extern __shared__ uint32_t tp_mark[];
3696    __shared__ unsigned long long s_acc[6];
3697    __shared__ unsigned int s_ratio;
3698    const int t = threadIdx.x;
3699    const int64_t qi = blockIdx.x;
3700    const int32_t* st = steps + qi * kStepCount;
3701    const int64_t n_kv = st[kStepNKv], n_bid = st[kStepNBid], width = st[kStepWidth];
3702    if (t < 6) s_acc[t] = 0ull;
3703    if (t == 0) s_ratio = 0u;
3704    const int64_t m = n_kv < width ? n_kv : width;
3705    unsigned long long dif = 0;
3706    for (int64_t j = t; j < m; j += 256) dif += ids[qi * cap + j] != ref_ids[qi * cap + j];
3707    const bool sparse = n_kv > width;
3708    const int md = !sparse ? 0 : tiles[qi / TC_QT] != 0 ? 2 : mode[qi];   // a flagged tile: every block scored again
3709    const int64_t nb = n_bid + 1, words = (nb + 31) / 32;
3710    if (sparse) for (int64_t i = t; i < words; i += 256) tp_mark[i] = 0u;
3711    __syncthreads();
3712    atomicAdd(&s_acc[0], dif);
3713    if (sparse && md == 1) {
3714        for (int r = 0; r < 8; ++r) {
3715            const int c = cnt[qi * 8 + r];
3716            for (int j = t; j < c; j += 256) {
3717                const int b = lists[(qi * 8 + r) * tp::kResCap + j];
3718                atomicOr(&tp_mark[b >> 5], 1u << (b & 31));
3719            }
3720        }
3721    }
3722    __syncthreads();
3723    if (sparse) {
3724        const float* s1 = scores + qi * max_blocks;
3725        const float* s3 = ref + qi * max_blocks;
3726        const float2 pq = md == 1 ? qc[qi] : make_float2(0.f, 0.f);
3727        unsigned long long again = 0, again_dif = 0, kept = 0, kept_out = 0;
3728        float ratio = 0.0f;
3729        for (int64_t b = t; b < nb; b += 256) {
3730            const bool exact = md == 2 || b == n_bid || ((tp_mark[b >> 5] >> (b & 31)) & 1u);
3731            if (exact) {
3732                ++again;
3733                again_dif += __float_as_uint(s1[b]) != __float_as_uint(s3[b]);
3734            } else {
3735                ++kept;
3736                const float e = __fmaf_ru(pq.x, kn[b].y, __fmaf_ru(pq.y, kn[b].x, tp::kAbs));
3737                const double d = fabs((double) s1[b] - (double) s3[b]);
3738                kept_out += !(d <= (double) e);
3739                const float r = (float) (d / (double) e);
3740                ratio = fmaxf(ratio, r == r ? r : tp_inf());
3741            }
3742        }
3743        atomicAdd(&s_acc[1], again);
3744        atomicAdd(&s_acc[2], again_dif);
3745        atomicAdd(&s_acc[3], kept);
3746        atomicAdd(&s_acc[4], kept_out);
3747        atomicMax(&s_ratio, __float_as_uint(ratio));
3748    }
3749    __syncthreads();
3750    if (t == 0) {
3751        atomicAdd(&g_tp_stats[tp::kChkQueries], 1ull);
3752        if (s_acc[0]) atomicAdd(&g_tp_stats[tp::kChkIdQueries], 1ull);
3753        atomicAdd(&g_tp_stats[tp::kChkIdEntries], s_acc[0]);
3754        atomicAdd(&g_tp_stats[tp::kChkRescored], s_acc[1]);
3755        atomicAdd(&g_tp_stats[tp::kChkRescoredDiff], s_acc[2]);
3756        atomicAdd(&g_tp_stats[tp::kChkKept], s_acc[3]);
3757        atomicAdd(&g_tp_stats[tp::kChkKeptOut], s_acc[4]);
3758        atomicMax(&g_tp_stats[tp::kChkRatioMax], (unsigned long long) s_ratio);
3759    }
3760}
3761
3762// The card runs qsa_block_scores_tc's tensor-core kernel (the reference of the two-pass scores), and the full kernel
3763// takes its shared memory.  The same dispatch rule as qsa_block_scores_tc: sm_80+, STRATA_QSA_WARP not set.
3764bool tp_device_ok() {
3765    static int ok[64] = {};   // 0 unknown, 1 yes, 2 no
3766    int dev = 0;
3767    if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return false; }
3768    if (ok[dev] == 0) {
3769        int major = 0;
3770        bool good = cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) == cudaSuccess;
3771        const char* w = std::getenv("STRATA_QSA_WARP");
3772        const int cc = w && (!std::strcmp(w, "1") || !std::strcmp(w, "select")) ? 7 : strata::cc_major_of(major);
3773        const int bytes = (TC_QT * TC_QS + TC_NB * TC_KS) * (int) sizeof(float);
3774        good = good && cc >= 8 &&
3775               cudaFuncSetAttribute(block_scores_tc_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, bytes) ==
3776                   cudaSuccess &&
3777               cudaFuncSetAttribute(tp_full_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, bytes) == cudaSuccess;
3778        cudaGetLastError();
3779        ok[dev] = good ? 1 : 2;
3780    }
3781    return ok[dev] == 1;
3782}
3783}  // namespace
3784
3785bool qsa_two_pass_on() {
3786    static two_pass::RequestStatus status(std::getenv("STRATA_SELECT_TWO_PASS"));
3787    if (!status.requested()) return false;
3788    // the card current at this call (a layer split can mix cards): sm_75 or STRATA_QSA_WARP=1|select keep the other
3789    // scorer there, so the switch says once that it is not used; checked here too, so a short prompt says it as well
3790    if (!tp_device_ok()) (void) status.on("this CUDA card or with STRATA_QSA_WARP");
3791    return true;
3792}
3793bool qsa_two_pass_check_on() {
3794    static const bool on = [] {
3795        const char* v = std::getenv("STRATA_SELECT_TWO_PASS_CHECK");
3796        return v && v[0] == '1' && v[1] == '\0';
3797    }();
3798    return on;
3799}
3800int64_t qsa_two_pass_min_blocks() {
3801    static const int64_t v = [] {
3802        const char* e = std::getenv("STRATA_SELECT_TWO_PASS_MIN");
3803        const long long x = e ? std::atoll(e) : (long long) two_pass::kMinBlocksDefault;
3804        return (int64_t) (x < 0 ? 0 : x);
3805    }();
3806    return v;
3807}
3808uint64_t qsa_two_pass_scratch_bytes(int64_t nq_cap, int64_t max_blocks) { return two_pass::layout(nq_cap, max_blocks).total; }
3809
3810bool qsa_two_pass_keys(const float* pooled, int64_t n_blocks, int64_t nq_cap, int64_t max_blocks, void* scratch,
3811                       uint64_t scratch_bytes, void* stream) {
3812    if (!qsa_two_pass_on() || !tp_device_ok() || n_blocks > max_blocks || nq_cap <= 0 || nq_cap > 4096) return false;
3813    const two_pass::Layout L = two_pass::layout(nq_cap, max_blocks);
3814    if (scratch == nullptr || scratch_bytes < L.total || (reinterpret_cast<uintptr_t>(scratch) & 15u) != 0) return false;
3815    if (n_blocks <= 0) return true;
3816    float2* kn = reinterpret_cast<float2*>(static_cast<uint8_t*>(scratch) + L.kn);
3817    tp_keys_kernel<<<(unsigned) ((n_blocks + 7) / 8), 256, 0, (cudaStream_t) stream>>>(pooled, n_blocks, kn);
3818    const cudaError_t e = cudaGetLastError();
3819    if (e != cudaSuccess) { std::fprintf(stderr, "qsa two-pass keys: %s\n", cudaGetErrorString(e)); std::exit(1); }
3820    return true;
3821}
3822
3823bool qsa_block_scores_two_pass(const float* pooled, const float* dead, const float* q_idx, const int32_t* steps,
3824                               int64_t nq, int64_t nq_cap, int64_t max_blocks, const QsaShapes& s, float* scores,
3825                               void* scratch, uint64_t scratch_bytes, void* stream, int64_t active_blocks) {
3826    if (nq <= 0) return true;
3827    if (!qsa_two_pass_on() || s.idx_dim != IDX_DIM || s.idx_n_head != IDX_HEADS || s.idx_block != R ||
3828        nq > nq_cap || nq_cap > 4096 || !tp_device_ok())
3829        return false;
3830    const two_pass::Layout L = two_pass::layout(nq_cap, max_blocks);
3831    if (scratch == nullptr || scratch_bytes < L.total || (reinterpret_cast<uintptr_t>(scratch) & 15u) != 0) return false;
3832    uint8_t* base = static_cast<uint8_t*>(scratch);
3833    const float2* kn = reinterpret_cast<const float2*>(base + L.kn);
3834    float2* qc = reinterpret_cast<float2*>(base + L.qc);
3835    int* mode = reinterpret_cast<int*>(base + L.mode);
3836    int* cnt = reinterpret_cast<int*>(base + L.cnt);
3837    int* ids = reinterpret_cast<int*>(base + L.ids);
3838    int* tiles = reinterpret_cast<int*>(base + L.tiles);
3839    const cudaStream_t st = (cudaStream_t) stream;
3840    const int64_t reach = active_blocks > 0 && active_blocks < max_blocks ? active_blocks : max_blocks;
3841    static std::atomic<bool> said{false};
3842    if (!said.exchange(true))
3843        std::fprintf(stderr, "qsa select: two-pass scores on (STRATA_SELECT_TWO_PASS=1): calls whose last query has %lld+ "
3844                             "blocks score every block in single-pass TF32 and again in 3xTF32 where the bound reaches the "
3845                             "cut-off (the same cells as the 3xTF32 scorer)\n", (long long) qsa_two_pass_min_blocks());
3846    const unsigned qtiles = (unsigned) ((nq + TC_QT - 1) / TC_QT);
3847    const int64_t per = (int64_t) TC_NB * TP1_ITER;
3848    tp_score1_kernel<<<dim3(qtiles, (unsigned) ((reach + per - 1) / per)), 128, 0, st>>>(pooled, q_idx, steps, nq,
3849                                                                                         max_blocks, reach, scores, tiles);
3850    block_scores_tail_kernel<<<(unsigned) nq, 32, 0, st>>>(dead, q_idx, steps, max_blocks, scores);
3851    tp_band_kernel<<<(unsigned) nq, TPB_T, (size_t) two_pass::kCandCap * 8, st>>>(scores, q_idx, steps, max_blocks, kn, qc,
3852                                                                                 mode, cnt, ids, tiles);
3853    tp_rescore_kernel<<<(unsigned) nq, 128, 0, st>>>(pooled, q_idx, max_blocks, mode, cnt, ids, tiles, scores);
3854    const int64_t ranges = (reach + (int64_t) TC_NB * TC_ITER - 1) / ((int64_t) TC_NB * TC_ITER);
3855    const int bytes = (TC_QT * TC_QS + TC_NB * TC_KS) * (int) sizeof(float);
3856    tp_full_kernel<<<dim3((unsigned) (ranges < 32 ? ranges : 32), qtiles), 128, bytes, st>>>(pooled, q_idx, steps, nq,
3857                                                                                             max_blocks, reach, tiles,
3858                                                                                             scores);
3859    const cudaError_t e = cudaGetLastError();
3860    if (e != cudaSuccess) { std::fprintf(stderr, "qsa two-pass scores: %s\n", cudaGetErrorString(e)); std::exit(1); }
3861    return true;
3862}
3863
3864void qsa_two_pass_check(const float* scores, const int32_t* ids, const float* ref_scores, const int32_t* ref_ids,
3865                        const int32_t* steps, int64_t nq, int64_t nq_cap, int64_t max_blocks, int64_t cap,
3866                        void* scratch, void* stream) {
3867    if (nq <= 0 || scratch == nullptr) return;
3868    const size_t mark = (size_t) ((max_blocks + 31) / 32) * 4;
3869    if (mark > 48 * 1024) {
3870        static std::atomic<bool> said{false};
3871        if (!said.exchange(true)) std::fprintf(stderr, "qsa two-pass check: %lld blocks are too many to check\n", (long long) max_blocks);
3872        return;
3873    }
3874    const two_pass::Layout L = two_pass::layout(nq_cap, max_blocks);
3875    const uint8_t* base = static_cast<const uint8_t*>(scratch);
3876    tp_check_kernel<<<(unsigned) nq, 256, mark, (cudaStream_t) stream>>>(
3877        scores, ids, ref_scores, ref_ids, steps, max_blocks, cap, reinterpret_cast<const float2*>(base + L.kn),
3878        reinterpret_cast<const float2*>(base + L.qc), reinterpret_cast<const int*>(base + L.mode),
3879        reinterpret_cast<const int*>(base + L.cnt), reinterpret_cast<const int*>(base + L.ids),
3880        reinterpret_cast<const int*>(base + L.tiles));
3881    const cudaError_t e = cudaGetLastError();
3882    if (e != cudaSuccess) { std::fprintf(stderr, "qsa two-pass check: %s\n", cudaGetErrorString(e)); std::exit(1); }
3883}
3884
3885bool qsa_two_pass_stats(unsigned long long* out, bool reset, void* stream) {
3886    const cudaStream_t st = (cudaStream_t) stream;
3887    void* p = nullptr;
3888    if (cudaGetSymbolAddress(&p, g_tp_stats) != cudaSuccess) { cudaGetLastError(); return false; }
3889    const size_t bytes = sizeof(unsigned long long) * two_pass::kStatCount;
3890    if (cudaMemcpyAsync(out, p, bytes, cudaMemcpyDeviceToHost, st) != cudaSuccess ||
3891        (reset && cudaMemsetAsync(p, 0, bytes, st) != cudaSuccess) || cudaStreamSynchronize(st) != cudaSuccess) {
3892        cudaGetLastError();
3893        return false;
3894    }
3895    return true;
3896}
3897#else   // HIP: the two-pass scorer is CUDA-only (the gfx12 WMMA scorer has another arithmetic); nothing runs
3898bool qsa_two_pass_on() {   // false; a set switch says once that it is not used here
3899    static two_pass::RequestStatus status(std::getenv("STRATA_SELECT_TWO_PASS"));
3900    return status.on("HIP");
3901}
3902bool qsa_two_pass_check_on() { return false; }
3903int64_t qsa_two_pass_min_blocks() { return two_pass::kMinBlocksDefault; }
3904uint64_t qsa_two_pass_scratch_bytes(int64_t nq_cap, int64_t max_blocks) { return two_pass::layout(nq_cap, max_blocks).total; }
3905bool qsa_two_pass_keys(const float*, int64_t, int64_t, int64_t, void*, uint64_t, void*) { return false; }
3906bool qsa_block_scores_two_pass(const float*, const float*, const float*, const int32_t*, int64_t, int64_t, int64_t,
3907                               const QsaShapes&, float*, void*, uint64_t, void*, int64_t) { return false; }
3908void qsa_two_pass_check(const float*, const int32_t*, const float*, const int32_t*, const int32_t*, int64_t, int64_t,
3909                        int64_t, int64_t, void*, void*) {}
3910bool qsa_two_pass_stats(unsigned long long*, bool, void*) { return false; }
3911#endif
3912
3913}  // namespace strata::kernels