okami.mom/strata

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

Niko1221Merge f-sycl-prs e106b4c86 into the batch 16 candidate (SYCL pull requests 4185 and 3153)a8a51b280

main
139.8 KiB3061 linesraw
1#include <sycl/ext/intel/experimental/grf_size_properties.hpp>
2// src/kernels/cuda/verify_kernels.cu - see include/strata/kernels/verify_kernels.hpp.
3//
4// The per-token arithmetic of every kernel here is transcribed from its single-token original (fused_gdn.cu,
5// elementwise.cu) with the same operation order, so a verify window reproduces plain decode bit for bit.
6#define DPCT_PROFILING_ENABLED
7#include <sycl/sycl.hpp>
8#include "strata/kprof.hpp"
9#include <sycl/ext/intel/experimental/grf_size_properties.hpp>
10#include "strata/core/geometry.hpp"
11#include <dpct/dpct.hpp>
12#include "strata/sycl_queue.hpp"
13#include "strata/sycl_doorbell.hpp"
14#include "strata/kernels/verify_kernels.hpp"
15#include "strata/kernels/resident_plan_mirror.hpp"
16#include "strata/kernels/dp4a.hpp"
17
18#include <algorithm>
19#include <cstdio>
20#include <cstdlib>
21#include <cmath>
22#include <atomic>
23#include <chrono>
24#include <memory>
25#include <mutex>
26#include <stdexcept>
27#include <thread>
28#include <vector>
29
30#ifndef STRATA_PLAN_LOCAL
31#define STRATA_PLAN_LOCAL 1   // 0: the original one-thread plan kernel (A/B)
32#endif
33namespace strata::kernels {
34namespace {
35
36constexpr int S = 128;          // GDN state size
37static_assert(S == strata::core::kCompiledGeometry.ssm_state_size, "verify_kernels is compiled for core/geometry.hpp");
38constexpr int RG = 4;
39constexpr int RPG = S / RG;
40
41void check(const char* what) {
42    /*
43    DPCT1010: SYCL uses exceptions to report errors and does not use the
44    error codes. The cudaGetLastError function call was replaced with 0. You
45    need to rewrite this code.
46    */
47    const dpct::err0 e = 0;
48    /*
49    DPCT1009: SYCL reports errors using exceptions and does not use error
50    codes. Please replace the "get_error_string_dummy(...)" with a real
51    error-handling function.
52    */
53}
54
55// `commit` (one token): the history then keeps it - [hist1, hist2, x_0], each thread its channel's, after reading them
56__dpct_inline__ void gdn_conv_l2_multi_kernel(float *hist,
57                                              const float *__restrict__ qkv,
58                                              const float *__restrict__ w,
59                                              float *__restrict__ h, int C,
60                                              int qk_heads, float eps,
61                                              int t_begin, bool commit) {
62    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
63auto &part =
64    *sycl::ext::oneapi::group_local_memory_for_overwrite<float[S / 32]>(
65        sycl::ext::oneapi::this_work_item::get_work_group<3>());
66    const int t = t_begin + item_ct1.get_group(1);
67    const int c = item_ct1.get_group(2) * S + item_ct1.get_local_id(2);
68    // the window of token t: [hist0, hist1, hist2, x_0, ..., x_t], its last four entries
69    float win[3];
70#pragma unroll
71    for (int j = 0; j < 3; ++j) {
72        const int src = t + j;          // index into [hist(3) | x...]
73        win[j] = src < 3 ? hist[c * 3 + src] : qkv[(size_t) (src - 3) * C + c];
74    }
75    const float v0 = win[0], v1 = win[1], v2 = win[2], x = qkv[(size_t) t * C + c];
76    if (commit) {
77        hist[c * 3] = v1;
78        hist[c * 3 + 1] = v2;
79        hist[c * 3 + 2] = x;
80    }
81    float sum = v0 * w[c * 4] + v1 * w[c * 4 + 1] + v2 * w[c * 4 + 2] + x * w[c * 4 + 3];
82    float y = sum / (1.0f + sycl::native::exp(-sum));
83    if ((int)item_ct1.get_group(2) < qk_heads) {
84        float sq = y * y;
85        /*
86DPCT1108: '__shfl_xor_sync' was migrated with the experimental feature
87masked sub_group function which may not be supported by all compilers or
88runtimes. You may need to adjust the code.
89*/
90#pragma unroll
91        for (int o = 16; o > 0; o >>= 1) sq +=
92            dpct::experimental::permute_sub_group_by_xor(
93                0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(),
94                sq, o);
95        if ((item_ct1.get_local_id(2) & 31) == 0)
96            part[item_ct1.get_local_id(2) >> 5] = sq;
97        /*
98        DPCT1118: SYCL group functions and algorithms must be encountered in
99        converged control flow. You may need to adjust the code.
100        */
101        /*
102        DPCT1065: Consider replacing sycl::nd_item::barrier() with
103        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
104        better performance if there is no access to global memory.
105        */
106        item_ct1.barrier();
107        const float ss = part[0] + part[1] + part[2] + part[3];
108        y *= sycl::rsqrt(ss + eps);
109    }
110    h[(size_t) t * C + c] = y;
111}
112
113__dpct_inline__ void
114gdn_conv_commit_kernel(float *__restrict__ hist, const float *__restrict__ qkv,
115                       int C, const int32_t *__restrict__ n_keep) {
116    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
117    const int c = item_ct1.get_group(2) * item_ct1.get_local_range(2) +
118                  item_ct1.get_local_id(2);
119    if (c >= C) return;
120    const int n = *n_keep;
121    if (n <= 0) return;
122    float seq[3];
123#pragma unroll
124    for (int j = 0; j < 3; ++j) {
125        const int src = n + j;          // the last three of [hist(3) | x_0..x_{n-1}]
126        seq[j] = src < 3 ? hist[c * 3 + src] : qkv[(size_t) (src - 3) * C + c];
127    }
128    hist[c * 3] = seq[0];
129    hist[c * 3 + 1] = seq[1];
130    hist[c * 3 + 2] = seq[2];
131}
132
133template <int MAX_T = kVerifyMaxT, bool EXACT_T = false>
134/*
135DPCT1110: The total declared local variable size in device function
136gdn_ab_multi_kernel exceeds 128 bytes and may cause high register pressure.
137Consult with your hardware vendor to find the total register size available and
138adjust the code, or use smaller sub-group size to avoid high register pressure.
139*/
140__dpct_inline__ void gdn_ab_multi_kernel(
141    const float *__restrict__ x, const uint16_t *__restrict__ wa,
142    const uint16_t *__restrict__ wb, const float *__restrict__ dt,
143    const float *__restrict__ ssm_a, float *__restrict__ gate,
144    float *__restrict__ beta, int n, int h_v, int T) {
145    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
146    const int row = item_ct1.get_group(2) * 2 + (item_ct1.get_local_id(2) >> 5),
147              lane = item_ct1.get_local_id(2) & 31;
148    if (row >= 2 * h_v) return;
149    const bool is_beta = row >= h_v;
150    const int r = is_beta ? row - h_v : row;
151    const sycl::uint4 *w4 = reinterpret_cast<const sycl::uint4 *>(
152        (is_beta ? wb : wa) + (size_t)r * n);
153    float acc[MAX_T];
154#pragma unroll
155    for (int t = 0; t < MAX_T; ++t) acc[t] = 0.0f;
156    for (int j = lane; j < n / 8; j += 32) {
157        /*
158        DPCT1098: The '*' expression is used instead of the __ldg call.
159        These two expressions do not provide the exact same functionality. Check
160        the generated code for potential precision and/or performance issues.
161        */
162        const sycl::uint4 wv = *(w4 + j);
163        const float w0 = sycl::bit_cast<float>(wv.x() << 16),
164                    w1 = sycl::bit_cast<float>(wv.x() & 0xffff0000u);
165        const float w2 = sycl::bit_cast<float>(wv.y() << 16),
166                    w3 = sycl::bit_cast<float>(wv.y() & 0xffff0000u);
167        const float w4f = sycl::bit_cast<float>(wv.z() << 16),
168                    w5 = sycl::bit_cast<float>(wv.z() & 0xffff0000u);
169        const float w6 = sycl::bit_cast<float>(wv.w() << 16),
170                    w7 = sycl::bit_cast<float>(wv.w() & 0xffff0000u);
171#pragma unroll
172        for (int t = 0; t < MAX_T; ++t) {
173            if (!EXACT_T && t >= T) break;
174            const float* xt = x + (size_t) t * n;
175            /*
176            DPCT1098: The '*' expression is used instead of the __ldg call.
177            These two expressions do not provide the exact same functionality.
178            Check the generated code for potential precision and/or performance
179            issues.
180            */
181            const sycl::float4 xa = *reinterpret_cast<const sycl::float4 *>(xt + j * 8);
182            /*
183            DPCT1098: The '*' expression is used instead of the __ldg call.
184            These two expressions do not provide the exact same functionality.
185            Check the generated code for potential precision and/or performance
186            issues.
187            */
188            const sycl::float4 xb = *reinterpret_cast<const sycl::float4 *>(xt + j * 8 + 4);
189            float a = acc[t];
190            a = sycl::fma((float)w0, (float)(xa.x()), a);
191                a = sycl::fma((float)w1, (float)(xa.y()), a);
192            a = sycl::fma((float)w2, (float)(xa.z()), a);
193                a = sycl::fma((float)w3, (float)(xa.w()), a);
194            a = sycl::fma((float)w4f, (float)(xb.x()), a);
195                a = sycl::fma((float)w5, (float)(xb.y()), a);
196            a = sycl::fma((float)w6, (float)(xb.z()), a);
197                a = sycl::fma((float)w7, (float)(xb.w()), a);
198            acc[t] = a;
199        }
200    }
201#pragma unroll
202    for (int t = 0; t < MAX_T; ++t) {
203        if (!EXACT_T && t >= T) break;
204        float a = acc[t];
205#pragma unroll
206        /*
207        DPCT1108: '__shfl_xor_sync' was migrated with the experimental
208        feature masked sub_group function which may not be supported by all
209        compilers or runtimes. You may need to adjust the code.
210        */
211        for (int o = 16; o > 0; o >>= 1) a +=
212            dpct::experimental::permute_sub_group_by_xor(
213                0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(),
214                a, o);
215        if (lane != 0) continue;
216        if (is_beta) {
217            beta[(size_t)t * h_v + r] = 1.0f / (1.0f + sycl::native::exp(-a));
218        } else {
219            const float v = a + dt[r];
220            const float sp = v > 20.0f ? v : sycl::log1p(sycl::native::exp(v));
221            gate[(size_t) t * h_v + r] = sp * ssm_a[r];
222        }
223    }
224}
225
226// State-only commit kernel: each head's 128 independent state columns are split across 4 blocks of 32 columns
227// (48 * 4 = 192 blocks of 128 threads across all SMs, vs 48 blocks of 512 threads), with no sq/o/norm/z/y work.
228/*
229DPCT1110: The total declared local variable size in device function
230gdn_step_commit_kernel exceeds 128 bytes and may cause high register pressure.
231Consult with your hardware vendor to find the total register size available and
232adjust the code, or use smaller sub-group size to avoid high register pressure.
233*/
234__dpct_inline__ void gdn_step_commit_kernel(
235    float *__restrict__ state, const float *__restrict__ hbuf, int C,
236    const float *__restrict__ gate, const float *__restrict__ beta, int h_k,
237    int h_v, const int32_t *__restrict__ n_keep) {
238    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
239    const int n = *n_keep;
240    if (n <= 0) return;
241    auto &sk = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[S]>(
242        sycl::ext::oneapi::this_work_item::get_work_group<3>());
243    auto &red =
244        *sycl::ext::oneapi::group_local_memory_for_overwrite<float[RG][32]>(
245            sycl::ext::oneapi::this_work_item::get_work_group<3>());
246    const int head = item_ct1.get_group(2);
247    const int col_local = item_ct1.get_local_id(2);
248    const int col = item_ct1.get_group(1) * 32 + col_local;
249    const int rg = item_ct1.get_local_id(1);
250    const int tid = rg * 32 + col_local;    // 0 .. 127
251    const int qh = head % h_k;
252    const int qk = S * h_k;
253    float s[RPG];
254    float* base = state + ((size_t) (rg * RPG) * h_v + head) * S + col;
255    const size_t row_stride = (size_t) h_v * S;
256#pragma unroll
257    for (int r = 0; r < RPG; ++r) s[r] = base[r * row_stride];
258    for (int t = 0; t < n; ++t) {
259        const float* ht = hbuf + (size_t) t * C;
260        /*
261        DPCT1118: SYCL group functions and algorithms must be encountered in
262        converged control flow. You may need to adjust the code.
263        */
264        /*
265        DPCT1065: Consider replacing sycl::nd_item::barrier() with
266        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
267        better performance if there is no access to global memory.
268        */
269        item_ct1.barrier();
270        sk[tid] = ht[qk + qh * S + tid];
271        /*
272        DPCT1118: SYCL group functions and algorithms must be encountered in
273        converged control flow. You may need to adjust the code.
274        */
275        /*
276        DPCT1065: Consider replacing sycl::nd_item::barrier() with
277        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
278        better performance if there is no access to global memory.
279        */
280        item_ct1.barrier();
281        const float g = sycl::native::exp(gate[(size_t)t * h_v + head]);
282        float kv = 0.0f;
283#pragma unroll
284        for (int r = 0; r < RPG; ++r)
285            kv = sycl::fma(s[r], sk[rg * RPG + r], kv);
286        red[rg][col_local] = kv;
287        /*
288        DPCT1118: SYCL group functions and algorithms must be encountered in
289        converged control flow. You may need to adjust the code.
290        */
291        /*
292        DPCT1065: Consider replacing sycl::nd_item::barrier() with
293        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
294        better performance if there is no access to global memory.
295        */
296        item_ct1.barrier();
297        const float kv_col = red[0][col_local] + red[1][col_local] + red[2][col_local] + red[3][col_local];
298        const float delta = (ht[2 * qk + head * S + col] - g * kv_col) * beta[(size_t) t * h_v + head];
299#pragma unroll
300        for (int r = 0; r < RPG; ++r)
301            s[r] = sycl::fma((float)g, s[r], sk[rg * RPG + r] * delta);
302    }
303#pragma unroll
304    for (int r = 0; r < RPG; ++r) base[r * row_stride] = s[r];
305}
306
307// S26 (STRATA_QFUSE=1): the q8_1 image of a 32-column block, written by the warp that holds those columns with
308// native_quantize_q8_1_kernel's quantizer (the same XOR-tree max and sum, d = amax / 127, roundf(x / d), ds = (d, sum)).
309struct GdnQ81 { sycl::half2 ds; int8_t qs[32]; };
310__dpct_inline__ void gdn_q8_1_store(GdnQ81 *__restrict__ xq, size_t idx,
311                                    float xi) {
312    // no contraction: xi is a product here, and fma(a, b, shfl) would round the first sum unlike the separate
313    // quantizer, which reads xi from memory (S26 harness: ds.sum differed by 1 ulp without this)
314#pragma clang fp contract(off)
315    float amax = sycl::fabs(xi), sum = xi;
316#pragma unroll
317    /*
318    DPCT1108: '__shfl_xor_sync' was migrated with the experimental feature
319    masked sub_group function which may not be supported by all compilers or
320    runtimes. You may need to adjust the code.
321    */
322    for (int o = 16; o > 0; o >>= 1) amax = sycl::fmax(
323        amax, dpct::experimental::permute_sub_group_by_xor(
324                  0xffffffffu,
325                  sycl::ext::oneapi::this_work_item::get_sub_group(), amax, o));
326#pragma unroll
327    /*
328    DPCT1108: '__shfl_xor_sync' was migrated with the experimental feature
329    masked sub_group function which may not be supported by all compilers or
330    runtimes. You may need to adjust the code.
331    */
332    for (int o = 16; o > 0; o >>= 1) sum +=
333        dpct::experimental::permute_sub_group_by_xor(
334            0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(),
335            sum, o);
336    const float d = amax / 127.0f;
337    const int8_t q = amax == 0.0f ? 0 : sycl::round(xi / d);
338    xq[idx / 32].qs[idx % 32] = q;
339    if (idx % 32 == 0) xq[idx / 32].ds = sycl::half2(d, sum);
340}
341
342template <bool ALL_OUT, bool Q, bool QK_REG = false>
343/*
344DPCT1110: The total declared local variable size in device function
345gdn_step_norm_multi_kernel exceeds 128 bytes and may cause high register
346pressure. Consult with your hardware vendor to find the total register size
347available and adjust the code, or use smaller sub-group size to avoid high
348register pressure.
349*/
350__dpct_inline__ void gdn_step_norm_multi_kernel(
351    float *__restrict__ state, const float *__restrict__ hbuf, int C,
352    const float *__restrict__ gate, const float *__restrict__ beta,
353    const float *__restrict__ z, const float *__restrict__ gamma, float eps,
354    float *__restrict__ y, int h_k, int h_v, int T,
355    const int32_t *__restrict__ n_keep, int t_out_begin,
356    GdnQ81 *__restrict__ xq, GdnGroups grp = {}) {
357    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
358    if (grp.n > 0) {   // group get_group(1) - its slot's state and its rows of the window's buffers
359        const int gi = item_ct1.get_group(1), f = grp.first[gi];
360        state = grp.state[gi];
361        hbuf += (size_t)f * C;
362        gate += (size_t)f * h_v;
363        beta += (size_t)f * h_v;
364        z += (size_t)f * S * h_v;
365        y += (size_t)f * S * h_v;
366        T = grp.ntok[gi];
367        n_keep = grp.keep[gi];
368    }
369auto &sk = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[2][S]>(
370    sycl::ext::oneapi::this_work_item::get_work_group<3>());
371    auto &sq =
372        *sycl::ext::oneapi::group_local_memory_for_overwrite<float[2][S]>(
373            sycl::ext::oneapi::this_work_item::get_work_group<3>());
374    auto &red_kv =
375        *sycl::ext::oneapi::group_local_memory_for_overwrite<float[RG][S]>(
376            sycl::ext::oneapi::this_work_item::get_work_group<3>());
377    auto &red_o =
378        *sycl::ext::oneapi::group_local_memory_for_overwrite<float[RG][S]>(
379            sycl::ext::oneapi::this_work_item::get_work_group<3>());
380    auto &wsum =
381        *sycl::ext::oneapi::group_local_memory_for_overwrite<float[S / 32]>(
382            sycl::ext::oneapi::this_work_item::get_work_group<3>());
383    const int head = item_ct1.get_group(2);
384    const int col = item_ct1.get_local_id(2);
385    const int rg = item_ct1.get_local_id(1);
386    const int qh = head % h_k;
387    const int qk = S * h_k;             // q at [0, qk), k at [qk, 2qk), v at [2qk, ...)
388    const int value_dim = S * h_v;
389    const int n = ALL_OUT ? T : (n_keep ? *n_keep : T);
390    if (!QK_REG && n > 0) {
391        if (rg == 0) sk[0][col] = hbuf[qk + qh * S + col];
392        else if (rg == 1 && (ALL_OUT || 0 >= t_out_begin)) sq[0][col] = hbuf[qh * S + col];
393    }
394    const float gam = (rg == 0) ? gamma[col] : 0.0f;
395    float s[RPG];
396    float* base = state + ((size_t) (rg * RPG) * h_v + head) * S + col;
397    const size_t row_stride = (size_t) h_v * S;
398#pragma unroll
399    /*
400    DPCT1098: The '*' expression is used instead of the __ldg call. These
401    two expressions do not provide the exact same functionality. Check the
402    generated code for potential precision and/or performance issues.
403    */
404    for (int r = 0; r < RPG; ++r) s[r] = ALL_OUT ? base[r * row_stride]
405                                                 : base[r * row_stride];
406    for (int t = 0; t < n; ++t) {
407        const int cur = t & 1, nxt = (t + 1) & 1;
408        const float* ht = hbuf + (size_t) t * C;
409        const bool need_out = ALL_OUT || (t >= t_out_begin);
410        /*
411        DPCT1118: SYCL group functions and algorithms must be encountered in
412        converged control flow. You may need to adjust the code.
413        */
414        /*
415        DPCT1065: Consider replacing sycl::nd_item::barrier() with
416        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
417        better performance if there is no access to global memory.
418        */
419        item_ct1.barrier();
420        float k_own = 0.0f, q_own = 0.0f;
421        auto sg = item_ct1.get_sub_group();
422        if constexpr (QK_REG) {
423            const int i = rg * RPG + sg.get_local_linear_id();
424            k_own = ht[qk + qh * S + i];
425            if (need_out) q_own = ht[qh * S + i];
426        }
427        if (!QK_REG && t + 1 < n) {
428            const float* ht_next = ht + C;
429            const bool need_next = ALL_OUT || (t + 1 >= t_out_begin);
430            if (rg == 0) sk[nxt][col] = ht_next[qk + qh * S + col];
431            else if (rg == 1 && need_next) sq[nxt][col] = ht_next[qh * S + col];
432        }
433        const float g = sycl::native::exp(gate[(size_t)t * h_v + head]);
434        float kv = 0.0f;
435#pragma unroll
436        for (int r = 0; r < RPG; ++r)
437            kv = sycl::fma(s[r], QK_REG ? sycl::select_from_group(sg, k_own, r) : sk[cur][rg * RPG + r], kv);
438        red_kv[rg][col] = kv;
439        /*
440        DPCT1118: SYCL group functions and algorithms must be encountered in
441        converged control flow. You may need to adjust the code.
442        */
443        /*
444        DPCT1065: Consider replacing sycl::nd_item::barrier() with
445        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
446        better performance if there is no access to global memory.
447        */
448        item_ct1.barrier();
449        const float kv_col = red_kv[0][col] + red_kv[1][col] + red_kv[2][col] + red_kv[3][col];
450        const float delta = (ht[2 * qk + head * S + col] - g * kv_col) * beta[(size_t) t * h_v + head];
451        if (!need_out) {
452#pragma unroll
453            for (int r = 0; r < RPG; ++r)
454                s[r] = sycl::fma((float)g, s[r],
455                                (QK_REG ? sycl::select_from_group(sg, k_own, r) : sk[cur][rg * RPG + r]) * delta);
456            continue;
457        }
458        float o = 0.0f;
459#pragma unroll
460        for (int r = 0; r < RPG; ++r) {
461            s[r] = sycl::fma((float)g, s[r],
462                            (QK_REG ? sycl::select_from_group(sg, k_own, r) : sk[cur][rg * RPG + r]) * delta);
463            o = sycl::fma(s[r], QK_REG ? sycl::select_from_group(sg, q_own, r) : sq[cur][rg * RPG + r], o);
464        }
465        red_o[rg][col] = o;
466        /*
467        DPCT1118: SYCL group functions and algorithms must be encountered in
468        converged control flow. You may need to adjust the code.
469        */
470        /*
471        DPCT1065: Consider replacing sycl::nd_item::barrier() with
472        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
473        better performance if there is no access to global memory.
474        */
475        item_ct1.barrier();
476        float oc = 0.0f, sq_part = 0.0f;
477        if (rg == 0) {
478            oc = (red_o[0][col] + red_o[1][col] + red_o[2][col] +
479                  red_o[3][col]) *
480                 sycl::rsqrt((float)S);
481            sq_part = oc * oc;
482        }
483        // every thread takes the shuffles, as the single-token kernel does: inside the `rg == 0` branch hipcc on
484        // gfx1151 gave another rounding for 3% of the outputs (gdn_parity section 5 on Aurora)
485        /*
486DPCT1108: '__shfl_xor_sync' was migrated with the experimental feature
487masked sub_group function which may not be supported by all compilers or
488runtimes. You may need to adjust the code.
489*/
490#pragma unroll
491        for (int o2 = 16; o2 > 0; o2 >>= 1) sq_part +=
492            dpct::experimental::permute_sub_group_by_xor(
493                0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(),
494                sq_part, o2);
495        if (rg == 0 && (col & 31) == 0) wsum[col >> 5] = sq_part;
496        /*
497        DPCT1118: SYCL group functions and algorithms must be encountered in
498        converged control flow. You may need to adjust the code.
499        */
500        /*
501        DPCT1065: Consider replacing sycl::nd_item::barrier() with
502        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
503        better performance if there is no access to global memory.
504        */
505        item_ct1.barrier();
506        if (rg == 0) {
507            const float ss = wsum[0] + wsum[1] + wsum[2] + wsum[3];
508            const float scale = sycl::rsqrt(ss / (float)S + eps);
509            const float zz = z[(size_t) t * value_dim + head * S + col];
510            const float yv =
511                oc * scale * gam * (1.0f / (1.0f + sycl::native::exp(-zz)));
512            y[(size_t) t * value_dim + head * S + col] = yv;
513            if constexpr (Q) gdn_q8_1_store(xq, (size_t) (t - t_out_begin) * value_dim + head * S + col, yv);
514        }
515    }
516    if (!ALL_OUT && n_keep != nullptr && n > 0) {
517#pragma unroll
518        for (int r = 0; r < RPG; ++r) base[r * row_stride] = s[r];
519    }
520}
521
522// S25 (STRATA_GDN_SPLIT=1): the same recurrence with each head's 128 state columns over 4 blocks of 32 columns
523// (128 threads: the same (column, row group) threads, each with the same 32 state rows), so 4x the blocks of
524// gdn_step_norm_multi_kernel - which ran one 512-thread block per head (32 blocks) and read the 2 MB state of a layer
525// at ~60 GB/s. Every column's arithmetic is the original's; the output norm, which needs all 128 columns of a head,
526// moves to gdn_out_norm_kernel: this kernel leaves the unnormalized output `oc` in y and the second kernel sums the
527// squares by the same warps (columns 32w..32w+31, the same butterfly) in the same order.
528// S26: OUT = false (the commit, whose outputs nobody reads) drops the output reduction and its two barriers; the
529// norm kernel below has the old kernel's code shape (S x RG threads, rg 0 holding oc), which makes it bitwise equal -
530// the 128-thread version differed from the old kernel by 1 ulp in ~7% of the outputs.
531constexpr int GS_COLS = 32;
532template <bool OUT>
533/*
534DPCT1110: The total declared local variable size in device function
535gdn_step_split_kernel exceeds 128 bytes and may cause high register pressure.
536Consult with your hardware vendor to find the total register size available and
537adjust the code, or use smaller sub-group size to avoid high register pressure.
538*/
539__dpct_inline__ void
540gdn_step_split_kernel(float *__restrict__ state, const float *__restrict__ hbuf,
541                      int C, const float *__restrict__ gate,
542                      const float *__restrict__ beta, float *__restrict__ y,
543                      int h_k, int h_v, int T,
544                      const int32_t *__restrict__ n_keep, int t_out_begin) {
545    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
546auto &sk = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[S]>(
547    sycl::ext::oneapi::this_work_item::get_work_group<3>());
548    auto &sq = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[S]>(
549        sycl::ext::oneapi::this_work_item::get_work_group<3>());
550    auto &red = *sycl::ext::oneapi::group_local_memory_for_overwrite<
551        float[RG][GS_COLS]>(
552        sycl::ext::oneapi::this_work_item::get_work_group<3>());
553    const int head = item_ct1.get_group(2);
554    const int c0 = item_ct1.get_group(1) * GS_COLS;
555    const int lc = item_ct1.get_local_id(2); // local column
556    const int col = c0 + lc;
557    const int rg = item_ct1.get_local_id(1);
558    const int tid = rg * GS_COLS + lc;
559    const int qh = head % h_k;
560    const int qk = S * h_k;
561    const int value_dim = S * h_v;
562    const int n = n_keep ? *n_keep : T;
563    float s[RPG];
564    float* base = state + ((size_t) (rg * RPG) * h_v + head) * S + col;
565    const size_t row_stride = (size_t) h_v * S;
566#pragma unroll
567    for (int r = 0; r < RPG; ++r) s[r] = base[r * row_stride];
568    for (int t = 0; t < n; ++t) {
569        const float* ht = hbuf + (size_t) t * C;
570        /*
571        DPCT1118: SYCL group functions and algorithms must be encountered in
572        converged control flow. You may need to adjust the code.
573        */
574        /*
575        DPCT1065: Consider replacing sycl::nd_item::barrier() with
576        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
577        better performance if there is no access to global memory.
578        */
579        item_ct1.barrier();
580        if (tid < S) { sk[tid] = ht[qk + qh * S + tid]; sq[tid] = ht[qh * S + tid]; }
581        /*
582        DPCT1118: SYCL group functions and algorithms must be encountered in
583        converged control flow. You may need to adjust the code.
584        */
585        /*
586        DPCT1065: Consider replacing sycl::nd_item::barrier() with
587        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
588        better performance if there is no access to global memory.
589        */
590        item_ct1.barrier();
591        const float g = sycl::native::exp(gate[(size_t)t * h_v + head]);
592        float kv = 0.0f;
593#pragma unroll
594        for (int r = 0; r < RPG; ++r)
595            kv = sycl::fma(s[r], sk[rg * RPG + r], kv);
596        red[rg][lc] = kv;
597        /*
598        DPCT1118: SYCL group functions and algorithms must be encountered in
599        converged control flow. You may need to adjust the code.
600        */
601        /*
602        DPCT1065: Consider replacing sycl::nd_item::barrier() with
603        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
604        better performance if there is no access to global memory.
605        */
606        item_ct1.barrier();
607        const float kv_col = red[0][lc] + red[1][lc] + red[2][lc] + red[3][lc];
608        const float delta = (ht[2 * qk + head * S + col] - g * kv_col) * beta[(size_t) t * h_v + head];
609        float o = 0.0f;
610#pragma unroll
611        for (int r = 0; r < RPG; ++r) {
612            s[r] = sycl::fma((float)g, s[r], sk[rg * RPG + r] * delta);
613            o = sycl::fma(s[r], sq[rg * RPG + r], o);
614        }
615        if (!OUT) continue;
616        /*
617        DPCT1118: SYCL group functions and algorithms must be encountered in
618        converged control flow. You may need to adjust the code.
619        */
620        /*
621        DPCT1065: Consider replacing sycl::nd_item::barrier() with
622        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
623        better performance if there is no access to global memory.
624        */
625        item_ct1.barrier();
626        red[rg][lc] = o;
627        /*
628        DPCT1118: SYCL group functions and algorithms must be encountered in
629        converged control flow. You may need to adjust the code.
630        */
631        /*
632        DPCT1065: Consider replacing sycl::nd_item::barrier() with
633        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
634        better performance if there is no access to global memory.
635        */
636        item_ct1.barrier();
637        if (rg == 0 && t >= t_out_begin)
638            y[(size_t)t * value_dim + head * S + col] =
639                (red[0][lc] + red[1][lc] + red[2][lc] + red[3][lc]) *
640                sycl::rsqrt((float)S);
641    }
642    if (n_keep != nullptr && n > 0) {
643#pragma unroll
644        for (int r = 0; r < RPG; ++r) base[r * row_stride] = s[r];
645    }
646}
647
648
649template <bool OUT>
650/*
651DPCT1110: The total declared local variable size in device function
652gdn_step_split_kernel exceeds 128 bytes and may cause high register pressure.
653Consult with your hardware vendor to find the total register size available and
654adjust the code, or use smaller sub-group size to avoid high register pressure.
655*/
656__dpct_inline__ void
657b60_gdn_split_local_kernel(float *__restrict__ state, const float *__restrict__ hbuf,
658                      int C, const float *__restrict__ gate,
659                      const float *__restrict__ beta, float *__restrict__ y,
660                      int h_k, int h_v, int T,
661                      const int32_t *__restrict__ n_keep, int t_out_begin) {
662    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
663auto &sk = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[S]>(
664    sycl::ext::oneapi::this_work_item::get_work_group<3>());
665    auto &sq = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[S]>(
666        sycl::ext::oneapi::this_work_item::get_work_group<3>());
667    auto &red = *sycl::ext::oneapi::group_local_memory_for_overwrite<
668        float[RG][GS_COLS]>(
669        sycl::ext::oneapi::this_work_item::get_work_group<3>());
670    const int head = item_ct1.get_group(2);
671    const int c0 = item_ct1.get_group(1) * GS_COLS;
672    const int lc = item_ct1.get_local_id(2); // local column
673    const int col = c0 + lc;
674    const int rg = item_ct1.get_local_id(1);
675    const int tid = rg * GS_COLS + lc;
676    const int qh = head % h_k;
677    const int qk = S * h_k;
678    const int value_dim = S * h_v;
679    const int n = n_keep ? *n_keep : T;
680    float s[RPG];
681    float* base = state + ((size_t) (rg * RPG) * h_v + head) * S + col;
682    const size_t row_stride = (size_t) h_v * S;
683#pragma unroll
684    for (int r = 0; r < RPG; ++r) s[r] = base[r * row_stride];
685    for (int t = 0; t < n; ++t) {
686        const float* ht = hbuf + (size_t) t * C;
687        /*
688        DPCT1118: SYCL group functions and algorithms must be encountered in
689        converged control flow. You may need to adjust the code.
690        */
691        /*
692        DPCT1065: Consider replacing sycl::nd_item::barrier() with
693        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
694        better performance if there is no access to global memory.
695        */
696        item_ct1.barrier(sycl::access::fence_space::local_space);
697        if (tid < S) { sk[tid] = ht[qk + qh * S + tid]; sq[tid] = ht[qh * S + tid]; }
698        /*
699        DPCT1118: SYCL group functions and algorithms must be encountered in
700        converged control flow. You may need to adjust the code.
701        */
702        /*
703        DPCT1065: Consider replacing sycl::nd_item::barrier() with
704        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
705        better performance if there is no access to global memory.
706        */
707        item_ct1.barrier(sycl::access::fence_space::local_space);
708        const float g = sycl::native::exp(gate[(size_t)t * h_v + head]);
709        float kv = 0.0f;
710#pragma unroll
711        for (int r = 0; r < RPG; ++r)
712            kv = sycl::fma(s[r], sk[rg * RPG + r], kv);
713        red[rg][lc] = kv;
714        /*
715        DPCT1118: SYCL group functions and algorithms must be encountered in
716        converged control flow. You may need to adjust the code.
717        */
718        /*
719        DPCT1065: Consider replacing sycl::nd_item::barrier() with
720        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
721        better performance if there is no access to global memory.
722        */
723        item_ct1.barrier(sycl::access::fence_space::local_space);
724        const float kv_col = red[0][lc] + red[1][lc] + red[2][lc] + red[3][lc];
725        const float delta = (ht[2 * qk + head * S + col] - g * kv_col) * beta[(size_t) t * h_v + head];
726        float o = 0.0f;
727#pragma unroll
728        for (int r = 0; r < RPG; ++r) {
729            s[r] = sycl::fma((float)g, s[r], sk[rg * RPG + r] * delta);
730            o = sycl::fma(s[r], sq[rg * RPG + r], o);
731        }
732        if (!OUT) continue;
733        /*
734        DPCT1118: SYCL group functions and algorithms must be encountered in
735        converged control flow. You may need to adjust the code.
736        */
737        /*
738        DPCT1065: Consider replacing sycl::nd_item::barrier() with
739        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
740        better performance if there is no access to global memory.
741        */
742        item_ct1.barrier(sycl::access::fence_space::local_space);
743        red[rg][lc] = o;
744        /*
745        DPCT1118: SYCL group functions and algorithms must be encountered in
746        converged control flow. You may need to adjust the code.
747        */
748        /*
749        DPCT1065: Consider replacing sycl::nd_item::barrier() with
750        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
751        better performance if there is no access to global memory.
752        */
753        item_ct1.barrier(sycl::access::fence_space::local_space);
754        if (rg == 0 && t >= t_out_begin)
755            y[(size_t)t * value_dim + head * S + col] =
756                (red[0][lc] + red[1][lc] + red[2][lc] + red[3][lc]) *
757                sycl::rsqrt((float)S);
758    }
759    if (n_keep != nullptr && n > 0) {
760#pragma unroll
761        for (int r = 0; r < RPG; ++r) base[r * row_stride] = s[r];
762    }
763}
764
765
766// S26: the state-only replay (the commit) with its per-token inputs prefetched - gate, beta and the v column of every
767// row up front, the next row's k / q while the current one computes. The arithmetic and its order are
768// gdn_step_split_kernel<false>'s (gfx1151 harness: state bitwise equal; 44.5 -> 39.1 us at 1 row, 47.4 -> 40.5 at 2,
769// 53.8 -> 42.9 at 4, h_v 48). With outputs the prefetch lost (register pressure), so the window keeps the plain split.
770template <int MAXT>
771/*
772DPCT1110: The total declared local variable size in device function
773gdn_state_replay_kernel exceeds 128 bytes and may cause high register pressure.
774Consult with your hardware vendor to find the total register size available and
775adjust the code, or use smaller sub-group size to avoid high register pressure.
776*/
777__dpct_inline__ void gdn_state_replay_kernel(
778    float *__restrict__ state, const float *__restrict__ hbuf, int C,
779    const float *__restrict__ gate, const float *__restrict__ beta, int h_k,
780    int h_v, int T, const int32_t *__restrict__ n_keep) {
781    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
782auto &sk = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[S]>(
783    sycl::ext::oneapi::this_work_item::get_work_group<3>());
784    auto &sq = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[S]>(
785        sycl::ext::oneapi::this_work_item::get_work_group<3>());
786    auto &red = *sycl::ext::oneapi::group_local_memory_for_overwrite<
787        float[RG][GS_COLS]>(
788        sycl::ext::oneapi::this_work_item::get_work_group<3>());
789    const int head = item_ct1.get_group(2);
790    const int c0 = item_ct1.get_group(1) * GS_COLS;
791    const int lc = item_ct1.get_local_id(2);
792    const int col = c0 + lc;
793    const int rg = item_ct1.get_local_id(1);
794    const int tid = rg * GS_COLS + lc;
795    const int qh = head % h_k;
796    const int qk = S * h_k;
797    const int n = n_keep ? *n_keep : T;
798    float gv[MAXT], bv[MAXT], vv[MAXT];
799#pragma unroll
800    for (int t = 0; t < MAXT; ++t) {
801        if (t < n) {
802            gv[t] = gate[(size_t) t * h_v + head];
803            bv[t] = beta[(size_t) t * h_v + head];
804            vv[t] = hbuf[(size_t) t * C + 2 * qk + head * S + col];
805        }
806    }
807    float kn = 0.0f, qn = 0.0f;
808    if (n > 0) { kn = hbuf[qk + qh * S + tid]; qn = hbuf[qh * S + tid]; }
809    float s[RPG];
810    float* base = state + ((size_t) (rg * RPG) * h_v + head) * S + col;
811    const size_t row_stride = (size_t) h_v * S;
812#pragma unroll
813    for (int r = 0; r < RPG; ++r) s[r] = base[r * row_stride];
814#pragma unroll
815    for (int t = 0; t < MAXT; ++t) {
816        if (t >= n) break;
817        /*
818        DPCT1118: SYCL group functions and algorithms must be encountered in
819        converged control flow. You may need to adjust the code.
820        */
821        /*
822        DPCT1065: Consider replacing sycl::nd_item::barrier() with
823        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
824        better performance if there is no access to global memory.
825        */
826        item_ct1.barrier();
827        sk[tid] = kn; sq[tid] = qn;
828        /*
829        DPCT1118: SYCL group functions and algorithms must be encountered in
830        converged control flow. You may need to adjust the code.
831        */
832        /*
833        DPCT1065: Consider replacing sycl::nd_item::barrier() with
834        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
835        better performance if there is no access to global memory.
836        */
837        item_ct1.barrier();
838        if (t + 1 < n) {
839            const float* hn = hbuf + (size_t) (t + 1) * C;
840            kn = hn[qk + qh * S + tid]; qn = hn[qh * S + tid];
841        }
842        const float g = sycl::native::exp(gv[t]);
843        float kv = 0.0f;
844#pragma unroll
845        for (int r = 0; r < RPG; ++r)
846            kv = sycl::fma(s[r], sk[rg * RPG + r], kv);
847        red[rg][lc] = kv;
848        /*
849        DPCT1118: SYCL group functions and algorithms must be encountered in
850        converged control flow. You may need to adjust the code.
851        */
852        /*
853        DPCT1065: Consider replacing sycl::nd_item::barrier() with
854        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
855        better performance if there is no access to global memory.
856        */
857        item_ct1.barrier();
858        const float kv_col = red[0][lc] + red[1][lc] + red[2][lc] + red[3][lc];
859        const float delta = (vv[t] - g * kv_col) * bv[t];
860        float o = 0.0f;   // unused: kept because the measured code had it (without it: 51 us instead of 39 at 1 row)
861#pragma unroll
862        for (int r = 0; r < RPG; ++r) {
863            s[r] = sycl::fma((float)g, s[r], sk[rg * RPG + r] * delta);
864            o = sycl::fma(s[r], sq[rg * RPG + r], o);
865        }
866        (void) o;
867    }
868    if (n_keep != nullptr && n > 0) {
869#pragma unroll
870        for (int r = 0; r < RPG; ++r) base[r * row_stride] = s[r];
871    }
872}
873// y = oc * rsqrt(mean(oc^2) + eps) * gamma * sigmoid(z) per head and token: gdn_step_norm_multi_kernel's tail with its
874// code shape (S x RG threads; rg 0 holds oc, the other row groups contribute 0 to wsum), reading oc from y
875template <bool Q>
876__dpct_inline__ void gdn_out_norm_kernel(
877    const float *__restrict__ z, const float *__restrict__ gamma, float eps,
878    float *__restrict__ y, int h_v, int T, const int32_t *__restrict__ n_keep,
879    int t_out_begin, GdnQ81 *__restrict__ xq) {
880    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
881auto &wsum =
882    *sycl::ext::oneapi::group_local_memory_for_overwrite<float[S * RG / 32]>(
883        sycl::ext::oneapi::this_work_item::get_work_group<3>());
884    const int head = item_ct1.get_group(2),
885              t = item_ct1.get_group(1) + t_out_begin,
886              col = item_ct1.get_local_id(2), rg = item_ct1.get_local_id(1);
887    const int tid = rg * S + col;
888    const int n = n_keep ? *n_keep : T;
889    if (t >= n) return;
890    const int value_dim = S * h_v;
891    float oc = 0.0f, sq_part = 0.0f;
892    if (rg == 0) {
893        oc = y[(size_t) t * value_dim + head * S + col];
894        sq_part = oc * oc;
895    }
896    /*
897DPCT1108: '__shfl_xor_sync' was migrated with the experimental feature
898masked sub_group function which may not be supported by all compilers or
899runtimes. You may need to adjust the code.
900*/
901#pragma unroll
902    for (int o2 = 16; o2 > 0; o2 >>= 1) sq_part +=
903        dpct::experimental::permute_sub_group_by_xor(
904            0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(),
905            sq_part, o2);
906    if ((tid & 31) == 0) wsum[tid >> 5] = sq_part;
907    /*
908    DPCT1065: Consider replacing sycl::nd_item::barrier() with
909    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
910    performance if there is no access to global memory.
911    */
912    item_ct1.barrier();
913    if (rg == 0) {
914        const float ss = wsum[0] + wsum[1] + wsum[2] + wsum[3];
915        const float scale = sycl::rsqrt(ss / (float)S + eps);
916        const float zz = z[(size_t) t * value_dim + head * S + col];
917        if constexpr (Q) {
918            const float yv = oc * scale * gamma[col] *
919                             (1.0f / (1.0f + sycl::native::exp(-zz)));
920            y[(size_t) t * value_dim + head * S + col] = yv;
921            gdn_q8_1_store(xq, (size_t) (t - t_out_begin) * value_dim + head * S + col, yv);
922        } else {
923            y[(size_t)t * value_dim + head * S + col] =
924                oc * scale * gamma[col] *
925                (1.0f / (1.0f + sycl::native::exp(-zz)));
926        }
927    }
928}
929
930// Commit has no output consumer. Keep the state update order.
931__dpct_inline__ void gdn_commit_state_multi_kernel(
932    float* __restrict__ state, const float* __restrict__ hbuf, int C,
933    const float* __restrict__ gate, const float* __restrict__ beta,
934    int h_k, int h_v, const int32_t* __restrict__ n_keep) {
935    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
936    auto& sk = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[S]>(
937        sycl::ext::oneapi::this_work_item::get_work_group<3>());
938    auto& red = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[RG][S]>(
939        sycl::ext::oneapi::this_work_item::get_work_group<3>());
940    const int head = item_ct1.get_group(2), col = item_ct1.get_local_id(2);
941    const int rg = item_ct1.get_local_id(1), tid = rg * S + col;
942    const int qh = head % h_k, qk = S * h_k;
943    const int n = *n_keep;
944    float s[RPG];
945    float* base = state + ((size_t)(rg * RPG) * h_v + head) * S + col;
946    const size_t row_stride = (size_t)h_v * S;
947#pragma unroll
948    for (int r = 0; r < RPG; ++r) s[r] = base[r * row_stride];
949    for (int t = 0; t < n; ++t) {
950        const float* ht = hbuf + (size_t)t * C;
951        item_ct1.barrier();
952        if (tid < S) sk[tid] = ht[qk + qh * S + tid];
953        item_ct1.barrier();
954        const float g = sycl::native::exp(gate[(size_t)t * h_v + head]);
955        float kv = 0.0f;
956#pragma unroll
957        for (int r = 0; r < RPG; ++r) kv = sycl::fma(s[r], sk[rg * RPG + r], kv);
958        red[rg][col] = kv;
959        item_ct1.barrier();
960        const float kv_col = red[0][col] + red[1][col] + red[2][col] + red[3][col];
961        const float delta = (ht[2 * qk + head * S + col] - g * kv_col) * beta[(size_t)t * h_v + head];
962#pragma unroll
963        for (int r = 0; r < RPG; ++r)
964            s[r] = sycl::fma((float)g, s[r], sk[rg * RPG + r] * delta);
965    }
966    if (n > 0) {
967#pragma unroll
968        for (int r = 0; r < RPG; ++r) base[r * row_stride] = s[r];
969    }
970}
971
972__dpct_inline__ void gdn_step_norm_qkreg_kernel(
973    float *__restrict__ state, const float *__restrict__ hbuf, int C,
974    const float *__restrict__ gate, const float *__restrict__ beta,
975    const float *__restrict__ z, const float *__restrict__ gamma, float eps,
976    float *__restrict__ y, int h_k, int h_v, int T,
977    const int32_t *__restrict__ n_keep, int t_out_begin) {
978    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
979    auto &red =
980        *sycl::ext::oneapi::group_local_memory_for_overwrite<float[RG][S]>(
981            sycl::ext::oneapi::this_work_item::get_work_group<3>());
982    auto &wsum = *sycl::ext::oneapi::group_local_memory_for_overwrite<
983        float[S * RG / 32]>(
984        sycl::ext::oneapi::this_work_item::get_work_group<3>());
985    const int head = item_ct1.get_group(2);
986    const int col = item_ct1.get_local_id(2);
987    const int rg = item_ct1.get_local_id(1);
988    const int tid = rg * S + col;
989    auto sg=item_ct1.get_sub_group();
990    const int lane=sg.get_local_linear_id();
991    const int qh = head % h_k;
992    const int qk = S * h_k;             // q at [0, qk), k at [qk, 2qk), v at [2qk, ...)
993    const int value_dim = S * h_v;
994    const int n = n_keep ? *n_keep : T;
995    float s[RPG];
996    float* base = state + ((size_t) (rg * RPG) * h_v + head) * S + col;
997    const size_t row_stride = (size_t) h_v * S;
998#pragma unroll
999    for (int r = 0; r < RPG; ++r) s[r] = base[r * row_stride];
1000    for (int t = 0; t < n; ++t) {
1001        const float* ht = hbuf + (size_t) t * C;
1002        /*
1003        DPCT1118: SYCL group functions and algorithms must be encountered in
1004        converged control flow. You may need to adjust the code.
1005        */
1006        /*
1007        DPCT1065: Consider replacing sycl::nd_item::barrier() with
1008        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
1009        better performance if there is no access to global memory.
1010        */
1011        item_ct1.barrier(); // the previous token is done with sk/sq/red/wsum
1012        const float k_own=ht[qk+qh*S+rg*RPG+lane];
1013        const float q_own=ht[qh*S+rg*RPG+lane];
1014        const float g = sycl::native::exp(gate[(size_t)t * h_v + head]);
1015        float kv = 0.0f;
1016#pragma unroll
1017        for (int r = 0; r < RPG; ++r)
1018            kv = sycl::fma(s[r], sycl::select_from_group(sg,k_own,r), kv);
1019        red[rg][col] = kv;
1020        /*
1021        DPCT1118: SYCL group functions and algorithms must be encountered in
1022        converged control flow. You may need to adjust the code.
1023        */
1024        /*
1025        DPCT1065: Consider replacing sycl::nd_item::barrier() with
1026        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
1027        better performance if there is no access to global memory.
1028        */
1029        item_ct1.barrier();
1030        const float kv_col = red[0][col] + red[1][col] + red[2][col] + red[3][col];
1031        const float delta = (ht[2 * qk + head * S + col] - g * kv_col) * beta[(size_t) t * h_v + head];
1032        float o = 0.0f;
1033#pragma unroll
1034        for (int r = 0; r < RPG; ++r) {
1035            s[r] = sycl::fma((float)g, s[r], sycl::select_from_group(sg,k_own,r) * delta);
1036            o = sycl::fma(s[r], sycl::select_from_group(sg,q_own,r), o);
1037        }
1038        /*
1039        DPCT1118: SYCL group functions and algorithms must be encountered in
1040        converged control flow. You may need to adjust the code.
1041        */
1042        /*
1043        DPCT1065: Consider replacing sycl::nd_item::barrier() with
1044        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
1045        better performance if there is no access to global memory.
1046        */
1047        item_ct1.barrier();
1048        red[rg][col] = o;
1049        /*
1050        DPCT1118: SYCL group functions and algorithms must be encountered in
1051        converged control flow. You may need to adjust the code.
1052        */
1053        /*
1054        DPCT1065: Consider replacing sycl::nd_item::barrier() with
1055        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
1056        better performance if there is no access to global memory.
1057        */
1058        item_ct1.barrier();
1059        float oc = 0.0f, sq_part = 0.0f;
1060        if (rg == 0) {
1061            oc = (red[0][col] + red[1][col] + red[2][col] + red[3][col]) *
1062                 sycl::rsqrt((float)S);
1063            sq_part = oc * oc;
1064        }
1065        if (t < t_out_begin) continue;   // a replayed token: its state update is needed, its output is not
1066        /*
1067DPCT1108: '__shfl_xor_sync' was migrated with the experimental feature
1068masked sub_group function which may not be supported by all compilers or
1069runtimes. You may need to adjust the code.
1070*/
1071#pragma unroll
1072        for (int o2 = 16; o2 > 0; o2 >>= 1) sq_part +=
1073            dpct::experimental::permute_sub_group_by_xor(
1074                0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(),
1075                sq_part, o2);
1076        if ((tid & 31) == 0) wsum[tid >> 5] = sq_part;
1077        /*
1078        DPCT1118: SYCL group functions and algorithms must be encountered in
1079        converged control flow. You may need to adjust the code.
1080        */
1081        /*
1082        DPCT1065: Consider replacing sycl::nd_item::barrier() with
1083        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
1084        better performance if there is no access to global memory.
1085        */
1086        item_ct1.barrier();
1087        if (rg == 0) {
1088            const float ss = wsum[0] + wsum[1] + wsum[2] + wsum[3];
1089            const float scale = sycl::rsqrt(ss / (float)S + eps);
1090            const float zz = z[(size_t) t * value_dim + head * S + col];
1091            y[(size_t)t * value_dim + head * S + col] =
1092                oc * scale * gamma[col] *
1093                (1.0f / (1.0f + sycl::native::exp(-zz)));
1094        }
1095    }
1096    if (n_keep != nullptr && n > 0) {
1097#pragma unroll
1098        for (int r = 0; r < RPG; ++r) base[r * row_stride] = s[r];
1099    }
1100}
1101
1102__dpct_inline__ void embedding_gather_dev_kernel(
1103    const uint8_t *__restrict__ codes, const float *__restrict__ scales,
1104    const float *__restrict__ offsets, const int32_t *__restrict__ tokens,
1105    int64_t n, int code_bits, int code_bias, int group_elems,
1106    unsigned long long row_codes, unsigned long long row_groups,
1107    float *__restrict__ out) {
1108    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
1109    const int t = item_ct1.get_group(1);
1110    const int64_t i =
1111        (int64_t)item_ct1.get_group(2) * item_ct1.get_local_range(2) +
1112        item_ct1.get_local_id(2);
1113    if (i >= n) return;
1114    const unsigned long long token = (unsigned long long) tokens[t];
1115    const uint8_t* c = codes + token * row_codes;
1116    const float* sc = scales + token * row_groups;
1117    const float* of = offsets ? offsets + token * row_groups : nullptr;
1118    const int per_byte = 8 / code_bits;
1119    const unsigned mask = (1u << code_bits) - 1u;
1120    const int code = (c[i / per_byte] >> ((i % per_byte) * code_bits)) & mask;
1121    const int64_t group = i / group_elems;
1122    /*
1123    DPCT1013: The rounding mode could not be specified and the generated
1124    code may have different accuracy than the original code. Verify the
1125    correctness. SYCL math built-in function rounding mode is aligned with
1126    OpenCL C 1.2 standard.
1127    */
1128    const float product = (float)(code + code_bias) * sc[group];
1129    /*
1130    DPCT1013: The rounding mode could not be specified and the generated
1131    code may have different accuracy than the original code. Verify the
1132    correctness. SYCL math built-in function rounding mode is aligned with
1133    OpenCL C 1.2 standard.
1134    */
1135    out[(size_t)t * n + i] = product + (of ? of[group] : 0.0f);
1136}
1137
1138__dpct_inline__ void broadcast_streams_kernel(const float *__restrict__ x,
1139                                              float *__restrict__ R, int64_t n,
1140                                              int hc) {
1141    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
1142    const int t = item_ct1.get_group(1);
1143    const int64_t i =
1144        (int64_t)item_ct1.get_group(2) * item_ct1.get_local_range(2) +
1145        item_ct1.get_local_id(2);
1146    if (i >= n * hc) return;
1147    R[(size_t) t * n * hc + i] = x[(size_t) t * n + i % n];
1148}
1149
1150__dpct_inline__ void copy_indexed_kernel(float *__restrict__ dst,
1151                                         const float *__restrict__ src,
1152                                         int64_t stride,
1153                                         const int32_t *__restrict__ index,
1154                                         int64_t n) {
1155    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
1156    const int idx = *index;
1157    if (idx < 0) return;
1158#pragma unroll
1159    for (int64_t i =
1160             (int64_t)item_ct1.get_group(2) * item_ct1.get_local_range(2) +
1161             item_ct1.get_local_id(2);
1162         i < n; i += (int64_t)item_ct1.get_group_range(2) *
1163                     item_ct1.get_local_range(2))
1164        dst[i] = src[(size_t) idx * stride + i];
1165}
1166
1167__dpct_inline__ void
1168fetch_blobs_kernel(const unsigned long long *__restrict__ src,
1169                   const int32_t *__restrict__ n, sycl::uint4 *__restrict__ dst,
1170                   long long per) {
1171    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
1172    const long long total = (long long)*n * per;
1173    for (long long i =
1174             (long long)item_ct1.get_group(2) * item_ct1.get_local_range(2) +
1175             item_ct1.get_local_id(2);
1176         i < total; i += (long long)item_ct1.get_group_range(2) *
1177                         item_ct1.get_local_range(2)) {
1178        const long long k = i / per, off = i - k * per;
1179        dst[i] = ((const sycl::uint4 *)src[k])[off];
1180    }
1181}
1182
1183__dpct_inline__ void rebase_ptrs_kernel(unsigned long long *ptr,
1184                                        const int32_t *n,
1185                                        unsigned long long base,
1186                                        long long bytes) {
1187    const int k =
1188        sycl::ext::oneapi::this_work_item::get_nd_item<3>().get_local_id(2);
1189    if (k < *n) ptr[k] = base + (unsigned long long) k * (unsigned long long) bytes;
1190}
1191
1192__dpct_inline__ void add_streams_broadcast_kernel(const float *__restrict__ h,
1193                                                  const float *__restrict__ e,
1194                                                  float *__restrict__ R,
1195                                                  int64_t n, int hc) {
1196    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
1197    const int t = item_ct1.get_group(1);
1198    const int64_t i =
1199        (int64_t)item_ct1.get_group(2) * item_ct1.get_local_range(2) +
1200        item_ct1.get_local_id(2);
1201    if (i >= n * hc) return;
1202    R[(size_t) t * n * hc + i] = h[(size_t) t * n * hc + i] + e[(size_t) t * n + i % n];
1203}
1204
1205__dpct_inline__ void ident_hits_kernel(const int32_t *__restrict__ ids, int n,
1206                                       int32_t *__restrict__ slot,
1207                                       int32_t *__restrict__ dst,
1208                                       int32_t *__restrict__ count) {
1209    const int i =
1210        sycl::ext::oneapi::this_work_item::get_nd_item<3>().get_local_id(2);
1211    if (i < n) { slot[i] = ids[i]; dst[i] = i; }
1212    if (i == 0) *count = n;
1213}
1214
1215// E = the widest element the row size divides into (16, 4 or 1 bytes): a Q6_K head row of 2560 values is 2100 bytes
1216template <typename E>
1217__dpct_inline__ void gather_rows_kernel(const E *__restrict__ src,
1218                                        long long row_e,
1219                                        const int32_t *__restrict__ ids,
1220                                        long long n, E *__restrict__ dst) {
1221    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
1222    const long long total = n * row_e;
1223    for (long long i =
1224             (long long)item_ct1.get_group(2) * item_ct1.get_local_range(2) +
1225             item_ct1.get_local_id(2);
1226         i < total; i += (long long)item_ct1.get_group_range(2) *
1227                         item_ct1.get_local_range(2)) {
1228        const long long r = i / row_e, o = i - r * row_e;
1229        dst[i] = src[(long long) ids[r] * row_e + o];
1230    }
1231}
1232
1233__dpct_inline__ void map_ids_kernel(int32_t *ids,
1234                                    const int32_t *__restrict__ table, int n) {
1235    const int i =
1236        sycl::ext::oneapi::this_work_item::get_nd_item<3>().get_local_id(2);
1237    if (i < n) ids[i] = table[ids[i]];
1238}
1239
1240__dpct_inline__ void row_top_prob_kernel(const float *__restrict__ logits,
1241                                         int n_vocab,
1242                                         const int32_t *__restrict__ ids,
1243                                         float *__restrict__ probs) {
1244    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
1245auto &part = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[32]>(
1246    sycl::ext::oneapi::this_work_item::get_work_group<3>());
1247    const int t = item_ct1.get_group(2);
1248    const float* l = logits + (size_t) t * n_vocab;
1249    const float m = l[ids[t]];
1250    float s = 0.0f;
1251#pragma unroll
1252    for (int i = item_ct1.get_local_id(2); i < n_vocab;
1253         i += item_ct1.get_local_range(2)) s += sycl::native::exp(l[i] - m);
1254    /*
1255DPCT1108: '__shfl_xor_sync' was migrated with the experimental feature
1256masked sub_group function which may not be supported by all compilers or
1257runtimes. You may need to adjust the code.
1258*/
1259#pragma unroll
1260    for (int o = 16; o > 0; o >>= 1) s +=
1261        dpct::experimental::permute_sub_group_by_xor(
1262            0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(), s,
1263            o);
1264    if ((item_ct1.get_local_id(2) & 31) == 0)
1265        part[item_ct1.get_local_id(2) >> 5] = s;
1266    item_ct1.barrier(sycl::access::fence_space::local_space);
1267    if (item_ct1.get_local_id(2) == 0) {
1268        float tot = 0.0f;
1269#pragma unroll
1270        for (int w = 0; w < (int)(item_ct1.get_local_range(2) >> 5); ++w) tot +=
1271            part[w];
1272        probs[t] = 1.0f / tot;
1273    }
1274}
1275
1276__dpct_inline__ void
1277mtp_select_kernel(const float *__restrict__ R_src, int64_t stride,
1278                  const int32_t *__restrict__ ids,
1279                  const int32_t *__restrict__ row_dev,
1280                  float *__restrict__ R_dst, int32_t *__restrict__ tok_dst,
1281                  int32_t *out, int j, const float *probs, float *out_p) {
1282    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
1283    const int row = *row_dev;
1284#pragma unroll
1285    for (int64_t i =
1286             (int64_t)item_ct1.get_group(2) * item_ct1.get_local_range(2) +
1287             item_ct1.get_local_id(2);
1288         i < stride; i += (int64_t)item_ct1.get_group_range(2) *
1289                          item_ct1.get_local_range(2))
1290        R_dst[i] = R_src[(size_t) row * stride + i];
1291    item_ct1.barrier(sycl::access::fence_space::local_space);
1292    if (item_ct1.get_group(2) == 0 && item_ct1.get_local_id(2) == 0) {
1293        const int32_t tok = ids[row];
1294        *tok_dst = tok;
1295        if (probs != nullptr && out_p != nullptr) ((volatile float*) out_p)[j] = probs[row];
1296        /*
1297        DPCT1078: Consider replacing memory_order::acq_rel with
1298        memory_order::seq_cst for correctness if strong memory order
1299        restrictions are needed.
1300        */
1301        sycl::atomic_fence(sycl::memory_order::acq_rel,
1302                           sycl::memory_scope::system);
1303        if (out != nullptr) ((volatile int32_t*) out)[j] = tok;
1304    }
1305}
1306
1307__dpct_inline__ void dense_steps_kernel(const int32_t *__restrict__ cells,
1308                                        int n, int32_t *__restrict__ steps) {
1309    const int i =
1310        sycl::ext::oneapi::this_work_item::get_nd_item<3>().get_local_id(2);
1311    if (i >= n) return;
1312    const int c = cells[i];
1313    steps[i * 4 + 0] = c;
1314    steps[i * 4 + 1] = c + 1;
1315    steps[i * 4 + 2] = (c + 1) / 4;
1316    steps[i * 4 + 3] = c + 1;
1317}
1318
1319// --pipeline-windows: the drafter's chain, teacher forced (see force_token)
1320__dpct_inline__ void force_token_kernel(int32_t *tok, const int32_t *force,
1321                                        int j) {
1322    const int32_t f = ((const volatile int32_t*) force)[j];
1323    if (f >= 0) *tok = f;
1324}
1325
1326}  // namespace
1327
1328void fetch_blobs(const unsigned long long* src, const int32_t* n, uint8_t* dst, int64_t blob_bytes, int cap, void* stream) {
1329    if (cap <= 0) return;
1330    if (blob_bytes % 16 != 0) { std::fprintf(stderr, "fetch_blobs: blob size must be a multiple of 16\n"); std::exit(1); }
1331    {
1332        auto exp_props = sycl::ext::oneapi::experimental::properties{
1333            sycl::ext::oneapi::experimental::use_root_sync};
1334
1335        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
1336            ->submit([&](sycl::handler &cgh) {
1337                auto blob_bytes_ct3 = (long long)(blob_bytes / 16);
1338
1339                cgh.parallel_for<
1340                    dpct_kernel_name<class fetch_blobs_kernel_14b6f5>>(
1341                    sycl::nd_range<3>(sycl::range(1, 1, 48 * 8) *
1342                                          sycl::range(1, 1, 256),
1343                                      sycl::range(1, 1, 256)),
1344                    exp_props, [=](sycl::nd_item<3> item_ct1) {
1345                        fetch_blobs_kernel(src, n, (sycl::uint4 *)dst,
1346                                           blob_bytes_ct3);
1347                    });
1348            });
1349    }
1350    check("fetch_blobs");
1351}
1352
1353void rebase_ptrs(unsigned long long* ptr, const int32_t* n, uint8_t* base, int64_t blob_bytes, void* stream) {
1354    {
1355        auto exp_props = sycl::ext::oneapi::experimental::properties{
1356            sycl::ext::oneapi::experimental::use_root_sync};
1357
1358        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
1359            ->template parallel_for<dpct_kernel_name<class rebase_ptrs_kernel_436f27>>(
1360                sycl::nd_range<3>(sycl::range(1, 1, 128),
1361                                  sycl::range(1, 1, 128)),
1362                exp_props, [=](sycl::nd_item<3> item_ct1) {
1363                    rebase_ptrs_kernel(ptr, n, (unsigned long long)base,
1364                                       (long long)blob_bytes);
1365                });
1366    }
1367    check("rebase_ptrs");
1368}
1369
1370void add_streams_broadcast(const float* h, const float* e, float* R, int64_t n_embd, int hc, int n_tok, void* stream) {
1371    {
1372        auto exp_props = sycl::ext::oneapi::experimental::properties{
1373            sycl::ext::oneapi::experimental::use_root_sync};
1374
1375        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
1376            ->template parallel_for<
1377                dpct_kernel_name<class add_streams_broadcast_kernel_7de8f5>>(
1378                sycl::nd_range<3>(
1379                    sycl::range(1, (unsigned)n_tok,
1380                                (unsigned)((n_embd * hc + 255) / 256)) *
1381                        sycl::range(1, 1, 256),
1382                    sycl::range(1, 1, 256)),
1383                exp_props, [=](sycl::nd_item<3> item_ct1) {
1384                    add_streams_broadcast_kernel(h, e, R, n_embd, hc);
1385                });
1386    }
1387    check("add_streams_broadcast");
1388}
1389
1390void ident_hits(const int32_t* ids, int n, int32_t* slot, int32_t* dst, int32_t* count, void* stream) {
1391    if (n < 1 || n > 1024) { std::fprintf(stderr, "ident_hits: n out of range\n"); std::exit(1); }
1392    /*
1393    DPCT1049: The work-group size passed to the SYCL kernel may exceed the
1394    limit. To get the device limit, query info::device::max_work_group_size.
1395    Adjust the work-group size if needed.
1396    */
1397    {
1398        auto exp_props = sycl::ext::oneapi::experimental::properties{
1399            sycl::ext::oneapi::experimental::use_root_sync};
1400
1401        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
1402            ->template parallel_for<dpct_kernel_name<class ident_hits_kernel_287489>>(
1403                sycl::nd_range<3>(sycl::range(1, 1, 1024),
1404                                  sycl::range(1, 1, 1024)),
1405                exp_props, [=](sycl::nd_item<3> item_ct1) {
1406                    ident_hits_kernel(ids, n, slot, dst, count);
1407                });
1408    }
1409    check("ident_hits");
1410}
1411
1412namespace {
1413__dpct_inline__ void
1414copy_row_to_first_kernel(const int32_t *__restrict__ row_dev, float *a,
1415                         int64_t a_n, float *b, int64_t b_n, float *c,
1416                         int64_t c_n) {
1417    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
1418    const int64_t row = *row_dev;
1419    if (row == 0) return;
1420    const int64_t i0 = (int64_t)item_ct1.get_group(2) *
1421                           item_ct1.get_local_range(2) +
1422                       item_ct1.get_local_id(2),
1423                  st = (int64_t)item_ct1.get_group_range(2) *
1424                       item_ct1.get_local_range(2);
1425#pragma unroll
1426    for (int64_t i = i0; i < a_n; i += st) a[i] = a[row * a_n + i];
1427#pragma unroll
1428    for (int64_t i = i0; i < b_n; i += st) b[i] = b[row * b_n + i];
1429#pragma unroll
1430    for (int64_t i = i0; i < c_n; i += st) c[i] = c[row * c_n + i];
1431}
1432}  // namespace
1433
1434void copy_row_to_first(const int32_t* row_dev, float* a, int64_t a_n, float* b, int64_t b_n, float* c, int64_t c_n,
1435                       void* stream) {
1436    {
1437        auto exp_props = sycl::ext::oneapi::experimental::properties{
1438            sycl::ext::oneapi::experimental::use_root_sync};
1439
1440        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
1441            ->template parallel_for<
1442                dpct_kernel_name<class copy_row_to_first_kernel_993785>>(
1443                sycl::nd_range<3>(sycl::range(1, 1, 16) *
1444                                      sycl::range(1, 1, 256),
1445                                  sycl::range(1, 1, 256)),
1446                exp_props, [=](sycl::nd_item<3> item_ct1) {
1447                    copy_row_to_first_kernel(row_dev, a, a_n, b, b_n, c, c_n);
1448                });
1449    }
1450    check("copy_row_to_first");
1451}
1452
1453void mtp_select(const float* R_src, int64_t R_stride, const int32_t* ids, const int32_t* row_dev, float* R_dst,
1454                int32_t* tok_dst, int32_t* out, int j, void* stream, const float* probs, float* out_p) {
1455    {
1456        auto exp_props = sycl::ext::oneapi::experimental::properties{
1457            sycl::ext::oneapi::experimental::use_root_sync};
1458
1459        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
1460            ->template parallel_for<dpct_kernel_name<class mtp_select_kernel_4611fe>>(
1461                sycl::nd_range<3>(sycl::range(1, 1, 256),
1462                                  sycl::range(1, 1, 256)),
1463                exp_props, [=](sycl::nd_item<3> item_ct1) {
1464                    mtp_select_kernel(R_src, R_stride, ids, row_dev, R_dst,
1465                                      tok_dst, out, j, probs, out_p);
1466                });
1467    }
1468    check("mtp_select");
1469}
1470
1471void force_token(int32_t* tok, const int32_t* force, int j, void* stream) {
1472    {
1473        auto exp_props = sycl::ext::oneapi::experimental::properties{
1474            sycl::ext::oneapi::experimental::use_root_sync};
1475
1476        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
1477            ->template parallel_for<dpct_kernel_name<class force_token_kernel_a9fa72>>(
1478                sycl::nd_range<3>(sycl::range(1, 1, 1), sycl::range(1, 1, 1)),
1479                exp_props, [=](sycl::nd_item<3> item_ct1) {
1480                    force_token_kernel(tok, force, j);
1481                });
1482    }
1483    check("force_token");
1484}
1485
1486void gather_rows(const uint8_t* src, int64_t row_bytes, const int32_t* ids, int64_t n, uint8_t* dst, void* stream) {
1487    dpct::queue_ptr s = strata::q_of(stream);
1488    if (row_bytes % 16 == 0)
1489    {
1490        auto exp_props = sycl::ext::oneapi::experimental::properties{
1491            sycl::ext::oneapi::experimental::use_root_sync};
1492
1493        strata::kprof::kp(s, __FILE__, __func__, __LINE__)->submit([&](sycl::handler &cgh) {
1494            long long row_bytes_ct1 = row_bytes / 16;
1495
1496            cgh.parallel_for<
1497                dpct_kernel_name<class gather_rows_kernel_b3ae5a, sycl::uint4>>(
1498                sycl::nd_range<3>(sycl::range(1, 1, 48 * 8) *
1499                                      sycl::range(1, 1, 256),
1500                                  sycl::range(1, 1, 256)),
1501                [=](sycl::nd_item<3> item_ct1) {
1502                    gather_rows_kernel((const sycl::uint4 *)src, row_bytes_ct1,
1503                                       ids, n, (sycl::uint4 *)dst);
1504                });
1505        });
1506    } else if (row_bytes % 4 == 0)
1507    {
1508        auto exp_props = sycl::ext::oneapi::experimental::properties{
1509            sycl::ext::oneapi::experimental::use_root_sync};
1510
1511        strata::kprof::kp(s, __FILE__, __func__, __LINE__)->submit([&](sycl::handler &cgh) {
1512            long long row_bytes_ct1 = row_bytes / 4;
1513
1514            cgh.parallel_for<
1515                dpct_kernel_name<class gather_rows_kernel_f256ac, uint32_t>>(
1516                sycl::nd_range<3>(sycl::range(1, 1, 48 * 8) *
1517                                      sycl::range(1, 1, 256),
1518                                  sycl::range(1, 1, 256)),
1519                [=](sycl::nd_item<3> item_ct1) {
1520                    gather_rows_kernel((const uint32_t *)src, row_bytes_ct1,
1521                                       ids, n, (uint32_t *)dst);
1522                });
1523        });
1524    } else {
1525        auto exp_props = sycl::ext::oneapi::experimental::properties{
1526            sycl::ext::oneapi::experimental::use_root_sync};
1527
1528        strata::kprof::kp(s, __FILE__, __func__, __LINE__)->template parallel_for<
1529            dpct_kernel_name<class gather_rows_kernel_c5b171, uint8_t>>(
1530            sycl::nd_range<3>(sycl::range(1, 1, 48 * 8) *
1531                                  sycl::range(1, 1, 256),
1532                              sycl::range(1, 1, 256)),
1533            [=](sycl::nd_item<3> item_ct1) {
1534                gather_rows_kernel(src, row_bytes, ids, n, dst);
1535            });
1536    }
1537    check("gather_rows");
1538}
1539
1540void map_ids(int32_t* ids, const int32_t* table, int n, void* stream) {
1541    {
1542        auto exp_props = sycl::ext::oneapi::experimental::properties{
1543            sycl::ext::oneapi::experimental::use_root_sync};
1544
1545        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
1546            ->template parallel_for<dpct_kernel_name<class map_ids_kernel_43a113>>(
1547                sycl::nd_range<3>(sycl::range(1, 1, 64), sycl::range(1, 1, 64)),
1548                exp_props, [=](sycl::nd_item<3> item_ct1) {
1549                    map_ids_kernel(ids, table, n);
1550                });
1551    }
1552    check("map_ids");
1553}
1554
1555void row_top_prob(const float* logits, int n_rows, int n_vocab, const int32_t* ids, float* probs, void* stream) {
1556    /*
1557    DPCT1049: The work-group size passed to the SYCL kernel may exceed the
1558    limit. To get the device limit, query info::device::max_work_group_size.
1559    Adjust the work-group size if needed.
1560    */
1561    {
1562        auto exp_props = sycl::ext::oneapi::experimental::properties{
1563            sycl::ext::oneapi::experimental::use_root_sync};
1564
1565        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
1566            ->template parallel_for<dpct_kernel_name<class row_top_prob_kernel_6adbe2>>(
1567                sycl::nd_range<3>(sycl::range(1, 1, n_rows) *
1568                                      sycl::range(1, 1, 1024),
1569                                  sycl::range(1, 1, 1024)),
1570                exp_props,
1571                [=](sycl::nd_item<3> item_ct1)
1572                    [[sycl::reqd_sub_group_size(32)]] {
1573                        row_top_prob_kernel(logits, n_vocab, ids, probs);
1574                    });
1575    }
1576    check("row_top_prob");
1577}
1578
1579#if !defined(__HIPCC__)   // warp-32 kernels: an AMD card keeps the one-block row_top_prob and sampler_greedy_kernel
1580namespace {
1581
1582constexpr int kArgMaxBlocks = 128, kArgThreads = 256, kTopBlocks = 8;
1583
1584// the larger value, on equality the lower index: sampler_greedy_kernel's order
1585__dpct_inline__ void arg_take(float ov, int oi, float &bv, int &bi) {
1586    if (ov > bv || (ov == bv && oi < bi)) { bv = ov; bi = oi; }
1587}
1588
1589// a block's (value, index) pick, in thread 0; `none` is the index of no candidate
1590__dpct_inline__ void arg_block(float &bv, int &bi, int none) {
1591    /*
1592    DPCT1115: The sycl::ext::oneapi::group_local_memory_for_overwrite is
1593    used to allocate group-local memory at the none kernel functor scope of a
1594    work-group data parallel kernel. You may need to adjust the code.
1595    */
1596    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
1597auto &sv = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[32]>(
1598    sycl::ext::oneapi::this_work_item::get_work_group<3>());
1599    /*
1600    DPCT1115: The sycl::ext::oneapi::group_local_memory_for_overwrite is
1601    used to allocate group-local memory at the none kernel functor scope of a
1602    work-group data parallel kernel. You may need to adjust the code.
1603    */
1604    auto &si = *sycl::ext::oneapi::group_local_memory_for_overwrite<int[32]>(
1605        sycl::ext::oneapi::this_work_item::get_work_group<3>());
1606    for (int off = 16; off > 0; off >>= 1) {
1607        /*
1608        DPCT1108: '__shfl_down_sync' was migrated with the experimental
1609        feature masked sub_group function which may not be supported by all
1610        compilers or runtimes. You may need to adjust the code.
1611        */
1612        /*
1613        DPCT1121: Make sure that the "bv" which is used in the SYCL group
1614        function/algorithm is initialized.
1615        */
1616        const float ov = dpct::experimental::shift_sub_group_left(
1617            0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(), bv,
1618            off);
1619        /*
1620        DPCT1108: '__shfl_down_sync' was migrated with the experimental
1621        feature masked sub_group function which may not be supported by all
1622        compilers or runtimes. You may need to adjust the code.
1623        */
1624        /*
1625        DPCT1121: Make sure that the "bi" which is used in the SYCL group
1626        function/algorithm is initialized.
1627        */
1628        const int oi = dpct::experimental::shift_sub_group_left(
1629            0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(), bi,
1630            off);
1631        arg_take(ov, oi, bv, bi);
1632    }
1633    const int warp = (int)(item_ct1.get_local_id(2) >> 5),
1634              lane = (int)(item_ct1.get_local_id(2) & 31);
1635    if (lane == 0) { sv[warp] = bv; si[warp] = bi; }
1636    /*
1637    DPCT1065: Consider replacing sycl::nd_item::barrier() with
1638    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
1639    performance if there is no access to global memory.
1640    */
1641    item_ct1.barrier();
1642    if (warp == 0) {
1643        const int nw = (int)(item_ct1.get_local_range(2) >> 5);
1644        bv = lane < nw ? sv[lane] : sycl::bit_cast<float, int>(0xff800000);
1645        bi = lane < nw ? si[lane] : none;
1646        for (int off = 16; off > 0; off >>= 1) {
1647            /*
1648            DPCT1108: '__shfl_down_sync' was migrated with the experimental
1649            feature masked sub_group function which may not be supported by all
1650            compilers or runtimes. You may need to adjust the code.
1651            */
1652            /*
1653            DPCT1121: Make sure that the "bv" which is used in the SYCL
1654            group function/algorithm is initialized.
1655            */
1656            const float ov = dpct::experimental::shift_sub_group_left(
1657                0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(),
1658                bv, off);
1659            /*
1660            DPCT1108: '__shfl_down_sync' was migrated with the experimental
1661            feature masked sub_group function which may not be supported by all
1662            compilers or runtimes. You may need to adjust the code.
1663            */
1664            /*
1665            DPCT1121: Make sure that the "bi" which is used in the SYCL
1666            group function/algorithm is initialized.
1667            */
1668            const int oi = dpct::experimental::shift_sub_group_left(
1669                0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(),
1670                bi, off);
1671            arg_take(ov, oi, bv, bi);
1672        }
1673    }
1674}
1675
1676// A row's scratch, whatever the launch's row count (one scratch serves windows of every size): its counter, then
1677// the blocks' values and indices.
1678struct ArgRow {
1679    unsigned counter;
1680    unsigned pad[3];
1681    float v[kArgMaxBlocks];
1682    int i[kArgMaxBlocks];
1683};
1684
1685// grid (blocks, rows): block b scans [b * per_block, +per_block) of its row
1686__dpct_inline__ void argmax_rows_kernel(const float *__restrict__ logits, int n,
1687                                        int per_block,
1688                                        ArgRow *__restrict__ rows,
1689                                        int32_t *out) {
1690    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
1691    const int row = (int)item_ct1.get_group(1), b = (int)item_ct1.get_group(2),
1692              nb = (int)item_ct1.get_group_range(2);
1693    unsigned* counter = &rows[row].counter;
1694    float* pv = rows[row].v;
1695    int* pi = rows[row].i;
1696    const float* l = logits + (size_t) row * n;
1697    const int lo = b * per_block, hi = sycl::min(n, lo + per_block);
1698    float bv = sycl::bit_cast<float, int>(0xff800000); // -inf
1699    int bi = n;
1700    for (int v = lo + (int)item_ct1.get_local_id(2); v < hi;
1701         v += (int)item_ct1.get_local_range(2)) {
1702        const float s = l[v];
1703        if (s > bv) { bv = s; bi = v; }
1704    }
1705    arg_block(bv, bi, n);
1706    auto &last = *sycl::ext::oneapi::group_local_memory_for_overwrite<bool>(
1707        sycl::ext::oneapi::this_work_item::get_work_group<3>());
1708    if (item_ct1.get_local_id(2) == 0) {
1709        pv[b] = bv;
1710        pi[b] = bi;
1711        /*
1712        DPCT1078: Consider replacing memory_order::acq_rel with
1713        memory_order::seq_cst for correctness if strong memory order
1714        restrictions are needed.
1715        */
1716        sycl::atomic_fence(sycl::memory_order::acq_rel,
1717                           sycl::memory_scope::device);
1718        last =
1719            dpct::atomic_fetch_add<sycl::access::address_space::generic_space>(
1720                counter, 1u) == (unsigned)(nb - 1);
1721    }
1722    /*
1723    DPCT1065: Consider replacing sycl::nd_item::barrier() with
1724    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
1725    performance if there is no access to global memory.
1726    */
1727    item_ct1.barrier();
1728    if (!last) return;
1729    /*
1730    DPCT1078: Consider replacing memory_order::acq_rel with
1731    memory_order::seq_cst for correctness if strong memory order restrictions
1732    are needed.
1733    */
1734    sycl::atomic_fence(sycl::memory_order::acq_rel, sycl::memory_scope::device);
1735    bv = sycl::bit_cast<float, int>(0xff800000);
1736    bi = n;
1737    if ((int)item_ct1.get_local_id(2) < nb) {
1738        bv = ((volatile const float *)pv)[item_ct1.get_local_id(2)];
1739        bi = ((volatile const int *)pi)[item_ct1.get_local_id(2)];
1740    }
1741    arg_block(bv, bi, n);
1742    if (item_ct1.get_local_id(2) == 0) {
1743        out[row] = bi < n ? bi : 0;   // no value above -inf: 0, as the one-block kernel
1744        *counter = 0;
1745    }
1746}
1747
1748// a row's top-probability scratch: its counter, then its 32 warps' sums
1749struct TopRow {
1750    unsigned counter;
1751    unsigned pad[3];
1752    float parts[32];
1753};
1754
1755// grid (kTopBlocks, rows), 1024 / kTopBlocks threads: thread j of block b is row_top_prob's thread b * blockDim + j
1756__dpct_inline__ void row_top_prob_split_kernel(const float *__restrict__ logits,
1757                                               int n_vocab,
1758                                               const int32_t *__restrict__ ids,
1759                                               float *__restrict__ probs,
1760                                               TopRow *__restrict__ rows) {
1761    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
1762    const int row = (int)item_ct1.get_group(1);
1763    float* parts = rows[row].parts;
1764    const float* l = logits + (size_t) row * n_vocab;
1765    const float m = l[ids[row]];
1766    const int vt = (int)(item_ct1.get_group(2) * item_ct1.get_local_range(2) +
1767                         item_ct1.get_local_id(2));
1768    float s = 0.0f;
1769#pragma unroll
1770    for (int i = vt; i < n_vocab; i += 1024) s += sycl::native::exp(l[i] - m);
1771    /*
1772DPCT1108: '__shfl_xor_sync' was migrated with the experimental feature
1773masked sub_group function which may not be supported by all compilers or
1774runtimes. You may need to adjust the code.
1775*/
1776#pragma unroll
1777    for (int o = 16; o > 0; o >>= 1) s +=
1778        dpct::experimental::permute_sub_group_by_xor(
1779            0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(), s,
1780            o);
1781    if ((item_ct1.get_local_id(2) & 31) == 0) parts[vt >> 5] = s;
1782    /*
1783    DPCT1078: Consider replacing memory_order::acq_rel with
1784    memory_order::seq_cst for correctness if strong memory order restrictions
1785    are needed.
1786    */
1787    sycl::atomic_fence(sycl::memory_order::acq_rel, sycl::memory_scope::device);
1788    /*
1789    DPCT1065: Consider replacing sycl::nd_item::barrier() with
1790    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
1791    performance if there is no access to global memory.
1792    */
1793    item_ct1.barrier();
1794    auto &last = *sycl::ext::oneapi::group_local_memory_for_overwrite<bool>(
1795        sycl::ext::oneapi::this_work_item::get_work_group<3>());
1796    if (item_ct1.get_local_id(2) == 0) last =
1797        dpct::atomic_fetch_add<sycl::access::address_space::generic_space>(
1798            &rows[row].counter, 1u) ==
1799        (unsigned)(item_ct1.get_group_range(2) - 1);
1800    /*
1801    DPCT1065: Consider replacing sycl::nd_item::barrier() with
1802    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
1803    performance if there is no access to global memory.
1804    */
1805    item_ct1.barrier();
1806    if (!last || item_ct1.get_local_id(2) != 0) return;
1807    /*
1808    DPCT1078: Consider replacing memory_order::acq_rel with
1809    memory_order::seq_cst for correctness if strong memory order restrictions
1810    are needed.
1811    */
1812    sycl::atomic_fence(sycl::memory_order::acq_rel, sycl::memory_scope::device);
1813    float tot = 0.0f;
1814#pragma unroll
1815    for (int w = 0; w < 32; ++w) tot += ((volatile const float *)parts)[w];
1816    probs[row] = 1.0f / tot;
1817    rows[row].counter = 0;
1818}
1819
1820}  // namespace
1821
1822uint64_t argmax_rows_scratch_bytes(int n_rows) { return (uint64_t) n_rows * sizeof(ArgRow); }
1823
1824void argmax_rows(const float* logits, int n_rows, int n, void* scratch, int32_t* out, void* stream) {
1825    if (n_rows <= 0) return;
1826    const int nb = std::min(kArgMaxBlocks, std::max(1, (n + 4095) / 4096));
1827    const int per_block = (n + nb - 1) / nb;
1828    {
1829        auto exp_props = sycl::ext::oneapi::experimental::properties{
1830            sycl::ext::oneapi::experimental::use_root_sync};
1831
1832        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
1833            ->template parallel_for<dpct_kernel_name<class argmax_rows_kernel_d5bcf6>>(
1834                sycl::nd_range<3>(
1835                    sycl::range(1, (unsigned)n_rows, (unsigned)nb) *
1836                        sycl::range(1, 1, kArgThreads),
1837                    sycl::range(1, 1, kArgThreads)),
1838                exp_props,
1839                [=](sycl::nd_item<3> item_ct1)
1840                    [[sycl::reqd_sub_group_size(32)]] {
1841                        argmax_rows_kernel(logits, n, per_block,
1842                                           (ArgRow *)scratch, out);
1843                    });
1844    }
1845    check("argmax_rows");
1846}
1847
1848uint64_t row_top_prob_scratch_bytes(int n_rows) { return (uint64_t) n_rows * sizeof(TopRow); }
1849
1850void row_top_prob_split(const float* logits, int n_rows, int n_vocab, const int32_t* ids, float* probs, void* scratch,
1851                        void* stream) {
1852    if (n_rows <= 0) return;
1853    {
1854        auto exp_props = sycl::ext::oneapi::experimental::properties{
1855            sycl::ext::oneapi::experimental::use_root_sync};
1856
1857        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
1858            ->template parallel_for<
1859                dpct_kernel_name<class row_top_prob_split_kernel_9495b0>>(
1860                sycl::nd_range<3>(sycl::range(1, (unsigned)n_rows, kTopBlocks) *
1861                                      sycl::range(1, 1, 1024 / kTopBlocks),
1862                                  sycl::range(1, 1, 1024 / kTopBlocks)),
1863                exp_props,
1864                [=](sycl::nd_item<3> item_ct1)
1865                    [[sycl::reqd_sub_group_size(32)]] {
1866                        row_top_prob_split_kernel(logits, n_vocab, ids, probs,
1867                                                  (TopRow *)scratch);
1868                    });
1869    }
1870    check("row_top_prob_split");
1871}
1872#else
1873uint64_t argmax_rows_scratch_bytes(int) { return 0; }
1874void argmax_rows(const float*, int, int, void*, int32_t*, void*) {
1875    std::fprintf(stderr, "argmax_rows: not built for this backend\n");
1876    std::exit(1);
1877}
1878uint64_t row_top_prob_scratch_bytes(int) { return 0; }
1879void row_top_prob_split(const float* logits, int n_rows, int n_vocab, const int32_t* ids, float* probs, void*,
1880                        void* stream) {
1881    row_top_prob(logits, n_rows, n_vocab, ids, probs, stream);
1882}
1883#endif
1884
1885bool multi_block_head_ops() {
1886#if defined(__HIPCC__)
1887    return false;
1888#else
1889    static const bool on = [] {
1890        const char* v = std::getenv("STRATA_MULTI_BLOCK_ARGMAX");
1891        return v == nullptr || std::atoi(v) != 0;
1892    }();
1893    return on;
1894#endif
1895}
1896
1897bool argmax_rows_wanted() try {
1898#if defined(__HIPCC__)
1899    return false;
1900#else
1901    // sm_80 to sm_89: sample_tokens' greedy pick there is the one-block kernel (sm_90+ has the cluster kernel)
1902    static const bool want = [] {
1903        int dev = 0, major = 0;
1904        if (DPCT_CHECK_ERROR(dev = dpct::get_current_device_id()) != 0 ||
1905            DPCT_CHECK_ERROR(
1906                major = dpct::get_device(dev).get_major_version()) != 0)
1907            return false;
1908        return major == 8;
1909    }();
1910    return want && multi_block_head_ops();
1911#endif
1912}
1913catch (sycl::exception const &exc) {
1914  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
1915            << ", line:" << __LINE__ << std::endl;
1916  std::exit(1);
1917}
1918
1919namespace {
1920__dpct_inline__ void window_ids_kernel(int32_t *steps, int window, int32_t *ids,
1921                                       long long stride) {
1922    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
1923    const int q = item_ct1.get_group(1);
1924    int32_t* st = steps + q * 4;
1925    const int n_kv = st[1];
1926    const int start = n_kv > window ? n_kv - window : 0;
1927    const int width = n_kv - start;
1928#pragma unroll
1929    for (int j = item_ct1.get_group(2) * item_ct1.get_local_range(2) +
1930                 item_ct1.get_local_id(2);
1931         j < width;
1932         j += item_ct1.get_group_range(2) * item_ct1.get_local_range(2))
1933        ids[q * stride + j] = start + j;
1934    /*
1935    DPCT1065: Consider replacing sycl::nd_item::barrier() with
1936    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
1937    performance if there is no access to global memory.
1938    */
1939    item_ct1.barrier();
1940    if (item_ct1.get_group(2) == 0 && item_ct1.get_local_id(2) == 0) st[3] =
1941        width;
1942}
1943}  // namespace
1944
1945void window_ids(int32_t* steps, int n, int window, int32_t* ids, int64_t ids_stride, void* stream) {
1946    {
1947        auto exp_props = sycl::ext::oneapi::experimental::properties{
1948            sycl::ext::oneapi::experimental::use_root_sync};
1949
1950        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
1951            ->template parallel_for<dpct_kernel_name<class window_ids_kernel_581536>>(
1952                sycl::nd_range<3>(sycl::range(1, (unsigned)n, 8) *
1953                                      sycl::range(1, 1, 256),
1954                                  sycl::range(1, 1, 256)),
1955                exp_props, [=](sycl::nd_item<3> item_ct1) {
1956                    window_ids_kernel(steps, window, ids,
1957                                      (long long)ids_stride);
1958                });
1959    }
1960    check("window_ids");
1961}
1962
1963void dense_steps(const int32_t* cells, int n, int32_t* steps, void* stream) {
1964    {
1965        auto exp_props = sycl::ext::oneapi::experimental::properties{
1966            sycl::ext::oneapi::experimental::use_root_sync};
1967
1968        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
1969            ->template parallel_for<dpct_kernel_name<class dense_steps_kernel_fd7245>>(
1970                sycl::nd_range<3>(sycl::range(1, 1, 64), sycl::range(1, 1, 64)),
1971                exp_props, [=](sycl::nd_item<3> item_ct1) {
1972                    dense_steps_kernel(cells, n, steps);
1973                });
1974    }
1975    check("dense_steps");
1976}
1977
1978void gdn_conv_l2_multi(const float* history, const float* qkv, const float* conv_w, float* h, int channels,
1979                       int qk_heads, float eps, int n_tok, void* stream, int t_begin, bool commit) {
1980    if (!history || !qkv || !conv_w || !h || channels % S != 0 || n_tok < 1 || n_tok > kVerifyMaxT ||
1981        (commit && (n_tok != 1 || t_begin != 0))) {
1982        std::fprintf(stderr, "gdn_conv_l2_multi: invalid arguments\n");
1983        std::exit(1);
1984    }
1985    {
1986        auto exp_props = sycl::ext::oneapi::experimental::properties{
1987            sycl::ext::oneapi::experimental::use_root_sync};
1988
1989        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
1990            ->template parallel_for<
1991                dpct_kernel_name<class gdn_conv_l2_multi_kernel_b3f737>>(
1992                sycl::nd_range<3>(
1993                    sycl::range(1, (unsigned)n_tok, (unsigned)(channels / S)) *
1994                        sycl::range(1, 1, S),
1995                    sycl::range(1, 1, S)),
1996                exp_props,
1997                [=](sycl::nd_item<3> item_ct1)
1998                    [[sycl::reqd_sub_group_size(32)]] {
1999                        gdn_conv_l2_multi_kernel(
2000                            const_cast<float *>(history), qkv, conv_w, h,
2001                            channels, qk_heads, eps, t_begin, commit);
2002                    });
2003    }
2004    check("gdn_conv_l2_multi");
2005}
2006
2007void gdn_conv_commit(float* history, const float* qkv, int channels, const int32_t* n_keep, void* stream) {
2008    {
2009        auto exp_props = sycl::ext::oneapi::experimental::properties{
2010            sycl::ext::oneapi::experimental::use_root_sync};
2011
2012        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
2013            ->template parallel_for<
2014                dpct_kernel_name<class gdn_conv_commit_kernel_dc1d7f>>(
2015                sycl::nd_range<3>(
2016                    sycl::range(1, 1, (unsigned)((channels + 255) / 256)) *
2017                        sycl::range(1, 1, 256),
2018                    sycl::range(1, 1, 256)),
2019                exp_props, [=](sycl::nd_item<3> item_ct1) {
2020                    gdn_conv_commit_kernel(history, qkv, channels, n_keep);
2021                });
2022    }
2023    check("gdn_conv_commit");
2024}
2025
2026void gdn_ab_multi(const float* x, const uint16_t* w_alpha, const uint16_t* w_beta, const float* dt, const float* ssm_a,
2027                  float* gate, float* beta, int n_embd, int h_v, int n_tok, void* stream) {
2028    if (n_embd % 8 != 0 || n_tok < 1 || n_tok > kVerifyMaxT) {
2029        std::fprintf(stderr, "gdn_ab_multi: invalid arguments\n");
2030        std::exit(1);
2031    }
2032    const unsigned blocks = (unsigned) ((2 * h_v + 1) / 2);
2033    dpct::queue_ptr st = strata::q_of(stream);
2034    switch (n_tok) {
2035    case 1: {
2036        auto exp_props = sycl::ext::oneapi::experimental::properties{
2037            sycl::ext::oneapi::experimental::use_root_sync};
2038
2039        strata::kprof::kp(st, __FILE__, __func__, __LINE__)->template parallel_for<
2040            dpct_kernel_name<class gdn_ab_multi_kernel_34dcce,
2041                             dpct_kernel_scalar<1>, dpct_kernel_scalar<true>>>(
2042            sycl::nd_range<3>(sycl::range(1, 1, blocks) * sycl::range(1, 1, 64),
2043                              sycl::range(1, 1, 64)),
2044            exp_props,
2045            [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {
2046                gdn_ab_multi_kernel<1, true>(x, w_alpha, w_beta, dt, ssm_a,
2047                                             gate, beta, n_embd, h_v, n_tok);
2048            });
2049    } break;
2050    case 2: {
2051        auto exp_props = sycl::ext::oneapi::experimental::properties{
2052            sycl::ext::oneapi::experimental::use_root_sync};
2053
2054        strata::kprof::kp(st, __FILE__, __func__, __LINE__)->template parallel_for<
2055            dpct_kernel_name<class gdn_ab_multi_kernel_34dcce,
2056                             dpct_kernel_scalar<2>, dpct_kernel_scalar<true>>>(
2057            sycl::nd_range<3>(sycl::range(1, 1, blocks) * sycl::range(1, 1, 64),
2058                              sycl::range(1, 1, 64)),
2059            exp_props,
2060            [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {
2061                gdn_ab_multi_kernel<2, true>(x, w_alpha, w_beta, dt, ssm_a,
2062                                             gate, beta, n_embd, h_v, n_tok);
2063            });
2064    } break;
2065    case 3: {
2066        auto exp_props = sycl::ext::oneapi::experimental::properties{
2067            sycl::ext::oneapi::experimental::use_root_sync};
2068
2069        strata::kprof::kp(st, __FILE__, __func__, __LINE__)->template parallel_for<
2070            dpct_kernel_name<class gdn_ab_multi_kernel_34dcce,
2071                             dpct_kernel_scalar<3>, dpct_kernel_scalar<true>>>(
2072            sycl::nd_range<3>(sycl::range(1, 1, blocks) * sycl::range(1, 1, 64),
2073                              sycl::range(1, 1, 64)),
2074            exp_props,
2075            [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {
2076                gdn_ab_multi_kernel<3, true>(x, w_alpha, w_beta, dt, ssm_a,
2077                                             gate, beta, n_embd, h_v, n_tok);
2078            });
2079    } break;
2080    case 4: {
2081        auto exp_props = sycl::ext::oneapi::experimental::properties{
2082            sycl::ext::oneapi::experimental::use_root_sync};
2083
2084        strata::kprof::kp(st, __FILE__, __func__, __LINE__)->template parallel_for<
2085            dpct_kernel_name<class gdn_ab_multi_kernel_34dcce,
2086                             dpct_kernel_scalar<4>, dpct_kernel_scalar<true>>>(
2087            sycl::nd_range<3>(sycl::range(1, 1, blocks) * sycl::range(1, 1, 64),
2088                              sycl::range(1, 1, 64)),
2089            exp_props,
2090            [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {
2091                gdn_ab_multi_kernel<4, true>(x, w_alpha, w_beta, dt, ssm_a,
2092                                             gate, beta, n_embd, h_v, n_tok);
2093            });
2094    } break;
2095    case 5: {
2096        auto exp_props = sycl::ext::oneapi::experimental::properties{
2097            sycl::ext::oneapi::experimental::use_root_sync};
2098
2099        strata::kprof::kp(st, __FILE__, __func__, __LINE__)->template parallel_for<
2100            dpct_kernel_name<class gdn_ab_multi_kernel_34dcce,
2101                             dpct_kernel_scalar<5>, dpct_kernel_scalar<true>>>(
2102            sycl::nd_range<3>(sycl::range(1, 1, blocks) * sycl::range(1, 1, 64),
2103                              sycl::range(1, 1, 64)),
2104            exp_props,
2105            [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {
2106                gdn_ab_multi_kernel<5, true>(x, w_alpha, w_beta, dt, ssm_a,
2107                                             gate, beta, n_embd, h_v, n_tok);
2108            });
2109    } break;
2110    case 6: {
2111        auto exp_props = sycl::ext::oneapi::experimental::properties{
2112            sycl::ext::oneapi::experimental::use_root_sync};
2113
2114        strata::kprof::kp(st, __FILE__, __func__, __LINE__)->template parallel_for<
2115            dpct_kernel_name<class gdn_ab_multi_kernel_34dcce,
2116                             dpct_kernel_scalar<6>, dpct_kernel_scalar<true>>>(
2117            sycl::nd_range<3>(sycl::range(1, 1, blocks) * sycl::range(1, 1, 64),
2118                              sycl::range(1, 1, 64)),
2119            exp_props,
2120            [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {
2121                gdn_ab_multi_kernel<6, true>(x, w_alpha, w_beta, dt, ssm_a,
2122                                             gate, beta, n_embd, h_v, n_tok);
2123            });
2124    } break;
2125    default: {
2126        auto exp_props = sycl::ext::oneapi::experimental::properties{
2127            sycl::ext::oneapi::experimental::use_root_sync};
2128
2129        strata::kprof::kp(st, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class gdn_ab_multi_kernel_34dcce,
2130                                          dpct_kernel_scalar<kVerifyMaxT>,
2131                                          dpct_kernel_scalar<false>>>(
2132            sycl::nd_range<3>(sycl::range(1, 1, blocks) * sycl::range(1, 1, 64),
2133                              sycl::range(1, 1, 64)),
2134            exp_props,
2135            [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {
2136                gdn_ab_multi_kernel<kVerifyMaxT, false>(x, w_alpha, w_beta, dt,
2137                                                        ssm_a, gate, beta,
2138                                                        n_embd, h_v, n_tok);
2139            });
2140    } break;
2141    }
2142    check("gdn_ab_multi");
2143}
2144
2145void gdn_step_norm_groups(const GdnGroups& groups, const float* h, int conv_channels, const float* gate, const float* beta,
2146                          const float* z, const float* gamma, float eps, float* y, int h_k, int h_v, bool commit,
2147                          void* stream) {
2148    if (groups.n < 1 || groups.n > 8 || !h || !gate || !beta || !z || !gamma || !y || h_k <= 0 || h_v % h_k) {
2149        std::fprintf(stderr, "gdn_step_norm_groups: invalid arguments\n");
2150        std::exit(1);
2151    }
2152    for (int i = 0; i < groups.n; ++i)
2153        if (!groups.state[i] || groups.ntok[i] < 1 || groups.ntok[i] > kVerifyMaxT || (commit && !groups.keep[i])) {
2154            std::fprintf(stderr, "gdn_step_norm_groups: invalid group %d\n", i);
2155            std::exit(1);
2156        }
2157    const dpct::dim3 g1((unsigned)h_v, (unsigned)groups.n), b1(S, RG);
2158    const GdnGroups grp = groups;
2159    auto exp_props = sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};
2160    // the kernel gdn_step_norm_multi picks for these calls: a window's rows (all outputs, no keep) or a commit of
2161    // one-row groups (keep, t_out_begin 0)
2162    if (commit)
2163        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class gdn_step_norm_groups_kernel_b1, dpct_kernel_scalar<false>>>(
2164            sycl::nd_range<3>(g1 * b1, b1), exp_props, [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {
2165                gdn_step_norm_multi_kernel<false, false>(nullptr, h, conv_channels, gate, beta, z, gamma, eps, y, h_k,
2166                                                         h_v, 0, nullptr, 0, nullptr, grp);
2167            });
2168    else
2169        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class gdn_step_norm_groups_kernel_b2, dpct_kernel_scalar<true>>>(
2170            sycl::nd_range<3>(g1 * b1, b1), exp_props, [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {
2171                gdn_step_norm_multi_kernel<true, false>(nullptr, h, conv_channels, gate, beta, z, gamma, eps, y, h_k,
2172                                                        h_v, 0, nullptr, 0, nullptr, grp);
2173            });
2174}
2175
2176void launch_b60_gdn_readonly_split_local(float* state,const float* h,int C,
2177 const float* gate,const float* beta,const float* z,const float* gamma,float* y,
2178 int HK,int HV,int T,void* stream);
2179void gdn_commit_state_multi(float* state, const float* h, int C, const float* gate, const float* beta,
2180                            int h_k, int h_v, int n_tok, const int32_t* n_keep, void* stream) {
2181    if (!state || !h || !gate || !beta || !n_keep || h_k <= 0 || h_v % h_k ||
2182        n_tok < 1 || n_tok > kVerifyMaxT)
2183        throw std::invalid_argument("GDN state-only commit arguments");
2184    auto properties = sycl::ext::oneapi::experimental::properties{
2185        sycl::ext::oneapi::experimental::use_root_sync};
2186    strata::q_of(stream)->parallel_for<dpct_kernel_name<class gdn_commit_state_multi_kernel_name>>(
2187        sycl::nd_range<3>(sycl::range(1,1,(unsigned)h_v) * sycl::range(1,RG,S), sycl::range(1,RG,S)),
2188        properties, [=](sycl::nd_item<3>) [[sycl::reqd_sub_group_size(32)]] {
2189            gdn_commit_state_multi_kernel(state,h,C,gate,beta,h_k,h_v,n_keep);
2190        });
2191    check("gdn_commit_state_multi");
2192}
2193
2194void gdn_step_norm_qkreg(float* state, const float* h, int conv_channels, const float* gate, const float* beta,
2195                         const float* z, const float* gamma, float eps, float* y, int h_k, int h_v, int n_tok,
2196                         const int32_t* n_keep, void* stream, int t_out_begin, void* xq_out);
2197void gdn_step_norm_multi(float* state, const float* h, int conv_channels, const float* gate, const float* beta,
2198                         const float* z, const float* gamma, float eps, float* y, int h_k, int h_v, int n_tok,
2199                         const int32_t* n_keep, void* stream, int t_out_begin, void* xq_out) {
2200    GdnQ81* const xq = static_cast<GdnQ81*>(xq_out);   // S26: non-null = also the outputs' q8_1 (STRATA_QFUSE)
2201    if (!state || !h || !gate || !beta || !z || !gamma || !y || h_k <= 0 || h_v % h_k || n_tok < 1 ||
2202        n_tok > kVerifyMaxT) {
2203        std::fprintf(stderr, "gdn_step_norm_multi: invalid arguments\n");
2204        std::exit(1);
2205    }
2206    static const bool b60_decode_pool = [] {
2207        const char* v=std::getenv("STRATA_PRIVATE_B60_NEXT_POOL");return v && v[0]=='1';
2208    }();
2209    if (b60_decode_pool && n_keep==nullptr && t_out_begin==0 && !xq &&
2210        conv_channels==10240 && h_k==16 && h_v==48 && eps==1e-6f && (n_tok == 2 || n_tok == 4)) {
2211        const unsigned device=dpct::get_device_id(strata::q_of(stream)->get_device());
2212        static std::atomic<uint64_t> reported{0};
2213        if(device<8) {
2214            const uint64_t bit=uint64_t(1)<<(device*8+unsigned(n_tok));
2215            if(!(reported.fetch_or(bit,std::memory_order_relaxed)&bit))
2216                std::fprintf(stderr,"[B60_GDN_SPLIT_LOCAL] capture device=%u T=%d\n",device,n_tok);
2217        }
2218        launch_b60_gdn_readonly_split_local(state,h,conv_channels,gate,beta,z,gamma,y,h_k,h_v,n_tok,stream);
2219        check("gdn_step_norm_multi");
2220        return;
2221    }
2222    static const bool qk_reg = strata::bm_default_on("STRATA_GDN_QK_REG", strata::q_of(stream)->get_device(), false);
2223    if (qk_reg && !xq && !n_keep && t_out_begin == 0 &&
2224        h_k == 16 && h_v == 48 && conv_channels == 10240 &&
2225        strata::intel_gpu_gen(strata::q_of(stream)->get_device()) == strata::IntelGpuGen::Battlemage) {
2226        static const bool note = [] {
2227            std::fprintf(stderr, "strata: GDN QK register broadcast enabled (GRF256)\n");
2228            return true;
2229        }();
2230        (void) note;
2231        auto props = sycl::ext::oneapi::experimental::properties{
2232            sycl::ext::oneapi::experimental::use_root_sync,
2233            sycl::ext::intel::experimental::grf_size<256>};
2234        strata::q_of(stream)->parallel_for<dpct_kernel_name<class gdn_qk_register>>(
2235            sycl::nd_range<3>(sycl::range(1, RG, (unsigned) h_v * S), sycl::range(1, RG, S)),
2236            props, [=](sycl::nd_item<3>) [[sycl::reqd_sub_group_size(32)]] {
2237                gdn_step_norm_multi_kernel<true, false, true>(
2238                    state, h, conv_channels, gate, beta, z, gamma, eps, y,
2239                    h_k, h_v, n_tok, nullptr, 0, nullptr);
2240            });
2241        check("gdn QK register");
2242        return;
2243    }
2244    static const bool qk_grf = [] { const char* e = std::getenv("STRATA_SYCL_GDN_QK_GRF256"); return e && e[0] == '1'; }();
2245    if (qk_grf && xq_out == nullptr && n_keep == nullptr && h_k == 16 && h_v == 48 && conv_channels == 10240) {
2246        gdn_step_norm_qkreg(state, h, conv_channels, gate, beta, z, gamma, eps, y,
2247                           h_k, h_v, n_tok, n_keep, stream, t_out_begin, xq_out);
2248        return;
2249    }
2250    static const bool split = [] { const char* v = std::getenv("STRATA_GDN_SPLIT"); return v && v[0] == '1'; }();
2251    // S26: the split runs where it is faster (gfx1151 harness, h_v 48: the commit 8-19% per call; a window of 2+ rows
2252    // 3-13%; one row: no gain, the old kernel stays) - bitwise equal in every case
2253    if (split && (t_out_begin >= n_tok || n_tok - t_out_begin >= 2)) {
2254        const dpct::dim3 grid((unsigned)h_v, S / GS_COLS), block(GS_COLS, RG);
2255        if (t_out_begin >= n_tok) {   // no outputs (the commit): the state only
2256                                      /*
2257                                      DPCT1049: The work-group size passed to the SYCL kernel may
2258                                      exceed the limit. To get the device limit, query
2259                                      info::device::max_work_group_size. Adjust the work-group size if
2260                                      needed.
2261                                      */
2262            auto exp_props = sycl::ext::oneapi::experimental::properties{
2263                sycl::ext::oneapi::experimental::use_root_sync};
2264
2265            strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
2266                ->template parallel_for<
2267                    dpct_kernel_name<class gdn_state_replay_kernel_e4d4c4,
2268                                     dpct_kernel_scalar<kVerifyMaxT>>>(
2269                    sycl::nd_range<3>(grid * block, block), exp_props,
2270                    [=](sycl::nd_item<3> item_ct1) {
2271                        gdn_state_replay_kernel<kVerifyMaxT>(
2272                            state, h, conv_channels, gate, beta, h_k, h_v,
2273                            n_tok, n_keep);
2274                    });
2275        } else {
2276            /*
2277            DPCT1049: The work-group size passed to the SYCL kernel may
2278            exceed the limit. To get the device limit, query
2279            info::device::max_work_group_size. Adjust the work-group size if
2280            needed.
2281            */
2282            {
2283                auto exp_props = sycl::ext::oneapi::experimental::properties{
2284                    sycl::ext::oneapi::experimental::use_root_sync};
2285
2286                strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
2287                    ->template parallel_for<
2288                        dpct_kernel_name<class gdn_step_split_kernel_83c676,
2289                                         dpct_kernel_scalar<true>>>(
2290                        sycl::nd_range<3>(grid * block, block), exp_props,
2291                        [=](sycl::nd_item<3> item_ct1) {
2292                            gdn_step_split_kernel<true>(
2293                                state, h, conv_channels, gate, beta, y, h_k,
2294                                h_v, n_tok, n_keep, t_out_begin);
2295                        });
2296            }
2297            const dpct::dim3 ng((unsigned)h_v, (unsigned)(n_tok - t_out_begin));
2298            /*
2299            DPCT1049: The work-group size passed to the SYCL kernel may
2300            exceed the limit. To get the device limit, query
2301            info::device::max_work_group_size. Adjust the work-group size if
2302            needed.
2303            */
2304            if (xq) {
2305                auto exp_props = sycl::ext::oneapi::experimental::properties{
2306                    sycl::ext::oneapi::experimental::use_root_sync};
2307
2308                strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
2309                    ->template parallel_for<
2310                        dpct_kernel_name<class gdn_out_norm_kernel_a650eb,
2311                                         dpct_kernel_scalar<true>>>(
2312                        sycl::nd_range<3>(ng * sycl::range(1, RG, S),
2313                                          sycl::range(1, RG, S)),
2314                        exp_props,
2315                        [=](sycl::nd_item<3> item_ct1)
2316                            [[sycl::reqd_sub_group_size(32)]] {
2317                                gdn_out_norm_kernel<true>(z, gamma, eps, y, h_v,
2318                                                          n_tok, n_keep,
2319                                                          t_out_begin, xq);
2320                            });
2321            }
2322            /*
2323            DPCT1049: The work-group size passed to the SYCL kernel may
2324            exceed the limit. To get the device limit, query
2325            info::device::max_work_group_size. Adjust the work-group size if
2326            needed.
2327            */
2328            else {
2329                auto exp_props = sycl::ext::oneapi::experimental::properties{
2330                    sycl::ext::oneapi::experimental::use_root_sync};
2331
2332                strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
2333                    ->template parallel_for<
2334                        dpct_kernel_name<class gdn_out_norm_kernel_f6dfab,
2335                                         dpct_kernel_scalar<false>>>(
2336                        sycl::nd_range<3>(ng * sycl::range(1, RG, S),
2337                                          sycl::range(1, RG, S)),
2338                        exp_props,
2339                        [=](sycl::nd_item<3> item_ct1)
2340                            [[sycl::reqd_sub_group_size(32)]] {
2341                                gdn_out_norm_kernel<false>(
2342                                    z, gamma, eps, y, h_v, n_tok, n_keep,
2343                                    t_out_begin, nullptr);
2344                            });
2345            }
2346        }
2347        check("gdn_step_norm_multi (split)");
2348        return;
2349    }
2350    static const bool commit_split = [] {
2351        const char* e = std::getenv("STRATA_GDN_COMMIT_SPLIT");
2352        return !e || e[0] != '0';
2353    }();
2354    if (commit_split && n_keep != nullptr && t_out_begin >= n_tok) {
2355        {
2356            auto exp_props = sycl::ext::oneapi::experimental::properties{
2357                sycl::ext::oneapi::experimental::use_root_sync};
2358
2359            strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
2360                ->template parallel_for<
2361                    dpct_kernel_name<class gdn_step_commit_kernel_5d9da7>>(
2362                    sycl::nd_range<3>(sycl::range(1, 4u, (unsigned)h_v) *
2363                                          sycl::range(1, RG, 32),
2364                                      sycl::range(1, RG, 32)),
2365                    exp_props, [=](sycl::nd_item<3> item_ct1) {
2366                        gdn_step_commit_kernel(state, h, conv_channels, gate,
2367                                               beta, h_k, h_v, n_keep);
2368                    });
2369        }
2370        check("gdn_step_commit");
2371        return;
2372    }
2373    const dpct::dim3 g1((unsigned)h_v), b1(S, RG);
2374    const bool all_out = n_keep == nullptr && t_out_begin <= 0;
2375    if (xq && t_out_begin < n_tok) {
2376        /*
2377        DPCT1049: The work-group size passed to the SYCL kernel may exceed
2378        the limit. To get the device limit, query
2379        info::device::max_work_group_size. Adjust the work-group size if needed.
2380        */
2381        if (all_out) {
2382            auto exp_props = sycl::ext::oneapi::experimental::properties{
2383                sycl::ext::oneapi::experimental::use_root_sync};
2384
2385            strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
2386                ->template parallel_for<dpct_kernel_name<
2387                    class gdn_step_norm_multi_kernel_42ae26,
2388                    dpct_kernel_scalar<true>, dpct_kernel_scalar<true>>>(
2389                    sycl::nd_range<3>(g1 * b1, b1), exp_props,
2390                    [=](sycl::nd_item<3> item_ct1)
2391                        [[sycl::reqd_sub_group_size(32)]] {
2392                            gdn_step_norm_multi_kernel<true, true>(
2393                                state, h, conv_channels, gate, beta, z, gamma,
2394                                eps, y, h_k, h_v, n_tok, nullptr, 0, xq);
2395                        });
2396        }
2397        /*
2398        DPCT1049: The work-group size passed to the SYCL kernel may exceed
2399        the limit. To get the device limit, query
2400        info::device::max_work_group_size. Adjust the work-group size if needed.
2401        */
2402        else {
2403            auto exp_props = sycl::ext::oneapi::experimental::properties{
2404                sycl::ext::oneapi::experimental::use_root_sync};
2405
2406            strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
2407                ->template parallel_for<dpct_kernel_name<
2408                    class gdn_step_norm_multi_kernel_42ae26,
2409                    dpct_kernel_scalar<false>, dpct_kernel_scalar<true>>>(
2410                    sycl::nd_range<3>(g1 * b1, b1), exp_props,
2411                    [=](sycl::nd_item<3> item_ct1)
2412                        [[sycl::reqd_sub_group_size(32)]] {
2413                            gdn_step_norm_multi_kernel<false, true>(
2414                                state, h, conv_channels, gate, beta, z, gamma,
2415                                eps, y, h_k, h_v, n_tok, n_keep, t_out_begin,
2416                                xq);
2417                        });
2418        }
2419    } else if (all_out) {
2420        /*
2421        DPCT1049: The work-group size passed to the SYCL kernel may exceed
2422        the limit. To get the device limit, query
2423        info::device::max_work_group_size. Adjust the work-group size if needed.
2424        */
2425        auto exp_props = sycl::ext::oneapi::experimental::properties{
2426            sycl::ext::oneapi::experimental::use_root_sync};
2427
2428        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
2429            ->template parallel_for<dpct_kernel_name<
2430                class gdn_step_norm_multi_kernel_42ae26,
2431                dpct_kernel_scalar<true>, dpct_kernel_scalar<false>>>(
2432                sycl::nd_range<3>(g1 * b1, b1), exp_props,
2433                [=](sycl::nd_item<3> item_ct1)
2434                    [[sycl::reqd_sub_group_size(32)]] {
2435                        gdn_step_norm_multi_kernel<true, false>(
2436                            state, h, conv_channels, gate, beta, z, gamma, eps,
2437                            y, h_k, h_v, n_tok, nullptr, 0, nullptr);
2438                    });
2439    } else {
2440        /*
2441        DPCT1049: The work-group size passed to the SYCL kernel may exceed
2442        the limit. To get the device limit, query
2443        info::device::max_work_group_size. Adjust the work-group size if needed.
2444        */
2445        auto exp_props = sycl::ext::oneapi::experimental::properties{
2446            sycl::ext::oneapi::experimental::use_root_sync};
2447
2448        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
2449            ->template parallel_for<dpct_kernel_name<
2450                class gdn_step_norm_multi_kernel_42ae26,
2451                dpct_kernel_scalar<false>, dpct_kernel_scalar<false>>>(
2452                sycl::nd_range<3>(g1 * b1, b1), exp_props,
2453                [=](sycl::nd_item<3> item_ct1)
2454                    [[sycl::reqd_sub_group_size(32)]] {
2455                        gdn_step_norm_multi_kernel<false, false>(
2456                            state, h, conv_channels, gate, beta, z, gamma, eps,
2457                            y, h_k, h_v, n_tok, n_keep, t_out_begin, nullptr);
2458                    });
2459    }
2460    check("gdn_step_norm_multi");
2461}
2462
2463namespace {
2464__dpct_inline__ void wait_flag_ge_kernel(const volatile uint32_t *flag,
2465                                         uint32_t value, uint32_t spin_max) {
2466    for (uint32_t spin = 0; spin < spin_max && strata::sys_load(flag) < value; ++spin) strata_spin_pause();
2467    /*
2468    DPCT1078: Consider replacing memory_order::acq_rel with
2469    memory_order::seq_cst for correctness if strong memory order restrictions
2470    are needed.
2471    */
2472    sycl::atomic_fence(sycl::memory_order::acq_rel, sycl::memory_scope::system);
2473}
2474}  // namespace
2475
2476namespace {
2477// one thread per window entry: up to kVerifyMaxT tokens x 10 routed experts (80), so 128 (#646 had 64: a window of
2478// 7+ tokens lost its last entries)
2479constexpr int kResidentPlanMax = 128;
2480static_assert(kVerifyMaxT * 10 <= kResidentPlanMax, "resident_plan: one thread per entry");
2481// the parallel scan keeps one partial sum per warp in s_wsum[4] and packs (entries << 16 | groups) in an int
2482static_assert(kResidentPlanMax <= 128 && kResidentPlanMax % 32 == 0, "resident_plan: at most 4 warps");
2483static_assert(kResidentPlanMax < 32768, "resident_plan: the packed entry count must stay below 2^15");
2484/*
2485DPCT1110: The total declared local variable size in device function
2486resident_plan_kernel exceeds 128 bytes and may cause high register pressure.
2487Consult with your hardware vendor to find the total register size available and
2488adjust the code, or use smaller sub-group size to avoid high register pressure.
2489*/
2490__dpct_inline__ void
2491resident_plan_kernel(const int32_t *__restrict__ ids, int n, int k,
2492                     const int32_t *__restrict__ res, int n_expert,
2493                     const uint8_t *cache_base,
2494                     const unsigned long long *slot_off, long long blob,
2495                     int32_t *__restrict__ pl, long long capx, uint32_t *skip,
2496                     uint32_t ring, const unsigned long long *__restrict__ mir,
2497                     volatile uint32_t *plan_err, int32_t *usage) {
2498    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
2499auto &s_ids = *sycl::ext::oneapi::group_local_memory_for_overwrite<
2500    int32_t[kResidentPlanMax]>(
2501    sycl::ext::oneapi::this_work_item::get_work_group<3>());
2502    auto &s_excl = *sycl::ext::oneapi::group_local_memory_for_overwrite<
2503        int32_t[kResidentPlanMax]>(
2504        sycl::ext::oneapi::this_work_item::get_work_group<3>());
2505    auto &s_wsum =
2506        *sycl::ext::oneapi::group_local_memory_for_overwrite<int32_t[4]>(
2507            sycl::ext::oneapi::this_work_item::get_work_group<3>());
2508    auto &s_bad = *sycl::ext::oneapi::group_local_memory_for_overwrite<int>(
2509        sycl::ext::oneapi::this_work_item::get_work_group<3>());
2510    const int tid = item_ct1.get_local_id(2);
2511    if (tid == 0) s_bad = 0;
2512    item_ct1.barrier(sycl::access::fence_space::local_space);
2513
2514    int32_t eid = -1;
2515    int32_t slot = -1;
2516    unsigned long long maddr = 0;   // SYCL port: a host-mirrored expert (not in VRAM): its pinned mirror, read over PCIe
2517    if (tid < n) {
2518        eid = ids[tid];
2519        s_ids[tid] = eid;
2520        slot = (eid >= 0 && eid < n_expert) ? res[eid] : -1;
2521        if (slot < 0 && eid >= 0 && eid < n_expert && mir != nullptr) maddr = mir[eid];
2522        if (usage != nullptr && eid >= 0 && eid < n_expert)   // the adaptive tier's routing counts (device side)
2523            sycl::atomic_ref<int32_t, sycl::memory_order::relaxed, sycl::memory_scope::device,
2524                             sycl::access::address_space::global_space>(usage[eid]).fetch_add(1);
2525        if (slot < 0 && maddr == 0)
2526            dpct::atomic_fetch_or<sycl::access::address_space::generic_space>(
2527                &s_bad, 1);
2528    }
2529    item_ct1.barrier(sycl::access::fence_space::local_space);
2530    if (s_bad) {
2531        if (tid == 0 && skip != nullptr) *skip = 0;
2532        if (tid == 0 && skip == nullptr) {   // #871: the all-resident graph has no host plan to fall back on
2533            pl[0] = 0; pl[1] = 0; pl[2] = 0;   // an empty plan: no expert runs on a stale pointer
2534            /*
2535            DPCT1078: Consider replacing memory_order::acq_rel with
2536            memory_order::seq_cst for correctness if strong memory order
2537            restrictions are needed.
2538            */
2539            if (plan_err != nullptr) {
2540                    *plan_err = 1;
2541                    sycl::atomic_fence(sycl::memory_order::acq_rel,
2542                                       sycl::memory_scope::system);
2543            }
2544        }
2545        return;
2546    }
2547
2548    int first_j = tid;
2549    int rank_in_group = 0;
2550    int count_same = 0;
2551    if (tid < n) {
2552#pragma unroll
2553        for (int j = 0; j < n; ++j) {
2554            if (s_ids[j] == eid) {
2555                if (j < first_j) first_j = j;
2556                if (j < tid) ++rank_in_group;
2557                ++count_same;
2558            }
2559        }
2560    }
2561    const bool is_first = (tid < n && first_j == tid && (slot >= 0 || maddr != 0));
2562    const int my_cnt = is_first ? count_same : 0;
2563    const int my_pack = (my_cnt << 16) | (is_first ? 1 : 0);
2564    const int lane = tid & 31;
2565    const int warp = tid >> 5;
2566    const int n_warps = item_ct1.get_local_range(2) / 32;
2567    int pref = my_pack;
2568#pragma unroll
2569    for (int d = 1; d < 32; d <<= 1) {
2570        /*
2571        DPCT1108: '__shfl_up_sync' was migrated with the experimental
2572        feature masked sub_group function which may not be supported by all
2573        compilers or runtimes. You may need to adjust the code.
2574        */
2575        const int up = dpct::experimental::shift_sub_group_right(
2576            0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(),
2577            pref, d);
2578        if (lane >= d) pref += up;
2579    }
2580    s_excl[tid] = pref - my_pack;
2581    if (lane == 31) {
2582        s_wsum[warp] = pref;
2583    }
2584    /*
2585    DPCT1065: Consider replacing sycl::nd_item::barrier() with
2586    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
2587    performance if there is no access to global memory.
2588    */
2589    item_ct1.barrier();
2590
2591    int32_t* counts = pl;
2592    int32_t* start = pl + 4;
2593    int32_t* dst = start + capx + 1;
2594    int32_t* tok = dst + capx;
2595    const long long ptr_off = ((4 + (capx + 1) + 2 * capx) + 1) & ~1ll;
2596    unsigned long long* ptr = (unsigned long long*) (pl + ptr_off);
2597    int32_t* start2 = pl + ptr_off + 4 * capx;
2598
2599    if (is_first) {
2600        int tot = s_excl[tid];
2601#pragma unroll
2602        for (int w = 0; w < n_warps; ++w) {
2603            if (w < warp) tot += s_wsum[w];
2604        }
2605        const int grp_idx = tot & 0xffff;
2606        const int ent_start = tot >> 16;
2607        ptr[grp_idx] = slot >= 0 ? (unsigned long long) (cache_base + (slot_off ? (size_t) slot_off[slot] : (size_t) slot * (size_t) blob))
2608                                 : maddr;
2609        start[grp_idx] = ent_start;
2610    }
2611    if (tid < n) {
2612        const int fj_warp = first_j >> 5;
2613        int fj_tot = s_excl[first_j];
2614#pragma unroll
2615        for (int w = 0; w < n_warps; ++w) {
2616            if (w < fj_warp) fj_tot += s_wsum[w];
2617        }
2618        const int out_idx = (fj_tot >> 16) + rank_in_group;
2619        dst[out_idx] = tid;
2620        tok[out_idx] = tid / k;
2621    }
2622    if (tid == 0) {
2623        int groups = 0;
2624        for (int w = 0; w < n_warps; ++w) groups += s_wsum[w];
2625        groups &= 0xffff;
2626        start[groups] = n;
2627        start2[0] = n;
2628        counts[0] = groups;
2629        counts[1] = n;
2630        counts[2] = 0;
2631        if (skip != nullptr) {
2632            /*
2633            DPCT1078: Consider replacing memory_order::acq_rel with
2634            memory_order::seq_cst for correctness if strong memory order
2635            restrictions are needed.
2636            */
2637            sycl::atomic_fence(sycl::memory_order::acq_rel,
2638                               sycl::memory_scope::device);
2639            strata::sys_store(skip, ring);
2640        }
2641    }
2642}
2643// The same plan in one block of 128 threads (n <= 128): thread i owns entry i. Groups are the distinct experts in
2644// order of first occurrence; group g's entries are its occurrences in increasing i - exactly the loop above
2645// (S26: the one-thread loop took ~44 us per call on gfx1151, 48 per window).
2646void resident_plan_par_kernel(const int32_t* __restrict__ ids, int n, int k, const int32_t* __restrict__ res,
2647                                         int n_expert, const uint8_t* cache_base, const unsigned long long* slot_off,
2648                                         long long blob, int32_t* __restrict__ pl, long long capx, uint32_t* skip,
2649                                         uint32_t ring) {
2650    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
2651auto &s_id = *sycl::ext::oneapi::group_local_memory_for_overwrite<int32_t[128]>(
2652    sycl::ext::oneapi::this_work_item::get_work_group<3>());
2653    auto &s_first =
2654        *sycl::ext::oneapi::group_local_memory_for_overwrite<int[128]>(
2655            sycl::ext::oneapi::this_work_item::get_work_group<3>());
2656    auto &s_size =
2657        *sycl::ext::oneapi::group_local_memory_for_overwrite<int[128]>(
2658            sycl::ext::oneapi::this_work_item::get_work_group<3>());
2659    auto &s_bad = *sycl::ext::oneapi::group_local_memory_for_overwrite<int>(
2660        sycl::ext::oneapi::this_work_item::get_work_group<3>());
2661    const int i = item_ct1.get_local_id(2);
2662    if (i == 0) s_bad = 0;
2663    item_ct1.barrier(sycl::access::fence_space::local_space);
2664    int32_t e = -1;
2665    if (i < n) {
2666        e = ids[i];
2667        s_id[i] = e;
2668        if (e < 0 || e >= n_expert || res[e] < 0) s_bad = 1;
2669    }
2670    item_ct1.barrier(sycl::access::fence_space::local_space);
2671    if (s_bad) { if (i == 0) *skip = 0; return; }
2672    int first = i, rank = 0, size = 0;
2673    if (i < n) {
2674        for (int j = 0; j < n; ++j) {
2675            const bool same = s_id[j] == e;
2676            if (same && j < first) first = j;
2677            if (same && j < i) ++rank;
2678            size += same;
2679        }
2680    }
2681    if (i < n) { s_first[i] = first; s_size[i] = size; }
2682    /*
2683    DPCT1065: Consider replacing sycl::nd_item::barrier() with
2684    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
2685    performance if there is no access to global memory.
2686    */
2687    item_ct1.barrier();
2688    int32_t* counts = pl;
2689    int32_t* start = pl + 4;
2690    int32_t* dst = start + capx + 1;
2691    int32_t* tok = dst + capx;
2692    const long long ptr_off = ((4 + (capx + 1) + 2 * capx) + 1) & ~1ll;
2693    unsigned long long* ptr = (unsigned long long*) (pl + ptr_off);
2694    int32_t* start2 = pl + ptr_off + 4 * capx;
2695    if (i < n) {
2696        // group of entry i = the number of first occurrences before `first`; its start = their sizes' sum
2697        int group = 0, gstart = 0;
2698#pragma unroll
2699        for (int j = 0; j < first; ++j)
2700            if (s_first[j] == j) { ++group; gstart += s_size[j]; }
2701        if (i == first) {
2702            const int32_t slot = res[e];
2703            ptr[group] = (unsigned long long) (cache_base + (slot_off ? (size_t) slot_off[slot] : (size_t) slot * (size_t) blob));
2704            start[group] = gstart;
2705        }
2706        dst[gstart + rank] = i;
2707        tok[gstart + rank] = i / k;
2708        if (i == 0) {
2709            int groups = 0;
2710#pragma unroll
2711            for (int j = 0; j < n; ++j) groups += s_first[j] == j;
2712            start[groups] = n;
2713            start2[0] = n;
2714            counts[0] = groups;
2715            counts[1] = n;
2716            counts[2] = 0;
2717        }
2718    }
2719    /*
2720    DPCT1078: Consider replacing memory_order::acq_rel with
2721    memory_order::seq_cst for correctness if strong memory order restrictions
2722    are needed.
2723    */
2724    sycl::atomic_fence(sycl::memory_order::acq_rel, sycl::memory_scope::device);
2725    /*
2726    DPCT1065: Consider replacing sycl::nd_item::barrier() with
2727    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
2728    performance if there is no access to global memory.
2729    */
2730    item_ct1.barrier();
2731    if (i == 0) *skip = ring;
2732}
2733__dpct_inline__ void wait_flag_ge_or_kernel(const volatile uint32_t *flag,
2734                                            uint32_t value,
2735                                            const volatile uint32_t *skip, uint32_t spin_max) {
2736    if (strata::sys_load(skip) == value) return;
2737    for (uint32_t spin = 0; spin < spin_max && strata::sys_load(flag) < value; ++spin) strata_spin_pause();
2738    /*
2739    DPCT1078: Consider replacing memory_order::acq_rel with
2740    memory_order::seq_cst for correctness if strong memory order restrictions
2741    are needed.
2742    */
2743    sycl::atomic_fence(sycl::memory_order::acq_rel, sycl::memory_scope::system);
2744}
2745__dpct_inline__ void copy_i32_unless_kernel(int32_t *__restrict__ dst,
2746                                            const volatile int32_t *src, int n,
2747                                            const uint32_t *skip,
2748                                            uint32_t value) {
2749    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
2750    if (strata::sys_load(skip) == value) return;
2751#pragma unroll
2752    for (int i = item_ct1.get_local_id(2); i < n;
2753         i += item_ct1.get_local_range(2)) dst[i] = src[i];
2754}
2755/*
2756DPCT1052: SYCL does not support the member access for a volatile qualified
2757vector type. The volatile qualifier was removed. You may need to rewrite the
2758code.
2759*/
2760__dpct_inline__ void copy_or_zero_kernel(sycl::float4 *__restrict__ dst,
2761                                         const sycl::float4 *src, long long n4,
2762                                         const uint32_t *skip, uint32_t value, bool pair) {
2763    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
2764    const bool zero = *skip == value;
2765#pragma unroll
2766    for (long long i =
2767             (long long)item_ct1.get_group(2) * item_ct1.get_local_range(2) +
2768             item_ct1.get_local_id(2);
2769         i < n4; i += (long long)item_ct1.get_group_range(2) *
2770                      item_ct1.get_local_range(2))
2771        dst[i] = zero ? sycl::float4(0.f, 0.f, 0.f, 0.f)
2772                      : (pair ? strata::load_mapped_float4(src + i) : const_cast<const sycl::float4 *>(src)[i]);
2773}
2774}  // namespace
2775
2776namespace {
2777const int32_t* g_mirror_res = nullptr;
2778const unsigned long long* g_mirror_table = nullptr;
2779int32_t* g_usage = nullptr;
2780long long g_mirror_entries = 0;   // 0: unchecked
2781// #1980: the layer slice `res_layer` belongs to the table the mirror was set for (a later stage passes its own)
2782bool in_mirror_table(const int32_t* res_layer) {
2783    if (g_mirror_res == nullptr || res_layer < g_mirror_res) return false;
2784    return g_mirror_entries <= 0 || res_layer - g_mirror_res < g_mirror_entries;
2785}
2786}
2787void resident_plan_set_mirror(const int32_t* d_res, const unsigned long long* mirror_table, int32_t* usage, long long entries) {
2788    g_mirror_entries = entries;
2789    g_usage = usage;
2790    g_mirror_res = d_res;
2791    g_mirror_table = mirror_table;
2792}
2793void resident_plan(const int32_t* ids, int n_entries, int k, const int32_t* res_layer, int n_expert,
2794                   const uint8_t* cache_base, const unsigned long long* slot_off, long long blob, int32_t* plan,
2795                   long long capx, uint32_t* skip, uint32_t ring, void* stream, uint32_t* plan_err) {
2796    const unsigned long long* mir = nullptr;   // SYCL port: the layer's slice of the host-mirror table, if any
2797    int32_t* use = nullptr;                    // the layer's slice of the device routing counts, if on
2798    if (g_mirror_table != nullptr && in_mirror_table(res_layer)) mir = g_mirror_table + (res_layer - g_mirror_res);
2799    if (g_usage != nullptr && in_mirror_table(res_layer)) use = g_usage + (res_layer - g_mirror_res);
2800    static const bool compact = strata::bm_default_on("STRATA_RESIDENT_PLAN_COMPACT", strata::q_of(stream)->get_device(), false);
2801    const int threads = compact ? std::max(32, ((n_entries + 31) / 32) * 32) : kResidentPlanMax;
2802    {
2803        auto exp_props = sycl::ext::oneapi::experimental::properties{
2804            sycl::ext::oneapi::experimental::use_root_sync};
2805
2806        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
2807            ->template parallel_for<dpct_kernel_name<class resident_plan_kernel_db6b7a>>(
2808                sycl::nd_range<3>(sycl::range(1, 1, threads),
2809                                  sycl::range(1, 1, threads)),
2810                exp_props,
2811                [=](sycl::nd_item<3> item_ct1)
2812                    [[sycl::reqd_sub_group_size(32)]] {
2813                        resident_plan_kernel(
2814                            ids, n_entries, k, res_layer, n_expert, cache_base,
2815                            slot_off, blob, plan, capx, skip, ring, mir, plan_err, use);
2816                    });
2817    }
2818    check("resident_plan");
2819}
2820void wait_flag_ge_or(const uint32_t* flag, uint32_t value, const uint32_t* skip, void* stream) {
2821    const uint32_t spin_max = strata::spin_max(*strata::q_of(stream));
2822    {
2823        auto exp_props = sycl::ext::oneapi::experimental::properties{
2824            sycl::ext::oneapi::experimental::use_root_sync};
2825
2826        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
2827            ->template parallel_for<
2828                dpct_kernel_name<class wait_flag_ge_or_kernel_2b2de3>>(
2829                sycl::nd_range<3>(sycl::range(1, 1, 1), sycl::range(1, 1, 1)),
2830                exp_props, [=](sycl::nd_item<3> item_ct1) {
2831                    wait_flag_ge_or_kernel(flag, value, skip, spin_max);
2832                });
2833    }
2834    check("wait_flag_ge_or");
2835}
2836void copy_i32_from_mapped_unless(int32_t* dst, const int32_t* src, long long n, const uint32_t* skip, uint32_t value,
2837                                 void* stream) {
2838    if (n <= 0) return;
2839    {
2840        auto exp_props = sycl::ext::oneapi::experimental::properties{
2841            sycl::ext::oneapi::experimental::use_root_sync};
2842
2843        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
2844            ->template parallel_for<
2845                dpct_kernel_name<class copy_i32_unless_kernel_d9d761>>(
2846                sycl::nd_range<3>(sycl::range(1, 1, 128),
2847                                  sycl::range(1, 1, 128)),
2848                exp_props, [=](sycl::nd_item<3> item_ct1) {
2849                    copy_i32_unless_kernel(dst, (const volatile int32_t *)src,
2850                                           (int)n, skip, value);
2851                });
2852    }
2853    check("copy_i32_from_mapped_unless");
2854}
2855void copy_or_zero_from_mapped(float* dst, const float* src, long long n, const uint32_t* skip, uint32_t value,
2856                              void* stream) {
2857    if (n <= 0) return;
2858    const long long n4 = n / 4;
2859    const bool pair = strata::a770_fast();
2860    const int blocks = (int) ((n4 + 255) / 256 < 64 ? (n4 + 255) / 256 : 64);
2861    {
2862        auto exp_props = sycl::ext::oneapi::experimental::properties{
2863            sycl::ext::oneapi::experimental::use_root_sync};
2864
2865        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
2866            ->template parallel_for<dpct_kernel_name<class copy_or_zero_kernel_5ef081>>(
2867                sycl::nd_range<3>(sycl::range(1, 1, blocks) *
2868                                      sycl::range(1, 1, 256),
2869                                  sycl::range(1, 1, 256)),
2870                exp_props, [=](sycl::nd_item<3> item_ct1) {
2871                    copy_or_zero_kernel((sycl::float4 *)dst,
2872                                        (const sycl::float4 *)src, n4,
2873                                        skip, value, pair);
2874                });
2875    }
2876    check("copy_or_zero_from_mapped");
2877}
2878
2879void wait_flag_ge(const uint32_t* flag, uint32_t value, void* stream) {
2880    const uint32_t spin_max = strata::spin_max(*strata::q_of(stream));
2881    {
2882        auto exp_props = sycl::ext::oneapi::experimental::properties{
2883            sycl::ext::oneapi::experimental::use_root_sync};
2884
2885        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
2886            ->template parallel_for<dpct_kernel_name<class wait_flag_ge_kernel_d7debf>>(
2887                sycl::nd_range<3>(sycl::range(1, 1, 1), sycl::range(1, 1, 1)),
2888                exp_props, [=](sycl::nd_item<3> item_ct1) {
2889                    wait_flag_ge_kernel(flag, value, spin_max);
2890                });
2891    }
2892    check("wait_flag_ge");
2893}
2894
2895void embedding_gather_dev(const uint8_t* codes, const float* scales, const float* offsets, const int32_t* tokens,
2896                          int n_tok, int64_t n, int code_bits, int code_bias, int group_elems, uint64_t row_codes,
2897                          uint64_t row_groups, float* out, void* stream) {
2898    {
2899        auto exp_props = sycl::ext::oneapi::experimental::properties{
2900            sycl::ext::oneapi::experimental::use_root_sync};
2901
2902        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
2903            ->template parallel_for<
2904                dpct_kernel_name<class embedding_gather_dev_kernel_600016>>(
2905                sycl::nd_range<3>(sycl::range(1, (unsigned)n_tok,
2906                                              (unsigned)((n + 255) / 256)) *
2907                                      sycl::range(1, 1, 256),
2908                                  sycl::range(1, 1, 256)),
2909                exp_props, [=](sycl::nd_item<3> item_ct1) {
2910                    embedding_gather_dev_kernel(
2911                        codes, scales, offsets, tokens, n, code_bits, code_bias,
2912                        group_elems, row_codes, row_groups, out);
2913                });
2914    }
2915    check("embedding_gather_dev");
2916}
2917
2918void broadcast_streams(const float* x, float* R, int64_t n_embd, int hc, int n_tok, void* stream) {
2919    {
2920        auto exp_props = sycl::ext::oneapi::experimental::properties{
2921            sycl::ext::oneapi::experimental::use_root_sync};
2922
2923        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
2924            ->template parallel_for<
2925                dpct_kernel_name<class broadcast_streams_kernel_aa4f6f>>(
2926                sycl::nd_range<3>(
2927                    sycl::range(1, (unsigned)n_tok,
2928                                (unsigned)((n_embd * hc + 255) / 256)) *
2929                        sycl::range(1, 1, 256),
2930                    sycl::range(1, 1, 256)),
2931                exp_props, [=](sycl::nd_item<3> item_ct1) {
2932                    broadcast_streams_kernel(x, R, n_embd, hc);
2933                });
2934    }
2935    check("broadcast_streams");
2936}
2937
2938void copy_indexed(float* dst, const float* src, int64_t stride, const int32_t* index, int64_t n, void* stream) {
2939    const unsigned blocks = (unsigned) ((n + 255) / 256 < 64 ? (n + 255) / 256 : 64);
2940    {
2941        auto exp_props = sycl::ext::oneapi::experimental::properties{
2942            sycl::ext::oneapi::experimental::use_root_sync};
2943
2944        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
2945            ->template parallel_for<dpct_kernel_name<class copy_indexed_kernel_b12e23>>(
2946                sycl::nd_range<3>(sycl::range(1, 1, blocks) *
2947                                      sycl::range(1, 1, 256),
2948                                  sycl::range(1, 1, 256)),
2949                exp_props, [=](sycl::nd_item<3> item_ct1) {
2950                    copy_indexed_kernel(dst, src, stride, index, n);
2951                });
2952    }
2953    check("copy_indexed");
2954}
2955
2956// Opt-in GPU stage timestamps. DG2 has no comparable device-wide clock, so
2957// read a live host USM clock uncached (the fork's gpu_stamp implementation).
2958// The writer is joined before runtime teardown and exists only in profile mode.
2959namespace {
2960uint64_t profile_now_ns() {
2961    return std::chrono::duration_cast<std::chrono::nanoseconds>(
2962        std::chrono::steady_clock::now().time_since_epoch()).count();
2963}
2964struct ProfileHostClock {
2965    sycl::context context;
2966    uint64_t* word;
2967    std::atomic<bool> stop{false};
2968    std::thread writer;
2969    explicit ProfileHostClock(const sycl::queue& q) : context(q.get_context()),
2970        word(sycl::malloc_host<uint64_t>(8, context)) {
2971        if (!word) throw std::runtime_error("gpu_stamp: host clock allocation failed");
2972        __atomic_store_n(word, profile_now_ns(), __ATOMIC_RELEASE);
2973        writer = std::thread([this] {
2974            while (!stop.load(std::memory_order_relaxed)) {
2975                __atomic_store_n(word, profile_now_ns(), __ATOMIC_RELEASE);
2976                for (int i = 0; i < 8; ++i) __builtin_ia32_pause();
2977            }
2978        });
2979    }
2980    ~ProfileHostClock() {
2981        stop.store(true, std::memory_order_relaxed);
2982        if (writer.joinable()) writer.join();
2983        // Keep the word alive until context teardown, as in the fork: a graph
2984        // may still retain its pointer when process-level statics are destroyed.
2985    }
2986};
2987uint64_t* profile_clock_word(const sycl::queue& q) {
2988    static std::mutex mu;
2989    static std::vector<std::unique_ptr<ProfileHostClock>> clocks;
2990    std::lock_guard<std::mutex> lock(mu);
2991    for (const auto& clock : clocks) if (clock->context == q.get_context()) return clock->word;
2992    clocks.push_back(std::make_unique<ProfileHostClock>(q));
2993    return clocks.back()->word;
2994}
2995}
2996
2997void gpu_stamp(unsigned long long* buf, int i, void* stream) {
2998    auto& q = *strata::q_of(stream);
2999    uint64_t* word = profile_clock_word(q);
3000    strata::kprof::kp(&q, __FILE__, __func__, __LINE__)->single_task([=] {
3001        sycl::atomic_fence(sycl::memory_order::acquire, sycl::memory_scope::system);
3002        buf[i] = strata::sys_load_mapped(word);
3003    });
3004}
3005
3006class B60GdnReadonlySplitLocal;
3007class B60GdnReadonlySplitLocalNorm;
3008void launch_b60_gdn_readonly_split_local(float* state,const float* h,int C,
3009 const float* gate,const float* beta,const float* z,const float* gamma,float* y,
3010 int HK,int HV,int T,void* stream){
3011  const auto props=sycl::ext::oneapi::experimental::properties{
3012   sycl::ext::oneapi::experimental::use_root_sync};
3013  auto* q=strata::q_of(stream);
3014  q->parallel_for<B60GdnReadonlySplitLocal>(
3015   sycl::nd_range<3>(sycl::range<3>(1,4*RG,size_t(HV)*GS_COLS),sycl::range<3>(1,RG,GS_COLS)),
3016   props,[=](sycl::nd_item<3>) {
3017    b60_gdn_split_local_kernel<true>(state,h,C,gate,beta,y,HK,HV,T,nullptr,0);
3018   });
3019  q->parallel_for<B60GdnReadonlySplitLocalNorm>(
3020   sycl::nd_range<3>(sycl::range<3>(1,T*RG,size_t(HV)*S),sycl::range<3>(1,RG,S)),
3021   props,[=](sycl::nd_item<3>) [[sycl::reqd_sub_group_size(32)]] {
3022    gdn_out_norm_kernel<false>(z,gamma,1e-6f,y,HV,T,nullptr,0,nullptr);
3023   });
3024}
3025
3026void gdn_step_norm_qkreg(float* state, const float* h, int conv_channels, const float* gate, const float* beta,
3027                         const float* z, const float* gamma, float eps, float* y, int h_k, int h_v, int n_tok,
3028                         const int32_t* n_keep, void* stream, int t_out_begin, void* xq_out) {
3029    if (xq_out != nullptr) throw std::invalid_argument("SYCL gdn_step_norm_qkreg: fused q8_1 output is not implemented");
3030    if (!state || !h || !gate || !beta || !z || !gamma || !y || h_k <= 0 || h_v % h_k || n_tok < 1 ||
3031        n_tok > kVerifyMaxT) {
3032        std::fprintf(stderr, "gdn_step_norm_qkreg: invalid arguments\n");
3033        std::exit(1);
3034    }
3035    /*
3036    DPCT1049: The work-group size passed to the SYCL kernel may exceed the
3037    limit. To get the device limit, query info::device::max_work_group_size.
3038    Adjust the work-group size if needed.
3039    */
3040    {
3041        auto exp_props = sycl::ext::oneapi::experimental::properties{
3042            sycl::ext::oneapi::experimental::use_root_sync,sycl::ext::intel::experimental::grf_size<256>};
3043
3044        strata::q_of(stream)
3045            ->parallel_for<
3046                dpct_kernel_name<class gdn_step_norm_qkreg_kernel_42ae26>>(
3047                sycl::nd_range<3>(sycl::range(1, 1, (unsigned)h_v) *
3048                                      sycl::range(1, RG, S),
3049                                  sycl::range(1, RG, S)),
3050                exp_props,
3051                [=](sycl::nd_item<3> item_ct1)
3052                    [[sycl::reqd_sub_group_size(32)]] {
3053                        gdn_step_norm_qkreg_kernel(
3054                            state, h, conv_channels, gate, beta, z, gamma, eps,
3055                            y, h_k, h_v, n_tok, n_keep, t_out_begin);
3056                    });
3057    }
3058    check("gdn_step_norm_qkreg");
3059}
3060
3061}  // namespace strata::kernels