okami.mom/strata

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

Niko1221Trial2 merge f-0291-pr-intel (2b4d43bac)5438023a6

main
100.0 KiB2152 linesraw
1// src/kernels/cuda/qsa_select.cu - see include/strata/kernels/qsa_select.hpp.
2#define DPCT_PROFILING_ENABLED
3#include <sycl/sycl.hpp>
4#include "strata/kprof.hpp"
5#include "strata/core/geometry.hpp"
6#include <dpct/dpct.hpp>
7#include "strata/sycl_queue.hpp"
8#include "strata/core/emulate.hpp"
9#include <cstdlib>
10#include <cstring>
11#include "strata/kernels/qsa_select.hpp"
12#include "strata/kernels/gfx_arch.hpp"
13
14#include <cfloat>
15#include <cstdio>
16#include <cstdlib>
17#include <cstring>
18
19namespace strata::kernels {
20namespace {
21
22constexpr int IDX_DIM = 128, IDX_HEADS = 4, R = 4;
23static_assert(IDX_DIM == strata::core::kCompiledGeometry.idx_key_dim && IDX_HEADS == strata::core::kCompiledGeometry.idx_q_heads && R == strata::core::kCompiledGeometry.idx_block,
24              "qsa_select is compiled for core/geometry.hpp");
25constexpr int SCORE_WARPS = 8;
26constexpr int TOPK_T = 256;
27
28__dpct_inline__ uint32_t order_key(float s) {
29    const float v = s + 0.0f;
30    if (!(v == v)) return 0u;
31    const uint32_t b = sycl::bit_cast<unsigned int>(v);
32    return (b & 0x80000000u) ? ~b : (b | 0x80000000u);
33}
34
35__dpct_inline__ void block_scores_kernel(const float *__restrict__ pooled,
36                                         const float *__restrict__ dead,
37                                         const float *__restrict__ q_idx,
38                                         const int32_t *__restrict__ steps,
39                                         int64_t max_blocks,
40                                         float *__restrict__ out) {
41    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
42    const int64_t qi = item_ct1.get_group(1);
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)item_ct1.get_group(2) * SCORE_WARPS +
46                      (item_ct1.get_local_id(2) >> 5);
47    if (b > n_bid || b >= max_blocks) return;
48    const int lane = item_ct1.get_local_id(2) & 31;
49    const float* key = (b == n_bid) ? dead : pooled + b * IDX_DIM;
50    const sycl::float4 k4 =
51        *reinterpret_cast<const sycl::float4 *>(key + lane * 4);
52    const float* q = q_idx + qi * IDX_HEADS * IDX_DIM + lane * 4;
53    float score = 0.0f;
54#pragma unroll
55    for (int h = 0; h < IDX_HEADS; ++h) {
56        const sycl::float4 q4 =
57            *reinterpret_cast<const sycl::float4 *>(q + h * IDX_DIM);
58        float d = k4.x() * q4.x() + k4.y() * q4.y() + k4.z() * q4.z() +
59                  k4.w() * q4.w();
60#pragma unroll
61        /*
62        DPCT1108: '__shfl_xor_sync' was migrated with the experimental
63        feature masked sub_group function which may not be supported by all
64        compilers or runtimes. You may need to adjust the code.
65        */
66        for (int o = 16; o > 0; o >>= 1) d +=
67            dpct::experimental::permute_sub_group_by_xor(
68                0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(),
69                d, o);
70        score += d > 0.0f ? d : 0.0f;
71    }
72    if (lane == 0) {
73        if (b == n_bid && n_kv % R != 0) score += 1e9f;
74        out[qi * max_blocks + b] = score;
75    }
76}
77
78/*
79DPCT1110: The total declared local variable size in device function
80block_topk_kernel exceeds 128 bytes and may cause high register pressure.
81Consult with your hardware vendor to find the total register size available and
82adjust the code, or use smaller sub-group size to avoid high register pressure.
83*/
84__dpct_inline__ void block_topk_kernel(const float *__restrict__ scores,
85                                       const int32_t *__restrict__ steps,
86                                       int64_t max_blocks, int64_t cap,
87                                       int32_t *__restrict__ ids) {
88    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
89auto &hist = *sycl::ext::oneapi::group_local_memory_for_overwrite<int[256]>(
90    sycl::ext::oneapi::this_work_item::get_work_group<3>());
91    auto &s_a =
92        *sycl::ext::oneapi::group_local_memory_for_overwrite<int[TOPK_T]>(
93            sycl::ext::oneapi::this_work_item::get_work_group<3>());
94    auto &s_b =
95        *sycl::ext::oneapi::group_local_memory_for_overwrite<int[TOPK_T]>(
96            sycl::ext::oneapi::this_work_item::get_work_group<3>());
97    auto &s_digit = *sycl::ext::oneapi::group_local_memory_for_overwrite<int>(
98        sycl::ext::oneapi::this_work_item::get_work_group<3>());
99    auto &s_above = *sycl::ext::oneapi::group_local_memory_for_overwrite<int>(
100        sycl::ext::oneapi::this_work_item::get_work_group<3>());
101    const int64_t qi = item_ct1.get_group(2);
102    const int32_t* st = steps + qi * kStepCount;
103    const int64_t n_kv = st[kStepNKv], n_bid = st[kStepNBid], width = st[kStepWidth];
104    int32_t* out = ids + qi * cap;
105    const int t = item_ct1.get_local_id(2);
106    if (n_kv <= width) {                               // everything is selected: the identity, ascending
107#pragma unroll
108        for (int64_t j = t; j < n_kv; j += TOPK_T) out[j] = (int32_t)j;
109        return;
110    }
111    const float* sc = scores + qi * max_blocks;
112    const int64_t nb = n_bid + 1;                      // blocks 0..n_bid, the last possibly empty
113    const int64_t per = (nb + TOPK_T - 1) / TOPK_T;
114    const int64_t b0 = (int64_t) t * per, b1 = (b0 + per < nb) ? b0 + per : nb;
115    auto weight = [&](int64_t b) -> int { return b < n_bid ? R : (int) (n_kv - n_bid * R); };
116    // ---- radix select: the largest key thr with (cells with key >= thr) >= width, 8 bits at a time
117    uint32_t prefix = 0;
118    int above = 0;                                     // cells strictly above the digits fixed so far
119    for (int shift = 24; shift >= 0; shift -= 8) {
120#pragma unroll
121        for (int i = t; i < 256; i += TOPK_T) hist[i] = 0;
122        /*
123        DPCT1118: SYCL group functions and algorithms must be encountered in
124        converged control flow. You may need to adjust the code.
125        */
126        /*
127        DPCT1065: Consider replacing sycl::nd_item::barrier() with
128        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
129        better performance if there is no access to global memory.
130        */
131        item_ct1.barrier();
132        const uint32_t hi_mask = shift == 24 ? 0u : (0xffffffffu << (shift + 8));
133        for (int64_t b = b0; b < b1; ++b) {
134            const int w = weight(b);
135            if (w == 0) continue;
136            const uint32_t k = order_key(sc[b]);
137            if ((k & hi_mask) == (prefix & hi_mask)) dpct::atomic_fetch_add<
138                sycl::access::address_space::generic_space>(
139                &hist[(k >> shift) & 255], w);
140        }
141        /*
142        DPCT1118: SYCL group functions and algorithms must be encountered in
143        converged control flow. You may need to adjust the code.
144        */
145        /*
146        DPCT1065: Consider replacing sycl::nd_item::barrier() with
147        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
148        better performance if there is no access to global memory.
149        */
150        item_ct1.barrier();
151        if (t == 0) {
152            int cum = above, d = 255;
153#pragma unroll
154            for (; d > 0; --d) {
155                if (cum + hist[d] >= width) break;
156                cum += hist[d];
157            }
158            s_digit = d;
159            s_above = cum;
160        }
161        /*
162        DPCT1118: SYCL group functions and algorithms must be encountered in
163        converged control flow. You may need to adjust the code.
164        */
165        /*
166        DPCT1065: Consider replacing sycl::nd_item::barrier() with
167        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
168        better performance if there is no access to global memory.
169        */
170        item_ct1.barrier();
171        prefix |= (uint32_t) s_digit << shift;
172        above = s_above;
173        /*
174        DPCT1118: SYCL group functions and algorithms must be encountered in
175        converged control flow. You may need to adjust the code.
176        */
177        /*
178        DPCT1065: Consider replacing sycl::nd_item::barrier() with
179        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
180        better performance if there is no access to global memory.
181        */
182        item_ct1.barrier();
183    }
184    const uint32_t thr = prefix;
185    const int64_t eq_budget = width - above;          // cells equal to thr that fit, lowest index first
186    // ---- per-thread counts of cells above and at the threshold, then their exclusive prefixes
187    int gt = 0, eq = 0;
188    for (int64_t b = b0; b < b1; ++b) {
189        const int w = weight(b);
190        if (w == 0) continue;
191        const uint32_t k = order_key(sc[b]);
192        if (k > thr) gt += w;
193        else if (k == thr) eq += w;
194    }
195    s_a[t] = gt;
196    s_b[t] = eq;
197    /*
198    DPCT1065: Consider replacing sycl::nd_item::barrier() with
199    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
200    performance if there is no access to global memory.
201    */
202    item_ct1.barrier();
203    if (t == 0) {
204        int ag = 0, ae = 0;
205        for (int i = 0; i < TOPK_T; ++i) {
206            const int g = s_a[i], e = s_b[i];
207            s_a[i] = ag; s_b[i] = ae;
208            ag += g; ae += e;
209        }
210    }
211    /*
212    DPCT1065: Consider replacing sycl::nd_item::barrier() with
213    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
214    performance if there is no access to global memory.
215    */
216    item_ct1.barrier();
217    const int64_t eq_before = s_b[t];
218    int64_t my_eq = eq_budget - eq_before;
219    if (my_eq < 0) my_eq = 0;
220    if (my_eq > eq) my_eq = eq;
221    const int sel = gt + (int) my_eq;
222    /*
223    DPCT1065: Consider replacing sycl::nd_item::barrier() with
224    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
225    performance if there is no access to global memory.
226    */
227    item_ct1.barrier();
228    s_a[t] = sel;
229    /*
230    DPCT1065: Consider replacing sycl::nd_item::barrier() with
231    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
232    performance if there is no access to global memory.
233    */
234    item_ct1.barrier();
235    if (t == 0) {
236        int a = 0;
237        for (int i = 0; i < TOPK_T; ++i) { const int c = s_a[i]; s_a[i] = a; a += c; }
238    }
239    /*
240    DPCT1065: Consider replacing sycl::nd_item::barrier() with
241    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
242    performance if there is no access to global memory.
243    */
244    item_ct1.barrier();
245    int64_t wpos = s_a[t];
246    int64_t eq_left = my_eq;
247    for (int64_t b = b0; b < b1; ++b) {
248        const int w = weight(b);
249        if (w == 0) continue;
250        const uint32_t k = order_key(sc[b]);
251        if (k > thr) {
252#pragma unroll
253            for (int c = 0; c < w; ++c) out[wpos++] = (int32_t)(b * R + c);
254        } else if (k == thr) {
255#pragma unroll
256            for (int c = 0; c < w && eq_left > 0; ++c, --eq_left)
257                out[wpos++] = (int32_t)(b * R + c);
258        }
259    }
260}
261
262
263// ---- QSA select on tensor cores (perf-review, after D-1): the block scores of many queries are one GEMM,
264// rows (query, indexer head) x columns (blocks), K = 128, with relu per head summed. 3xTF32 (each operand split
265// into a TF32 hi and lo part, hi*hi + hi*lo + lo*hi) keeps FP32-level accuracy; the summation order differs from
266// the warp kernel, so a score can move in its last bits and a near-tie can select differently (not bitwise).
267// Blocks < n_bid only; the tail block n_bid (the `dead` key, +1e9) is scored by the warp kernel's own code.
268constexpr int TC_QT = 16;                 // queries per CTA (one m16 tile per indexer head)
269constexpr int TC_NB = 32;                 // blocks per tile (4 warps x n8)
270constexpr int TC_ITER = 4;                // tiles per CTA (the query tile is loaded once)
271constexpr int TC_QS = IDX_HEADS * IDX_DIM + 4;   // query row stride in floats
272constexpr int TC_KS = IDX_DIM + 4;               // key row stride
273
274// TF32 conversion and MMA need sm_80: below it they compile to a trap and qsa_block_scores_tc refuses the device
275#if defined(__HIPCC__)          // AMD: no mma.sync / cp.async; the host keeps the warp kernel (below)
276#define STRATA_SEL_SM80 0
277#elif 0   // SYCL: inline PTX (mma/ldmatrix/cp.async) - the XMX port is pending; see tools/fixups.py
278#define STRATA_SEL_SM80 1
279#else
280#define STRATA_SEL_SM80 0
281#endif
282__dpct_inline__ uint32_t tf32_hi(float x) {
283#if STRATA_SEL_SM80
284    uint32_t r;
285    /*
286    DPCT1053: Migration of device assembly code is not supported.
287    */
288    asm("cvt.rna.tf32.f32 %0, %1;" : "=r"(r) : "f"(x));
289    return r;
290#else
291    return sycl::bit_cast<uint32_t>(x);
292#endif
293}
294__dpct_inline__ void mma_tf32(float *c, const uint32_t *a, const uint32_t *b) {
295#if !STRATA_SEL_SM80
296    /* unreachable on SYCL: the launcher refuses this device */
297#else
298    /*
299    DPCT1053: Migration of device assembly code is not supported.
300    */
301    asm volatile("mma.sync.aligned.m16n8k8.row.col.f32.tf32.tf32.f32 "
302                 "{%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, "
303                 "{%0,%1,%2,%3};\n"
304                 : "+f"(c[0]), "+f"(c[1]), "+f"(c[2]), "+f"(c[3])
305                 : "r"(a[0]), "r"(a[1]), "r"(a[2]), "r"(a[3]), "r"(b[0]),
306                   "r"(b[1]));
307#endif
308}
309
310/*
311DPCT1110: The total declared local variable size in device function
312block_scores_tc_kernel exceeds 128 bytes and may cause high register pressure.
313Consult with your hardware vendor to find the total register size available and
314adjust the code, or use smaller sub-group size to avoid high register pressure.
315*/
316__dpct_inline__ void block_scores_tc_kernel(
317    const float *__restrict__ pooled, const float *__restrict__ q_idx,
318    const int32_t *__restrict__ steps, int64_t nq, int64_t max_blocks,
319    int64_t reach, float *__restrict__ out, uint8_t *dpct_local) {
320    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
321    auto sm = (float *)dpct_local;
322    float* sQ = sm;                                   // [TC_QT][TC_QS]
323    float* sK = sm + TC_QT * TC_QS;                   // [TC_NB][TC_KS]
324    auto &s_nbid =
325        *sycl::ext::oneapi::group_local_memory_for_overwrite<int[TC_QT]>(
326            sycl::ext::oneapi::this_work_item::get_work_group<3>());
327    const int t = item_ct1.get_local_id(2), lane = t & 31, warp = t >> 5,
328              gid = lane >> 2, tig = lane & 3;
329    const int64_t q0 = (int64_t)item_ct1.get_group(1) * TC_QT;
330    for (int i = t; i < TC_QT * IDX_HEADS * IDX_DIM / 4; i += 128) {
331        const int r = i / (IDX_HEADS * IDX_DIM / 4), c = i % (IDX_HEADS * IDX_DIM / 4);
332        sycl::float4 v = sycl::float4(0.f, 0.f, 0.f, 0.f);
333        if (q0 + r < nq) v = reinterpret_cast<const sycl::float4 *>(
334            q_idx + (q0 + r) * IDX_HEADS * IDX_DIM)[c];
335        *reinterpret_cast<sycl::float4 *>(sQ + r * TC_QS + c * 4) = v;
336    }
337    if (t < TC_QT) s_nbid[t] = q0 + t < nq ? steps[(q0 + t) * kStepCount + kStepNBid] : 0;
338    int lo_nbid = 0x7fffffff, hi_nbid = 0;
339    item_ct1.barrier(sycl::access::fence_space::local_space);
340#pragma unroll
341    for (int i = 0; i < TC_QT; ++i) {
342        if (q0 + i >= nq) break;
343        lo_nbid = sycl::min(lo_nbid, s_nbid[i]);
344        hi_nbid = sycl::max(hi_nbid, s_nbid[i]);
345    }
346    for (int it = 0; it < TC_ITER; ++it) {
347        const int64_t b0 =
348            ((int64_t)item_ct1.get_group(2) * TC_ITER + it) * TC_NB;
349        if (b0 >= reach || b0 >= hi_nbid) break;      // blocks >= every query's n_bid: nothing to score
350        /*
351        DPCT1118: SYCL group functions and algorithms must be encountered in
352        converged control flow. You may need to adjust the code.
353        */
354        /*
355        DPCT1065: Consider replacing sycl::nd_item::barrier() with
356        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
357        better performance if there is no access to global memory.
358        */
359        item_ct1.barrier(); // the previous tile's reads are done
360        for (int i = t; i < TC_NB * IDX_DIM / 4; i += 128) {
361            const int r = i / (IDX_DIM / 4), c = i % (IDX_DIM / 4);
362            sycl::float4 v = sycl::float4(0.f, 0.f, 0.f, 0.f);
363            if (b0 + r < hi_nbid) v = reinterpret_cast<const sycl::float4 *>(
364                pooled + (b0 + r) * IDX_DIM)[c];
365            *reinterpret_cast<sycl::float4 *>(sK + r * TC_KS + c * 4) = v;
366        }
367        /*
368        DPCT1118: SYCL group functions and algorithms must be encountered in
369        converged control flow. You may need to adjust the code.
370        */
371        /*
372        DPCT1065: Consider replacing sycl::nd_item::barrier() with
373        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
374        better performance if there is no access to global memory.
375        */
376        item_ct1.barrier();
377        float acc[IDX_HEADS][4];
378#pragma unroll
379        for (int h = 0; h < IDX_HEADS; ++h) acc[h][0] = acc[h][1] = acc[h][2] = acc[h][3] = 0.f;
380        const float* kr = sK + (warp * 8 + gid) * TC_KS;
381#pragma unroll 4
382        for (int k0 = 0; k0 < IDX_DIM; k0 += 8) {
383            const float kx0 = kr[k0 + tig], kx1 = kr[k0 + tig + 4];
384            uint32_t bh[2], bl[2];
385            bh[0] = tf32_hi(kx0);
386            bh[1] = tf32_hi(kx1);
387            bl[0] = tf32_hi(kx0 - sycl::bit_cast<float>(bh[0]));
388            bl[1] = tf32_hi(kx1 - sycl::bit_cast<float>(bh[1]));
389#pragma unroll
390            for (int h = 0; h < IDX_HEADS; ++h) {
391                const float* qa = sQ + h * IDX_DIM + k0 + tig;
392                const float x0 = qa[gid * TC_QS], x1 = qa[(gid + 8) * TC_QS];
393                const float x2 = qa[gid * TC_QS + 4], x3 = qa[(gid + 8) * TC_QS + 4];
394                uint32_t ah[4], al[4];
395                ah[0] = tf32_hi(x0); ah[1] = tf32_hi(x1); ah[2] = tf32_hi(x2); ah[3] = tf32_hi(x3);
396                al[0] = tf32_hi(x0 - sycl::bit_cast<float>(ah[0]));
397                al[1] = tf32_hi(x1 - sycl::bit_cast<float>(ah[1]));
398                al[2] = tf32_hi(x2 - sycl::bit_cast<float>(ah[2]));
399                al[3] = tf32_hi(x3 - sycl::bit_cast<float>(ah[3]));
400                mma_tf32(acc[h], al, bh);
401                mma_tf32(acc[h], ah, bl);
402                mma_tf32(acc[h], ah, bh);
403            }
404        }
405        // relu per head, heads added in order (as the warp kernel), written where the block completed for the query
406        const int64_t bc = b0 + warp * 8 + 2 * tig;
407#pragma unroll
408        for (int half = 0; half < 2; ++half) {
409            const int qr = gid + half * 8;
410            const int64_t qi = q0 + qr;
411            if (qi >= nq) continue;
412            const int nb = s_nbid[qr];
413#pragma unroll
414            for (int j = 0; j < 2; ++j) {
415                const int64_t b = bc + j;
416                if (b >= nb || b >= max_blocks) continue;
417                float score = 0.0f;
418#pragma unroll
419                for (int h = 0; h < IDX_HEADS; ++h) {
420                    const float d = acc[h][half * 2 + j];
421                    score += d > 0.0f ? d : 0.0f;
422                }
423                out[qi * max_blocks + b] = score;
424            }
425        }
426    }
427}
428
429#if defined(__HIPCC__)
430// ---- gfx12 (RDNA4: gfx1200 / gfx1201) scorer on v_wmma_f32_16x16x16_bf16 (wave32).  Same GEMM as above: for a tile of 16
431// queries, every block's score is sum over the 4 indexer heads of relu(q_h . k), K = 128.  FP32-level accuracy from a
432// three-way bf16 split of both operands (x = hi + mid + lo EXACTLY - the top 8, next 8 and last 8 bits of the fp32
433// mantissa, so bf16's fp32-sized exponent range needs no scaling) and the six products of order <= 2, smallest first;
434// like the TF32 kernel it sums in another order than the warp kernel (not bitwise).  The tail block n_bid is the warp
435// kernel's arithmetic (block_scores_tail_kernel).
436//   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):
437//   a lane ends up with 8 consecutive blocks of ONE query, written as one run.  No LDS for keys: a lane reads its
438//   32-byte slice of the key row from global (the 16 query tiles of a launch re-read them from L2); the queries are
439//   split once per CTA into LDS.
440// gfx11 (RDNA3 / RDNA3.5) has the same instruction with another fragment layout: a lane holds all 16 k of its row
441// (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)
442// the first, SEL_ROW(i, g) the D row of element i.  Same products, same order per element as on gfx12.
443#if defined(__gfx1200__) || defined(__gfx1201__)
444#define STRATA_SEL_GFX12 1
445#define STRATA_SEL_GFX11 0
446#elif defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1150__) || \
447    defined(__gfx1151__)
448#define STRATA_SEL_GFX12 0
449#define STRATA_SEL_GFX11 1
450#else
451#define STRATA_SEL_GFX12 0
452#define STRATA_SEL_GFX11 0
453#endif
454#if STRATA_SEL_GFX11
455constexpr int SEL_KL = 16;
456#define SEL_KOFF(g) 0
457#define SEL_ROW(i, g) (2 * (i) + (g))
458#else
459constexpr int SEL_KL = 8;
460#define SEL_KOFF(g) ((g) * 8)
461#define SEL_ROW(i, g) ((g) * 8 + (i))
462#endif
463typedef short sel_s8 __attribute__((ext_vector_type(SEL_KL)));
464typedef float sel_f8 __attribute__((ext_vector_type(8)));
465typedef uint32_t sel_u4 __attribute__((ext_vector_type(SEL_KL / 2)));
466constexpr int WQT = 16;                    // queries per CTA (the N of one WMMA)
467constexpr int WITER = 4;                   // key tiles per warp (the CTA covers 4 warps * WITER * 16 blocks)
468constexpr int WQS = IDX_DIM + 8;           // bf16 elements per LDS row: 272 bytes, conflict-free 16-byte reads
469
470__device__ __forceinline__ sel_f8 wmma_bf16(const sel_s8& a, const sel_s8& b, const sel_f8& c) {
471#if STRATA_SEL_GFX12
472    return __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32_gfx12(a, b, c);
473#elif STRATA_SEL_GFX11
474    return __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32(a, b, c);
475#else
476    /* unreachable on SYCL: the launcher refuses this device */
477    return c;
478#endif
479}
480// the bf16 pieces of x as fp32 bit patterns whose upper 16 bits are the bf16 (lower 16 are zero)
481__device__ __forceinline__ void split3(float x, uint32_t& hi, uint32_t& mid, uint32_t& lo) {
482    hi = sycl::bit_cast<uint32_t>(x) & 0xffff0000u;
483    const float r1 = x - __uint_as_float(hi);                   // exact
484    mid = sycl::bit_cast<uint32_t>(r1) & 0xffff0000u;
485    lo = sycl::bit_cast<uint32_t>(r1 - __uint_as_float(mid)) & 0xffff0000u;   // exact: at most 8 significant bits left
486}
487__device__ __forceinline__ uint32_t pack_bf16x2(uint32_t a, uint32_t b) {   // low half = a's bf16, high half = b's
488#if STRATA_SEL_GFX12 || STRATA_SEL_GFX11
489    return __builtin_amdgcn_perm(b, a, 0x07060302u);
490#else
491    return (a >> 16) | (b & 0xffff0000u);
492#endif
493}
494
495__global__ void __launch_bounds__(128) block_scores_wmma_kernel(const float* __restrict__ pooled,
496                                                                const float* __restrict__ q_idx,
497                                                                const int32_t* __restrict__ steps, int64_t nq,
498                                                                int64_t max_blocks, int64_t reach,
499                                                                float* __restrict__ out) {
500    __shared__ __align__(16) uint16_t sq[3][IDX_HEADS][WQT][WQS];   // hi / mid / lo, [head][query][dim]
501    __shared__ int s_nbid[WQT];
502    const int t = threadIdx.x, lane = t & 31, warp = t >> 5, l16 = lane & 15, g = lane >> 4;
503    const int64_t q0 = (int64_t) blockIdx.y * WQT;
504    for (int i = t; i < WQT * IDX_HEADS * IDX_DIM / 4; i += 128) {
505        const int row = i / (IDX_DIM / 4), c = i % (IDX_DIM / 4);
506        const int qr = row / IDX_HEADS, h = row % IDX_HEADS;
507        float4 v = make_float4(0.f, 0.f, 0.f, 0.f);
508        if (q0 + qr < nq) v = reinterpret_cast<const float4*>(q_idx + (q0 + qr) * IDX_HEADS * IDX_DIM)[h * (IDX_DIM / 4) + c];
509        const float x[4] = {v.x, v.y, v.z, v.w};
510        uint32_t hb[4], mb[4], lb[4];
511#pragma unroll
512        for (int j = 0; j < 4; ++j) split3(x[j], hb[j], mb[j], lb[j]);
513        *reinterpret_cast<uint2*>(&sq[0][h][qr][c * 4]) = make_uint2(pack_bf16x2(hb[0], hb[1]), pack_bf16x2(hb[2], hb[3]));
514        *reinterpret_cast<uint2*>(&sq[1][h][qr][c * 4]) = make_uint2(pack_bf16x2(mb[0], mb[1]), pack_bf16x2(mb[2], mb[3]));
515        *reinterpret_cast<uint2*>(&sq[2][h][qr][c * 4]) = make_uint2(pack_bf16x2(lb[0], lb[1]), pack_bf16x2(lb[2], lb[3]));
516    }
517    if (t < WQT) s_nbid[t] = q0 + t < nq ? steps[(q0 + t) * kStepCount + kStepNBid] : 0;
518    __syncthreads();
519    int hi_nbid = 0;
520#pragma unroll
521    for (int i = 0; i < WQT; ++i) hi_nbid = max(hi_nbid, s_nbid[i]);
522    const int64_t qi = q0 + l16;
523    const int nb_q = s_nbid[l16];
524    for (int it = 0; it < WITER; ++it) {
525        const int64_t b0 = (((int64_t) blockIdx.x * WITER + it) * 4 + warp) * 16;
526        if (b0 >= reach || b0 >= hi_nbid) break;          // warp-uniform; later tiles start higher
527        const int64_t row = b0 + l16;
528        const bool rv = row < hi_nbid && row < max_blocks;
529        const float* kp = pooled + (rv ? row : 0) * IDX_DIM + SEL_KOFF(g);
530        // acc: the hi*hi products; cor: the five smaller ones (<= 2^-8 of it). Kept apart and added once at the end: a
531        // correction summed into the big accumulator is rounded to ITS ulp at every one of the 48 steps (measured: 8e-7
532        // of the score scale; apart, near the warp kernel's)
533        sel_f8 acc[IDX_HEADS], cor[IDX_HEADS];
534#pragma unroll
535        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};
536#pragma unroll 2
537        for (int kk = 0; kk < IDX_DIM / 16; ++kk) {
538            float x[SEL_KL];
539#pragma unroll
540            for (int j = 0; j < SEL_KL / 4; ++j) {
541                float4 kv = make_float4(0.f, 0.f, 0.f, 0.f);
542                if (rv) kv = *reinterpret_cast<const float4*>(kp + kk * 16 + 4 * j);
543                x[4 * j] = kv.x; x[4 * j + 1] = kv.y; x[4 * j + 2] = kv.z; x[4 * j + 3] = kv.w;
544            }
545            uint32_t hb[SEL_KL], mb[SEL_KL], lb[SEL_KL];
546#pragma unroll
547            for (int j = 0; j < SEL_KL; ++j) split3(x[j], hb[j], mb[j], lb[j]);
548            sel_u4 ah, am, al;
549#pragma unroll
550            for (int j = 0; j < SEL_KL / 2; ++j) {
551                ah[j] = pack_bf16x2(hb[2 * j], hb[2 * j + 1]);
552                am[j] = pack_bf16x2(mb[2 * j], mb[2 * j + 1]);
553                al[j] = pack_bf16x2(lb[2 * j], lb[2 * j + 1]);
554            }
555            const sel_s8 Ah = __builtin_bit_cast(sel_s8, ah), Am = __builtin_bit_cast(sel_s8, am),
556                         Al = __builtin_bit_cast(sel_s8, al);
557#pragma unroll
558            for (int h = 0; h < IDX_HEADS; ++h) {
559                const sel_s8 Bh = *reinterpret_cast<const sel_s8*>(&sq[0][h][l16][kk * 16 + SEL_KOFF(g)]);
560                const sel_s8 Bm = *reinterpret_cast<const sel_s8*>(&sq[1][h][l16][kk * 16 + SEL_KOFF(g)]);
561                const sel_s8 Bl = *reinterpret_cast<const sel_s8*>(&sq[2][h][l16][kk * 16 + SEL_KOFF(g)]);
562                cor[h] = wmma_bf16(Al, Bh, cor[h]);
563                cor[h] = wmma_bf16(Ah, Bl, cor[h]);
564                cor[h] = wmma_bf16(Am, Bm, cor[h]);
565                cor[h] = wmma_bf16(Ah, Bm, cor[h]);
566                cor[h] = wmma_bf16(Am, Bh, cor[h]);
567                acc[h] = wmma_bf16(Ah, Bh, acc[h]);
568            }
569        }
570        // relu per head, heads added in order (as the warp kernel); this lane: query qi, blocks b0 + SEL_ROW(i, g)
571        if (qi < nq) {
572#pragma unroll
573            for (int i = 0; i < 8; ++i) {
574                const int64_t b = b0 + SEL_ROW(i, g);
575                if (b >= nb_q || b >= max_blocks) continue;
576                float score = 0.0f;
577#pragma unroll
578                for (int h = 0; h < IDX_HEADS; ++h) {
579                    const float d = acc[h][i] + cor[h][i];
580                    score += d > 0.0f ? d : 0.0f;
581                }
582                out[qi * max_blocks + b] = score;
583            }
584        }
585    }
586}
587
588// the WMMA kernel needs gfx12 (gfx1200/gfx1201) or gfx11 (gfx110x/gfx115x: the other fragment layout) code objects
589bool sel_gfx12_device() {
590    static int ok[64] = {};   // per device: 0 unknown, 1 yes, 2 no
591    int dev = 0;
592    if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return false; }
593    if (ok[dev] == 0) {
594        cudaDeviceProp prop;
595        ok[dev] = (cudaGetDeviceProperties(&prop, dev) == cudaSuccess &&
596                   (std::strncmp(prop.gcnArchName, "gfx1200", 7) == 0 || std::strncmp(prop.gcnArchName, "gfx1201", 7) == 0 ||
597                    strata::kernels::gfx_arch_is_gfx11_wmma(prop.gcnArchName)))
598                      ? 1 : 2;
599        cudaGetLastError();
600    }
601    return ok[dev] == 1;
602}
603#endif  // __HIPCC__
604
605// the tail block n_bid of each query: exactly block_scores_kernel's arithmetic for that block
606__dpct_inline__ void block_scores_tail_kernel(const float *__restrict__ dead,
607                                              const float *__restrict__ q_idx,
608                                              const int32_t *__restrict__ steps,
609                                              int64_t max_blocks,
610                                              float *__restrict__ out) {
611    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
612    const int64_t qi = item_ct1.get_group(2);
613    const int32_t* st = steps + qi * kStepCount;
614    const int64_t n_kv = st[kStepNKv], n_bid = st[kStepNBid];
615    if (n_bid >= max_blocks) return;
616    const int lane = item_ct1.get_local_id(2) & 31;
617    const sycl::float4 k4 =
618        *reinterpret_cast<const sycl::float4 *>(dead + lane * 4);
619    const float* q = q_idx + qi * IDX_HEADS * IDX_DIM + lane * 4;
620    float score = 0.0f;
621#pragma unroll
622    for (int h = 0; h < IDX_HEADS; ++h) {
623        const sycl::float4 q4 =
624            *reinterpret_cast<const sycl::float4 *>(q + h * IDX_DIM);
625        float d = k4.x() * q4.x() + k4.y() * q4.y() + k4.z() * q4.z() +
626                  k4.w() * q4.w();
627#pragma unroll
628        /*
629        DPCT1108: '__shfl_xor_sync' was migrated with the experimental
630        feature masked sub_group function which may not be supported by all
631        compilers or runtimes. You may need to adjust the code.
632        */
633        for (int o = 16; o > 0; o >>= 1) d +=
634            dpct::experimental::permute_sub_group_by_xor(
635                0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(),
636                d, o);
637        score += d > 0.0f ? d : 0.0f;
638    }
639    if (lane == 0) {
640        if (n_kv % R != 0) score += 1e9f;
641        out[qi * max_blocks + n_bid] = score;
642    }
643}
644
645// ---- the same top-k with each query's keys read once: 1,024 threads hold up to TK_PER consecutive blocks' keys in
646// registers (contexts up to 4 * 1024 * TK_PER cells), per-warp histograms, block-wide scans. The selection rule is
647// block_topk_kernel's (radix threshold, ties to the lowest index, cells ascending): identical ids.
648constexpr int TK_T = 1024;
649constexpr int TK_PER = 33;
650#if defined(__HIPCC__)
651// AMD (RDNA, wave32): a 1,024-thread block may use 192 VGPRs per lane, so the keys of 66 blocks per thread fit - contexts
652// up to 4 * 1024 * 66 = 270,336 cells (the 262,144 --max-context) keep the register kernel. NVIDIA's 64 registers per
653// thread at 1,024 threads allow only TK_PER.
654constexpr int TK_PER_MAX = 66;
655#else
656constexpr int TK_PER_MAX = TK_PER;
657#endif
658
659__dpct_inline__ int block_excl_scan(int v, int *s_warp, int &total) {
660    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
661    const int lane = item_ct1.get_local_id(2) & 31,
662              warp = item_ct1.get_local_id(2) >> 5;
663    int x = v;
664#pragma unroll
665    for (int o = 1; o < 32; o <<= 1) {
666        /*
667        DPCT1108: '__shfl_up_sync' was migrated with the experimental feature
668        masked sub_group function which may not be supported by all compilers or
669        runtimes. You may need to adjust the code.
670        */
671        const int y = dpct::experimental::shift_sub_group_right(
672            0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(), x,
673            o);
674        if (lane >= o) x += y;
675    }
676    if (lane == 31) s_warp[warp] = x;
677    /*
678    DPCT1065: Consider replacing sycl::nd_item::barrier() with
679    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
680    performance if there is no access to global memory.
681    */
682    item_ct1.barrier();
683    if (warp == 0) {
684        int w = s_warp[lane];
685        int z = w;
686#pragma unroll
687        for (int o = 1; o < 32; o <<= 1) {
688            /*
689            DPCT1108: '__shfl_up_sync' was migrated with the experimental
690            feature masked sub_group function which may not be supported by all
691            compilers or runtimes. You may need to adjust the code.
692            */
693            const int y = dpct::experimental::shift_sub_group_right(
694                0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(),
695                z, o);
696            if (lane >= o) z += y;
697        }
698        s_warp[lane] = z - w;               // exclusive per warp
699        if (lane == 31) s_warp[32] = z;     // total
700    }
701    /*
702    DPCT1065: Consider replacing sycl::nd_item::barrier() with
703    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
704    performance if there is no access to global memory.
705    */
706    item_ct1.barrier();
707    const int r = s_warp[warp] + x - v;
708    total = s_warp[32];
709    /*
710    DPCT1065: Consider replacing sycl::nd_item::barrier() with
711    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
712    performance if there is no access to global memory.
713    */
714    item_ct1.barrier();
715    return r;
716}
717
718template <int PER>
719/*
720DPCT1110: The total declared local variable size in device function
721block_topk_reg_kernel exceeds 128 bytes and may cause high register pressure.
722Consult with your hardware vendor to find the total register size available and
723adjust the code, or use smaller sub-group size to avoid high register pressure.
724*/
725__dpct_inline__ void block_topk_reg_kernel(const float *__restrict__ scores,
726                                           const int32_t *__restrict__ steps,
727                                           int64_t max_blocks, int64_t cap,
728                                           int32_t *__restrict__ ids) {
729    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
730auto &hist =
731    *sycl::ext::oneapi::group_local_memory_for_overwrite<int[TK_T / 32][256]>(
732        sycl::ext::oneapi::this_work_item::get_work_group<3>());
733    auto &s_warp =
734        *sycl::ext::oneapi::group_local_memory_for_overwrite<int[33]>(
735            sycl::ext::oneapi::this_work_item::get_work_group<3>());
736    auto &s_digit = *sycl::ext::oneapi::group_local_memory_for_overwrite<int>(
737        sycl::ext::oneapi::this_work_item::get_work_group<3>());
738    auto &s_above = *sycl::ext::oneapi::group_local_memory_for_overwrite<int>(
739        sycl::ext::oneapi::this_work_item::get_work_group<3>());
740    const int64_t qi = item_ct1.get_group(2);
741    const int32_t* st = steps + qi * kStepCount;
742    const int64_t n_kv = st[kStepNKv], n_bid = st[kStepNBid], width = st[kStepWidth];
743    int32_t* out = ids + qi * cap;
744    const int t = item_ct1.get_local_id(2), lane = t & 31, warp = t >> 5;
745    if (n_kv <= width) {
746#pragma unroll
747        for (int64_t j = t; j < n_kv; j += TK_T) out[j] = (int32_t)j;
748        return;
749    }
750    const float* sc = scores + qi * max_blocks;
751    const int64_t nb = n_bid + 1;
752    const int64_t per = (nb + TK_T - 1) / TK_T;       // <= PER (the caller checks)
753    const int64_t b0 = (int64_t) t * per, b1 = (b0 + per < nb) ? b0 + per : nb;
754    uint32_t key[PER];
755#pragma unroll
756    for (int j = 0; j < PER; ++j) key[j] = (b0 + j < b1) ? order_key(sc[b0 + j]) : 0u;
757    auto weight = [&](int64_t b) -> int { return b < n_bid ? R : (int) (n_kv - n_bid * R); };
758    uint32_t prefix = 0;
759    int above = 0;
760    for (int shift = 24; shift >= 0; shift -= 8) {
761#pragma unroll
762        for (int i = lane; i < 256; i += 32) hist[warp][i] = 0;
763        sycl::group_barrier(sycl::ext::oneapi::this_work_item::get_sub_group());
764        const uint32_t hi_mask = shift == 24 ? 0u : (0xffffffffu << (shift + 8));
765#pragma unroll
766        for (int j = 0; j < PER; ++j) {
767            const int64_t b = b0 + j;
768            if (b >= b1) break;
769            const int w = weight(b);
770            if (w == 0) continue;
771            if ((key[j] & hi_mask) == (prefix & hi_mask))
772                dpct::atomic_fetch_add<
773                    sycl::access::address_space::generic_space>(
774                    &hist[warp][(key[j] >> shift) & 255], w);
775        }
776        /*
777        DPCT1118: SYCL group functions and algorithms must be encountered in
778        converged control flow. You may need to adjust the code.
779        */
780        /*
781        DPCT1065: Consider replacing sycl::nd_item::barrier() with
782        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
783        better performance if there is no access to global memory.
784        */
785        item_ct1.barrier();
786        if (t < 256) {                                // fold the warps' histograms into warp 0's
787            int s = 0;
788#pragma unroll
789            for (int w2 = 0; w2 < TK_T / 32; ++w2) s += hist[w2][t];
790            hist[0][t] = s;
791        }
792        /*
793        DPCT1118: SYCL group functions and algorithms must be encountered in
794        converged control flow. You may need to adjust the code.
795        */
796        /*
797        DPCT1065: Consider replacing sycl::nd_item::barrier() with
798        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
799        better performance if there is no access to global memory.
800        */
801        item_ct1.barrier();
802        if (t == 0) {
803            int cum = above, d = 255;
804#pragma unroll
805            for (; d > 0; --d) {
806                if (cum + hist[0][d] >= width) break;
807                cum += hist[0][d];
808            }
809            s_digit = d;
810            s_above = cum;
811        }
812        /*
813        DPCT1118: SYCL group functions and algorithms must be encountered in
814        converged control flow. You may need to adjust the code.
815        */
816        /*
817        DPCT1065: Consider replacing sycl::nd_item::barrier() with
818        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
819        better performance if there is no access to global memory.
820        */
821        item_ct1.barrier();
822        prefix |= (uint32_t) s_digit << shift;
823        above = s_above;
824        /*
825        DPCT1118: SYCL group functions and algorithms must be encountered in
826        converged control flow. You may need to adjust the code.
827        */
828        /*
829        DPCT1065: Consider replacing sycl::nd_item::barrier() with
830        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
831        better performance if there is no access to global memory.
832        */
833        item_ct1.barrier();
834    }
835    const uint32_t thr = prefix;
836    const int64_t eq_budget = width - above;
837    int gt = 0, eq = 0;
838#pragma unroll
839    for (int j = 0; j < PER; ++j) {
840        const int64_t b = b0 + j;
841        if (b >= b1) break;
842        const int w = weight(b);
843        if (w == 0) continue;
844        if (key[j] > thr) gt += w;
845        else if (key[j] == thr) eq += w;
846    }
847    int tot;
848    const int eq_before = block_excl_scan(eq, s_warp, tot);
849    int64_t my_eq = eq_budget - eq_before;
850    if (my_eq < 0) my_eq = 0;
851    if (my_eq > eq) my_eq = eq;
852    const int sel = gt + (int) my_eq;
853    int64_t wpos = block_excl_scan(sel, s_warp, tot);
854    int64_t eq_left = my_eq;
855#pragma unroll
856    for (int j = 0; j < PER; ++j) {
857        const int64_t b = b0 + j;
858        if (b >= b1) break;
859        const int w = weight(b);
860        if (w == 0) continue;
861        if (key[j] > thr) {
862#pragma unroll
863            for (int c = 0; c < w; ++c) out[wpos++] = (int32_t)(b * R + c);
864        } else if (key[j] == thr) {
865#pragma unroll
866            for (int c = 0; c < w && eq_left > 0; ++c, --eq_left)
867                out[wpos++] = (int32_t)(b * R + c);
868        }
869    }
870}
871
872#if !defined(__HIPCC__)
873// ---- a query with more blocks than the register kernel holds (contexts past 4 * 1024 * TK_PER cells): the register
874// kernel's threads, per-warp histograms and warp scans, with each key read from memory again on every pass.  A
875// histogram has no order, so on the four radix passes thread t reads blocks t, t + 1024, ...: a warp reads 32
876// neighbours at a time.  The cells are emitted ascending in the order (warp, row, lane): warp w holds the `per` rows
877// of 32 consecutive blocks from block w * 32 * per.  block_topk_kernel's selection rule (radix threshold, ties to the
878// lowest index): identical ids.
879/*
880DPCT1110: The total declared local variable size in device function
881block_topk_wide_kernel exceeds 128 bytes and may cause high register pressure.
882Consult with your hardware vendor to find the total register size available and
883adjust the code, or use smaller sub-group size to avoid high register pressure.
884*/
885__dpct_inline__ void block_topk_wide_kernel(const float *__restrict__ scores,
886                                            const int32_t *__restrict__ steps,
887                                            int64_t max_blocks, int64_t cap,
888                                            int32_t *__restrict__ ids) {
889    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
890auto &hist =
891    *sycl::ext::oneapi::group_local_memory_for_overwrite<int[TK_T / 32][256]>(
892        sycl::ext::oneapi::this_work_item::get_work_group<3>());
893    auto &s_gt =
894        *sycl::ext::oneapi::group_local_memory_for_overwrite<int[TK_T / 32]>(
895            sycl::ext::oneapi::this_work_item::get_work_group<3>());
896    auto &s_eq =
897        *sycl::ext::oneapi::group_local_memory_for_overwrite<int[TK_T / 32]>(
898            sycl::ext::oneapi::this_work_item::get_work_group<3>());
899    auto &s_digit = *sycl::ext::oneapi::group_local_memory_for_overwrite<int>(
900        sycl::ext::oneapi::this_work_item::get_work_group<3>());
901    auto &s_above = *sycl::ext::oneapi::group_local_memory_for_overwrite<int>(
902        sycl::ext::oneapi::this_work_item::get_work_group<3>());
903    const int64_t qi = item_ct1.get_group(2);
904    const int32_t* st = steps + qi * kStepCount;
905    const int64_t n_kv = st[kStepNKv], n_bid = st[kStepNBid], width = st[kStepWidth];
906    int32_t* out = ids + qi * cap;
907    const int t = item_ct1.get_local_id(2), lane = t & 31, warp = t >> 5;
908    if (n_kv <= width) {
909#pragma unroll
910        for (int64_t j = t; j < n_kv; j += TK_T) out[j] = (int32_t)j;
911        return;
912    }
913    const float* sc = scores + qi * max_blocks;
914    const int64_t nb = n_bid + 1;
915    const int64_t per = (nb + TK_T - 1) / TK_T;       // rows of 32 blocks per warp
916    auto weight = [&](int64_t b) -> int { return b < n_bid ? R : (int) (n_kv - n_bid * R); };
917    uint32_t prefix = 0;
918    int above = 0;
919    for (int shift = 24; shift >= 0; shift -= 8) {
920#pragma unroll
921        for (int i = lane; i < 256; i += 32) hist[warp][i] = 0;
922        sycl::group_barrier(sycl::ext::oneapi::this_work_item::get_sub_group());
923        const uint32_t hi_mask = shift == 24 ? 0u : (0xffffffffu << (shift + 8));
924        for (int64_t b = t; b < nb; b += TK_T) {
925            const int w = weight(b);
926            if (w == 0) continue;
927            const uint32_t k = order_key(sc[b]);
928            if ((k & hi_mask) == (prefix & hi_mask)) dpct::atomic_fetch_add<
929                sycl::access::address_space::generic_space>(
930                &hist[warp][(k >> shift) & 255], w);
931        }
932        /*
933        DPCT1118: SYCL group functions and algorithms must be encountered in
934        converged control flow. You may need to adjust the code.
935        */
936        /*
937        DPCT1065: Consider replacing sycl::nd_item::barrier() with
938        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
939        better performance if there is no access to global memory.
940        */
941        item_ct1.barrier();
942        if (t < 256) {                                // fold the warps' histograms into warp 0's
943            int sum = 0;
944#pragma unroll
945            for (int w2 = 0; w2 < TK_T / 32; ++w2) sum += hist[w2][t];
946            hist[0][t] = sum;
947        }
948        /*
949        DPCT1118: SYCL group functions and algorithms must be encountered in
950        converged control flow. You may need to adjust the code.
951        */
952        /*
953        DPCT1065: Consider replacing sycl::nd_item::barrier() with
954        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
955        better performance if there is no access to global memory.
956        */
957        item_ct1.barrier();
958        if (t == 0) {
959            int cum = above, d = 255;
960#pragma unroll
961            for (; d > 0; --d) {
962                if (cum + hist[0][d] >= width) break;
963                cum += hist[0][d];
964            }
965            s_digit = d;
966            s_above = cum;
967        }
968        /*
969        DPCT1118: SYCL group functions and algorithms must be encountered in
970        converged control flow. You may need to adjust the code.
971        */
972        /*
973        DPCT1065: Consider replacing sycl::nd_item::barrier() with
974        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
975        better performance if there is no access to global memory.
976        */
977        item_ct1.barrier();
978        prefix |= (uint32_t) s_digit << shift;
979        above = s_above;
980        /*
981        DPCT1118: SYCL group functions and algorithms must be encountered in
982        converged control flow. You may need to adjust the code.
983        */
984        /*
985        DPCT1065: Consider replacing sycl::nd_item::barrier() with
986        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
987        better performance if there is no access to global memory.
988        */
989        item_ct1.barrier();
990    }
991    const uint32_t thr = prefix;
992    const int eq_budget = (int) (width - above);      // cells equal to thr that fit, lowest index first
993    const int64_t w0 = (int64_t) warp * 32 * per;
994    int gt = 0, eq = 0;
995    for (int64_t b = w0 + lane; b < nb && b < w0 + 32 * per; b += 32) {
996        const int w = weight(b);
997        if (w == 0) continue;
998        const uint32_t k = order_key(sc[b]);
999        if (k > thr) gt += w;
1000        else if (k == thr) eq += w;
1001    }
1002#pragma unroll
1003    for (int o = 16; o > 0; o >>= 1) {
1004        /*
1005        DPCT1108: '__shfl_xor_sync' was migrated with the experimental
1006        feature masked sub_group function which may not be supported by all
1007        compilers or runtimes. You may need to adjust the code.
1008        */
1009        gt += dpct::experimental::permute_sub_group_by_xor(
1010            0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(), gt,
1011            o);
1012        /*
1013        DPCT1108: '__shfl_xor_sync' was migrated with the experimental
1014        feature masked sub_group function which may not be supported by all
1015        compilers or runtimes. You may need to adjust the code.
1016        */
1017        eq += dpct::experimental::permute_sub_group_by_xor(
1018            0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(), eq,
1019            o);
1020    }
1021    if (lane == 0) { s_gt[warp] = gt; s_eq[warp] = eq; }
1022    /*
1023    DPCT1065: Consider replacing sycl::nd_item::barrier() with
1024    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
1025    performance if there is no access to global memory.
1026    */
1027    item_ct1.barrier();
1028    if (t == 0) {                                     // per warp: the selected cells and the tied cells before it
1029        int eb = 0, sb = 0;
1030        for (int w2 = 0; w2 < TK_T / 32; ++w2) {
1031            const int g2 = s_gt[w2], e2 = s_eq[w2];
1032            const int take = eq_budget - eb < 0 ? 0 : (eq_budget - eb > e2 ? e2 : eq_budget - eb);
1033            s_gt[w2] = sb;
1034            s_eq[w2] = eb;
1035            sb += g2 + take;
1036            eb += e2;
1037        }
1038    }
1039    /*
1040    DPCT1065: Consider replacing sycl::nd_item::barrier() with
1041    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
1042    performance if there is no access to global memory.
1043    */
1044    item_ct1.barrier();
1045    int run_sel = s_gt[warp], run_eq = s_eq[warp];
1046    for (int64_t r0 = w0; r0 < nb && r0 < w0 + 32 * per; r0 += 32) {
1047        const int64_t b = r0 + lane;
1048        const int w = b < nb ? weight(b) : 0;
1049        const uint32_t k = w ? order_key(sc[b]) : 0u;
1050        const int my_gt = (w && k > thr) ? w : 0, my_eq = (w && k == thr) ? w : 0;
1051        if (sycl::reduce_over_group(
1052                sycl::ext::oneapi::this_work_item::get_sub_group(),
1053                (0xffffffffu &
1054                 (0x1 << sycl::ext::oneapi::this_work_item::get_sub_group()
1055                             .get_local_linear_id())) &&
1056                        (my_gt | my_eq) != 0
1057                    ? (0x1 << sycl::ext::oneapi::this_work_item::get_sub_group()
1058                                  .get_local_linear_id())
1059                    : 0,
1060                sycl::ext::oneapi::plus<>()) ==
1061            0u) continue; // a row without a selected block
1062        int pe = my_eq;                               // tied cells up to and with this lane
1063#pragma unroll
1064        for (int o = 1; o < 32; o <<= 1) {
1065            /*
1066            DPCT1108: '__shfl_up_sync' was migrated with the experimental
1067            feature masked sub_group function which may not be supported by all
1068            compilers or runtimes. You may need to adjust the code.
1069            */
1070            const int y = dpct::experimental::shift_sub_group_right(
1071                0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(),
1072                pe, o);
1073            if (lane >= o) pe += y;
1074        }
1075        const int left = eq_budget - (run_eq + pe - my_eq);
1076        const int take = left < 0 ? 0 : (left > my_eq ? my_eq : left);
1077        const int my_sel = my_gt + take;
1078        int ps = my_sel;
1079#pragma unroll
1080        for (int o = 1; o < 32; o <<= 1) {
1081            /*
1082            DPCT1108: '__shfl_up_sync' was migrated with the experimental
1083            feature masked sub_group function which may not be supported by all
1084            compilers or runtimes. You may need to adjust the code.
1085            */
1086            const int y = dpct::experimental::shift_sub_group_right(
1087                0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(),
1088                ps, o);
1089            if (lane >= o) ps += y;
1090        }
1091        int32_t* dst = out + run_sel + ps - my_sel;
1092#pragma unroll
1093        for (int c = 0; c < my_sel; ++c) dst[c] = (int32_t)(b * R + c);
1094        /*
1095        DPCT1108: '__shfl_sync' was migrated with the experimental feature
1096        masked sub_group function which may not be supported by all compilers or
1097        runtimes. You may need to adjust the code.
1098        */
1099        run_eq += dpct::experimental::select_from_sub_group(
1100            0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(), pe,
1101            31);
1102        /*
1103        DPCT1108: '__shfl_sync' was migrated with the experimental feature
1104        masked sub_group function which may not be supported by all compilers or
1105        runtimes. You may need to adjust the code.
1106        */
1107        run_sel += dpct::experimental::select_from_sub_group(
1108            0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(), ps,
1109            31);
1110    }
1111}
1112#endif
1113
1114
1115// Block scores with every key block read ONCE for all of a call's queries (block_scores_kernel's grid is
1116// (max_blocks / 8) x nq: ~24,600 mostly-idle blocks per layer at a decode window, each key re-read per query).  A fixed
1117// grid strides over the blocks; per (block, query) the same arithmetic in the same order as block_scores_kernel.
1118// qsa_block_scores takes it for every call without an active-block count and at most MQ queries: the captured decode
1119// window, the uncaptured decode, and prefill's pooled16 call.
1120constexpr int MQ = 8;
1121/*
1122DPCT1110: The total declared local variable size in device function
1123block_scores_multi_kernel exceeds 128 bytes and may cause high register
1124pressure. Consult with your hardware vendor to find the total register size
1125available and adjust the code, or use smaller sub-group size to avoid high
1126register pressure.
1127*/
1128__dpct_inline__ void block_scores_multi_kernel(
1129    const float *__restrict__ pooled, const float *__restrict__ dead,
1130    const float *__restrict__ q_idx, const int32_t *__restrict__ steps, int nq,
1131    int64_t max_blocks, float *__restrict__ out, bool early_exit, QsaScoreRows srow = {}) {
1132    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
1133auto &qs = *sycl::ext::oneapi::group_local_memory_for_overwrite<
1134    float[MQ * IDX_HEADS * IDX_DIM]>(
1135    sycl::ext::oneapi::this_work_item::get_work_group<3>());
1136    auto &s_nkv =
1137        *sycl::ext::oneapi::group_local_memory_for_overwrite<int64_t[MQ]>(
1138            sycl::ext::oneapi::this_work_item::get_work_group<3>());
1139    auto &s_nbid =
1140        *sycl::ext::oneapi::group_local_memory_for_overwrite<int64_t[MQ]>(
1141            sycl::ext::oneapi::this_work_item::get_work_group<3>());
1142    if (!early_exit)
1143#pragma unroll
1144        for (int i = item_ct1.get_local_id(2); i < nq * IDX_HEADS * IDX_DIM;
1145             i += item_ct1.get_local_range(2)) qs[i] = q_idx[i];
1146    if (item_ct1.get_local_id(2) < nq) {
1147        s_nkv[item_ct1.get_local_id(2)] =
1148            steps[item_ct1.get_local_id(2) * kStepCount + kStepNKv];
1149        s_nbid[item_ct1.get_local_id(2)] =
1150            steps[item_ct1.get_local_id(2) * kStepCount + kStepNBid];
1151    }
1152    item_ct1.barrier(sycl::access::fence_space::local_space);
1153    int64_t top = 0;
1154#pragma unroll
1155    for (int q = 0; q < nq; ++q) top = s_nbid[q] > top ? s_nbid[q] : top;
1156    if (early_exit) {
1157        // (#783, stuchapin909) a CTA whose first block is past the batch's largest n_bid has no work: the grid is a
1158        // fixed 256 CTAs and a decode window reaches only a few of them, so those return before staging the queries.
1159        // Every thread of the CTA takes the same branch (top and blockIdx are CTA-uniform), so the barrier is safe.
1160        if ((int64_t)item_ct1.get_group(2) * SCORE_WARPS > top) return;
1161#pragma unroll
1162        for (int i = item_ct1.get_local_id(2); i < nq * IDX_HEADS * IDX_DIM;
1163             i += item_ct1.get_local_range(2)) qs[i] = q_idx[i];
1164        /*
1165        DPCT1118: SYCL group functions and algorithms must be encountered in
1166        converged control flow. You may need to adjust the code.
1167        */
1168        item_ct1.barrier(sycl::access::fence_space::local_space);
1169    }
1170    const int lane = item_ct1.get_local_id(2) & 31;
1171    const int64_t wstride = (int64_t)item_ct1.get_group_range(2) * SCORE_WARPS;
1172    for (int64_t b = (int64_t)item_ct1.get_group(2) * SCORE_WARPS +
1173                     (item_ct1.get_local_id(2) >> 5);
1174         b <= top && b < max_blocks; b += wstride) {
1175        // srow.n > 0: each query reads its own sequence's keys; else one set of keys for every query
1176        const bool own = srow.n > 0;
1177        const sycl::float4 kp = own ? sycl::float4{} : *reinterpret_cast<const sycl::float4 *>(
1178            pooled + b * IDX_DIM + lane * 4);
1179        const sycl::float4 kd = own ? sycl::float4{} :
1180            *reinterpret_cast<const sycl::float4 *>(dead + lane * 4);
1181        for (int qi = 0; qi < nq; ++qi) {
1182            const int64_t n_bid = s_nbid[qi];
1183            if (b > n_bid) continue;
1184            const sycl::float4 k4 = !own ? ((b == n_bid) ? kd : kp)
1185                : (b == n_bid) ? *reinterpret_cast<const sycl::float4 *>(srow.dead[qi] + lane * 4)
1186                               : *reinterpret_cast<const sycl::float4 *>(srow.pooled[qi] + b * IDX_DIM + lane * 4);
1187            const float* q = qs + qi * IDX_HEADS * IDX_DIM + lane * 4;
1188            float score = 0.0f;
1189#pragma unroll
1190            for (int h = 0; h < IDX_HEADS; ++h) {
1191                const sycl::float4 q4 =
1192                    *reinterpret_cast<const sycl::float4 *>(q + h * IDX_DIM);
1193                float d = k4.x() * q4.x() + k4.y() * q4.y() + k4.z() * q4.z() +
1194                          k4.w() * q4.w();
1195#pragma unroll
1196                /*
1197                DPCT1108: '__shfl_xor_sync' was migrated with the
1198                experimental feature masked sub_group function which may not be
1199                supported by all compilers or runtimes. You may need to adjust
1200                the code.
1201                */
1202                for (int o = 16; o > 0; o >>= 1) d +=
1203                    dpct::experimental::permute_sub_group_by_xor(
1204                        0xffffffffu,
1205                        sycl::ext::oneapi::this_work_item::get_sub_group(), d,
1206                        o);
1207                score += d > 0.0f ? d : 0.0f;
1208            }
1209            if (lane == 0) {
1210                if (b == n_bid && s_nkv[qi] % R != 0) score += 1e9f;
1211                out[qi * max_blocks + b] = score;
1212            }
1213        }
1214    }
1215}
1216
1217#if !defined(__HIPCC__)
1218// ---- the decode top-k on a thread-block cluster (sm_90+; S19).  One CTA per query (block_topk_reg_kernel, or
1219// block_topk_kernel above 33,792 blocks: a --max-context over ~135K) makes four radix passes and two scans over up to
1220// 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
1221// CTAs shares a query: CTA r holds the keys of blocks [r * per, (r + 1) * per) in shared memory, builds the digit
1222// histogram of its keys, and PUSHES it into slot r of every CTA's `hin` (distributed shared memory); after one cluster
1223// barrier each CTA sums the CL_N slots itself, so all of them take the same digit.  The emit pass needs each CTA's
1224// cells above / at the threshold: pushed the same way, then each CTA offsets its own by the ranks before it.
1225// RTX 5070, per call at capacity = context (decode_cluster_parity --bench): 21.9 -> 15.6 us at 32K, 58 -> 18 at 128K,
1226// 200 -> 22 at 262K (the one-CTA kernels' digit search was serial, too: one thread over 256 bins per pass).
1227//
1228// IDENTICAL IDS, by construction rather than by luck: the threshold thr (the width-th largest key, cells counted with
1229// their weights) and `above` (cells with a larger key) are pure functions of the multiset of (key, weight) - integer
1230// histograms, summed in any order - and the digit rule is block_topk_kernel's, written as a scan (the largest digit d
1231// whose cells at or above it reach `need`; 0 when none). The cells emitted are then fixed: every cell of a block with
1232// key > thr, and the first eq_budget = width - above cells at thr in ascending order (a block at thr may be cut),
1233// written in ascending cell order. Position of a thread's first cell = (cells above thr before it) + min(cells at thr
1234// before it, eq_budget): the telescoped sum of the reference's per-thread clamp. NaN keys are 0 (order_key) as there.
1235//
1236// Barriers: barrier.cluster arrive / wait (each CTA's threads all take part; it also orders the CTA's own shared
1237// memory, so it doubles as __syncthreads). Phase 0 is a relaxed arrive at entry, waited before the first remote store
1238// (a CTA's shared memory exists once it runs). Pushes go out before the arrive that releases them, and nothing reads
1239// another CTA's memory after the last wait - so a CTA may exit without a closing barrier (a wait counts the threads
1240// that have not exited). `hin` alternates by pass parity: CTA x reads slot buffer p&1 in pass p before arriving at
1241// pass p+1's barrier, and nobody writes buffer p&1 again (pass p+2) before waiting on that barrier.
1242constexpr int CL_N = 8;        // CTAs per query (the portable cluster size)
1243constexpr int CL_T = 1024;     // threads per CTA
1244constexpr int CL_MAXQ = 16;    // larger calls (prefill sub-batches) fill the GPU with one CTA per query already
1245#if defined(DPCT_COMPATIBILITY_TEMP) && DPCT_COMPATIBILITY_TEMP >= 900
1246#define STRATA_SEL_CLUSTER 1
1247#else
1248#define STRATA_SEL_CLUSTER 0   // an older target's code is a trap; qsa_block_topk_cluster never launches it there
1249#endif
1250
1251#if STRATA_SEL_CLUSTER
1252__dpct_inline__ void cl_arrive_relaxed() {
1253    /*
1254    DPCT1053: Migration of device assembly code is not supported.
1255    */
1256    asm volatile("barrier.cluster.arrive.relaxed.aligned;\n" ::: "memory");
1257}
1258/*
1259DPCT1053: Migration of device assembly code is not supported.
1260*/
1261__dpct_inline__ void cl_arrive() {
1262    asm volatile("barrier.cluster.arrive.release.aligned;\n" :: : "memory");
1263}
1264/*
1265DPCT1053: Migration of device assembly code is not supported.
1266*/
1267__dpct_inline__ void cl_wait() {
1268    asm volatile("barrier.cluster.wait.acquire.aligned;\n" :: : "memory");
1269}
1270__dpct_inline__ unsigned cl_rank() {
1271    unsigned r;
1272    /*
1273    DPCT1053: Migration of device assembly code is not supported.
1274    */
1275    asm volatile("mov.u32 %0, %%cluster_ctarank;\n" : "=r"(r));
1276    return r;
1277}
1278template <typename T>
1279__dpct_inline__ T *cl_map(T *p,
1280                          unsigned rank) { // p in CTA `rank`'s shared memory
1281    uint64_t o;
1282    /*
1283    DPCT1053: Migration of device assembly code is not supported.
1284    */
1285    asm volatile("mapa.u64 %0, %1, %2;\n"
1286                 : "=l"(o)
1287                 : "l"((uint64_t)p), "r"(rank));
1288    return reinterpret_cast<T*>(o);
1289}
1290// exclusive block scan of a 64-bit value over CL_T threads; `total` = the CTA's sum
1291__dpct_inline__ unsigned long long cl_excl_scan64(unsigned long long v,
1292                                                  unsigned long long *s_warp,
1293                                                  unsigned long long &total) {
1294    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
1295    const int lane = item_ct1.get_local_id(2) & 31,
1296              warp = item_ct1.get_local_id(2) >> 5;
1297    unsigned long long x = v;
1298#pragma unroll
1299    for (int o = 1; o < 32; o <<= 1) {
1300        /*
1301        DPCT1108: '__shfl_up_sync' was migrated with the experimental feature
1302        masked sub_group function which may not be supported by all compilers or
1303        runtimes. You may need to adjust the code.
1304        */
1305        const unsigned long long y = dpct::experimental::shift_sub_group_right(
1306            0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(), x,
1307            o);
1308        if (lane >= o) x += y;
1309    }
1310    if (lane == 31) s_warp[warp] = x;
1311    /*
1312    DPCT1065: Consider replacing sycl::nd_item::barrier() with
1313    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
1314    performance if there is no access to global memory.
1315    */
1316    item_ct1.barrier();
1317    if (warp == 0) {
1318        const unsigned long long w = s_warp[lane];
1319        unsigned long long z = w;
1320#pragma unroll
1321        for (int o = 1; o < 32; o <<= 1) {
1322            /*
1323            DPCT1108: '__shfl_up_sync' was migrated with the experimental
1324            feature masked sub_group function which may not be supported by all
1325            compilers or runtimes. You may need to adjust the code.
1326            */
1327            const unsigned long long y =
1328                dpct::experimental::shift_sub_group_right(
1329                    0xffffffffu,
1330                    sycl::ext::oneapi::this_work_item::get_sub_group(), z, o);
1331            if (lane >= o) z += y;
1332        }
1333        s_warp[lane] = z - w;
1334        if (lane == 31) s_warp[32] = z;
1335    }
1336    /*
1337    DPCT1065: Consider replacing sycl::nd_item::barrier() with
1338    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
1339    performance if there is no access to global memory.
1340    */
1341    item_ct1.barrier();
1342    total = s_warp[32];
1343    return s_warp[warp] + x - v;
1344}
1345#endif
1346
1347// grid (CL_N, nq), cluster (CL_N, 1, 1), CL_T threads, dynamic shared memory: ceil(max_blocks / CL_N) keys
1348/*
1349DPCT1110: The total declared local variable size in device function
1350block_topk_cluster_kernel exceeds 128 bytes and may cause high register
1351pressure. Consult with your hardware vendor to find the total register size
1352available and adjust the code, or use smaller sub-group size to avoid high
1353register pressure.
1354*/
1355void block_topk_cluster_kernel(const float *__restrict__ scores,
1356                               const int32_t *__restrict__ steps,
1357                               int64_t max_blocks, int64_t cap,
1358                               int32_t *__restrict__ ids, uint8_t *dpct_local) {
1359#if STRATA_SEL_CLUSTER
1360    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
1361    auto keys = (uint32_t *)dpct_local; // this CTA's blocks' keys
1362    auto &hin =
1363        *sycl::ext::oneapi::group_local_memory_for_overwrite<int[2][CL_N][256]>(
1364            sycl::ext::oneapi::this_work_item::get_work_group<
1365                3>()); // the cluster's histograms, slot = the pushing rank
1366    auto &hloc =
1367        *sycl::ext::oneapi::group_local_memory_for_overwrite<int[2][256]>(
1368            sycl::ext::oneapi::this_work_item::get_work_group<
1369                3>()); // this CTA's histogram
1370    auto &cnt = *sycl::ext::oneapi::group_local_memory_for_overwrite<
1371        unsigned long long[CL_N]>(
1372        sycl::ext::oneapi::this_work_item::get_work_group<
1373            3>()); // per rank: its cells above thr (low 32 bits) and at it
1374                   // (high)
1375    auto &s_warp = *sycl::ext::oneapi::group_local_memory_for_overwrite<
1376        unsigned long long[33]>(
1377        sycl::ext::oneapi::this_work_item::get_work_group<3>());
1378    auto &s_prefix =
1379        *sycl::ext::oneapi::group_local_memory_for_overwrite<uint32_t>(
1380            sycl::ext::oneapi::this_work_item::get_work_group<3>());
1381    auto &s_above = *sycl::ext::oneapi::group_local_memory_for_overwrite<int>(
1382        sycl::ext::oneapi::this_work_item::get_work_group<3>());
1383    const unsigned rank = cl_rank();
1384    const int t = item_ct1.get_local_id(2), lane = t & 31, warp = t >> 5;
1385    cl_arrive_relaxed();                                // phase 0: this CTA runs
1386    const int64_t qi = item_ct1.get_group(1);
1387    const int32_t* st = steps + qi * kStepCount;
1388    const int64_t n_kv = st[kStepNKv], n_bid = st[kStepNBid], width = st[kStepWidth];
1389    int32_t* out = ids + qi * cap;
1390    if (n_kv <= width) {                                // the identity, split over the cluster; no remote access
1391#pragma unroll
1392        for (int64_t j = (int64_t)rank * CL_T + t; j < n_kv;
1393             j += (int64_t)CL_N * CL_T) out[j] = (int32_t)j;
1394        return;
1395    }
1396    // the tail block n_bid weighs its cells (0..3); with none it is not a candidate (the reference skips w == 0)
1397    const int wtail = (int) (n_kv - n_bid * R);
1398    const int64_t nbe = n_bid + (wtail > 0 ? 1 : 0);
1399    const int64_t per = (nbe + CL_N - 1) / CL_N;       // <= ceil(max_blocks / CL_N), the keys the host sized
1400    const int64_t lo = (int64_t) rank * per < nbe ? (int64_t) rank * per : nbe;
1401    const int64_t hi = lo + per < nbe ? lo + per : nbe;
1402    const int n = (int) (hi - lo);
1403    const int tail_i = (wtail > 0 && n_bid >= lo && n_bid < hi) ? (int) (n_bid - lo) : -1;
1404    const float* sc = scores + qi * max_blocks + lo;
1405#pragma unroll
1406    for (int i = t; i < n; i += CL_T) keys[i] = order_key(sc[i]);
1407#pragma unroll
1408    for (int i = t; i < 2 * 256; i += CL_T)(&hloc[0][0])[i] = 0;
1409    /*
1410    DPCT1065: Consider replacing sycl::nd_item::barrier() with
1411    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
1412    performance if there is no access to global memory.
1413    */
1414    item_ct1.barrier();
1415    uint32_t prefix = 0;
1416    int above = 0;                                      // cells strictly above the digits fixed so far
1417    for (int pass = 0; pass < 4; ++pass) {
1418        const int shift = 24 - 8 * pass;
1419        const uint32_t hmask = pass == 0 ? 0u : (0xffffffffu << (shift + 8));
1420        int* hl = hloc[pass & 1];
1421        // warp-aggregated: the scores share their top bits, so plain atomics would queue on a few bins
1422        for (int i0 = 0; i0 < n; i0 += CL_T) {
1423            const int i = i0 + t;
1424            int bin = -1;
1425            if (i < n) {
1426                const uint32_t k = keys[i];
1427                if ((k & hmask) == prefix) bin = (int) ((k >> shift) & 255);
1428            }
1429            const unsigned same = dpct::match_any_over_sub_group(
1430                sycl::ext::oneapi::this_work_item::get_sub_group(), 0xffffffffu,
1431                bin);
1432            if (bin >= 0 && lane == dpct::ffs<int>(same) - 1)
1433                dpct::atomic_fetch_add<
1434                    sycl::access::address_space::generic_space>(
1435                    &hl[bin], sycl::popcount(same) * R);
1436            if (bin >= 0 && i == tail_i) dpct::atomic_fetch_add<
1437                sycl::access::address_space::generic_space>(&hl[bin],
1438                                                            wtail - R);
1439        }
1440        /*
1441        DPCT1118: SYCL group functions and algorithms must be encountered in
1442        converged control flow. You may need to adjust the code.
1443        */
1444        /*
1445        DPCT1065: Consider replacing sycl::nd_item::barrier() with
1446        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
1447        better performance if there is no access to global memory.
1448        */
1449        item_ct1.barrier();
1450        if (pass == 0) cl_wait();                       // phase 0 done: every CTA's shared memory is there
1451        for (int i = t; i < CL_N * 64; i += CL_T) {     // the histogram into slot `rank` of every CTA, as int4
1452            const int dst = i >> 6, c = i & 63;
1453            *cl_map(reinterpret_cast<sycl::int4 *>(&hin[pass & 1][rank][0]) + c,
1454                    (unsigned)dst) =
1455                reinterpret_cast<const sycl::int4 *>(hl)[c];
1456        }
1457#pragma unroll
1458        for (int i = t; i < 256; i += CL_T) hloc[(pass + 1) & 1][i] = 0;
1459        cl_arrive();
1460        cl_wait();
1461        if (warp == 0) {
1462            // lane L owns digits 255 - 8L down to 248 - 8L; the digit holding the need-th cell from the top
1463            const int need = (int) width - above;
1464            int tot[8], part = 0;
1465#pragma unroll
1466            for (int k = 0; k < 8; ++k) {
1467                const int d = 255 - 8 * lane - k;
1468                int v = 0;
1469#pragma unroll
1470                for (int r = 0; r < CL_N; ++r) v += hin[pass & 1][r][d];
1471                tot[k] = v;
1472                part += v;
1473            }
1474            int incl = part;
1475#pragma unroll
1476            for (int o = 1; o < 32; o <<= 1) {
1477                /*
1478                DPCT1108: '__shfl_up_sync' was migrated with the experimental
1479                feature masked sub_group function which may not be supported by
1480                all compilers or runtimes. You may need to adjust the code.
1481                */
1482                const int y = dpct::experimental::shift_sub_group_right(
1483                    0xffffffffu,
1484                    sycl::ext::oneapi::this_work_item::get_sub_group(), incl,
1485                    o);
1486                if (lane >= o) incl += y;
1487            }
1488            const int excl = incl - part;
1489            const unsigned hit = sycl::reduce_over_group(
1490                sycl::ext::oneapi::this_work_item::get_sub_group(),
1491                (0xffffffffu &
1492                 (0x1 << sycl::ext::oneapi::this_work_item::get_sub_group()
1493                             .get_local_linear_id())) &&
1494                        excl < need && incl >= need
1495                    ? (0x1 << sycl::ext::oneapi::this_work_item::get_sub_group()
1496                                  .get_local_linear_id())
1497                    : 0,
1498                sycl::ext::oneapi::plus<>());
1499            // no hit cannot happen (the cells total n_kv > width); the reference would then take digit 0
1500            const int who = hit ? dpct::ffs<int>(hit) - 1 : 31;
1501            if (lane == who) {
1502                int acc = excl, k = 0;
1503#pragma unroll
1504                for (; k < 7; ++k) {
1505                    if (acc + tot[k] >= need) break;
1506                    acc += tot[k];
1507                }
1508                s_prefix = prefix | ((uint32_t) (255 - 8 * lane - k) << shift);
1509                s_above = above + acc;
1510            }
1511        }
1512        /*
1513        DPCT1118: SYCL group functions and algorithms must be encountered in
1514        converged control flow. You may need to adjust the code.
1515        */
1516        /*
1517        DPCT1065: Consider replacing sycl::nd_item::barrier() with
1518        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
1519        better performance if there is no access to global memory.
1520        */
1521        item_ct1.barrier();
1522        prefix = s_prefix;
1523        above = s_above;
1524    }
1525    const uint32_t thr = prefix;
1526    const int64_t eq_budget = width - above;           // cells at thr that fit, lowest index first
1527    // each thread a contiguous run of the CTA's keys; an odd run length keeps the shared reads conflict-free
1528    int seg = (n + CL_T - 1) / CL_T;
1529    if ((seg & 1) == 0 && seg > 0) ++seg;
1530    const int s0 = t * seg < n ? t * seg : n, s1 = s0 + seg < n ? s0 + seg : n;
1531    uint32_t gt = 0, eq = 0;
1532    for (int i = s0; i < s1; ++i) {
1533        const uint32_t k = keys[i], w = i == tail_i ? (uint32_t) wtail : (uint32_t) R;
1534        if (k > thr) gt += w;
1535        else if (k == thr) eq += w;
1536    }
1537    unsigned long long cta;
1538    const unsigned long long before =
1539        cl_excl_scan64((unsigned long long) gt | ((unsigned long long) eq << 32), s_warp, cta);
1540    if (t < CL_N) *cl_map(&cnt[rank], (unsigned) t) = cta;
1541    cl_arrive();
1542    cl_wait();
1543    int64_t gt_off = 0, eq_off = 0;
1544#pragma unroll
1545    for (unsigned r = 0; r < rank; ++r) {
1546        gt_off += (int64_t) (cnt[r] & 0xffffffffu);
1547        eq_off += (int64_t) (cnt[r] >> 32);
1548    }
1549    const int64_t eq_before = eq_off + (int64_t) (before >> 32);
1550    int64_t wpos = gt_off + (int64_t) (before & 0xffffffffu) + (eq_before < eq_budget ? eq_before : eq_budget);
1551    int64_t eq_left = eq_budget - eq_before;
1552    if (eq_left < 0) eq_left = 0;
1553    for (int i = s0; i < s1; ++i) {
1554        const uint32_t k = keys[i];
1555        const int w = i == tail_i ? wtail : R;
1556        const int64_t b = lo + i;
1557        if (k > thr) {
1558#pragma unroll
1559            for (int c = 0; c < w; ++c) out[wpos++] = (int32_t)(b * R + c);
1560        } else if (k == thr) {
1561#pragma unroll
1562            for (int c = 0; c < w && eq_left > 0; ++c, --eq_left)
1563                out[wpos++] = (int32_t)(b * R + c);
1564        }
1565    }
1566#else
1567    (void) scores; (void) steps; (void) max_blocks; (void) cap; (void) ids;
1568    /* unreachable on SYCL: the launcher refuses this device */
1569#endif
1570}
1571#endif  // !__HIPCC__
1572}  // namespace
1573
1574void qsa_block_scores_rows(const QsaScoreRows& rows, const float* q_idx, const int32_t* steps, int64_t nq,
1575                           int64_t max_blocks, const QsaShapes& s, float* scores, void* stream) {
1576    if (nq <= 0) return;
1577    if (s.idx_dim != IDX_DIM || s.idx_n_head != IDX_HEADS || s.idx_block != R || nq > MQ || rows.n != nq) {
1578        std::fprintf(stderr, "qsa_block_scores_rows: unsupported geometry\n");
1579        std::exit(1);
1580    }
1581    static const bool early = [] { const char* v = std::getenv("STRATA_QSA_EARLY_EXIT"); return v == nullptr || std::atoi(v) != 0; }();
1582    const QsaScoreRows srow = rows;
1583    auto exp_props = sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};
1584    strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)->submit([&](sycl::handler &cgh) {
1585        auto early_ct7 = early;
1586        cgh.parallel_for<dpct_kernel_name<class block_scores_rows_kernel_a3>>(
1587            sycl::nd_range<3>(sycl::range(1, 1, 256) * sycl::range(1, 1, SCORE_WARPS * 32),
1588                              sycl::range(1, 1, SCORE_WARPS * 32)),
1589            exp_props, [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {
1590                block_scores_multi_kernel(nullptr, nullptr, q_idx, steps, (int)nq, max_blocks, scores, early_ct7, srow);
1591            });
1592    });
1593}
1594
1595// SYCL port: the prompt path's block scores as oneMKL GEMM tiles (prefill.cpp): S[q * IDX_HEADS + h][b - b0] is
1596// pooled[b] . q_idx[q][h] for the blocks [b0, b0 + nb); this turns them into scores[q][b] - relu per indexer head,
1597// summed in head order - and gives block n_bid the dead key with block_scores_kernel's +1e9 rule. Blocks past a
1598// query's n_bid are not written, as in qsa_block_scores. FP32, another summation order than the warp kernel: not
1599// bitwise (relative error 2-4e-7; the same selection but for near-ties).
1600void qsa_block_scores_reduce(const float* S, int64_t ld, int64_t b0, int64_t nb, const float* dead, const float* q_idx,
1601                             const int32_t* steps, int64_t nq, int64_t max_blocks, float* scores, void* stream) {
1602    if (nq <= 0 || nb <= 0) return;
1603    strata::q_of(stream)->parallel_for(sycl::range<2>((size_t) nq, (size_t) nb), [=](sycl::id<2> it) {
1604        const int64_t qi = (int64_t) it[0], b = b0 + (int64_t) it[1];
1605        const int64_t n_kv = steps[qi * kStepCount + kStepNKv], n_bid = steps[qi * kStepCount + kStepNBid];
1606        if (b > n_bid || b >= max_blocks) return;
1607        float score = 0.0f;
1608        if (b == n_bid) {
1609            for (int h = 0; h < IDX_HEADS; ++h) {
1610                float d = 0.0f;
1611                for (int i = 0; i < IDX_DIM; ++i) d += dead[i] * q_idx[(qi * IDX_HEADS + h) * IDX_DIM + i];
1612                score += d > 0.0f ? d : 0.0f;
1613            }
1614            if (n_kv % R != 0) score += 1e9f;
1615        } else {
1616            for (int h = 0; h < IDX_HEADS; ++h) {
1617                const float d = S[(size_t) (qi * IDX_HEADS + h) * (size_t) ld + (size_t) (b - b0)];
1618                score += d > 0.0f ? d : 0.0f;
1619            }
1620        }
1621        scores[(size_t) qi * (size_t) max_blocks + (size_t) b] = score;
1622    });
1623}
1624
1625void qsa_block_scores(const float* pooled, const float* dead, const float* q_idx, const int32_t* steps, int64_t nq,
1626                      int64_t max_blocks, const QsaShapes& s, float* scores, void* stream, int64_t active_blocks) {
1627    if (nq <= 0) return;
1628    if (s.idx_dim != IDX_DIM || s.idx_n_head != IDX_HEADS || s.idx_block != R || nq > 65535) {
1629        std::fprintf(stderr, "qsa_block_scores: unsupported indexer geometry\n");
1630        std::exit(1);
1631    }
1632    // a block past a query's n_bid returns at once: the grid need only reach the batch's largest n_bid (C-1)
1633    static const bool multi = [] { const char* v = std::getenv("STRATA_SCORES_MULTI"); return v == nullptr || std::atoi(v) != 0; }();
1634    if (multi && nq <= MQ && active_blocks <= 0) {   // no active count: decode (captured or not) and prefill's pooled16
1635        // STRATA_QSA_EARLY_EXIT=0 keeps the old staging (every CTA loads the queries first); the scores are the same bits
1636        static const bool early = [] { const char* v = std::getenv("STRATA_QSA_EARLY_EXIT"); return v == nullptr || std::atoi(v) != 0; }();
1637        {
1638            auto exp_props = sycl::ext::oneapi::experimental::properties{
1639                sycl::ext::oneapi::experimental::use_root_sync};
1640
1641            strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
1642                ->submit([&](sycl::handler &cgh) {
1643                    auto early_ct7 = early;
1644
1645                    cgh.parallel_for<dpct_kernel_name<
1646                        class block_scores_multi_kernel_dea7d4>>(
1647                        sycl::nd_range<3>(
1648                            sycl::range(1, 1, 256) *
1649                                sycl::range(1, 1, SCORE_WARPS * 32),
1650                            sycl::range(1, 1, SCORE_WARPS * 32)),
1651                        exp_props,
1652                        [=](sycl::nd_item<3> item_ct1)
1653                            [[sycl::reqd_sub_group_size(32)]] {
1654                                block_scores_multi_kernel(
1655                                    pooled, dead, q_idx, steps, (int)nq,
1656                                    max_blocks, scores, early_ct7);
1657                            });
1658                });
1659        }
1660        /*
1661        DPCT1010: SYCL uses exceptions to report errors and does not use
1662        the error codes. The cudaGetLastError function call was replaced with 0.
1663        You need to rewrite this code.
1664        */
1665        const dpct::err0 e = 0;
1666        /*
1667        DPCT1009: SYCL reports errors using exceptions and does not use
1668        error codes. Please replace the "get_error_string_dummy(...)" with a
1669        real error-handling function.
1670        */
1671
1672        return;
1673    }
1674    const int64_t reach = active_blocks > 0 && active_blocks < max_blocks ? active_blocks : max_blocks;
1675    const dpct::dim3 grid((unsigned)((reach + SCORE_WARPS - 1) / SCORE_WARPS),
1676                          (unsigned)nq);
1677    {
1678        auto exp_props = sycl::ext::oneapi::experimental::properties{
1679            sycl::ext::oneapi::experimental::use_root_sync};
1680
1681        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
1682            ->template parallel_for<dpct_kernel_name<class block_scores_kernel_925c9d>>(
1683                sycl::nd_range<3>(grid * sycl::range(1, 1, SCORE_WARPS * 32),
1684                                  sycl::range(1, 1, SCORE_WARPS * 32)),
1685                exp_props,
1686                [=](sycl::nd_item<3> item_ct1)
1687                    [[sycl::reqd_sub_group_size(32)]] {
1688                        block_scores_kernel(pooled, dead, q_idx, steps,
1689                                            max_blocks, scores);
1690                    });
1691    }
1692    /*
1693    DPCT1010: SYCL uses exceptions to report errors and does not use the
1694    error codes. The cudaGetLastError function call was replaced with 0. You
1695    need to rewrite this code.
1696    */
1697    const dpct::err0 e = 0;
1698    /*
1699    DPCT1009: SYCL reports errors using exceptions and does not use error
1700    codes. Please replace the "get_error_string_dummy(...)" with a real
1701    error-handling function.
1702    */
1703}
1704
1705bool qsa_block_scores_tc(const float *pooled, const float *dead,
1706                         const float *q_idx, const int32_t *steps, int64_t nq,
1707                         int64_t max_blocks, const QsaShapes &s, float *scores,
1708                         void *stream, int64_t active_blocks) try {
1709    if (nq <= 0) return true;
1710    if (s.idx_dim != IDX_DIM || s.idx_n_head != IDX_HEADS || s.idx_block != R || nq > 65535 * TC_QT) return false;
1711#if defined(__HIPCC__)
1712    // AMD: the gfx12 (RDNA4) WMMA scorer, opt-in (STRATA_SELECT_WMMA=1): it selects slightly differently from the warp
1713    // kernel (254/256 queries the same), so the default keeps the warp kernel; every other target keeps it too (false)
1714    static const bool wmma_on = [] {
1715        const char* v = std::getenv("STRATA_SELECT_WMMA");
1716        return v != nullptr && v[0] != '\0' && v[0] != '0';
1717    }();
1718    if (!wmma_on || !sel_gfx12_device()) return false;
1719    {
1720        const int64_t reach = active_blocks > 0 && active_blocks < max_blocks ? active_blocks : max_blocks;
1721        const int64_t per = (int64_t) 4 * WITER * 16;
1722        const dim3 grid((unsigned) ((reach + per - 1) / per), (unsigned) ((nq + WQT - 1) / WQT));
1723        block_scores_wmma_kernel<<<grid, 128, 0, (cudaStream_t) stream>>>(pooled, q_idx, steps, nq, max_blocks, reach, scores);
1724        block_scores_tail_kernel<<<(unsigned) nq, 32, 0, (cudaStream_t) stream>>>(dead, q_idx, steps, max_blocks, scores);
1725        const cudaError_t e = cudaGetLastError();
1726        if (e != cudaSuccess) { std::fprintf(stderr, "qsa_block_scores_tc: %s\n", cudaGetErrorString(e)); std::exit(1); }
1727        return true;
1728    }
1729#else
1730    {   // sm_80 or newer (TF32 MMA); an older card keeps the warp kernel
1731        static int cc_major[64] = {};
1732        int dev = 0;
1733        /*
1734        DPCT1026: The call to cudaGetLastError was removed because this
1735        functionality is redundant in SYCL.
1736        */
1737        if (DPCT_CHECK_ERROR(dev = dpct::get_current_device_id()) != 0 ||
1738            dev < 0 || dev >= 64) {
1739            ; return false;
1740        }
1741        if (cc_major[dev] == 0) {
1742            int major = 0;
1743            if (DPCT_CHECK_ERROR(
1744                    major = dpct::get_device(dev).get_major_version()) != 0) {
1745                /*
1746                DPCT1026: The call to cudaGetLastError was removed because
1747                this functionality is redundant in SYCL.
1748                */
1749                return false;
1750            }
1751            // STRATA_QSA_WARP=1|select (an A/B arm): the pre-sm_80 kernels on any card, as RTX 20 runs them
1752            const char* w = std::getenv("STRATA_QSA_WARP");
1753            cc_major[dev] = w && (!std::strcmp(w, "1") || !std::strcmp(w, "select")) ? 7 : strata::cc_major_of(major);
1754        }
1755        (void) cc_major[dev];
1756        return false;   // SYCL: the tensor-core kernel is not ported yet; the caller takes the older kernel
1757    }
1758    static bool attr[64] = {};   // the shared-memory opt-in is per device (a layer split runs it on several)
1759    int adev = 0;
1760    adev = dpct::get_current_device_id();
1761    /*
1762    DPCT1083: The size of local memory in the migrated code may be different
1763    from the original code. Check that the allocated memory size in the migrated
1764    code is correct.
1765    */
1766    const int bytes = (TC_QT * TC_QS + TC_NB * TC_KS) * (int)sizeof(float);
1767    if (!attr[adev]) {
1768        /*
1769        DPCT1027: The call to cudaFuncSetAttribute was replaced with 0
1770        because SYCL currently does not support corresponding setting.
1771        */
1772        if (0 != 0) {
1773            /*
1774            DPCT1026: The call to cudaGetLastError was removed because this
1775            functionality is redundant in SYCL.
1776            */
1777            return false;
1778        }
1779        attr[adev] = true;
1780    }
1781    const int64_t reach = active_blocks > 0 && active_blocks < max_blocks ? active_blocks : max_blocks;
1782    const int64_t per = (int64_t) TC_NB * TC_ITER;
1783    const dpct::dim3 grid((unsigned)((reach + per - 1) / per),
1784                          (unsigned)((nq + TC_QT - 1) / TC_QT));
1785    {
1786        auto exp_props = sycl::ext::oneapi::experimental::properties{
1787            sycl::ext::oneapi::experimental::use_root_sync};
1788
1789        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
1790            ->submit([&](sycl::handler &cgh) {
1791                sycl::local_accessor<uint8_t, 1> dpct_local_acc_ct1(
1792                    sycl::range(bytes), cgh);
1793
1794                cgh.parallel_for<
1795                    dpct_kernel_name<class block_scores_tc_kernel_bc5f07>>(
1796                    sycl::nd_range<3>(grid * sycl::range(1, 1, 128),
1797                                      sycl::range(1, 1, 128)),
1798                    exp_props, [=](sycl::nd_item<3> item_ct1) {
1799                        block_scores_tc_kernel(
1800                            pooled, q_idx, steps, nq, max_blocks, reach, scores,
1801                            dpct_local_acc_ct1
1802                                .get_multi_ptr<sycl::access::decorated::no>()
1803                                .get());
1804                    });
1805            });
1806    }
1807    {
1808        auto exp_props = sycl::ext::oneapi::experimental::properties{
1809            sycl::ext::oneapi::experimental::use_root_sync};
1810
1811        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
1812            ->template parallel_for<
1813                dpct_kernel_name<class block_scores_tail_kernel_70dfaa>>(
1814                sycl::nd_range<3>(sycl::range(1, 1, (unsigned)nq) *
1815                                      sycl::range(1, 1, 32),
1816                                  sycl::range(1, 1, 32)),
1817                exp_props,
1818                [=](sycl::nd_item<3> item_ct1)
1819                    [[sycl::reqd_sub_group_size(32)]] {
1820                        block_scores_tail_kernel(dead, q_idx, steps, max_blocks,
1821                                                 scores);
1822                    });
1823    }
1824    /*
1825    DPCT1010: SYCL uses exceptions to report errors and does not use the
1826    error codes. The cudaGetLastError function call was replaced with 0. You
1827    need to rewrite this code.
1828    */
1829    const dpct::err0 e = 0;
1830    /*
1831    DPCT1009: SYCL reports errors using exceptions and does not use error
1832    codes. Please replace the "get_error_string_dummy(...)" with a real
1833    error-handling function.
1834    */
1835
1836    return true;
1837#endif
1838}
1839catch (sycl::exception const &exc) {
1840  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
1841            << ", line:" << __LINE__ << std::endl;
1842  std::exit(1);
1843}
1844
1845void qsa_block_topk_ref(const float* scores, const int32_t* steps, int64_t nq, int64_t max_blocks, int64_t cap,
1846                        const QsaShapes& s, int32_t* ids, void* stream) {
1847    if (nq <= 0) return;
1848    if (s.idx_block != R || cap < qsa_selection_width(kTopkMaxCells, s)) {
1849        std::fprintf(stderr, "qsa_block_topk: unsupported geometry or cap\n");
1850        std::exit(1);
1851    }
1852    {
1853        auto exp_props = sycl::ext::oneapi::experimental::properties{
1854            sycl::ext::oneapi::experimental::use_root_sync};
1855
1856        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
1857            ->template parallel_for<dpct_kernel_name<class block_topk_kernel_213104>>(
1858                sycl::nd_range<3>(sycl::range(1, 1, (unsigned)nq) *
1859                                      sycl::range(1, 1, TOPK_T),
1860                                  sycl::range(1, 1, TOPK_T)),
1861                exp_props, [=](sycl::nd_item<3> item_ct1) {
1862                    block_topk_kernel(scores, steps, max_blocks, cap, ids);
1863                });
1864    }
1865    /*
1866    DPCT1010: SYCL uses exceptions to report errors and does not use the
1867    error codes. The cudaGetLastError function call was replaced with 0. You
1868    need to rewrite this code.
1869    */
1870    const dpct::err0 e = 0;
1871    /*
1872    DPCT1009: SYCL reports errors using exceptions and does not use error
1873    codes. Please replace the "get_error_string_dummy(...)" with a real
1874    error-handling function.
1875    */
1876}
1877
1878#if !defined(__HIPCC__)
1879// Only Turing has a retained model measurement for this CUDA dispatch. Other CUDA devices keep the capacity rule
1880// (the RTX 5070 regression below). Cache the properties per calling thread; layer-split device switches are checked.
1881static bool topk_active_turing_device() try {
1882    int dev = 0;
1883    if (DPCT_CHECK_ERROR(dev = dpct::get_current_device_id()) !=
1884        0) return false;
1885    static thread_local int cached_device = -1;
1886    static thread_local bool turing = false;
1887    if (dev != cached_device) {
1888        dpct::device_info prop{};
1889        if (DPCT_CHECK_ERROR(dpct::get_device(dev).get_device_info(prop)) !=
1890            0) return false;
1891        /*
1892        DPCT1005: The SYCL device version is different from CUDA Compute
1893        Compatibility. You may need to rewrite this code.
1894        */
1895        turing = prop.get_major_version() == 7 && prop.get_minor_version() == 5;
1896        cached_device = dev;
1897    }
1898    return turing;
1899}
1900catch (sycl::exception const &exc) {
1901  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
1902            << ", line:" << __LINE__ << std::endl;
1903  std::exit(1);
1904}
1905#endif
1906
1907bool qsa_block_topk_cluster(const float *scores, const int32_t *steps,
1908                            int64_t nq, int64_t max_blocks, int64_t cap,
1909                            const QsaShapes &s, int32_t *ids,
1910                            void *stream) try {
1911#if 1   // SYCL port: no thread-block clusters (sm_90): the caller takes the plain top-k
1912    (void) scores; (void) steps; (void) nq; (void) max_blocks; (void) cap; (void) s; (void) ids; (void) stream;
1913    return false;
1914#else
1915    if (nq <= 0) return true;
1916    if (s.idx_block != R || cap < qsa_selection_width(kTopkMaxCells, s) || nq > 65535 || max_blocks <= 0) return false;
1917    const size_t smem = (size_t) ((max_blocks + CL_N - 1) / CL_N) * sizeof(uint32_t);
1918    // Per device (a layer split runs on several): 1 the cluster kernel runs here, 2 it does not. It needs sm_90+ (the
1919    // card's, or STRATA_EMULATE_CC's) AND code built for it: a build with only older code JIT-compiles their PTX, whose
1920    // copy of this kernel is a trap - the function's PTX version says which. `opt`: the dynamic shared memory opted in.
1921    static int ok[64] = {};
1922    static size_t opt[64] = {};
1923    int dev = 0;
1924    /*
1925    DPCT1026: The call to cudaGetLastError was removed because this
1926    functionality is redundant in SYCL.
1927    */
1928    if (DPCT_CHECK_ERROR(dev = dpct::get_current_device_id()) != 0 || dev < 0 ||
1929        dev >= 64) {
1930        ; return false;
1931    }
1932    if (ok[dev] == 0) {
1933        int major = 0;
1934        dpct::kernel_function_info fa{};
1935        const bool code =
1936            DPCT_CHECK_ERROR(
1937                major = dpct::get_device(dev).get_major_version()) == 0 &&
1938            strata::cc_major_of(major) >= 9 &&
1939            DPCT_CHECK_ERROR(dpct::get_kernel_function_info(
1940                &fa, (const void *)block_topk_cluster_kernel)) == 0 &&
1941            fa.ptxVersion >= 90 && fa.binaryVersion >= 90;
1942        /*
1943        DPCT1026: The call to cudaGetLastError was removed because this
1944        functionality is redundant in SYCL.
1945        */
1946        ok[dev] = code ? 1 : 2;
1947    }
1948    if (ok[dev] != 1) return false;
1949    if (smem > opt[dev]) {   // a larger capacity: opt in, and check that a cluster of CL_N such CTAs can be resident
1950        int clusters = 0;
1951        cudaLaunchConfig_t q{};
1952        cudaLaunchAttribute qa[1];
1953        qa[0].id = cudaLaunchAttributeClusterDimension;
1954        qa[0].val.clusterDim.x = CL_N;
1955        qa[0].val.clusterDim.y = 1;
1956        qa[0].val.clusterDim.z = 1;
1957        q.gridDim = dpct::dim3(CL_N, 1, 1);
1958        q.blockDim = dpct::dim3(CL_T, 1, 1);
1959        q.dynamicSmemBytes = smem;
1960        q.attrs = qa;
1961        q.numAttrs = 1;
1962        /*
1963        DPCT1027: The call to cudaFuncSetAttribute was replaced with 0
1964        because SYCL currently does not support corresponding setting.
1965        */
1966        if (0 != 0 ||
1967            /*
1968            DPCT1007: Migration of cudaOccupancyMaxActiveClusters is not
1969            supported.
1970            */
1971            cudaOccupancyMaxActiveClusters(&clusters, block_topk_cluster_kernel,
1972                                           &q) != 0 ||
1973            clusters < 1) {
1974            /*
1975            DPCT1026: The call to cudaGetLastError was removed because this
1976            functionality is redundant in SYCL.
1977            */
1978            return false; // this capacity takes the one-CTA kernels; a smaller
1979                          // one may still fit
1980        }
1981        opt[dev] = smem;
1982    }
1983    cudaLaunchConfig_t cfg{};
1984    cudaLaunchAttribute at[1];
1985    at[0].id = cudaLaunchAttributeClusterDimension;
1986    at[0].val.clusterDim.x = CL_N;
1987    at[0].val.clusterDim.y = 1;
1988    at[0].val.clusterDim.z = 1;
1989    cfg.gridDim = dpct::dim3(CL_N, (unsigned)nq, 1);
1990    cfg.blockDim = dpct::dim3(CL_T, 1, 1);
1991    cfg.dynamicSmemBytes = smem;
1992    cfg.stream = strata::q_of(stream);
1993    cfg.attrs = at;
1994    cfg.numAttrs = 1;
1995    const dpct::err0 e = cudaLaunchKernelEx(
1996        &cfg, block_topk_cluster_kernel, scores, steps, max_blocks, cap, ids);
1997    /*
1998    DPCT1009: SYCL reports errors using exceptions and does not use error
1999    codes. Please replace the "get_error_string_dummy(...)" with a real
2000    error-handling function.
2001    */
2002
2003    return true;
2004#endif
2005}
2006catch (sycl::exception const &exc) {
2007  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
2008            << ", line:" << __LINE__ << std::endl;
2009  std::exit(1);
2010}
2011
2012void qsa_block_topk(const float* scores, const int32_t* steps, int64_t nq, int64_t max_blocks, int64_t cap,
2013                    const QsaShapes& s, int32_t* ids, void* stream, int64_t active_blocks) {
2014    // keys in registers when every query's blocks fit (contexts up to ~135K cells), else (CUDA) the same threads
2015    // reading them from memory; the same ids. STRATA_TOPK_OLD=1: the original kernel
2016    static const bool old = std::getenv("STRATA_TOPK_OLD") != nullptr;
2017    if (nq <= 0) return;
2018#if !defined(__HIPCC__)
2019    // sm_90+: a cluster of CL_N CTAs per query for the calls of a few queries (decode windows); the same ids.
2020    // STRATA_QSA_CLUSTER=0: the one-CTA kernels below
2021    static const bool cluster = [] {
2022        const char* v = std::getenv("STRATA_QSA_CLUSTER");
2023        return !v || std::atoi(v) != 0;
2024    }();
2025    if (cluster && !old && nq <= CL_MAXQ && qsa_block_topk_cluster(scores, steps, nq, max_blocks, cap, s, ids, stream))
2026        return;
2027#endif
2028    // the blocks a query can have: the call's active count when the caller knows it (the prompt path), else the capacity.
2029    // Decode (no count) keeps the capacity rule and the original register width: nothing changes there.
2030#if defined(__HIPCC__)
2031    const bool counted = active_blocks > 0;
2032#else
2033    // Turing: --max-context 262144 makes the stride 65538, even while a 131K prompt's active blocks fit in
2034    // TK_T * TK_PER registers. Use the prefill bound on sm_75, keeping max_blocks as the score-row stride.
2035    // Other CUDA devices keep 0.1.32's capacity rule: #337 was measured on RDNA4, and RTX 5070 64K prompts were
2036    // 1-3% slower. Decode/captured graphs omit the bound and never query the device here.
2037    static const bool capacity_guard = std::getenv("STRATA_TOPK_CAPACITY_GUARD") != nullptr;
2038    // STRATA_TOPK_ACTIVE_ANY=1 (tests): the Turing dispatch on any CUDA card, so qsa_topk_active_parity checks it
2039    // on whatever card runs the tests (the kernels are the same on every architecture)
2040    static const bool any_card = [] { const char* v = std::getenv("STRATA_TOPK_ACTIVE_ANY"); return v && v[0] == '1'; }();
2041    const bool counted = !capacity_guard && active_blocks > 0 && active_blocks <= max_blocks &&
2042                         (any_card || topk_active_turing_device());
2043#endif
2044    const int64_t reach = counted && active_blocks < max_blocks ? active_blocks : max_blocks;
2045    const int64_t fit = (int64_t) TK_T * (counted ? TK_PER_MAX : TK_PER);
2046#if defined(__HIPCC__)
2047    constexpr int64_t kRegMinBlocks = 7168;   // gfx1201: below ~28K cells the 1,024-thread kernel's fixed cost loses to the ref
2048    const bool too_small = counted && reach < kRegMinBlocks;
2049    if (old || too_small || reach > fit) {
2050#else
2051    constexpr int64_t kWideMinBlocks = 4608;   // RTX 3060: a prompt batch below ~18K cells is faster on the ref
2052    const bool too_small = reach > fit && active_blocks > 0 && active_blocks < kWideMinBlocks;
2053    if (old || too_small) {
2054#endif
2055        qsa_block_topk_ref(scores, steps, nq, max_blocks, cap, s, ids, stream);
2056        return;
2057    }
2058    if (s.idx_block != R || cap < qsa_selection_width(kTopkMaxCells, s)) {
2059        std::fprintf(stderr, "qsa_block_topk: unsupported geometry or cap\n");
2060        std::exit(1);
2061    }
2062#if !defined(__HIPCC__)
2063    // Turing prefill (the `counted` bound) above ~90K cells (22,528 blocks): the wide kernel, which reads the keys
2064    // coalesced, instead of the register kernel's uncoalesced per-thread runs (PR #743: 131K, 1.03 -> 0.75 ms); the
2065    // same ids.  STRATA_TOPK_STREAM=0 restores the register kernel there.
2066    static const bool turing_wide = [] {
2067        const char* v = std::getenv("STRATA_TOPK_STREAM");
2068        return v == nullptr || v[0] != '0';
2069    }();
2070    if (reach > fit || (turing_wide && counted && reach > 22528))   // past the register kernel's reach, or Turing's band
2071        /*
2072        DPCT1049: The work-group size passed to the SYCL kernel may exceed
2073        the limit. To get the device limit, query
2074        info::device::max_work_group_size. Adjust the work-group size if needed.
2075        */
2076    {
2077        auto exp_props = sycl::ext::oneapi::experimental::properties{
2078            sycl::ext::oneapi::experimental::use_root_sync};
2079
2080        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
2081            ->template parallel_for<
2082                dpct_kernel_name<class block_topk_wide_kernel_5162c4>>(
2083                sycl::nd_range<3>(sycl::range(1, 1, (unsigned)nq) *
2084                                      sycl::range(1, 1, TK_T),
2085                                  sycl::range(1, 1, TK_T)),
2086                exp_props,
2087                [=](sycl::nd_item<3> item_ct1)
2088                    [[sycl::reqd_sub_group_size(32)]] {
2089                        block_topk_wide_kernel(scores, steps, max_blocks, cap,
2090                                               ids);
2091                    });
2092    } else
2093#endif
2094        if (reach <= (int64_t)TK_T * TK_PER)
2095        /*
2096        DPCT1049: The work-group size passed to the SYCL kernel may exceed
2097        the limit. To get the device limit, query
2098        info::device::max_work_group_size. Adjust the work-group size if needed.
2099        */
2100    {
2101        auto exp_props = sycl::ext::oneapi::experimental::properties{
2102            sycl::ext::oneapi::experimental::use_root_sync};
2103
2104        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
2105            ->template parallel_for<dpct_kernel_name<class block_topk_reg_kernel_6ae5f0,
2106                                            dpct_kernel_scalar<TK_PER>>>(
2107                sycl::nd_range<3>(sycl::range(1, 1, (unsigned)nq) *
2108                                      sycl::range(1, 1, TK_T),
2109                                  sycl::range(1, 1, TK_T)),
2110                exp_props,
2111                [=](sycl::nd_item<3> item_ct1)
2112                    [[sycl::reqd_sub_group_size(32)]] {
2113                        block_topk_reg_kernel<TK_PER>(scores, steps, max_blocks,
2114                                                      cap, ids);
2115                    });
2116    } else
2117    /*
2118    DPCT1049: The work-group size passed to the SYCL kernel may exceed
2119    the limit. To get the device limit, query
2120    info::device::max_work_group_size. Adjust the work-group size if needed.
2121    */
2122    {
2123        auto exp_props = sycl::ext::oneapi::experimental::properties{
2124            sycl::ext::oneapi::experimental::use_root_sync};
2125
2126        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
2127            ->template parallel_for<dpct_kernel_name<class block_topk_reg_kernel_10a848,
2128                                            dpct_kernel_scalar<TK_PER_MAX>>>(
2129                sycl::nd_range<3>(sycl::range(1, 1, (unsigned)nq) *
2130                                      sycl::range(1, 1, TK_T),
2131                                  sycl::range(1, 1, TK_T)),
2132                exp_props,
2133                [=](sycl::nd_item<3> item_ct1)
2134                    [[sycl::reqd_sub_group_size(32)]] {
2135                        block_topk_reg_kernel<TK_PER_MAX>(scores, steps,
2136                                                          max_blocks, cap, ids);
2137                    });
2138    }
2139    /*
2140    DPCT1010: SYCL uses exceptions to report errors and does not use the
2141    error codes. The cudaGetLastError function call was replaced with 0. You
2142    need to rewrite this code.
2143    */
2144    const dpct::err0 e = 0;
2145    /*
2146    DPCT1009: SYCL reports errors using exceptions and does not use error
2147    codes. Please replace the "get_error_string_dummy(...)" with a real
2148    error-handling function.
2149    */
2150}
2151
2152}  // namespace strata::kernels