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
155.9 KiB3167 linesraw
1// src/prefill/kernels.cu - see include/strata/prefill/kernels.hpp.
2#define DPCT_PROFILING_ENABLED
3#include <sycl/sycl.hpp>
4#include "strata/kprof.hpp"
5#include <dpct/dpct.hpp>
6#include "strata/sycl_queue.hpp"
7#include "strata/prefill/kernels.hpp"
8#include "strata/prefill/gdn_xe.hpp"
9#include "strata/kernels/mrope.hpp"
10#include "strata/kernels/gfx_arch.hpp"
11#include "strata/kernels/router_top10.hpp"
12
13#include <algorithm>
14
15#include <algorithm>
16#include <cfloat>
17#include <cmath>
18#include <cstdio>
19#include <cstdlib>
20#include <cstring>
21#include <stdexcept>
22
23#include "strata/core/geometry.hpp"
24
25namespace strata::prefill {
26namespace {
27
28constexpr int N = strata::core::kCompiledGeometry.n_embd, HC = strata::core::kCompiledGeometry.hc, D = N * HC, LR = strata::core::kCompiledGeometry.hc_lr;
29constexpr int KU = strata::core::kCompiledGeometry.n_expert_used;   // routed experts per token (10 for Flash-Next)
30constexpr int NHQ = strata::core::kCompiledGeometry.n_head, NKVH = strata::core::kCompiledGeometry.n_head_kv;   // query heads (24) and KV heads (2), head width 256
31constexpr int64_t FFC = strata::core::kCompiledGeometry.n_ff;   // the routed (and shared) expert width: 640 for Flash-Next
32constexpr int S = strata::core::kCompiledGeometry.ssm_state_size, HK = strata::core::kCompiledGeometry.ssm_k_heads, HV = strata::core::kCompiledGeometry.ssm_v_heads, C = strata::core::kCompiledGeometry.ssm_conv_channels;
33
34__dpct_inline__ float warp_sum(float v) {
35#pragma unroll
36    /*
37    DPCT1108: '__shfl_xor_sync' was migrated with the experimental feature
38    masked sub_group function which may not be supported by all compilers or
39    runtimes. You may need to adjust the code.
40    */
41    for (int o = 16; o > 0; o >>= 1) v +=
42        dpct::experimental::permute_sub_group_by_xor(
43            0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(), v,
44            o);
45    return v;
46}
47__dpct_inline__ float warp_max(float v) {
48#pragma unroll
49    /*
50    DPCT1108: '__shfl_xor_sync' was migrated with the experimental feature
51    masked sub_group function which may not be supported by all compilers or
52    runtimes. You may need to adjust the code.
53    */
54    for (int o = 16; o > 0; o >>= 1) v = sycl::fmax(
55        v, dpct::experimental::permute_sub_group_by_xor(
56               0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(),
57               v, o));
58    return v;
59}
60__dpct_inline__ uint16_t bf(float f) {
61    uint32_t u = sycl::bit_cast<unsigned int>(f);
62    u += 0x7fffu + ((u >> 16) & 1u);
63    return (uint16_t) (u >> 16);
64}
65// The BF16 GEMMs' second operand (STRATA_PREFILL_BF16X2): what the BF16 image `hi` left out of f, itself in BF16.
66// W.hi + W.lo carries ~16 mantissa bits of the activation - the decode path's FP32 x to within ~1e-5.
67__dpct_inline__ uint16_t bf_lo(float f, uint16_t hi) {
68    return bf(f - sycl::bit_cast<float>((uint32_t)hi << 16));
69}
70__dpct_inline__ float sigm(float x) {
71    return 1.0f / (1.0f + sycl::native::exp(-x));
72}
73__dpct_inline__ uint16_t hf(float f) {
74    return sycl::bit_cast<unsigned short, sycl::half>(
75               sycl::vec<float, 1>(f)
76                   .convert<sycl::half, sycl::rounding_mode::rte>()[0]);
77}
78// A SwiGLU product for an FP16 GEMM: saturated, so a token with a massive activation cannot turn into inf and then
79// NaN in the down projection (decode's q8_1 has room to ~8e6; FP16 ends at 65504).  A NaN stays NaN (fminf/fmaxf
80// would make it -65504 and hide where it came from); finite values below 65504 round exactly as before.
81__dpct_inline__ uint16_t hf_sat(float f) {
82    return hf(sycl::isnan(f) ? f
83                             : sycl::fmin(sycl::fmax(f, -65504.0f), 65504.0f));
84}
85// The prompt path's 16-bit activation image for the BF16-weight GEMMs: BF16, or FP16 where the GEMM library is fast
86// only in FP16 (prompt_f16() in gemm.cu: rocBLAS on gfx103x).  Set once per device before the first prompt.
87#if defined(__HIPCC__)   // HIP only (#835): the CUDA kernels stay exactly as they were, they never read the flag
88__device__ int g_act_f16 = 0;
89__device__ __forceinline__ uint16_t act16(float f) { return g_act_f16 ? hf_sat(f) : bf(f); }
90#else
91__dpct_inline__ uint16_t act16(float f) { return bf(f); }
92#endif
93// block-wide sum for blockDim.x <= 1024, result broadcast
94inline float block_sum(float v, float *sh) {
95    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
96    const int lane = item_ct1.get_local_id(2) & 31,
97              w = item_ct1.get_local_id(2) >> 5;
98    v = warp_sum(v);
99    /*
100    DPCT1065: Consider replacing sycl::nd_item::barrier() with
101    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
102    performance if there is no access to global memory.
103    */
104    item_ct1.barrier();
105    if (lane == 0) sh[w] = v;
106    /*
107    DPCT1065: Consider replacing sycl::nd_item::barrier() with
108    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
109    performance if there is no access to global memory.
110    */
111    item_ct1.barrier();
112    const int nw = (item_ct1.get_local_range(2) + 31) >> 5;
113    float t =
114        (item_ct1.get_local_id(2) < nw) ? sh[item_ct1.get_local_id(2)] : 0.0f;
115    if (w == 0) t = warp_sum(t);
116    if (item_ct1.get_local_id(2) == 0) sh[0] = t;
117    /*
118    DPCT1065: Consider replacing sycl::nd_item::barrier() with
119    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
120    performance if there is no access to global memory.
121    */
122    item_ct1.barrier();
123    return sh[0];
124}
125void check(const char* what) {
126    /*
127    DPCT1010: SYCL uses exceptions to report errors and does not use the
128    error codes. The cudaGetLastError function call was replaced with 0. You
129    need to rewrite this code.
130    */
131    const dpct::err0 e = 0;
132    /*
133    DPCT1009: SYCL reports errors using exceptions and does not use error
134    codes. Please replace the "get_error_string_dummy(...)" with a real
135    error-handling function.
136    */
137}
138unsigned blocks_for(int64_t n, int t = 256) { return (unsigned) ((n + t - 1) / t); }
139
140// ---------------------------------------------------------------- hyper-connection
141__dpct_inline__ void gr_norm_kernel(const float *__restrict__ R,
142                                    const float *__restrict__ w, float eps,
143                                    float *__restrict__ xn,
144                                    uint16_t *__restrict__ xn16,
145                                    uint16_t *__restrict__ xn16_lo) {
146    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
147auto &sh = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[32]>(
148    sycl::ext::oneapi::this_work_item::get_work_group<3>());
149    const int64_t row = item_ct1.get_group(2); // t * 4 + c
150    const int c = (int) (row % HC);
151    const float* r = R + row * N;
152    float ss = 0.0f;
153#pragma unroll
154    for (int d = item_ct1.get_local_id(2); d < N;
155         d += item_ct1.get_local_range(2)) ss += r[d] * r[d];
156    const float rs = sycl::rsqrt(block_sum(ss, sh) / (float)N + eps);
157    for (int d = item_ct1.get_local_id(2); d < N;
158         d += item_ct1.get_local_range(2)) {
159        const float v = r[d] * rs * w[c * N + d];
160        xn[row * N + d] = v;
161        const uint16_t h = act16(v);
162        xn16[row * N + d] = h;
163        if (xn16_lo) xn16_lo[row * N + d] = bf_lo(v, h);
164    }
165}
166// F-1: the row scale only (and the BF16 image); gr_mix_r_kernel recomputes r * rs * w itself, in the same order,
167// so the FP32 copy of the normalized rows (T x 10240 floats) is neither written nor read
168__dpct_inline__ void gr_norm_rs_kernel(const float *__restrict__ R,
169                                       const float *__restrict__ w, float eps,
170                                       float *__restrict__ rs_out,
171                                       uint16_t *__restrict__ xn16,
172                                       uint16_t *__restrict__ xn16_lo,
173                                       int64_t ldx) {
174    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
175auto &sh = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[32]>(
176    sycl::ext::oneapi::this_work_item::get_work_group<3>());
177    const int64_t row = item_ct1.get_group(2); // t * 4 + c
178    const int c = (int) (row % HC);
179    const float* r = R + row * N;
180    const int64_t xo = (row / HC) * ldx + (int64_t) c * N;   // the BF16 image's row (token stride ldx)
181    float ss = 0.0f;
182#pragma unroll
183    for (int d = item_ct1.get_local_id(2); d < N;
184         d += item_ct1.get_local_range(2)) ss += r[d] * r[d];
185    const float rs = sycl::rsqrt(block_sum(ss, sh) / (float)N + eps);
186    if (item_ct1.get_local_id(2) == 0) rs_out[row] = rs;
187    for (int d = item_ct1.get_local_id(2); d < N;
188         d += item_ct1.get_local_range(2)) {
189        const float v = r[d] * rs * w[c * N + d];
190        const uint16_t h = act16(v);
191        xn16[xo + d] = h;
192        if (xn16_lo) xn16_lo[xo + d] = bf_lo(v, h);
193    }
194}
195__dpct_inline__ void
196gr_mix_r_kernel(const float *__restrict__ R, const float *__restrict__ rs,
197                const float *__restrict__ w, const float *__restrict__ g,
198                float *__restrict__ mixed, uint16_t *__restrict__ mixed16,
199                int64_t T, uint16_t *__restrict__ mixed_h,
200                uint16_t *__restrict__ mixed16_lo) {
201    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
202    const int64_t i =
203        (int64_t)item_ct1.get_group(2) * item_ct1.get_local_range(2) +
204        item_ct1.get_local_id(2);
205    if (i >= T * N) return;
206    const int64_t t = i / N, d = i % N;
207    float s = 0.0f;
208#pragma unroll
209    for (int c = 0; c < HC; ++c) {
210        const int64_t j = t * D + c * N + d;
211        const float x = R[j] * rs[t * HC + c] * w[c * N + d];   // gr_norm_kernel's value, bit for bit
212        s = sycl::fma((float)x, sigm(g[j]), s);
213    }
214    s /= (float) HC;
215    mixed[i] = s;
216    if (mixed16) {
217        const uint16_t h = act16(s);
218        mixed16[i] = h;
219        if (mixed16_lo) mixed16_lo[i] = bf_lo(s, h);
220    }
221    if (mixed_h) mixed_h[i] = hf(s);
222}
223// F-2: gr_write_kernel for one row (t, c), then gr_norm_rs_kernel's reduction over it with the next half's norm
224// weights - the same thread-to-element mapping (256 threads, stride 256) and block_sum, so rs and the BF16 image are
225// the same bits, and R is not read back
226constexpr int GRW_PER = (N + 255) / 256;
227__dpct_inline__ void
228gr_write_norm_rs_kernel(float *__restrict__ R, const float *__restrict__ bo,
229                        const float *__restrict__ inj, int64_t inj_ld,
230                        const float *__restrict__ w, float eps,
231                        float *__restrict__ rs_out, uint16_t *__restrict__ xn16,
232                        uint16_t *__restrict__ xn16_lo, int64_t ldx) {
233    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
234auto &sh = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[32]>(
235    sycl::ext::oneapi::this_work_item::get_work_group<3>());
236    const int64_t row = item_ct1.get_group(2); // t * 4 + c
237    const int64_t t = row / HC;
238    const int c = (int) (row % HC);
239    float* r = R + row * N;
240    const int64_t xo = t * ldx + (int64_t) c * N;
241    const float sc = 2.0f * sigm(inj[t * inj_ld + c] / (float) HC);
242    float v[GRW_PER];
243    float ss = 0.0f;
244    int k = 0;
245#pragma unroll
246    for (int d = item_ct1.get_local_id(2); d < N; d += 256, ++k) {
247        const float x = sycl::fma((float)(bo[t * N + d]), (float)sc, r[d]);
248        r[d] = x;
249        v[k] = x;
250        ss += x * x;
251    }
252    const float rs = sycl::rsqrt(block_sum(ss, sh) / (float)N + eps);
253    if (item_ct1.get_local_id(2) == 0) rs_out[row] = rs;
254    k = 0;
255#pragma unroll
256    for (int d = item_ct1.get_local_id(2); d < N; d += 256, ++k) {
257        const float x = v[k] * rs * w[c * N + d];
258        const uint16_t h = act16(x);
259        xn16[xo + d] = h;
260        if (xn16_lo) xn16_lo[xo + d] = bf_lo(x, h);
261    }
262}
263// S23 (opt-in STRATA_CVEC_FUSE=1): a steered layer's FFN write, its control vector and the next half's norm in one
264// pass over R (was gr_write + cvec_apply + gr_norm_rs: three).  The write is gr_write_kernel's, the vector
265// cvec_kernel's (the same per-thread dot order over d = tid + 256 k, the same two-level xor reduction), the norm
266// gr_norm_rs_kernel's (the same ss order and block_sum): the same bits.
267/*
268DPCT1110: The total declared local variable size in device function
269gr_write_cvec_norm_rs_kernel exceeds 128 bytes and may cause high register
270pressure. Consult with your hardware vendor to find the total register size
271available and adjust the code, or use smaller sub-group size to avoid high
272register pressure.
273*/
274__dpct_inline__ void gr_write_cvec_norm_rs_kernel(
275    float *__restrict__ R, const float *__restrict__ bo,
276    const float *__restrict__ inj, int64_t inj_ld,
277    const float *__restrict__ v_l, const float *__restrict__ s_l,
278    const int *__restrict__ on, int mode, const float *__restrict__ w,
279    float eps, float *__restrict__ rs_out, uint16_t *__restrict__ xn16,
280    uint16_t *__restrict__ xn16_lo, int64_t ldx) {
281    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
282auto &sh = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[32]>(
283    sycl::ext::oneapi::this_work_item::get_work_group<3>());
284    auto &part = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[8]>(
285        sycl::ext::oneapi::this_work_item::get_work_group<3>());
286    const int64_t row = item_ct1.get_group(2); // t * 4 + c
287    const int64_t t = row / HC;
288    const int c = (int) (row % HC);
289    float* r = R + row * N;
290    const float sc = 2.0f * sigm(inj[t * inj_ld + c] / (float) HC);
291    const float s = *s_l;
292    const bool steer = *on != 0 && s != 0.0f;
293    float x[GRW_PER];
294    float dot = 0.0f;
295    int k = 0;
296#pragma unroll
297    for (int d = item_ct1.get_local_id(2); d < N; d += 256, ++k) {
298        const float xv = sycl::fma((float)(bo[t * N + d]), (float)sc, r[d]);
299        x[k] = xv;
300        if (steer && mode == 0) dot =
301            sycl::fma((float)xv, (float)(v_l[d]), dot);
302    }
303    if (steer && mode == 0) {
304#pragma unroll
305        /*
306        DPCT1108: '__shfl_xor_sync' was migrated with the experimental
307        feature masked sub_group function which may not be supported by all
308        compilers or runtimes. You may need to adjust the code.
309        */
310        for (int o = 16; o > 0; o >>= 1) dot +=
311            dpct::experimental::permute_sub_group_by_xor(
312                0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(),
313                dot, o);
314        if ((item_ct1.get_local_id(2) & 31) == 0)
315            part[item_ct1.get_local_id(2) >> 5] = dot;
316        /*
317        DPCT1118: SYCL group functions and algorithms must be encountered in
318        converged control flow. You may need to adjust the code.
319        */
320        /*
321        DPCT1065: Consider replacing sycl::nd_item::barrier() with
322        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
323        better performance if there is no access to global memory.
324        */
325        item_ct1.barrier();
326        if (item_ct1.get_local_id(2) < 32) {
327            float p = item_ct1.get_local_id(2) < 8
328                          ? part[item_ct1.get_local_id(2)]
329                          : 0.0f;
330#pragma unroll
331            /*
332            DPCT1108: '__shfl_xor_sync' was migrated with the experimental
333            feature masked sub_group function which may not be supported by all
334            compilers or runtimes. You may need to adjust the code.
335            */
336            for (int o = 16; o > 0; o >>= 1) p +=
337                dpct::experimental::permute_sub_group_by_xor(
338                    0xffffffffu,
339                    sycl::ext::oneapi::this_work_item::get_sub_group(), p, o);
340            if (item_ct1.get_local_id(2) == 0) part[0] = p;
341        }
342        /*
343        DPCT1118: SYCL group functions and algorithms must be encountered in
344        converged control flow. You may need to adjust the code.
345        */
346        /*
347        DPCT1065: Consider replacing sycl::nd_item::barrier() with
348        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
349        better performance if there is no access to global memory.
350        */
351        item_ct1.barrier();
352        dot = part[0] * s;
353    }
354    float ss = 0.0f;
355    k = 0;
356#pragma unroll
357    for (int d = item_ct1.get_local_id(2); d < N; d += 256, ++k) {
358        float xv = x[k];
359        if (steer) xv =
360            mode == 0 ? sycl::fma(-dot, (float)(v_l[d]), xv) : xv + v_l[d];
361        r[d] = xv;
362        x[k] = xv;
363        ss += xv * xv;
364    }
365    const float rs = sycl::rsqrt(block_sum(ss, sh) / (float)N + eps);
366    if (item_ct1.get_local_id(2) == 0) rs_out[row] = rs;
367    k = 0;
368#pragma unroll
369    for (int d = item_ct1.get_local_id(2); d < N; d += 256, ++k) {
370        const float y = x[k] * rs * w[c * N + d];
371        const uint16_t h = act16(y);
372        xn16[t * ldx + (int64_t) c * N + d] = h;
373        if (xn16_lo) xn16_lo[t * ldx + (int64_t) c * N + d] = bf_lo(y, h);
374    }
375}
376__dpct_inline__ void gr_silu_kernel(const float *__restrict__ lo,
377                                    uint16_t *__restrict__ lo16,
378                                    uint16_t *__restrict__ lo16_lo, int64_t n) {
379    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
380    const int64_t i =
381        (int64_t)item_ct1.get_group(2) * item_ct1.get_local_range(2) +
382        item_ct1.get_local_id(2);
383    if (i >= n) return;
384    const float x = lo[i] / (float) HC;
385    const float v = x / (1.0f + sycl::native::exp(-x));
386    const uint16_t h = act16(v);
387    lo16[i] = h;
388    if (lo16_lo) lo16_lo[i] = bf_lo(v, h);
389}
390__dpct_inline__ void gr_mix_kernel(const float *__restrict__ xn,
391                                   const float *__restrict__ g,
392                                   float *__restrict__ mixed,
393                                   uint16_t *__restrict__ mixed16, int64_t T,
394                                   uint16_t *__restrict__ mixed_h,
395                                   uint16_t *__restrict__ mixed16_lo) {
396    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
397    const int64_t i =
398        (int64_t)item_ct1.get_group(2) * item_ct1.get_local_range(2) +
399        item_ct1.get_local_id(2);
400    if (i >= T * N) return;
401    const int64_t t = i / N, d = i % N;
402    float s = 0.0f;
403#pragma unroll
404    for (int c = 0; c < HC; ++c) {
405        const int64_t j = t * D + c * N + d;
406        s = sycl::fma((float)(xn[j]), sigm(g[j]), s);
407    }
408    s /= (float) HC;
409    mixed[i] = s;
410    if (mixed16) {
411        const uint16_t h = act16(s);
412        mixed16[i] = h;
413        if (mixed16_lo) mixed16_lo[i] = bf_lo(s, h);
414    }
415    if (mixed_h) mixed_h[i] = hf(s);
416}
417__dpct_inline__ void gr_write_kernel(float *__restrict__ R,
418                                     const float *__restrict__ bo,
419                                     const float *__restrict__ inj,
420                                     int64_t inj_ld, int64_t T) {
421    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
422    const int64_t i =
423        (int64_t)item_ct1.get_group(2) * item_ct1.get_local_range(2) +
424        item_ct1.get_local_id(2);
425    if (i >= T * D) return;
426    const int64_t t = i / D, c = (i % D) / N, d = i % N;
427    R[i] = sycl::fma((float)(bo[t * N + d]),
428                     2.0f * sigm(inj[t * inj_ld + c] / (float)HC), R[i]);
429}
430__dpct_inline__ void gr_broadcast_kernel(const float *__restrict__ e,
431                                         float *__restrict__ R, int64_t T) {
432    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
433    const int64_t i =
434        (int64_t)item_ct1.get_group(2) * item_ct1.get_local_range(2) +
435        item_ct1.get_local_id(2);
436    if (i >= T * D) return;
437    const int64_t t = i / D, d = i % N;
438    R[i] = e[t * N + d];
439}
440
441// ---------------------------------------------------------------- GDN
442__dpct_inline__ void gdn_gates_kernel(const float *__restrict__ ab,
443                                      const float *__restrict__ dt,
444                                      const float *__restrict__ ssm_a,
445                                      float *__restrict__ gate,
446                                      float *__restrict__ beta, int64_t T) {
447    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
448    const int64_t i =
449        (int64_t)item_ct1.get_group(2) * item_ct1.get_local_range(2) +
450        item_ct1.get_local_id(2);
451    if (i >= T * HV) return;
452    const int64_t t = i / HV, h = i % HV;
453    const float v = ab[t * 2 * HV + h] + dt[h];
454    gate[i] = (v > 20.0f ? v : sycl::log1p(sycl::native::exp(v))) * ssm_a[h];
455    beta[i] = sigm(ab[t * 2 * HV + HV + h]);
456}
457// one thread per channel, walks the chunk; then a second kernel normalises
458__dpct_inline__ void gdn_conv_kernel(float *__restrict__ hist,
459                                     const float *__restrict__ qkv,
460                                     const float *__restrict__ w,
461                                     float *__restrict__ h, int64_t T) {
462    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
463    const int c = item_ct1.get_group(2) * item_ct1.get_local_range(2) +
464                  item_ct1.get_local_id(2);
465    if (c >= C) return;
466    float v0 = hist[c * 3], v1 = hist[c * 3 + 1], v2 = hist[c * 3 + 2];
467    const float w0 = w[c * 4], w1 = w[c * 4 + 1], w2 = w[c * 4 + 2], w3 = w[c * 4 + 3];
468    for (int64_t t = 0; t < T; ++t) {
469        const float x = qkv[t * C + c];
470        const float s = v0 * w0 + v1 * w1 + v2 * w2 + x * w3;
471        h[t * C + c] = s / (1.0f + sycl::native::exp(-s));
472        v0 = v1; v1 = v2; v2 = x;
473    }
474    hist[c * 3] = v0; hist[c * 3 + 1] = v1; hist[c * 3 + 2] = v2;
475}
476// C-3: the same 4-tap causal conv, tiled over tokens: thread (c, tile) reads its tile's 3 predecessors from the
477// chunk (or the history before it) instead of carrying them - the conv reads inputs, not its own outputs, so the
478// tiles are independent. The same expression per element (so the same bits); the history is written afterwards.
479constexpr int CONV_TILE = 64;
480__dpct_inline__ void gdn_conv_tiled_kernel(const float *__restrict__ hist,
481                                           const float *__restrict__ qkv,
482                                           const float *__restrict__ w,
483                                           float *__restrict__ h, int64_t T) {
484    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
485    const int c = item_ct1.get_group(2) * item_ct1.get_local_range(2) +
486                  item_ct1.get_local_id(2);
487    if (c >= C) return;
488    const int64_t t0 = (int64_t)item_ct1.get_group(1) * CONV_TILE;
489    if (t0 >= T) return;
490    const int64_t t1 = t0 + CONV_TILE < T ? t0 + CONV_TILE : T;
491    auto input = [&](int64_t t) -> float { return t >= 0 ? qkv[t * C + c] : hist[c * 3 + (int) (t + 3)]; };
492    float v0 = input(t0 - 3), v1 = input(t0 - 2), v2 = input(t0 - 1);
493    const float w0 = w[c * 4], w1 = w[c * 4 + 1], w2 = w[c * 4 + 2], w3 = w[c * 4 + 3];
494    for (int64_t t = t0; t < t1; ++t) {
495        const float x = qkv[t * C + c];
496        const float s = v0 * w0 + v1 * w1 + v2 * w2 + x * w3;
497        h[t * C + c] = s / (1.0f + sycl::native::exp(-s));
498        v0 = v1; v1 = v2; v2 = x;
499    }
500}
501// Aurora (S23, opt-in STRATA_GDN_CONVL2=1): gdn_conv_tiled_kernel with gdn_l2_kernel folded in.  A block's 128 threads
502// are the 128 channels of one head, so for the q / k heads (block < 2 HK) the norm's sum of squares is the block's:
503// the same warp_sum, the same four partials added in the same order, the same v * rsqrtf(ss + eps) on the same
504// stored value - the same bits, without writing h and reading it back (16 tokens per round).
505__dpct_inline__ void gdn_conv_l2_kernel(const float *__restrict__ hist,
506                                        const float *__restrict__ qkv,
507                                        const float *__restrict__ w,
508                                        float *__restrict__ h, int64_t T,
509                                        float eps) {
510    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
511    const int c = item_ct1.get_group(2) * item_ct1.get_local_range(2) +
512                  item_ct1.get_local_id(2);
513    const int64_t t0 = (int64_t)item_ct1.get_group(1) * CONV_TILE;
514    if (t0 >= T) return;
515    const int64_t t1 = t0 + CONV_TILE < T ? t0 + CONV_TILE : T;
516    auto input = [&](int64_t t) -> float { return t >= 0 ? qkv[t * C + c] : hist[c * 3 + (int) (t + 3)]; };
517    float v0 = input(t0 - 3), v1 = input(t0 - 2), v2 = input(t0 - 1);
518    const float w0 = w[c * 4], w1 = w[c * 4 + 1], w2 = w[c * 4 + 2], w3 = w[c * 4 + 3];
519    for (int64_t t = t0; t < t1; ++t) {   // gdn_conv_tiled_kernel's loop, verbatim
520        const float x = qkv[t * C + c];
521        const float s = v0 * w0 + v1 * w1 + v2 * w2 + x * w3;
522        h[t * C + c] = s / (1.0f + sycl::native::exp(-s));
523        v0 = v1; v1 = v2; v2 = x;
524    }
525    if (item_ct1.get_group(2) >= 2 * HK) return; // v channels: no norm
526    auto &part =
527        *sycl::ext::oneapi::group_local_memory_for_overwrite<float[16][4]>(
528            sycl::ext::oneapi::this_work_item::get_work_group<3>());
529    for (int64_t tb = t0; tb < t1; tb += 16) {
530        const int n = (int) (t1 - tb < 16 ? t1 - tb : 16);
531        for (int j = 0; j < n; ++j) {   // (each thread reads back its own stored value)
532            const float v = h[(tb + j) * C + c];
533            // gdn_l2_kernel as the compiler built it: the first xor step adds the partner's rounded square to an
534            // unrounded own one (an fma), the other steps are plain adds - spelled out so no contraction can differ
535            /*
536            DPCT1108: '__shfl_xor_sync' was migrated with the experimental
537            feature masked sub_group function which may not be supported by all
538            compilers or runtimes. You may need to adjust the code.
539            */
540            /*
541            DPCT1013: The rounding mode could not be specified and the
542            generated code may have different accuracy than the original code.
543            Verify the correctness. SYCL math built-in function rounding mode is
544            aligned with OpenCL C 1.2 standard.
545            */
546            float sq = sycl::fma(
547                v, v,
548                dpct::experimental::permute_sub_group_by_xor(
549                    0xffffffffu,
550                    sycl::ext::oneapi::this_work_item::get_sub_group(), v * v,
551                    16));
552#pragma unroll
553            /*
554            DPCT1108: '__shfl_xor_sync' was migrated with the experimental
555            feature masked sub_group function which may not be supported by all
556            compilers or runtimes. You may need to adjust the code.
557            */
558            /*
559            DPCT1013: The rounding mode could not be specified and the
560            generated code may have different accuracy than the original code.
561            Verify the correctness. SYCL math built-in function rounding mode is
562            aligned with OpenCL C 1.2 standard.
563            */
564            for (int o = 8; o > 0; o >>= 1) sq =
565                sq + dpct::experimental::permute_sub_group_by_xor(
566                         0xffffffffu,
567                         sycl::ext::oneapi::this_work_item::get_sub_group(), sq,
568                         o);
569            if ((item_ct1.get_local_id(2) & 31) == 0)
570                part[j][item_ct1.get_local_id(2) >> 5] = sq;
571        }
572        /*
573        DPCT1118: SYCL group functions and algorithms must be encountered in
574        converged control flow. You may need to adjust the code.
575        */
576        /*
577        DPCT1065: Consider replacing sycl::nd_item::barrier() with
578        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
579        better performance if there is no access to global memory.
580        */
581        item_ct1.barrier();
582        for (int j = 0; j < n; ++j) {
583            const float ss = part[j][0] + part[j][1] + part[j][2] + part[j][3];
584            h[(tb + j) * C + c] = h[(tb + j) * C + c] * sycl::rsqrt(ss + eps);
585        }
586        /*
587        DPCT1118: SYCL group functions and algorithms must be encountered in
588        converged control flow. You may need to adjust the code.
589        */
590        /*
591        DPCT1065: Consider replacing sycl::nd_item::barrier() with
592        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
593        better performance if there is no access to global memory.
594        */
595        item_ct1.barrier();
596    }
597}
598// the history after the chunk: its last three inputs (the older history where the chunk is shorter than 3)
599__dpct_inline__ void gdn_conv_hist_kernel(float *__restrict__ hist,
600                                          const float *__restrict__ qkv,
601                                          int64_t T) {
602    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
603    const int c = item_ct1.get_group(2) * item_ct1.get_local_range(2) +
604                  item_ct1.get_local_id(2);
605    if (c >= C) return;
606    float v[3];
607    for (int k = 0; k < 3; ++k) {
608        const int64_t t = T - 3 + k;
609        v[k] = t >= 0 ? qkv[t * C + c] : hist[c * 3 + (int) (t + 3)];
610    }
611    hist[c * 3] = v[0]; hist[c * 3 + 1] = v[1]; hist[c * 3 + 2] = v[2];
612}
613__dpct_inline__ void gdn_l2_kernel(float *__restrict__ h, float eps) {
614    // block (t, head) over the 32 q/k heads, 128 threads
615    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
616    const int64_t t = item_ct1.get_group(1);
617    const int head = item_ct1.get_group(2);
618    float* x = h + t * C + head * S;
619    const float v = x[item_ct1.get_local_id(2)];
620    float sq = warp_sum(v * v);
621    auto &part = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[4]>(
622        sycl::ext::oneapi::this_work_item::get_work_group<3>());
623    if ((item_ct1.get_local_id(2) & 31) == 0)
624        part[item_ct1.get_local_id(2) >> 5] = sq;
625    /*
626    DPCT1065: Consider replacing sycl::nd_item::barrier() with
627    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
628    performance if there is no access to global memory.
629    */
630    item_ct1.barrier();
631    const float ss = part[0] + part[1] + part[2] + part[3];
632    x[item_ct1.get_local_id(2)] = v * sycl::rsqrt(ss + eps);
633}
634constexpr int RG = 4, RPG = S / RG;
635/*
636DPCT1110: The total declared local variable size in device function
637gdn_rec_kernel exceeds 128 bytes and may cause high register pressure. Consult
638with your hardware vendor to find the total register size available and adjust
639the code, or use smaller sub-group size to avoid high register pressure.
640*/
641__dpct_inline__ void
642gdn_rec_kernel(float *__restrict__ state, const float *__restrict__ h,
643               const float *__restrict__ gate, const float *__restrict__ beta,
644               const float *__restrict__ z, const float *__restrict__ gamma,
645               float eps, float *__restrict__ y, uint16_t *__restrict__ y16,
646               int64_t T, int64_t ld16) {
647    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
648auto &sk = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[S]>(
649    sycl::ext::oneapi::this_work_item::get_work_group<3>());
650    auto &sq = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[S]>(
651        sycl::ext::oneapi::this_work_item::get_work_group<3>());
652    auto &red =
653        *sycl::ext::oneapi::group_local_memory_for_overwrite<float[RG][S]>(
654            sycl::ext::oneapi::this_work_item::get_work_group<3>());
655    auto &wsum =
656        *sycl::ext::oneapi::group_local_memory_for_overwrite<float[16]>(
657            sycl::ext::oneapi::this_work_item::get_work_group<3>());
658    const int head = item_ct1.get_group(2), col = item_ct1.get_local_id(2),
659              rg = item_ct1.get_local_id(1), tid = rg * S + col;
660    const int qh = head % HK;
661    float s[RPG];
662    float* base = state + ((size_t) (rg * RPG) * HV + head) * S + col;
663    const size_t rs = (size_t) HV * S;
664#pragma unroll
665    for (int r = 0; r < RPG; ++r) s[r] = base[r * rs];
666    const float g_col = gamma[col];
667    for (int64_t t = 0; t < T; ++t) {
668        const float* ht = h + t * C;
669        /*
670        DPCT1118: SYCL group functions and algorithms must be encountered in
671        converged control flow. You may need to adjust the code.
672        */
673        /*
674        DPCT1065: Consider replacing sycl::nd_item::barrier() with
675        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
676        better performance if there is no access to global memory.
677        */
678        item_ct1.barrier();
679        if (tid < S) { sq[tid] = ht[qh * S + tid]; sk[tid] = ht[HK * S + qh * S + tid]; }
680        /*
681        DPCT1118: SYCL group functions and algorithms must be encountered in
682        converged control flow. You may need to adjust the code.
683        */
684        /*
685        DPCT1065: Consider replacing sycl::nd_item::barrier() with
686        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
687        better performance if there is no access to global memory.
688        */
689        item_ct1.barrier();
690        const float g = sycl::native::exp(gate[t * HV + head]);
691        float kv = 0.0f;
692#pragma unroll
693        for (int r = 0; r < RPG; ++r)
694            kv = sycl::fma(s[r], sk[rg * RPG + r], kv);
695        red[rg][col] = kv;
696        /*
697        DPCT1118: SYCL group functions and algorithms must be encountered in
698        converged control flow. You may need to adjust the code.
699        */
700        /*
701        DPCT1065: Consider replacing sycl::nd_item::barrier() with
702        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
703        better performance if there is no access to global memory.
704        */
705        item_ct1.barrier();
706        const float kv_col = red[0][col] + red[1][col] + red[2][col] + red[3][col];
707        const float delta = (ht[2 * HK * S + head * S + col] - g * kv_col) * beta[t * HV + head];
708        float o = 0.0f;
709#pragma unroll
710        for (int r = 0; r < RPG; ++r) {
711            s[r] = sycl::fma((float)g, s[r], sk[rg * RPG + r] * delta);
712            o = sycl::fma(s[r], sq[rg * RPG + r], o);
713        }
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();
724        red[rg][col] = o;
725        /*
726        DPCT1118: SYCL group functions and algorithms must be encountered in
727        converged control flow. You may need to adjust the code.
728        */
729        /*
730        DPCT1065: Consider replacing sycl::nd_item::barrier() with
731        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
732        better performance if there is no access to global memory.
733        */
734        item_ct1.barrier();
735        float oc = 0.0f, sp = 0.0f;
736        if (rg == 0) {
737            oc = (red[0][col] + red[1][col] + red[2][col] + red[3][col]) *
738                 sycl::rsqrt((float)S);
739            sp = oc * oc;
740        }
741        sp = warp_sum(sp);
742        if ((tid & 31) == 0) wsum[tid >> 5] = sp;
743        /*
744        DPCT1118: SYCL group functions and algorithms must be encountered in
745        converged control flow. You may need to adjust the code.
746        */
747        /*
748        DPCT1065: Consider replacing sycl::nd_item::barrier() with
749        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
750        better performance if there is no access to global memory.
751        */
752        item_ct1.barrier();
753        if (rg == 0) {
754            const float ss = wsum[0] + wsum[1] + wsum[2] + wsum[3];
755            const float v = oc * sycl::rsqrt(ss / (float)S + eps) * g_col *
756                            sigm(z[t * HV * S + head * S + col]);
757            y[t * HV * S + head * S + col] = v;
758            y16[t * ld16 + head * S + col] = hf(v);
759        }
760    }
761#pragma unroll
762    for (int r = 0; r < RPG; ++r) base[r * rs] = s[r];
763}
764
765// D-2: the recurrence with the value columns split over 4 blocks per head (4x the blocks of the kernel above, a
766// quarter of its threads per __syncthreads), and the output norm - the only step that couples the head's columns -
767// in its own kernel. Per column the same arithmetic in the same order (the 4 row-group partial sums added as
768// red[0] + red[1] + red[2] + red[3]; the norm's warp sums over the same 32-column warps): the same bits.
769constexpr int CB = 32, NCB = S / CB;
770/*
771DPCT1110: The total declared local variable size in device function
772gdn_rec_cols_kernel exceeds 128 bytes and may cause high register pressure.
773Consult with your hardware vendor to find the total register size available and
774adjust the code, or use smaller sub-group size to avoid high register pressure.
775*/
776__dpct_inline__ void gdn_rec_cols_kernel(float *__restrict__ state,
777                                         const float *__restrict__ h,
778                                         const float *__restrict__ gate,
779                                         const float *__restrict__ beta,
780                                         float *__restrict__ oc_out,
781                                         int64_t T) {
782    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
783auto &sk = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[S]>(
784    sycl::ext::oneapi::this_work_item::get_work_group<3>());
785    auto &sq = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[S]>(
786        sycl::ext::oneapi::this_work_item::get_work_group<3>());
787    auto &red =
788        *sycl::ext::oneapi::group_local_memory_for_overwrite<float[RG][CB]>(
789            sycl::ext::oneapi::this_work_item::get_work_group<3>());
790    const int head = item_ct1.get_group(2) / NCB,
791              cb = item_ct1.get_group(2) % NCB;
792    const int c = item_ct1.get_local_id(2), rg = item_ct1.get_local_id(1),
793              tid = rg * CB + c, col = cb * CB + c;
794    const int qh = head % HK;
795    float s[RPG];
796    float* base = state + ((size_t) (rg * RPG) * HV + head) * S + col;
797    const size_t rs = (size_t) HV * S;
798#pragma unroll
799    for (int r = 0; r < RPG; ++r) s[r] = base[r * rs];
800    for (int64_t t = 0; t < T; ++t) {
801        const float* ht = h + t * C;
802        /*
803        DPCT1118: SYCL group functions and algorithms must be encountered in
804        converged control flow. You may need to adjust the code.
805        */
806        /*
807        DPCT1065: Consider replacing sycl::nd_item::barrier() with
808        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
809        better performance if there is no access to global memory.
810        */
811        item_ct1.barrier();
812        if (tid < S) { sq[tid] = ht[qh * S + tid]; sk[tid] = ht[HK * S + qh * S + tid]; }
813        /*
814        DPCT1118: SYCL group functions and algorithms must be encountered in
815        converged control flow. You may need to adjust the code.
816        */
817        /*
818        DPCT1065: Consider replacing sycl::nd_item::barrier() with
819        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
820        better performance if there is no access to global memory.
821        */
822        item_ct1.barrier();
823        const float g = sycl::native::exp(gate[t * HV + head]);
824        float kv = 0.0f;
825#pragma unroll
826        for (int r = 0; r < RPG; ++r)
827            kv = sycl::fma(s[r], sk[rg * RPG + r], kv);
828        red[rg][c] = kv;
829        /*
830        DPCT1118: SYCL group functions and algorithms must be encountered in
831        converged control flow. You may need to adjust the code.
832        */
833        /*
834        DPCT1065: Consider replacing sycl::nd_item::barrier() with
835        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
836        better performance if there is no access to global memory.
837        */
838        item_ct1.barrier();
839        const float kv_col = red[0][c] + red[1][c] + red[2][c] + red[3][c];
840        const float delta = (ht[2 * HK * S + head * S + col] - g * kv_col) * beta[t * HV + head];
841        float o = 0.0f;
842#pragma unroll
843        for (int r = 0; r < RPG; ++r) {
844            s[r] = sycl::fma((float)g, s[r], sk[rg * RPG + r] * delta);
845            o = sycl::fma(s[r], sq[rg * RPG + r], o);
846        }
847        /*
848        DPCT1118: SYCL group functions and algorithms must be encountered in
849        converged control flow. You may need to adjust the code.
850        */
851        /*
852        DPCT1065: Consider replacing sycl::nd_item::barrier() with
853        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
854        better performance if there is no access to global memory.
855        */
856        item_ct1.barrier();
857        red[rg][c] = o;
858        /*
859        DPCT1118: SYCL group functions and algorithms must be encountered in
860        converged control flow. You may need to adjust the code.
861        */
862        /*
863        DPCT1065: Consider replacing sycl::nd_item::barrier() with
864        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
865        better performance if there is no access to global memory.
866        */
867        item_ct1.barrier();
868        if (rg == 0) oc_out[t * HV * S + head * S + col] =
869            (red[0][c] + red[1][c] + red[2][c] + red[3][c]) *
870            sycl::rsqrt((float)S);
871    }
872#pragma unroll
873    for (int r = 0; r < RPG; ++r) base[r * rs] = s[r];
874}
875// gdn_rec_cols_kernel with the next token's inputs (q/k rows, v, gate, beta) loaded into registers while this token
876// computes (software pipelining).  The same arithmetic in the same order: the same bits, and the same CB-column split.
877// STRATA_GDN_PIPELINE=0: gdn_rec_cols_kernel.
878/*
879DPCT1110: The total declared local variable size in device function
880gdn_rec_cols_pipe_kernel exceeds 128 bytes and may cause high register pressure.
881Consult with your hardware vendor to find the total register size available and
882adjust the code, or use smaller sub-group size to avoid high register pressure.
883*/
884__dpct_inline__ void gdn_rec_cols_pipe_kernel(float *__restrict__ state,
885                                              const float *__restrict__ h,
886                                              const float *__restrict__ gate,
887                                              const float *__restrict__ beta,
888                                              float *__restrict__ oc_out,
889                                              int64_t T) {
890    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
891    constexpr int NT = CB * RG,
892                  LPT = S / NT; // threads, q/k rows loaded per thread
893    auto &sk = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[S]>(
894        sycl::ext::oneapi::this_work_item::get_work_group<3>());
895    auto &sq = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[S]>(
896        sycl::ext::oneapi::this_work_item::get_work_group<3>());
897    auto &red =
898        *sycl::ext::oneapi::group_local_memory_for_overwrite<float[RG][CB]>(
899            sycl::ext::oneapi::this_work_item::get_work_group<3>());
900    const int head = item_ct1.get_group(2) / NCB,
901              cb = item_ct1.get_group(2) % NCB;
902    const int c = item_ct1.get_local_id(2), rg = item_ct1.get_local_id(1),
903              tid = rg * CB + c, col = cb * CB + c;
904    const int qh = head % HK;
905    float s[RPG];
906    float* base = state + ((size_t) (rg * RPG) * HV + head) * S + col;
907    const size_t rs = (size_t) HV * S;
908#pragma unroll
909    for (int r = 0; r < RPG; ++r) s[r] = base[r * rs];
910    float nq[LPT], nk[LPT], nv = 0.0f, ng = 0.0f, nb = 0.0f;
911    auto fetch = [&](int64_t t) {
912        const float* ht = h + t * C;
913#pragma unroll
914        for (int u = 0; u < LPT; ++u) { nq[u] = ht[qh * S + tid + u * NT]; nk[u] = ht[HK * S + qh * S + tid + u * NT]; }
915        nv = ht[2 * HK * S + head * S + col];
916        ng = gate[t * HV + head];
917        nb = beta[t * HV + head];
918    };
919    if (T > 0) fetch(0);
920    for (int64_t t = 0; t < T; ++t) {
921        float cq[LPT], ck[LPT];
922#pragma unroll
923        for (int u = 0; u < LPT; ++u) { cq[u] = nq[u]; ck[u] = nk[u]; }
924        const float cv = nv, cg = ng, cbt = nb;
925        /*
926        DPCT1118: SYCL group functions and algorithms must be encountered in
927        converged control flow. You may need to adjust the code.
928        */
929        /*
930        DPCT1065: Consider replacing sycl::nd_item::barrier() with
931        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
932        better performance if there is no access to global memory.
933        */
934        item_ct1.barrier();
935#pragma unroll
936        for (int u = 0; u < LPT; ++u) { sq[tid + u * NT] = cq[u]; sk[tid + u * NT] = ck[u]; }
937        /*
938        DPCT1118: SYCL group functions and algorithms must be encountered in
939        converged control flow. You may need to adjust the code.
940        */
941        /*
942        DPCT1065: Consider replacing sycl::nd_item::barrier() with
943        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
944        better performance if there is no access to global memory.
945        */
946        item_ct1.barrier();
947        if (t + 1 < T) fetch(t + 1);
948        const float g = sycl::native::exp(cg);
949        float kv = 0.0f;
950#pragma unroll
951        for (int r = 0; r < RPG; ++r)
952            kv = sycl::fma(s[r], sk[rg * RPG + r], kv);
953        red[rg][c] = kv;
954        /*
955        DPCT1118: SYCL group functions and algorithms must be encountered in
956        converged control flow. You may need to adjust the code.
957        */
958        /*
959        DPCT1065: Consider replacing sycl::nd_item::barrier() with
960        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
961        better performance if there is no access to global memory.
962        */
963        item_ct1.barrier();
964        const float kv_col = red[0][c] + red[1][c] + red[2][c] + red[3][c];
965        const float delta = (cv - g * kv_col) * cbt;
966        float o = 0.0f;
967#pragma unroll
968        for (int r = 0; r < RPG; ++r) {
969            s[r] = sycl::fma((float)g, s[r], sk[rg * RPG + r] * delta);
970            o = sycl::fma(s[r], sq[rg * RPG + r], o);
971        }
972        /*
973        DPCT1118: SYCL group functions and algorithms must be encountered in
974        converged control flow. You may need to adjust the code.
975        */
976        /*
977        DPCT1065: Consider replacing sycl::nd_item::barrier() with
978        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
979        better performance if there is no access to global memory.
980        */
981        item_ct1.barrier();
982        red[rg][c] = o;
983        /*
984        DPCT1118: SYCL group functions and algorithms must be encountered in
985        converged control flow. You may need to adjust the code.
986        */
987        /*
988        DPCT1065: Consider replacing sycl::nd_item::barrier() with
989        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
990        better performance if there is no access to global memory.
991        */
992        item_ct1.barrier();
993        if (rg == 0) oc_out[t * HV * S + head * S + col] =
994            (red[0][c] + red[1][c] + red[2][c] + red[3][c]) *
995            sycl::rsqrt((float)S);
996    }
997#pragma unroll
998    for (int r = 0; r < RPG; ++r) base[r * rs] = s[r];
999}
1000
1001__dpct_inline__ void gdn_rec_cols_pipe_local_kernel(float* state,const float* h,const float* gate,const float* beta,float* oc_out,int64_t T){
1002    auto it=sycl::ext::oneapi::this_work_item::get_nd_item<3>();auto sg=it.get_sub_group();
1003    const int head=it.get_group(2)/NCB,cb=it.get_group(2)%NCB;
1004    const int c=it.get_local_id(2),rg=it.get_local_id(1),lane=c&15,col=cb*CB+c,qh=head%HK;
1005    auto& kvred=*sycl::ext::oneapi::group_local_memory_for_overwrite<float[RG][CB]>(it.get_group());
1006    auto& ored=*sycl::ext::oneapi::group_local_memory_for_overwrite<float[RG][CB]>(it.get_group());
1007    float st[RPG];float* base=state+((size_t(rg*RPG)*HV+head)*S+col);const size_t stride=size_t(HV)*S;
1008#pragma unroll
1009    for(int r=0;r<RPG;++r)st[r]=base[r*stride];
1010    for(int64_t t=0;t<T;++t){
1011        const float* row=h+t*C;
1012        const float* qp=row+qh*S+rg*RPG;const float* kp=row+HK*S+qh*S+rg*RPG;
1013        const float q0=qp[lane],q1=qp[lane+16],k0=kp[lane],k1=kp[lane+16];
1014        const float cv=row[2*HK*S+head*S+col],cg=gate[t*HV+head],cbt=beta[t*HV+head];
1015        const float g=sycl::native::exp(cg);float kv=0.f;
1016#pragma unroll
1017        for(int r=0;r<RPG;++r){const float k=sycl::group_broadcast(sg,r<16?k0:k1,r&15);kv=sycl::fma(st[r],k,kv);}
1018        kvred[rg][c]=kv;it.barrier(sycl::access::fence_space::local_space);
1019        const float kvcol=kvred[0][c]+kvred[1][c]+kvred[2][c]+kvred[3][c];
1020        const float delta=(cv-g*kvcol)*cbt;float o=0.f;
1021#pragma unroll
1022        for(int r=0;r<RPG;++r){
1023            const float k=sycl::group_broadcast(sg,r<16?k0:k1,r&15);
1024            const float q=sycl::group_broadcast(sg,r<16?q0:q1,r&15);
1025            st[r]=sycl::fma(g,st[r],k*delta);o=sycl::fma(st[r],q,o);
1026        }
1027        ored[rg][c]=o;it.barrier(sycl::access::fence_space::local_space);
1028        if(rg==0)oc_out[(size_t(t)*HV+head)*S+col]=(ored[0][c]+ored[1][c]+ored[2][c]+ored[3][c])*sycl::rsqrt(float(S));
1029    }
1030#pragma unroll
1031    for(int r=0;r<RPG;++r)base[r*stride]=st[r];
1032}
1033
1034#if !defined(__HIPCC__)
1035// The recurrence with one thread for the three value heads that share a key head (head % HK): column c of heads
1036// qh, qh + 16 and qh + 32, row group rg.  gdn_rec_cols_pipe_kernel spends its time in shared memory, not in
1037// arithmetic: every thread of a warp needs the same 32 q and k values per token (the k twice), and a warp receives one
1038// such broadcast value per clock however wide the load.  Here every q/k value a thread loads feeds three heads, and a
1039// token's k row goes into registers once for both of its uses.  The inputs come in blocks of GDN_TB tokens, copied to
1040// shared memory by cp.async while the block before computes (one token ahead is shorter than a load from L2 takes),
1041// and the two cross-row-group sums have their own arrays, so a token needs 2 __syncthreads instead of 5: the second
1042// one of a token orders every read of rkv before the next token's writes, the next token's first one every read of ro
1043// before the writes after it.  64 blocks instead of 192.  Per value head and column the same arithmetic in the same
1044// order: the same bits (src/prefill/gdn_rec_parity.cu checks them and times the variants: 1.41x on a 4080 Super).
1045// sm_80+ cards that hold its 64 blocks at once (gdn_keyhead_ok); STRATA_GDN_KEYHEAD=0: gdn_rec_cols_pipe_kernel.
1046#if 1   // SYCL port: plain copies (no cp.async)
1047#define STRATA_GDN_CP_ASYNC 0   // Turing builds: plain copies (never launched there, see gdn_keyhead_ok)
1048#else
1049#define STRATA_GDN_CP_ASYNC 1
1050#endif
1051__dpct_inline__ void gdn_cp4(float *smem, const float *gmem) {
1052#if STRATA_GDN_CP_ASYNC
1053    /*
1054    DPCT1053: Migration of device assembly code is not supported.
1055    */
1056    asm volatile("cp.async.ca.shared.global [%0], [%1], 4;\n" ::"r"(
1057                     (unsigned)__cvta_generic_to_shared(smem)),
1058                 "l"(gmem));
1059#else
1060    *smem = *gmem;
1061#endif
1062}
1063__dpct_inline__ void gdn_cp16(float *smem, const float *gmem) {
1064#if STRATA_GDN_CP_ASYNC
1065#if defined(__SYCL_DEVICE_ONLY__) && defined(__NVPTX__)
1066    asm volatile("cp.async.cg.shared.global [%0], [%1], 16;\n" ::"r"(
1067                     (unsigned)__cvta_generic_to_shared(smem)),
1068                 "l"(gmem));
1069#else
1070    *(((uint32_t *)(uintptr_t)(unsigned)__cvta_generic_to_shared(smem))) =
1071        *(((uint32_t *)(uintptr_t)gmem));
1072    if (16 > 4)
1073        *(((uint32_t *)(uintptr_t)(unsigned)__cvta_generic_to_shared(smem)) +
1074          1) = *(((uint32_t *)(uintptr_t)gmem) + 1);
1075    if (16 > 8)
1076        *(((uint32_t *)(uintptr_t)(unsigned)__cvta_generic_to_shared(smem)) +
1077          2) = *(((uint32_t *)(uintptr_t)gmem) + 2);
1078    if (16 > 12)
1079        *(((uint32_t *)(uintptr_t)(unsigned)__cvta_generic_to_shared(smem)) +
1080          3) = *(((uint32_t *)(uintptr_t)gmem) + 3);
1081#endif
1082#else
1083    *reinterpret_cast<sycl::float4*>(smem) = *reinterpret_cast<const sycl::float4*>(gmem);
1084#endif
1085}
1086__dpct_inline__ void gdn_cp_commit() {
1087#if STRATA_GDN_CP_ASYNC
1088#if defined(__SYCL_DEVICE_ONLY__) && defined(__NVPTX__)
1089    asm volatile("cp.async.commit_group;\n" ::);
1090#else
1091
1092#endif
1093#endif
1094}
1095__dpct_inline__ void
1096gdn_cp_wait_prev() { // every group but the newest has landed
1097#if STRATA_GDN_CP_ASYNC
1098#if defined(__SYCL_DEVICE_ONLY__) && defined(__NVPTX__)
1099    asm volatile("cp.async.wait_group 1;\n" ::);
1100#else
1101
1102#endif
1103#endif
1104}
1105constexpr int GDN_TB = 8, VPK = HV / HK;   // tokens per staged block, value heads per key head
1106/*
1107DPCT1110: The total declared local variable size in device function
1108gdn_rec_kh_kernel exceeds 128 bytes and may cause high register pressure.
1109Consult with your hardware vendor to find the total register size available and
1110adjust the code, or use smaller sub-group size to avoid high register pressure.
1111*/
1112__dpct_inline__ void gdn_rec_kh_kernel(float *__restrict__ state,
1113                                       const float *__restrict__ h,
1114                                       const float *__restrict__ gate,
1115                                       const float *__restrict__ beta,
1116                                       float *__restrict__ oc_out, int64_t T) {
1117    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
1118    constexpr int TB = GDN_TB, NT = CB * RG, QKP = S / 4,
1119                  VP = CB / 4; // threads, 16-byte pieces of a q/k row, of v
1120    auto &sq =
1121        *sycl::ext::oneapi::group_local_memory_for_overwrite<float[2][TB][S]>(
1122            sycl::ext::oneapi::this_work_item::get_work_group<3>());
1123    auto &sk =
1124        *sycl::ext::oneapi::group_local_memory_for_overwrite<float[2][TB][S]>(
1125            sycl::ext::oneapi::this_work_item::get_work_group<3>());
1126    auto &sv = *sycl::ext::oneapi::group_local_memory_for_overwrite<
1127        float[2][TB][VPK][CB]>(
1128        sycl::ext::oneapi::this_work_item::get_work_group<3>());
1129    auto &sg =
1130        *sycl::ext::oneapi::group_local_memory_for_overwrite<float[2][TB][VPK]>(
1131            sycl::ext::oneapi::this_work_item::get_work_group<3>());
1132    auto &sb =
1133        *sycl::ext::oneapi::group_local_memory_for_overwrite<float[2][TB][VPK]>(
1134            sycl::ext::oneapi::this_work_item::get_work_group<3>());
1135    auto &rkv = *sycl::ext::oneapi::group_local_memory_for_overwrite<
1136        float[VPK][RG][CB]>(
1137        sycl::ext::oneapi::this_work_item::get_work_group<3>());
1138    auto &ro = *sycl::ext::oneapi::group_local_memory_for_overwrite<
1139        float[VPK][RG][CB]>(
1140        sycl::ext::oneapi::this_work_item::get_work_group<3>());
1141    const int qh = item_ct1.get_group(2) / NCB,
1142              cb = item_ct1.get_group(2) % NCB;
1143    const int c = item_ct1.get_local_id(2), rg = item_ct1.get_local_id(1),
1144              tid = rg * CB + c, col = cb * CB + c;
1145    float s[VPK][RPG];
1146    const size_t rs = (size_t) HV * S;
1147#pragma unroll
1148    for (int j = 0; j < VPK; ++j) {
1149        const float* base = state + ((size_t) (rg * RPG) * HV + qh + j * HK) * S + col;
1150#pragma unroll
1151        for (int r = 0; r < RPG; ++r) s[j][r] = base[r * rs];
1152    }
1153    const int64_t nblk = (T + TB - 1) / TB;
1154    auto stage = [&](int64_t k) {   // tokens [k * TB, k * TB + TB) into buffer k & 1
1155        const int bb = (int) (k & 1);
1156        const int64_t t0 = k * TB;
1157        for (int p = tid; p < TB * 2 * QKP; p += NT) {
1158            const int i = p / (2 * QKP), w = p % (2 * QKP), isk = w / QKP, jj = (w % QKP) * 4;
1159            if (t0 + i < T)
1160                gdn_cp16(isk ? &sk[bb][i][jj] : &sq[bb][i][jj], h + (t0 + i) * C + (isk ? HK * S : 0) + qh * S + jj);
1161        }
1162        for (int p = tid; p < TB * VPK * VP; p += NT) {
1163            const int i = p / (VPK * VP), w = p % (VPK * VP), j = w / VP, jj = (w % VP) * 4;
1164            if (t0 + i < T)
1165                gdn_cp16(&sv[bb][i][j][jj], h + (t0 + i) * C + 2 * HK * S + (qh + j * HK) * S + cb * CB + jj);
1166        }
1167        for (int p = tid; p < 2 * TB * VPK; p += NT) {
1168            const int isb = p / (TB * VPK), w = p % (TB * VPK), i = w / VPK, j = w % VPK;
1169            if (t0 + i < T)
1170                gdn_cp4(isb ? &sb[bb][i][j] : &sg[bb][i][j], (isb ? beta : gate) + (t0 + i) * HV + qh + j * HK);
1171        }
1172    };
1173    if (nblk > 0) stage(0);
1174    gdn_cp_commit();
1175    for (int64_t k = 0; k < nblk; ++k) {
1176        // buffer (k + 1) & 1 was read by block k - 1, whose last token's second __syncthreads every thread has passed
1177        if (k + 1 < nblk) stage(k + 1);
1178        gdn_cp_commit();
1179        gdn_cp_wait_prev();
1180        /*
1181        DPCT1118: SYCL group functions and algorithms must be encountered in
1182        converged control flow. You may need to adjust the code.
1183        */
1184        /*
1185        DPCT1065: Consider replacing sycl::nd_item::barrier() with
1186        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
1187        better performance if there is no access to global memory.
1188        */
1189        item_ct1.barrier();
1190        const int bb = (int) (k & 1);
1191        const int n = (int) ((T - k * TB) < TB ? (T - k * TB) : TB);
1192        for (int i = 0; i < n; ++i) {
1193            const int64_t t = k * TB + i;
1194            float kc[RPG];
1195#pragma unroll
1196            for (int r = 0; r < RPG; ++r) kc[r] = sk[bb][i][rg * RPG + r];
1197            float g[VPK], kv[VPK], delta[VPK], o[VPK];
1198#pragma unroll
1199            for (int j = 0; j < VPK; ++j) {
1200                g[j] = sycl::native::exp(sg[bb][i][j]); kv[j] = 0.0f;
1201                o[j] = 0.0f;
1202            }
1203#pragma unroll
1204            for (int r = 0; r < RPG; ++r)
1205#pragma unroll
1206                for (int j = 0; j < VPK; ++j)
1207                    kv[j] = sycl::fma(s[j][r], kc[r], kv[j]);
1208#pragma unroll
1209            for (int j = 0; j < VPK; ++j) rkv[j][rg][c] = kv[j];
1210            /*
1211            DPCT1118: SYCL group functions and algorithms must be
1212            encountered in converged control flow. You may need to adjust the
1213            code.
1214            */
1215            /*
1216            DPCT1065: Consider replacing sycl::nd_item::barrier() with
1217            sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
1218            better performance if there is no access to global memory.
1219            */
1220            item_ct1.barrier();
1221#pragma unroll
1222            for (int j = 0; j < VPK; ++j) {
1223                const float kv_col = rkv[j][0][c] + rkv[j][1][c] + rkv[j][2][c] + rkv[j][3][c];
1224                delta[j] = (sv[bb][i][j][c] - g[j] * kv_col) * sb[bb][i][j];
1225            }
1226#pragma unroll
1227            for (int r = 0; r < RPG; ++r) {
1228                const float qr = sq[bb][i][rg * RPG + r];
1229#pragma unroll
1230                for (int j = 0; j < VPK; ++j) {
1231                    s[j][r] = sycl::fma(g[j], s[j][r], kc[r] * delta[j]);
1232                    o[j] = sycl::fma(s[j][r], (float)qr, o[j]);
1233                }
1234            }
1235#pragma unroll
1236            for (int j = 0; j < VPK; ++j) ro[j][rg][c] = o[j];
1237            /*
1238            DPCT1118: SYCL group functions and algorithms must be
1239            encountered in converged control flow. You may need to adjust the
1240            code.
1241            */
1242            /*
1243            DPCT1065: Consider replacing sycl::nd_item::barrier() with
1244            sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
1245            better performance if there is no access to global memory.
1246            */
1247            item_ct1.barrier();
1248            if (rg < VPK)   // row group j writes head j's output
1249                oc_out[t * HV * S + (qh + rg * HK) * S + col] =
1250                    (ro[rg][0][c] + ro[rg][1][c] + ro[rg][2][c] +
1251                     ro[rg][3][c]) *
1252                    sycl::rsqrt((float)S);
1253        }
1254    }
1255#pragma unroll
1256    for (int j = 0; j < VPK; ++j) {
1257        float* base = state + ((size_t) (rg * RPG) * HV + qh + j * HK) * S + col;
1258#pragma unroll
1259        for (int r = 0; r < RPG; ++r) base[r * rs] = s[j][r];
1260    }
1261}
1262// gdn_rec_kh_kernel where it pays: a CUDA card with cp.async (sm_80+) that holds all 64 of its blocks at once (each
1263// walks the whole chunk, so blocks left for a second wave would double the time), and not with 48 to 63 SMs.  The
1264// busiest SM sets the pace: from 64 SMs up this kernel has one block per SM, below that two on some SMs (1.5 times as
1265// long), while the kernel before has ceil(192 / SMs); two against at most four is a draw.  With the engine's grids on
1266// a 4080 SUPER held to fewer SMs (gdn_rec_parity --bench): 1.40-1.42x at 64 to 80 SMs, 1.02-1.04x at 48 to 63,
1267// 1.28-1.31x at 39 to 47, 1.53-1.57x at 32 to 38; an Ampere card gained less at 82 SMs (1.28x on a 3090 against
1268// 1.41x here), so 48 to 63 SMs keep the kernel before.  Per call, from the current device (a layer split can mix
1269// cards).
1270bool gdn_keyhead_ok() {
1271    // SYCL port: upstream picks it by SM count and occupancy (NVIDIA thresholds, measured on Ada/Ampere). On Xe the
1272    // key-head kernel is an A/B until measured: STRATA_GDN_KEYHEAD=1 runs it, anything else keeps the kernel before.
1273    static const bool on = [] { const char* v = std::getenv("STRATA_GDN_KEYHEAD"); return v != nullptr && std::atoi(v) == 1; }();
1274    return on;
1275}
1276#endif
1277#if defined(__HIPCC__)   // the Aurora (gfx11) recurrence kernels: AMD builds only
1278// Aurora (S23): the recurrence with the column-split grid of gdn_rec_cols_pipe_kernel (four 32-column blocks per value
1279// head) but FOUR LANES per column, lane g holding the column's state rows 32g .. 32g + 31 in registers - exactly the
1280// row group the old kernel's thread (col, rg = g) held - so a token needs no __syncthreads: the four kv / o partials
1281// meet through wave shuffles and are added in the old order red[0] + red[1] + red[2] + red[3] (the same bits;
1282// tests/hip/gdn_rec_head.cpp).  The q/k rows, v, gate and beta are staged in LDS HT tokens at a time, the next chunk
1283// loaded into registers while this one computes, and a token's k and q rows are read into registers before its
1284// products (one LDS latency per token, not one per load).  The old kernels took ~4 barriers per token and ~3.5 us
1285// per token and layer on the Radeon 8060S; the output norm runs after it in gdn_out_norm_warp_kernel.
1286// STRATA_GDN_HEAD=0: the old kernels.
1287constexpr int HT = 4;                           // tokens per staged chunk (LDS ~10 KB: all 192 blocks resident)
1288constexpr int QCB = 32;                         // columns per block
1289constexpr int QTH = QCB * 4;                    // threads per block: 4 lanes per column
1290constexpr int QRS = 36;                         // staged row-group stride (32 rows + 4 pad: the 4 groups' reads
1291                                                // land in different LDS banks)
1292constexpr int QPF = HT * 2 * S / 4 / QTH;       // float4 of q/k each thread prefetches per chunk (2)
1293__global__ void __launch_bounds__(QTH) gdn_rec_quad_kernel(float* __restrict__ state, const float* __restrict__ h,
1294                                                           const float* __restrict__ gate, const float* __restrict__ beta,
1295                                                           float* __restrict__ oc_out, int64_t T) {
1296    __shared__ __align__(16) float sqk[2][HT][2][4 * QRS];   // [buffer][token][q | k][group][row (padded)]
1297    __shared__ float sgb[2][2][HT];                         // [buffer][gate | beta][token]
1298    __shared__ float sv[2][HT][QCB];                        // [buffer][token][column] v
1299    const int head = blockIdx.x / (S / QCB), cb = blockIdx.x % (S / QCB);
1300    const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5;
1301    const int g = lane >> 3, cl = wave * 8 + (lane & 7), col = cb * QCB + cl;   // row group, column in block / head
1302    const int qh = head % HK;
1303    float s[32];
1304    {
1305        const float* base = state + ((size_t) (g * 32) * HV + head) * S + col;
1306#pragma unroll
1307        for (int r = 0; r < 32; ++r) s[r] = base[(size_t) r * HV * S];
1308    }
1309    float4 pf[QPF];
1310    float pv[HT], pgb = 0.0f;
1311    // chunk c's inputs into registers: q/k (float4 i of the chunk's [token][q|k][S/4] block), the column's v (lanes of
1312    // group 0) and gate (threads 0..HT-1) / beta (HT..2HT-1) of token `tid % HT`
1313    auto fetch = [&](int64_t c) {
1314        const int64_t t0 = c * HT;
1315#pragma unroll
1316        for (int u = 0; u < QPF; ++u) {
1317            const int i = tid + u * QTH;
1318            const int tt = i / (2 * S / 4), rem = i % (2 * S / 4), part = rem / (S / 4), r4 = rem % (S / 4);
1319            const int64_t t = t0 + tt;
1320            pf[u] = t < T ? *reinterpret_cast<const float4*>(h + t * C + part * HK * S + qh * S + r4 * 4)
1321                          : make_float4(0.f, 0.f, 0.f, 0.f);
1322        }
1323        if (g == 0) {
1324#pragma unroll
1325            for (int tt = 0; tt < HT; ++tt) {
1326                const int64_t t = t0 + tt;
1327                pv[tt] = t < T ? h[t * C + 2 * HK * S + head * S + col] : 0.0f;
1328            }
1329        }
1330        if (tid < 2 * HT) {
1331            const int64_t t = t0 + (tid % HT);
1332            pgb = t < T ? (tid < HT ? gate : beta)[t * HV + head] : 0.0f;
1333        }
1334    };
1335    const float rs_s = rsqrtf((float) S);
1336    const int src0 = lane & 7;                       // lane of group 0 for this column; group j is src0 + 8 j
1337    const int64_t nch = (T + HT - 1) / HT;
1338    if (nch > 0) fetch(0);
1339    for (int64_t c = 0; c < nch; ++c) {
1340        const int b = (int) (c & 1);
1341        if (g == 0) {
1342#pragma unroll
1343            for (int tt = 0; tt < HT; ++tt) sv[b][tt][cl] = pv[tt];
1344        }
1345#pragma unroll
1346        for (int u = 0; u < QPF; ++u) {
1347            const int i = tid + u * QTH;
1348            const int tt = i / (2 * S / 4), rem = i % (2 * S / 4), part = rem / (S / 4), r4 = rem % (S / 4);
1349            const int row = r4 * 4;
1350            *reinterpret_cast<float4*>(&sqk[b][tt][part][(row >> 5) * QRS + (row & 31)]) = pf[u];
1351        }
1352        if (tid < 2 * HT) sgb[b][tid / HT][tid % HT] = pgb;
1353        __syncthreads();                               // chunk c staged (buffer b was last read two chunks ago)
1354        if (c + 1 < nch) fetch(c + 1);
1355        const int64_t t0 = c * HT;
1356        const int nt = (int) (T - t0 < HT ? T - t0 : HT);
1357        for (int tt = 0; tt < nt; ++tt) {
1358            float k[32], q[32];
1359            {
1360                const float4* k4 = reinterpret_cast<const float4*>(&sqk[b][tt][1][g * QRS]);
1361                const float4* q4 = reinterpret_cast<const float4*>(&sqk[b][tt][0][g * QRS]);
1362#pragma unroll
1363                for (int j = 0; j < 8; ++j) {
1364                    const float4 kk = k4[j], qq = q4[j];
1365                    k[4 * j] = kk.x; k[4 * j + 1] = kk.y; k[4 * j + 2] = kk.z; k[4 * j + 3] = kk.w;
1366                    q[4 * j] = qq.x; q[4 * j + 1] = qq.y; q[4 * j + 2] = qq.z; q[4 * j + 3] = qq.w;
1367                }
1368            }
1369            const float g_exp = __expf(sgb[b][0][tt]);
1370            float kv = 0.0f;
1371#pragma unroll
1372            for (int r = 0; r < 32; ++r) kv = fmaf(s[r], k[r], kv);
1373            const float p0 = __shfl_sync(0xffffffffu, kv, src0), p1 = __shfl_sync(0xffffffffu, kv, src0 + 8),
1374                        p2 = __shfl_sync(0xffffffffu, kv, src0 + 16), p3 = __shfl_sync(0xffffffffu, kv, src0 + 24);
1375            const float kv_col = p0 + p1 + p2 + p3;
1376            const float cvt = sv[b][tt][cl], cbt = sgb[b][1][tt];
1377            const float delta = (cvt - g_exp * kv_col) * cbt;
1378            float o = 0.0f;
1379#pragma unroll
1380            for (int r = 0; r < 32; ++r) {
1381                s[r] = fmaf(g_exp, s[r], k[r] * delta);
1382                o = fmaf(s[r], q[r], o);
1383            }
1384            const float o0 = __shfl_sync(0xffffffffu, o, src0), o1 = __shfl_sync(0xffffffffu, o, src0 + 8),
1385                        o2 = __shfl_sync(0xffffffffu, o, src0 + 16), o3 = __shfl_sync(0xffffffffu, o, src0 + 24);
1386            if (g == 0) oc_out[(t0 + tt) * HV * S + head * S + col] = (o0 + o1 + o2 + o3) * rs_s;
1387        }
1388    }
1389    {
1390        float* base = state + ((size_t) (g * 32) * HV + head) * S + col;
1391#pragma unroll
1392        for (int r = 0; r < 32; ++r) base[(size_t) r * HV * S] = s[r];
1393    }
1394}
1395// Aurora (S23, opt-in STRATA_GDN_PP=1): gdn_rec_quad_kernel with the same arithmetic in the same order, two changes in
1396// how it is compiled.  (1) The VGPR count: the 32 state-row addresses of the first loads were kept live across the
1397// whole walk to be reused by the final stores (64 VGPRs, 196 in all = 7 waves a SIMD for the 192 blocks of 4 waves
1398// that need 9.6): the stores' lane offset goes through an asm so the addresses are made again, 133 VGPRs, all blocks
1399// resident.  (2) A full chunk's four tokens run with the state alternating between two register sets (the update
1400// writes the other set), so the compiler emits no 32 register copies after the update.
1401__global__ void __launch_bounds__(QTH) gdn_rec_quad_pp_kernel(float* __restrict__ state, const float* __restrict__ h,
1402                                                           const float* __restrict__ gate, const float* __restrict__ beta,
1403                                                           float* __restrict__ oc_out, int64_t T) {
1404    __shared__ __align__(16) float sqk[2][HT][2][4 * QRS];   // [buffer][token][q | k][group][row (padded)]
1405    __shared__ float sgb[2][2][HT];                         // [buffer][gate | beta][token]
1406    __shared__ float sv[2][HT][QCB];                        // [buffer][token][column] v
1407    const int head = blockIdx.x / (S / QCB), cb = blockIdx.x % (S / QCB);
1408    const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5;
1409    const int g = lane >> 3, cl = wave * 8 + (lane & 7), col = cb * QCB + cl;   // row group, column in block / head
1410    const int qh = head % HK;
1411    float s[32];
1412    {
1413        const float* sb = state + (size_t) head * S;
1414        const uint32_t voff = (uint32_t) ((g * 32) * HV * S + col);
1415#pragma unroll
1416        for (int r = 0; r < 32; ++r) s[r] = sb[(size_t) r * HV * S + voff];
1417    }
1418    float4 pf[QPF];
1419    float pv[HT], pgb = 0.0f;
1420    // chunk c's inputs into registers: q/k (float4 i of the chunk's [token][q|k][S/4] block), the column's v (lanes of
1421    // group 0) and gate (threads 0..HT-1) / beta (HT..2HT-1) of token `tid % HT`
1422    auto fetch = [&](int64_t c) {
1423        const int64_t t0 = c * HT;
1424#pragma unroll
1425        for (int u = 0; u < QPF; ++u) {
1426            const int i = tid + u * QTH;
1427            const int tt = i / (2 * S / 4), rem = i % (2 * S / 4), part = rem / (S / 4), r4 = rem % (S / 4);
1428            const int64_t t = t0 + tt;
1429            pf[u] = t < T ? *reinterpret_cast<const float4*>(h + t * C + part * HK * S + qh * S + r4 * 4)
1430                          : make_float4(0.f, 0.f, 0.f, 0.f);
1431        }
1432        if (g == 0) {
1433#pragma unroll
1434            for (int tt = 0; tt < HT; ++tt) {
1435                const int64_t t = t0 + tt;
1436                pv[tt] = t < T ? h[t * C + 2 * HK * S + head * S + col] : 0.0f;
1437            }
1438        }
1439        if (tid < 2 * HT) {
1440            const int64_t t = t0 + (tid % HT);
1441            pgb = t < T ? (tid < HT ? gate : beta)[t * HV + head] : 0.0f;
1442        }
1443    };
1444    const float rs_s = rsqrtf((float) S);
1445    const int src0 = lane & 7;                       // lane of group 0 for this column; group j is src0 + 8 j
1446    const int64_t nch = (T + HT - 1) / HT;
1447    if (nch > 0) fetch(0);
1448    for (int64_t c = 0; c < nch; ++c) {
1449        const int b = (int) (c & 1);
1450        if (g == 0) {
1451#pragma unroll
1452            for (int tt = 0; tt < HT; ++tt) sv[b][tt][cl] = pv[tt];
1453        }
1454#pragma unroll
1455        for (int u = 0; u < QPF; ++u) {
1456            const int i = tid + u * QTH;
1457            const int tt = i / (2 * S / 4), rem = i % (2 * S / 4), part = rem / (S / 4), r4 = rem % (S / 4);
1458            const int row = r4 * 4;
1459            *reinterpret_cast<float4*>(&sqk[b][tt][part][(row >> 5) * QRS + (row & 31)]) = pf[u];
1460        }
1461        if (tid < 2 * HT) sgb[b][tid / HT][tid % HT] = pgb;
1462        __syncthreads();                               // chunk c staged (buffer b was last read two chunks ago)
1463        if (c + 1 < nch) fetch(c + 1);
1464        const int64_t t0 = c * HT;
1465        const int nt = (int) (T - t0 < HT ? T - t0 : HT);
1466        auto token = [&](int tt, float (&sin)[32], float (&sout)[32]) {
1467            float k[32], q[32];
1468            {
1469                const float4* k4 = reinterpret_cast<const float4*>(&sqk[b][tt][1][g * QRS]);
1470                const float4* q4 = reinterpret_cast<const float4*>(&sqk[b][tt][0][g * QRS]);
1471#pragma unroll
1472                for (int j = 0; j < 8; ++j) {
1473                    const float4 kk = k4[j], qq = q4[j];
1474                    k[4 * j] = kk.x; k[4 * j + 1] = kk.y; k[4 * j + 2] = kk.z; k[4 * j + 3] = kk.w;
1475                    q[4 * j] = qq.x; q[4 * j + 1] = qq.y; q[4 * j + 2] = qq.z; q[4 * j + 3] = qq.w;
1476                }
1477            }
1478            const float g_exp = __expf(sgb[b][0][tt]);
1479            float kv = 0.0f;
1480#pragma unroll
1481            for (int r = 0; r < 32; ++r) kv = fmaf(sin[r], k[r], kv);
1482            const float p0 = __shfl_sync(0xffffffffu, kv, src0), p1 = __shfl_sync(0xffffffffu, kv, src0 + 8),
1483                        p2 = __shfl_sync(0xffffffffu, kv, src0 + 16), p3 = __shfl_sync(0xffffffffu, kv, src0 + 24);
1484            const float kv_col = p0 + p1 + p2 + p3;
1485            const float cvt = sv[b][tt][cl], cbt = sgb[b][1][tt];
1486            const float delta = (cvt - g_exp * kv_col) * cbt;
1487            float o = 0.0f;
1488#pragma unroll
1489            for (int r = 0; r < 32; ++r) {
1490                sout[r] = fmaf(g_exp, sin[r], k[r] * delta);
1491                o = fmaf(sout[r], q[r], o);
1492            }
1493            const float o0 = __shfl_sync(0xffffffffu, o, src0), o1 = __shfl_sync(0xffffffffu, o, src0 + 8),
1494                        o2 = __shfl_sync(0xffffffffu, o, src0 + 16), o3 = __shfl_sync(0xffffffffu, o, src0 + 24);
1495            if (g == 0) oc_out[(t0 + tt) * HV * S + head * S + col] = (o0 + o1 + o2 + o3) * rs_s;
1496        };
1497        if (nt == HT) {   // the state alternates between two register sets: no copy after the update
1498            float s2[32];
1499            token(0, s, s2);
1500            token(1, s2, s);
1501            token(2, s, s2);
1502            token(3, s2, s);
1503        } else {
1504            for (int tt = 0; tt < nt; ++tt) {
1505                float s2[32];
1506                token(tt, s, s2);
1507#pragma unroll
1508                for (int r = 0; r < 32; ++r) s[r] = s2[r];
1509            }
1510        }
1511    }
1512    {
1513        float* sb = state + (size_t) head * S;
1514        uint32_t voff = (uint32_t) ((g * 32) * HV * S + col);
1515        asm volatile("" : "+v"(voff));   // (so the loads' 32 addresses are not kept alive across the whole loop)
1516#pragma unroll
1517        for (int r = 0; r < 32; ++r) sb[(size_t) r * HV * S + voff] = s[r];
1518    }
1519}
1520
1521// Aurora (S23, opt-in STRATA_GDN_PP=2): gdn_rec_quad_kernel with two columns per lane (a wave: 4 row groups x 8 lanes x
1522// 2 columns = 16 columns; a block of 4 waves 64 columns, 96 blocks).  A lane's two columns share the k / q rows it
1523// reads from shared memory (half the LDS reads and shuffles per column, the kernel's limit) and give each wave two
1524// independent dependency chains; the 384 waves fit in one round at 230 VGPRs.  Per column the same arithmetic in
1525// the same order (the same bits as gdn_rec_quad_kernel).  The store of the state goes through an asm for the reason
1526// given at gdn_rec_quad_pp_kernel.
1527
1528// ---- C2: two columns per lane (a wave: 4 row groups x 8 lanes x 2 columns = 16 columns; a block of 4 waves 64
1529// columns).  A lane's two columns share the k / q rows it reads from LDS (half the LDS reads and shuffles per column
1530// and two independent dependency chains in each wave).  Per column the same arithmetic in the same order.
1531constexpr int C2CB = 64;                          // columns per block
1532constexpr int C2PF = HT * 2 * S / 4 / QTH;        // float4 of q/k each thread prefetches per chunk (2)
1533__global__ void __launch_bounds__(QTH) gdn_rec_quad2c_kernel(float* __restrict__ state, const float* __restrict__ h,
1534                                                             const float* __restrict__ gate, const float* __restrict__ beta,
1535                                                             float* __restrict__ oc_out, int64_t T) {
1536    __shared__ __align__(16) float sqk[2][HT][2][4 * QRS];
1537    __shared__ float sgb[2][2][HT];
1538    __shared__ float sv[2][HT][C2CB];
1539    const int head = blockIdx.x / (S / C2CB), cb = blockIdx.x % (S / C2CB);
1540    const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5;
1541    const int g = lane >> 3, cl0 = wave * 16 + (lane & 7), cl1 = cl0 + 8;   // the lane's two columns in the block
1542    const int col0 = cb * C2CB + cl0, col1 = cb * C2CB + cl1;
1543    const int qh = head % HK;
1544    float s0[32], s1[32];
1545    {
1546        const float* sb = state + (size_t) head * S;
1547        const uint32_t voff = (uint32_t) ((g * 32) * HV * S);
1548#pragma unroll
1549        for (int r = 0; r < 32; ++r) { s0[r] = sb[(size_t) r * HV * S + voff + col0]; s1[r] = sb[(size_t) r * HV * S + voff + col1]; }
1550    }
1551    float4 pf[C2PF];
1552    float pv[2][HT], pgb = 0.0f;
1553    auto fetch = [&](int64_t c) {
1554        const int64_t t0 = c * HT;
1555#pragma unroll
1556        for (int u = 0; u < C2PF; ++u) {
1557            const int i = tid + u * QTH;
1558            const int tt = i / (2 * S / 4), rem = i % (2 * S / 4), part = rem / (S / 4), r4 = rem % (S / 4);
1559            const int64_t t = t0 + tt;
1560            pf[u] = t < T ? *reinterpret_cast<const float4*>(h + t * C + part * HK * S + qh * S + r4 * 4)
1561                          : make_float4(0.f, 0.f, 0.f, 0.f);
1562        }
1563        if (g == 0) {
1564#pragma unroll
1565            for (int tt = 0; tt < HT; ++tt) {
1566                const int64_t t = t0 + tt;
1567                pv[0][tt] = t < T ? h[t * C + 2 * HK * S + head * S + col0] : 0.0f;
1568                pv[1][tt] = t < T ? h[t * C + 2 * HK * S + head * S + col1] : 0.0f;
1569            }
1570        }
1571        if (tid < 2 * HT) {
1572            const int64_t t = t0 + (tid % HT);
1573            pgb = t < T ? (tid < HT ? gate : beta)[t * HV + head] : 0.0f;
1574        }
1575    };
1576    const float rs_s = rsqrtf((float) S);
1577    const int src0 = lane & 7;
1578    const int64_t nch = (T + HT - 1) / HT;
1579    if (nch > 0) fetch(0);
1580    for (int64_t c = 0; c < nch; ++c) {
1581        const int b = (int) (c & 1);
1582        if (g == 0) {
1583#pragma unroll
1584            for (int tt = 0; tt < HT; ++tt) { sv[b][tt][cl0] = pv[0][tt]; sv[b][tt][cl1] = pv[1][tt]; }
1585        }
1586#pragma unroll
1587        for (int u = 0; u < C2PF; ++u) {
1588            const int i = tid + u * QTH;
1589            const int tt = i / (2 * S / 4), rem = i % (2 * S / 4), part = rem / (S / 4), r4 = rem % (S / 4);
1590            const int row = r4 * 4;
1591            *reinterpret_cast<float4*>(&sqk[b][tt][part][(row >> 5) * QRS + (row & 31)]) = pf[u];
1592        }
1593        if (tid < 2 * HT) sgb[b][tid / HT][tid % HT] = pgb;
1594        __syncthreads();
1595        if (c + 1 < nch) fetch(c + 1);
1596        const int64_t t0 = c * HT;
1597        const int nt = (int) (T - t0 < HT ? T - t0 : HT);
1598        for (int tt = 0; tt < nt; ++tt) {
1599            float k[32], q[32];
1600            {
1601                const float4* k4 = reinterpret_cast<const float4*>(&sqk[b][tt][1][g * QRS]);
1602                const float4* q4 = reinterpret_cast<const float4*>(&sqk[b][tt][0][g * QRS]);
1603#pragma unroll
1604                for (int j = 0; j < 8; ++j) {
1605                    const float4 kk = k4[j], qq = q4[j];
1606                    k[4 * j] = kk.x; k[4 * j + 1] = kk.y; k[4 * j + 2] = kk.z; k[4 * j + 3] = kk.w;
1607                    q[4 * j] = qq.x; q[4 * j + 1] = qq.y; q[4 * j + 2] = qq.z; q[4 * j + 3] = qq.w;
1608                }
1609            }
1610            const float g_exp = __expf(sgb[b][0][tt]);
1611            float kv0 = 0.0f, kv1 = 0.0f;
1612#pragma unroll
1613            for (int r = 0; r < 32; ++r) { kv0 = fmaf(s0[r], k[r], kv0); kv1 = fmaf(s1[r], k[r], kv1); }
1614            const float a0 = __shfl_sync(0xffffffffu, kv0, src0), a1 = __shfl_sync(0xffffffffu, kv0, src0 + 8),
1615                        a2 = __shfl_sync(0xffffffffu, kv0, src0 + 16), a3 = __shfl_sync(0xffffffffu, kv0, src0 + 24);
1616            const float b0 = __shfl_sync(0xffffffffu, kv1, src0), b1 = __shfl_sync(0xffffffffu, kv1, src0 + 8),
1617                        b2 = __shfl_sync(0xffffffffu, kv1, src0 + 16), b3 = __shfl_sync(0xffffffffu, kv1, src0 + 24);
1618            const float kvc0 = a0 + a1 + a2 + a3, kvc1 = b0 + b1 + b2 + b3;
1619            const float cbt = sgb[b][1][tt];
1620            const float d0 = (sv[b][tt][cl0] - g_exp * kvc0) * cbt, d1 = (sv[b][tt][cl1] - g_exp * kvc1) * cbt;
1621            float o0 = 0.0f, o1 = 0.0f;
1622#pragma unroll
1623            for (int r = 0; r < 32; ++r) {
1624                s0[r] = fmaf(g_exp, s0[r], k[r] * d0);
1625                s1[r] = fmaf(g_exp, s1[r], k[r] * d1);
1626                o0 = fmaf(s0[r], q[r], o0);
1627                o1 = fmaf(s1[r], q[r], o1);
1628            }
1629            const float x0 = __shfl_sync(0xffffffffu, o0, src0), x1 = __shfl_sync(0xffffffffu, o0, src0 + 8),
1630                        x2 = __shfl_sync(0xffffffffu, o0, src0 + 16), x3 = __shfl_sync(0xffffffffu, o0, src0 + 24);
1631            const float y0 = __shfl_sync(0xffffffffu, o1, src0), y1 = __shfl_sync(0xffffffffu, o1, src0 + 8),
1632                        y2 = __shfl_sync(0xffffffffu, o1, src0 + 16), y3 = __shfl_sync(0xffffffffu, o1, src0 + 24);
1633            if (g == 0) {
1634                oc_out[(t0 + tt) * HV * S + head * S + col0] = (x0 + x1 + x2 + x3) * rs_s;
1635                oc_out[(t0 + tt) * HV * S + head * S + col1] = (y0 + y1 + y2 + y3) * rs_s;
1636            }
1637        }
1638    }
1639    {
1640        float* sb = state + (size_t) head * S;
1641        uint32_t voff = (uint32_t) ((g * 32) * HV * S);
1642        asm volatile("" : "+v"(voff));
1643#pragma unroll
1644        for (int r = 0; r < 32; ++r) { sb[(size_t) r * HV * S + voff + col0] = s0[r]; sb[(size_t) r * HV * S + voff + col1] = s1[r]; }
1645    }
1646}
1647
1648// gdn_out_norm_kernel's body over a grid-stride walk of the (token, head) rows: the old kernel launched a 128-thread
1649// block per row (T * 48 blocks; ~45 GB/s on the 8060S).  The same code per row (the same compiled arithmetic: a wave
1650// per row with four values per lane rounded differently in its first xor step).
1651template <bool WY>
1652__global__ void __launch_bounds__(S) gdn_out_norm_loop_kernel(const float* __restrict__ z, const float* __restrict__ gamma,
1653                                                              float eps, float* __restrict__ y, uint16_t* __restrict__ y16,
1654                                                              int64_t rows, int64_t ld16) {
1655    __shared__ float wsum[4];
1656    const int col = threadIdx.x;
1657    for (int64_t row = blockIdx.x; row < rows; row += gridDim.x) {
1658        const size_t at = (size_t) row * S + col;
1659        const float oc = y[at];
1660        // (warp_sum as the compiler built it: the first xor step adds the partner's rounded square to an unrounded own
1661        // one, an fma; spelled out so neither instance's contraction can differ)
1662        float sp = __fmaf_rn(oc, oc, __shfl_xor_sync(0xffffffffu, __fmul_rn(oc, oc), 16));
1663#pragma unroll
1664        for (int o = 8; o > 0; o >>= 1) sp = __fadd_rn(sp, __shfl_xor_sync(0xffffffffu, sp, o));
1665        __syncthreads();                               // the previous row's sums are read
1666        if ((col & 31) == 0) wsum[col >> 5] = sp;
1667        __syncthreads();
1668        const float ss = wsum[0] + wsum[1] + wsum[2] + wsum[3];
1669        const float bp = oc * rsqrtf(ss / (float) S + eps) * gamma[col], sg = sigm(z[at]);
1670        const size_t o16 = (size_t) (row / HV) * ld16 + (size_t) (row % HV) * S + col;
1671        if constexpr (WY) {
1672            const float v = bp * sg;
1673            y[at] = v;
1674            y16[o16] = hf(v);
1675        } else {
1676            // STRATA_GDN_NOY=1: nothing reads the FP32 result (403 MB per 16K chunk).  The FP16 value is what the
1677            // compiler makes of hf(v) next to the store: v_fma_mixlo_f16, the product rounded to FP16 once
1678            unsigned r;
1679            asm("v_fma_mixlo_f16 %0, %1, %2, 0" : "=v"(r) : "v"(sg), "v"(bp));
1680            y16[o16] = (uint16_t) r;
1681        }
1682    }
1683}
1684#endif   // __HIPCC__
1685__dpct_inline__ void gdn_out_norm_kernel(const float *__restrict__ z,
1686                                         const float *__restrict__ gamma,
1687                                         float eps, float *__restrict__ y,
1688                                         uint16_t *__restrict__ y16,
1689                                         int64_t ld16) {
1690    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
1691auto &wsum = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[4]>(
1692    sycl::ext::oneapi::this_work_item::get_work_group<3>());
1693    const int64_t t = item_ct1.get_group(2);
1694    const int head = item_ct1.get_group(1), col = item_ct1.get_local_id(2);
1695    const size_t at = (size_t) t * HV * S + (size_t) head * S + col;
1696    const float oc = y[at];
1697    float sp = warp_sum(oc * oc);
1698    if ((col & 31) == 0) wsum[col >> 5] = sp;
1699    item_ct1.barrier(sycl::access::fence_space::local_space);
1700    const float ss = wsum[0] + wsum[1] + wsum[2] + wsum[3];
1701    const float v = oc * sycl::rsqrt(ss / (float)S + eps) * gamma[col] *
1702                    sigm(z[t * HV * S + head * S + col]);
1703    y16[(size_t) t * ld16 + (size_t) head * S + col] = hf(v);   // (the FP32 normalized value is not stored: nothing reads it)
1704}
1705
1706// ---------------------------------------------------------------- MoE
1707template <int REG>
1708/*
1709DPCT1110: The total declared local variable size in device function
1710route_kernel exceeds 128 bytes and may cause high register pressure. Consult
1711with your hardware vendor to find the total register size available and adjust
1712the code, or use smaller sub-group size to avoid high register pressure.
1713*/
1714__dpct_inline__ void route_kernel(const float *__restrict__ logits,
1715                                  int32_t *__restrict__ ids,
1716                                  float *__restrict__ wout, int64_t T) {
1717    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
1718    const int64_t t =
1719        (int64_t)item_ct1.get_group(2) * (item_ct1.get_local_range(2) >> 5) +
1720        (item_ct1.get_local_id(2) >> 5);
1721    if (t >= T) return;
1722    const int lane = item_ct1.get_local_id(2) & 31;
1723    const float* lg = logits + t * (REG * 32);
1724    float v[REG];
1725#pragma unroll
1726    for (int i = 0; i < REG; ++i) v[i] = lg[lane + i * 32];
1727    float mx = -INFINITY;
1728#pragma unroll
1729    for (int i = 0; i < REG; ++i) mx = sycl::fmax(mx, v[i]);
1730    mx = warp_max(mx);
1731    float sum = 0.0f;
1732#pragma unroll
1733    for (int i = 0; i < REG; ++i) {
1734        v[i] = sycl::native::exp(v[i] - mx); sum += v[i];
1735    }
1736    const float rcp = 1.0f / warp_sum(sum);
1737#pragma unroll
1738    for (int i = 0; i < REG; ++i) {
1739        v[i] *= rcp; if (sycl::isnan(v[i])) v[i] = -FLT_MAX;
1740    }
1741    float selected = 0.0f, selected_sum = 0.0f;
1742    for (int rank = 0; rank < KU; ++rank) {
1743        float best = v[0];
1744        int ex = lane;
1745#pragma unroll
1746        for (int i = 1; i < REG; ++i) if (v[i] > best) { best = v[i]; ex = lane + i * 32; }
1747#pragma unroll
1748        for (int m = 16; m; m >>= 1) {
1749            /*
1750            DPCT1108: '__shfl_xor_sync' was migrated with the experimental
1751            feature masked sub_group function which may not be supported by all
1752            compilers or runtimes. You may need to adjust the code.
1753            */
1754            const float ob = dpct::experimental::permute_sub_group_by_xor(
1755                0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(),
1756                best, m);
1757            /*
1758            DPCT1108: '__shfl_xor_sync' was migrated with the experimental
1759            feature masked sub_group function which may not be supported by all
1760            compilers or runtimes. You may need to adjust the code.
1761            */
1762            const int oi = dpct::experimental::permute_sub_group_by_xor(
1763                0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(),
1764                ex, m);
1765            if (ob > best || (ob == best && oi < ex)) { best = ob; ex = oi; }
1766        }
1767        if ((ex & 31) == lane) { v[ex / 32] = -INFINITY; selected_sum += best; }
1768        if (lane == 0) ids[t * KU + rank] = ex;
1769        if (rank == lane) selected = best;
1770    }
1771    selected_sum = sycl::fmax(warp_sum(selected_sum), 6.103515625e-5f);
1772    if (lane < KU) wout[t * KU + lane] = selected / selected_sum;
1773}
1774// Strata blob: gate/up codes [1280][640 B], down codes [2560][160 B], gate/up scales [1280][40] f16, down scales [2560][10] f16
1775template <bool HALF>
1776/*
1777DPCT1110: The total declared local variable size in device function
1778blob_dequant_kernel exceeds 128 bytes and may cause high register pressure.
1779Consult with your hardware vendor to find the total register size available and
1780adjust the code, or use smaller sub-group size to avoid high register pressure.
1781*/
1782__dpct_inline__ void blob_dequant_kernel(const uint8_t *__restrict__ blob,
1783                                         uint16_t *__restrict__ gu16,
1784                                         uint16_t *__restrict__ d16) {
1785    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
1786    constexpr size_t O_D_CODES = (size_t)1280 * 640,
1787                     O_GU_SC = O_D_CODES + (size_t)2560 * 160,
1788                     O_D_SC = O_GU_SC + (size_t)1280 * 40 * 2;
1789    const int64_t i =
1790        (int64_t)item_ct1.get_group(2) * item_ct1.get_local_range(2) +
1791        item_ct1.get_local_id(2); // one thread per 4 weights (one code byte)
1792    const int64_t n_gu = 1280LL * 640, n_d = 2560LL * 160;
1793    if (i < n_gu) {
1794        const int64_t row = i / 640, byte = i % 640;
1795        const uint8_t c = blob[row * 640 + byte];
1796        const uint8_t* sp = blob + O_GU_SC + (size_t) (row * 40 + (byte * 4) / 64) * 2;
1797        const float d =
1798            sycl::vec<sycl::half, 1>(sycl::bit_cast<sycl::half, unsigned short>(
1799                                         (uint16_t)(sp[0] | (sp[1] << 8))))
1800                .convert<float, sycl::rounding_mode::automatic>()[0];
1801        uint16_t* o = gu16 + row * 2560 + byte * 4;
1802#pragma unroll
1803        for (int k = 0; k < 4; ++k) { const float v = (float) (((c >> (2 * k)) & 3) - 1) * d; o[k] = HALF ? hf(v) : bf(v); }
1804    } else if (i < n_gu + n_d) {
1805        const int64_t j = i - n_gu, row = j / 160, byte = j % 160;
1806        const uint8_t c = blob[O_D_CODES + row * 160 + byte];
1807        const uint8_t* sp = blob + O_D_SC + (size_t) (row * 10 + (byte * 4) / 64) * 2;
1808        const float d =
1809            sycl::vec<sycl::half, 1>(sycl::bit_cast<sycl::half, unsigned short>(
1810                                         (uint16_t)(sp[0] | (sp[1] << 8))))
1811                .convert<float, sycl::rounding_mode::automatic>()[0];
1812        uint16_t* o = d16 + row * 640 + byte * 4;
1813#pragma unroll
1814        for (int k = 0; k < 4; ++k) { const float v = (float) (((c >> (2 * k)) & 3) - 1) * d; o[k] = HALF ? hf(v) : bf(v); }
1815    }
1816}
1817__dpct_inline__ void swiglu_il_kernel(const float *__restrict__ gu,
1818                                      uint16_t *__restrict__ h16, int64_t n) {
1819    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
1820    const int64_t i =
1821        (int64_t)item_ct1.get_group(2) * item_ct1.get_local_range(2) +
1822        item_ct1.get_local_id(2);
1823    if (i >= n * FFC) return;
1824    const int64_t r = i / FFC, k = i % FFC;
1825    const float g = gu[r * (2 * FFC) + 2 * k], u = gu[r * (2 * FFC) + 2 * k + 1];
1826    h16[i] = hf_sat(g / (1.0f + sycl::native::exp(-g)) * u);
1827}
1828__dpct_inline__ void swiglu_pair_kernel(const float *__restrict__ g,
1829                                        const float *__restrict__ u,
1830                                        uint16_t *__restrict__ h16, int64_t n) {
1831    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
1832    const int64_t i =
1833        (int64_t)item_ct1.get_group(2) * item_ct1.get_local_range(2) +
1834        item_ct1.get_local_id(2);
1835    if (i >= n * FFC) return;
1836    const float a = g[i];
1837    h16[i] = hf_sat(a / (1.0f + sycl::native::exp(-a)) * u[i]);
1838}
1839__dpct_inline__ void gather_rows16_kernel(const uint16_t *__restrict__ x,
1840                                          const int32_t *__restrict__ src,
1841                                          uint16_t *__restrict__ dst, int64_t n,
1842                                          int64_t width) {
1843    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
1844    const int64_t i =
1845        (int64_t)item_ct1.get_group(2) * item_ct1.get_local_range(2) +
1846        item_ct1.get_local_id(2); // one uint4 (8 bf16)
1847    const int64_t per = width / 8;
1848    if (i >= n * per) return;
1849    const int64_t r = i / per, j = i % per;
1850    reinterpret_cast<sycl::uint4 *>(dst)[r * per + j] =
1851        reinterpret_cast<const sycl::uint4 *>(x)[(int64_t)src[r] * per + j];
1852}
1853__dpct_inline__ void moe_combine_kernel(const float *__restrict__ Dm,
1854                                        const int32_t *__restrict__ slot,
1855                                        const float *__restrict__ w,
1856                                        const float *__restrict__ shared,
1857                                        const float *__restrict__ sg,
1858                                        float *__restrict__ bo, int64_t T) {
1859    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
1860    const int64_t i =
1861        (int64_t)item_ct1.get_group(2) * item_ct1.get_local_range(2) +
1862        item_ct1.get_local_id(2);
1863    if (i >= T * N) return;
1864    const int64_t t = i / N, d = i % N;
1865    float s = 0.0f;
1866#pragma unroll
1867    for (int k = 0; k < KU; ++k)
1868        s = sycl::fma((float)(w[t * KU + k]),
1869                      (float)(Dm[(int64_t)slot[t * KU + k] * N + d]), s);
1870    bo[i] = s + shared[i] * sigm(sg[t]);
1871}
1872
1873// W (X5): four columns per thread, one float4 load per slot; the per-element expression and the k order are unchanged
1874// (bitwise equal to moe_combine_kernel). Needs 16-byte aligned Dm / shared / bo (N * 4 bytes per row is a multiple of 16).
1875/*
1876DPCT1110: The total declared local variable size in device function
1877moe_combine4_kernel exceeds 128 bytes and may cause high register pressure.
1878Consult with your hardware vendor to find the total register size available and
1879adjust the code, or use smaller sub-group size to avoid high register pressure.
1880*/
1881__dpct_inline__ void moe_combine4_kernel(
1882    const float *__restrict__ Dm, const int32_t *__restrict__ slot,
1883    const float *__restrict__ w, const sycl::float4 *__restrict__ shared,
1884    const float *__restrict__ sg, sycl::float4 *__restrict__ bo, int64_t T) {
1885    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
1886    const int64_t i =
1887        (int64_t)item_ct1.get_group(2) * item_ct1.get_local_range(2) +
1888        item_ct1.get_local_id(2); // float4 index
1889    if (i >= T * (N / 4)) return;
1890    const int64_t t = i / (N / 4), d = (i % (N / 4)) * 4;
1891    sycl::float4 s = sycl::float4(0.0f, 0.0f, 0.0f, 0.0f);
1892    sycl::float4 v[KU];
1893    float ww[KU];
1894#pragma unroll
1895    for (int k = 0; k < KU; ++k) {
1896        ww[k] = w[t * KU + k];
1897        v[k] = *reinterpret_cast<const sycl::float4 *>(
1898            Dm + (int64_t)slot[t * KU + k] * N + d);
1899    }
1900#pragma unroll
1901    for (int k = 0; k < KU; ++k) {
1902        s.x() = sycl::fma(ww[k], v[k].x(), s.x());
1903            s.y() = sycl::fma(ww[k], v[k].y(), s.y());
1904        s.z() = sycl::fma(ww[k], v[k].z(), s.z());
1905            s.w() = sycl::fma(ww[k], v[k].w(), s.w());
1906    }
1907    const float g = sigm(sg[t]);
1908    const sycl::float4 sh = shared[i];
1909    bo[i] = sycl::float4(s.x() + sh.x() * g, s.y() + sh.y() * g,
1910                         s.z() + sh.z() * g, s.w() + sh.w() * g);
1911}
1912
1913// ---------------------------------------------------------------- QSA helpers
1914__dpct_inline__ void rms_rows_kernel(float *__restrict__ x,
1915                                     const float *__restrict__ w, int64_t cols,
1916                                     int64_t ld, float eps) {
1917    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
1918auto &sh = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[32]>(
1919    sycl::ext::oneapi::this_work_item::get_work_group<3>());
1920    float *r = x + (int64_t)item_ct1.get_group(2) * ld;
1921    float ss = 0.0f;
1922#pragma unroll
1923    for (int64_t c = item_ct1.get_local_id(2); c < cols;
1924         c += item_ct1.get_local_range(2)) ss += r[c] * r[c];
1925    const float s = sycl::rsqrt(block_sum(ss, sh) / (float)cols + eps);
1926    /*
1927    DPCT1065: Consider replacing sycl::nd_item::barrier() with
1928    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
1929    performance if there is no access to global memory.
1930    */
1931    item_ct1.barrier();
1932#pragma unroll
1933    for (int64_t c = item_ct1.get_local_id(2); c < cols;
1934         c += item_ct1.get_local_range(2)) r[c] = s * r[c] * w[c];
1935}
1936// TAB (#280, STRATA_ROPE_TABLE=1): the angles from the session's float64 table.  The host launches <false> whenever
1937// no table applies - the default - so the default kernel is 0.1.31's code exactly (the table read is not in it;
1938// with it merely skipped at run time, the compiled default path changed its results).
1939template <bool TAB>
1940__dpct_inline__ void
1941rope_kernel(float *__restrict__ x, int64_t heads, int64_t dim, int64_t ld,
1942            int64_t pos0, float theta_scale, float freq_scale, float corr_low,
1943            float corr_high, float ext_factor, float mscale,
1944            const int32_t *__restrict__ mtab, strata::kernels::RopeTab rt) {
1945    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
1946    const int64_t row = item_ct1.get_group(2); // t * heads + h
1947    const int pair = item_ct1.get_local_id(2); // 0..31
1948    const int64_t t = row / heads, h = row % heads;
1949    float* p = x + t * ld + h * dim;
1950    float c, s;
1951    if (!(TAB && strata::kernels::rope_tab_cs(rt, strata::kernels::mrope_pos(mtab, (int) (pos0 + t), pair), pair, c,
1952                                              s))) {
1953        const float theta_extrap =
1954            (float)strata::kernels::mrope_pos(mtab, (int)(pos0 + t), pair) *
1955            dpct::pow(theta_scale, (float)pair);
1956        strata::kernels::rope_scaled_angle(theta_extrap, freq_scale, corr_low, corr_high, ext_factor, mscale,
1957                                           pair, c, s);
1958    }
1959    const float a = p[pair], b = p[pair + 32];
1960    p[pair] = a * c - b * s;
1961    p[pair + 32] = a * s + b * c;
1962}
1963__dpct_inline__ void split_q_kernel(const float *__restrict__ qf,
1964                                    float *__restrict__ q, int64_t T) {
1965    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
1966    const int64_t i =
1967        (int64_t)item_ct1.get_group(2) * item_ct1.get_local_range(2) +
1968        item_ct1.get_local_id(2);
1969    if (i >= T * NHQ * 256) return;
1970    const int64_t t = i / (NHQ * 256), h = (i / 256) % NHQ, d = i % 256;
1971    q[i] = qf[t * NHQ * 512 + h * 512 + d];
1972}
1973__dpct_inline__ void gate_attn_kernel(const float *__restrict__ a,
1974                                      const float *__restrict__ qf,
1975                                      uint16_t *__restrict__ o16, int64_t T,
1976                                      int64_t ld16) {
1977    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
1978    const int64_t i =
1979        (int64_t)item_ct1.get_group(2) * item_ct1.get_local_range(2) +
1980        item_ct1.get_local_id(2);
1981    if (i >= T * NHQ * 256) return;
1982    const int64_t t = i / (NHQ * 256), h = (i / 256) % NHQ, d = i % 256;
1983    o16[t * ld16 + h * 256 + d] =
1984        hf(a[i] * (1.0f / (1.0f + sycl::native::exp(
1985                                      -qf[t * NHQ * 512 + h * 512 + 256 + d]))));
1986}
1987
1988// one block per (token, kv head, 64-value group); 64 threads. KV streaming: the pool page only if the block is
1989// resident (table >= 0), and the host copy and the prompt path's staging pool (both identity layout) when given.
1990__dpct_inline__ void
1991kv_append_kernel(const float *__restrict__ K, const float *__restrict__ V,
1992                 int64_t pos0, const int32_t *__restrict__ table,
1993                 int64_t page_size, uint16_t *k_pool, uint16_t *v_pool,
1994                 int8_t *k_q, int8_t *v_q, uint16_t *k_scale, uint16_t *v_scale,
1995                 strata::kernels::KvHostPools host,
1996                 strata::kernels::KvHostPools stage, bool wide_host) {
1997    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
1998    const int64_t t = item_ct1.get_group(2);
1999    const int kvh = item_ct1.get_group(1), g = item_ct1.get_group(0) >> 1;
2000    const bool is_v = (item_ct1.get_group(0) & 1) != 0;
2001    const int d = g * 64 + item_ct1.get_local_id(2);
2002    const float x = (is_v ? V : K)[t * (NKVH * 256) + kvh * 256 + d];
2003    const int64_t pos = pos0 + t;
2004    const int64_t page = table[pos / page_size];
2005    const int64_t row = (page * 2 + kvh) * page_size + pos % page_size;
2006    const int64_t row_id = ((pos / page_size) * 2 + kvh) * page_size + pos % page_size;
2007    // 0.1.43: the host copy and the staging pool are written 4 bytes a lane, 64 contiguous bytes a group, instead of one
2008    // 1- or 2-byte store per lane: on a B70 the 1-byte stores into the pinned host KV (--kv-resident) ran at ~30 MB/s
2009    // (kv_append: 161 ms a layer for 4,096 tokens, 2 s of a 4K prompt), the same bytes in 4-byte stores are a few ms.
2010    const int lid = (int) item_ct1.get_local_id(2);
2011    if (k_pool != nullptr) {
2012        const uint16_t h = hf(x);
2013        if (page >= 0) (is_v ? v_pool : k_pool)[row * 256 + d] = h;
2014        if (wide_host && (host.k_pool != nullptr || stage.k_pool != nullptr)) {
2015            auto &s16 = *sycl::ext::oneapi::group_local_memory_for_overwrite<uint16_t[64]>(
2016                sycl::ext::oneapi::this_work_item::get_work_group<3>());
2017            s16[lid] = h;
2018            item_ct1.barrier(sycl::access::fence_space::local_space);
2019            if (lid < 32) {
2020                const uint32_t w = (uint32_t) s16[2 * lid] | ((uint32_t) s16[2 * lid + 1] << 16);
2021                if (host.k_pool != nullptr)
2022                    ((uint32_t *) ((is_v ? host.v_pool : host.k_pool) + row_id * 256 + g * 64))[lid] = w;
2023                if (stage.k_pool != nullptr)
2024                    ((uint32_t *) ((is_v ? stage.v_pool : stage.k_pool) + row_id * 256 + g * 64))[lid] = w;
2025            }
2026            return;
2027        }
2028        if (host.k_pool != nullptr) (is_v ? host.v_pool : host.k_pool)[row_id * 256 + d] = h;
2029        if (stage.k_pool != nullptr) (is_v ? stage.v_pool : stage.k_pool)[row_id * 256 + d] = h;
2030        return;
2031    }
2032    float a = sycl::fabs(x);
2033    /*
2034DPCT1108: '__shfl_xor_sync' was migrated with the experimental feature
2035masked sub_group function which may not be supported by all compilers or
2036runtimes. You may need to adjust the code.
2037*/
2038#pragma unroll
2039    for (int o = 16; o > 0; o >>= 1) a = sycl::fmax(
2040        a, dpct::experimental::permute_sub_group_by_xor(
2041               0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(),
2042               a, o));
2043    auto &wm = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[2]>(
2044        sycl::ext::oneapi::this_work_item::get_work_group<3>());
2045    if ((item_ct1.get_local_id(2) & 31) == 0)
2046        wm[item_ct1.get_local_id(2) >> 5] = a;
2047    /*
2048    DPCT1065: Consider replacing sycl::nd_item::barrier() with
2049    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
2050    performance if there is no access to global memory.
2051    */
2052    item_ct1.barrier();
2053    const float amax = sycl::fmax(wm[0], wm[1]);
2054    const uint16_t sb = hf(amax / 127.0f);
2055    const float sf =
2056        sycl::vec<sycl::half, 1>(sycl::bit_cast<sycl::half, unsigned short>(sb))
2057            .convert<float, sycl::rounding_mode::automatic>()[0];
2058    int q = 0;
2059    if (sf > 0.0f) {
2060        q = sycl::vec<float, 1>{(x / sf)}
2061                .convert<int, sycl::rounding_mode::rte>()[0];
2062        q = q < -127 ? -127 : (q > 127 ? 127 : q);
2063    }
2064    if (page >= 0) {
2065        (is_v ? v_q : k_q)[row * 256 + d] = (int8_t) q;
2066        if (item_ct1.get_local_id(2) == 0)(is_v ? v_scale
2067                                                : k_scale)[row * 4 + g] = sb;
2068    }
2069    if (wide_host && (host.k_q != nullptr || stage.k_q != nullptr)) {
2070        auto &s8 = *sycl::ext::oneapi::group_local_memory_for_overwrite<int8_t[64]>(
2071            sycl::ext::oneapi::this_work_item::get_work_group<3>());
2072        s8[lid] = (int8_t) q;
2073        item_ct1.barrier(sycl::access::fence_space::local_space);
2074        if (lid < 16) {
2075            const uint32_t w = (uint32_t) (uint8_t) s8[4 * lid] | ((uint32_t) (uint8_t) s8[4 * lid + 1] << 8) |
2076                               ((uint32_t) (uint8_t) s8[4 * lid + 2] << 16) | ((uint32_t) (uint8_t) s8[4 * lid + 3] << 24);
2077            if (host.k_q != nullptr) ((uint32_t *) ((is_v ? host.v_q : host.k_q) + row_id * 256 + g * 64))[lid] = w;
2078            if (stage.k_q != nullptr) ((uint32_t *) ((is_v ? stage.v_q : stage.k_q) + row_id * 256 + g * 64))[lid] = w;
2079        }
2080        if (lid == 0) {
2081            if (host.k_q != nullptr) (is_v ? host.v_scale : host.k_scale)[row_id * 4 + g] = sb;
2082            if (stage.k_q != nullptr) (is_v ? stage.v_scale : stage.k_scale)[row_id * 4 + g] = sb;
2083        }
2084        return;
2085    }
2086    if (host.k_q != nullptr) {
2087        (is_v ? host.v_q : host.k_q)[row_id * 256 + d] = (int8_t) q;
2088        if (item_ct1.get_local_id(2) ==
2089            0)(is_v ? host.v_scale : host.k_scale)[row_id * 4 + g] = sb;
2090    }
2091    if (stage.k_q != nullptr) {
2092        (is_v ? stage.v_q : stage.k_q)[row_id * 256 + d] = (int8_t) q;
2093        if (item_ct1.get_local_id(2) ==
2094            0)(is_v ? stage.v_scale : stage.k_scale)[row_id * 4 + g] = sb;
2095    }
2096}
2097__dpct_inline__ void to_f16_kernel(const float *__restrict__ x,
2098                                   uint16_t *__restrict__ y, int64_t n) {
2099    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
2100#pragma unroll
2101    for (int64_t i =
2102             (int64_t)item_ct1.get_group(2) * item_ct1.get_local_range(2) +
2103             item_ct1.get_local_id(2);
2104         i < n; i += (int64_t)item_ct1.get_group_range(2) *
2105                     item_ct1.get_local_range(2))
2106        y[i] = hf(x[i]);
2107}
2108__dpct_inline__ void round_f16_kernel(const float *__restrict__ x,
2109                                      float *__restrict__ y, int64_t n) {
2110    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
2111#pragma unroll
2112    for (int64_t i =
2113             (int64_t)item_ct1.get_group(2) * item_ct1.get_local_range(2) +
2114             item_ct1.get_local_id(2);
2115         i < n; i += (int64_t)item_ct1.get_group_range(2) *
2116                     item_ct1.get_local_range(2))
2117        y[i] = sycl::vec<sycl::half, 1>(
2118                   sycl::vec<float, 1>(x[i])
2119                       .convert<sycl::half, sycl::rounding_mode::rte>()[0])
2120                   .convert<float, sycl::rounding_mode::automatic>()[0];
2121}
2122__dpct_inline__ void to_bf16_kernel(const float *__restrict__ x,
2123                                    uint16_t *__restrict__ y,
2124                                    uint16_t *__restrict__ ylo, int64_t n) {
2125    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
2126    for (int64_t i =
2127             (int64_t)item_ct1.get_group(2) * item_ct1.get_local_range(2) +
2128             item_ct1.get_local_id(2);
2129         i < n; i += (int64_t)item_ct1.get_group_range(2) *
2130                     item_ct1.get_local_range(2)) {
2131        const uint16_t h = act16(x[i]);
2132        y[i] = h;
2133        if (ylo) ylo[i] = bf_lo(x[i], h);
2134    }
2135}
2136
2137// S23 (opt-in STRATA_HC_UPMIX=1, gfx11): the hyper-connection read's up projection with gr_mix_r as its epilogue.  The
2138// up GEMM's FP32 output `gated` (T x 10240: 671 MB per 16K chunk) is never written or read back: a block computes a
2139// tile of 64 tokens x 64 columns for all 4 streams on the matrix cores (BF16 in, FP32 accumulate over K = 320; the
2140// lo16 and w_up tiles staged in LDS), and each lane already holds the 4 streams' values of its (token, column) - the
2141// mix (x_c = R * rs * w, sum of x_c * sigmoid(gated_c), / 4) runs in registers, in gr_mix_r_kernel's order.  The
2142// GEMM sums K in another order than hipBLASLt: rounding-level, hence opt-in and quality-gated.
2143#if defined(__HIPCC__)
2144typedef __bf16 um_b16 __attribute__((ext_vector_type(16)));
2145typedef float um_f8 __attribute__((ext_vector_type(8)));
2146__device__ __forceinline__ um_f8 um_wmma(um_b16 a, um_b16 b, um_f8 c) {
2147#if defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1150__) || defined(__gfx1151__)
2148    return __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32(a, b, c);
2149#else
2150    (void) a; (void) b; return c;   // not a gfx11 device pass: never launched (runtime gate)
2151#endif
2152}
2153constexpr int UM_T = 128, UM_D = 16, UM_LD = LR + 8;   // a block: 128 tokens x 16 columns x the 4 streams
2154__device__ __forceinline__ um_b16 um_frag(const uint16_t* p) {   // 16 BF16 (32 bytes, 16-byte aligned)
2155    const uint4 a = *reinterpret_cast<const uint4*>(p), b = *reinterpret_cast<const uint4*>(p + 8);
2156    const uint32_t w[8] = {a.x, a.y, a.z, a.w, b.x, b.y, b.z, b.w};
2157    return __builtin_bit_cast(um_b16, w);
2158}
2159// The block's w_up rows (16 columns x 4 streams x all 320 k) are staged in LDS once; each wave streams its own 16
2160// tokens' lo16 rows from global memory (every A fragment feeds the 4 streams' WMMAs) - one barrier per block.
2161__global__ void __launch_bounds__(256) gr_upmix_kernel(const uint16_t* __restrict__ lo16, const uint16_t* __restrict__ wu,
2162                                                       const float* __restrict__ R, const float* __restrict__ rs,
2163                                                       const float* __restrict__ w, float* __restrict__ mixed,
2164                                                       uint16_t* __restrict__ mixed16, uint16_t* __restrict__ mixed_h,
2165                                                       int64_t T) {
2166    __shared__ __align__(16) uint16_t sB[HC * UM_D][UM_LD];
2167    const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5, l16 = lane & 15, hi = lane >> 4;
2168    // blocks ordered column-tile fastest: the blocks in flight share a token tile, so the epilogue's R reads run
2169    // along rows (token-tile fastest scattered them over 512 rows x 40 KB per block: 28 ms instead of 3.7 at 8K)
2170    const int64_t t0 = (int64_t) blockIdx.y * UM_T + 16 * wave;
2171    const int d0 = blockIdx.x * UM_D;
2172    for (int i = tid; i < HC * UM_D * (LR / 8); i += 256) {
2173        const int rr = i / (LR / 8), q = i % (LR / 8);
2174        const int c = rr / UM_D, dd = rr % UM_D;
2175        *reinterpret_cast<uint4*>(&sB[rr][8 * q]) = *reinterpret_cast<const uint4*>(wu + (size_t) (c * N + d0 + dd) * LR + 8 * q);
2176    }
2177    __syncthreads();
2178    if (t0 >= T) return;
2179    const int64_t ta = t0 + l16 < T ? t0 + l16 : T - 1;
2180    const uint16_t* arow = lo16 + ta * LR;
2181    um_f8 acc[HC];
2182#pragma unroll
2183    for (int c = 0; c < HC; ++c) acc[c] = um_f8{0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f};
2184#pragma unroll
2185    for (int ks = 0; ks < LR; ks += 16) {
2186        const um_b16 a = um_frag(arow + ks);
2187#pragma unroll
2188        for (int c = 0; c < HC; ++c) acc[c] = um_wmma(a, um_frag(&sB[c * UM_D + l16][ks]), acc[c]);
2189    }
2190    const int d = d0 + l16;
2191#pragma unroll
2192    for (int i = 0; i < 8; ++i) {
2193        const int64_t t = t0 + 2 * i + hi;
2194        if (t >= T) continue;
2195        float s = 0.0f;
2196#pragma unroll
2197        for (int c = 0; c < HC; ++c) {
2198            const float x = R[t * D + c * N + d] * rs[t * HC + c] * w[c * N + d];   // gr_mix_r_kernel's order
2199            s = fmaf(x, sigm(acc[c][i]), s);
2200        }
2201        s /= (float) HC;
2202        mixed[t * N + d] = s;
2203        if (mixed16) mixed16[t * N + d] = act16(s);
2204        if (mixed_h) mixed_h[t * N + d] = hf(s);
2205    }
2206}
2207#endif
2208}  // namespace
2209
2210void kv_append(const float* K, const float* V, int64_t T, int64_t pos0, const int32_t* page_table, int64_t page_size,
2211               uint16_t* k_pool, uint16_t* v_pool, int8_t* k_q, int8_t* v_q, uint16_t* k_scale, uint16_t* v_scale,
2212               void* stream, const strata::kernels::KvHostPools* host, const strata::kernels::KvHostPools* stage) {
2213    if (T <= 0) return;
2214    static const bool wide_env = [] { const char* v = std::getenv("STRATA_KV_WIDE_HOST"); return !(v && v[0] == '0'); }();
2215    const bool wide = wide_env;
2216    {
2217        auto exp_props = sycl::ext::oneapi::experimental::properties{
2218            sycl::ext::oneapi::experimental::use_root_sync};
2219
2220        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
2221            ->submit([&](sycl::handler &cgh) {
2222                strata::kernels::KvHostPools
2223                    host_host_strata_kernels_KvHostPools_ct11 =
2224                        host ? *host : strata::kernels::KvHostPools{};
2225                strata::kernels::KvHostPools
2226                    stage_stage_strata_kernels_KvHostPools_ct12 =
2227                        stage ? *stage : strata::kernels::KvHostPools{};
2228
2229                cgh.parallel_for<
2230                    dpct_kernel_name<class kv_append_kernel_850222>>(
2231                    sycl::nd_range<3>(sycl::range(8, 2, (unsigned)T) *
2232                                          sycl::range(1, 1, 64),
2233                                      sycl::range(1, 1, 64)),
2234                    exp_props,
2235                    [=](sycl::nd_item<3> item_ct1)
2236                        [[sycl::reqd_sub_group_size(32)]] {
2237                            kv_append_kernel(
2238                                K, V, pos0, page_table, page_size, k_pool,
2239                                v_pool, k_q, v_q, k_scale, v_scale,
2240                                host_host_strata_kernels_KvHostPools_ct11,
2241                                stage_stage_strata_kernels_KvHostPools_ct12, wide);
2242                        });
2243            });
2244    }
2245    check("kv_append");
2246}
2247void set_act_f16(bool on) {
2248#if !defined(__HIPCC__)
2249    (void) on;   // CUDA: the activation image is always BF16
2250    return;
2251#else
2252    const int v = on ? 1 : 0;
2253    if (cudaMemcpyToSymbol(g_act_f16, &v, sizeof v) != cudaSuccess) {
2254        std::fprintf(stderr, "prefill: setting the FP16 activation image failed: %s\n", cudaGetErrorString(cudaGetLastError()));
2255        std::exit(1);
2256    }
2257#endif
2258}
2259void to_f16(const float* x, uint16_t* y, int64_t n, void* stream) {
2260    if (n <= 0) return;
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<dpct_kernel_name<class to_f16_kernel_c8575f>>(
2267                sycl::nd_range<3>(sycl::range(1, 1,
2268                                              (unsigned)((n + 255) / 256 < 4096
2269                                                             ? (n + 255) / 256
2270                                                             : 4096)) *
2271                                      sycl::range(1, 1, 256),
2272                                  sycl::range(1, 1, 256)),
2273                exp_props, [=](sycl::nd_item<3> item_ct1) {
2274                    to_f16_kernel(x, y, n);
2275                });
2276    }
2277    check("to_f16");
2278}
2279void round_f16(const float* x, float* y, int64_t n, void* stream) {
2280    if (n <= 0) return;
2281    {
2282        auto exp_props = sycl::ext::oneapi::experimental::properties{
2283            sycl::ext::oneapi::experimental::use_root_sync};
2284
2285        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
2286            ->template parallel_for<dpct_kernel_name<class round_f16_kernel_877aa1>>(
2287                sycl::nd_range<3>(sycl::range(1, 1,
2288                                              (unsigned)((n + 255) / 256 < 4096
2289                                                             ? (n + 255) / 256
2290                                                             : 4096)) *
2291                                      sycl::range(1, 1, 256),
2292                                  sycl::range(1, 1, 256)),
2293                exp_props, [=](sycl::nd_item<3> item_ct1) {
2294                    round_f16_kernel(x, y, n);
2295                });
2296    }
2297    check("round_f16");
2298}
2299void to_bf16(const float* x, uint16_t* y, int64_t n, void* stream, uint16_t* ylo) {
2300    if (n <= 0) return;
2301    {
2302        auto exp_props = sycl::ext::oneapi::experimental::properties{
2303            sycl::ext::oneapi::experimental::use_root_sync};
2304
2305        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
2306            ->template parallel_for<dpct_kernel_name<class to_bf16_kernel_44d81a>>(
2307                sycl::nd_range<3>(sycl::range(1, 1,
2308                                              (unsigned)((n + 255) / 256 < 4096
2309                                                             ? (n + 255) / 256
2310                                                             : 4096)) *
2311                                      sycl::range(1, 1, 256),
2312                                  sycl::range(1, 1, 256)),
2313                exp_props, [=](sycl::nd_item<3> item_ct1) {
2314                    to_bf16_kernel(x, y, ylo, n);
2315                });
2316    }
2317    check("to_bf16");
2318}
2319
2320void gr_norm(const float* R, const float* w_norm, float eps, float* xn, uint16_t* xn16, int64_t T, void* stream,
2321             uint16_t* xn16_lo, bool /*f16img: the Turing FP16 image of xn16 (CUDA only)*/) {
2322    {
2323        auto exp_props = sycl::ext::oneapi::experimental::properties{
2324            sycl::ext::oneapi::experimental::use_root_sync};
2325
2326        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
2327            ->template parallel_for<dpct_kernel_name<class gr_norm_kernel_f38542>>(
2328                sycl::nd_range<3>(sycl::range(1, 1, (unsigned)(T * HC)) *
2329                                      sycl::range(1, 1, 256),
2330                                  sycl::range(1, 1, 256)),
2331                exp_props,
2332                [=](sycl::nd_item<3> item_ct1)
2333                    [[sycl::reqd_sub_group_size(32)]] {
2334                        gr_norm_kernel(R, w_norm, eps, xn, xn16, xn16_lo);
2335                    });
2336    }
2337    check("gr_norm");
2338}
2339void gr_norm_rs(const float* R, const float* w_norm, float eps, float* rs, uint16_t* xn16, int64_t T, void* stream,
2340                uint16_t* xn16_lo, int64_t ldx, bool /*f16img*/) {
2341    {
2342        auto exp_props = sycl::ext::oneapi::experimental::properties{
2343            sycl::ext::oneapi::experimental::use_root_sync};
2344
2345        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
2346            ->submit([&](sycl::handler &cgh) {
2347                auto ldx_ldx_D_ct6 = ldx > 0 ? ldx : D;
2348
2349                cgh.parallel_for<
2350                    dpct_kernel_name<class gr_norm_rs_kernel_6c01ba>>(
2351                    sycl::nd_range<3>(sycl::range(1, 1, (unsigned)(T * HC)) *
2352                                          sycl::range(1, 1, 256),
2353                                      sycl::range(1, 1, 256)),
2354                    exp_props,
2355                    [=](sycl::nd_item<3> item_ct1)
2356                        [[sycl::reqd_sub_group_size(32)]] {
2357                            gr_norm_rs_kernel(R, w_norm, eps, rs, xn16, xn16_lo,
2358                                              ldx_ldx_D_ct6);
2359                        });
2360            });
2361    }
2362    check("gr_norm_rs");
2363}
2364void gr_mix_r(const float* R, const float* rs, const float* w_norm, const float* gated, float* mixed, uint16_t* mixed16,
2365              int64_t T, void* stream, uint16_t* mixed_h, uint16_t* mixed16_lo) {
2366    {
2367        auto exp_props = sycl::ext::oneapi::experimental::properties{
2368            sycl::ext::oneapi::experimental::use_root_sync};
2369
2370        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
2371            ->template parallel_for<dpct_kernel_name<class gr_mix_r_kernel_a64dc1>>(
2372                sycl::nd_range<3>(sycl::range(1, 1, blocks_for(T * N)) *
2373                                      sycl::range(1, 1, 256),
2374                                  sycl::range(1, 1, 256)),
2375                exp_props, [=](sycl::nd_item<3> item_ct1) {
2376                    gr_mix_r_kernel(R, rs, w_norm, gated, mixed, mixed16, T,
2377                                    mixed_h, mixed16_lo);
2378                });
2379    }
2380    check("gr_mix_r");
2381}
2382bool gr_upmix(const uint16_t* lo16, const uint16_t* w_up, const float* R, const float* rs, const float* w_norm,
2383              float* mixed, uint16_t* mixed16, uint16_t* mixed_h, int64_t T, void* stream) {
2384#if defined(__HIPCC__)
2385    static const bool gfx11 = [] {
2386        int dev = 0;
2387        cudaDeviceProp p;
2388        if (cudaGetDevice(&dev) != cudaSuccess || cudaGetDeviceProperties(&p, dev) != cudaSuccess) return false;
2389        return strata::kernels::gfx_arch_is_gfx11_wmma(p.gcnArchName);
2390    }();
2391    if (!gfx11 || T <= 0) return false;
2392    gr_upmix_kernel<<<dim3(N / UM_D, (unsigned) ((T + UM_T - 1) / UM_T)), 256, 0, (cudaStream_t) stream>>>(
2393        lo16, w_up, R, rs, w_norm, mixed, mixed16, mixed_h, T);
2394    check("gr_upmix");
2395    return true;
2396#else
2397    (void) lo16; (void) w_up; (void) R; (void) rs; (void) w_norm; (void) mixed; (void) mixed16; (void) mixed_h;
2398    (void) T; (void) stream;
2399    return false;
2400#endif
2401}
2402void gr_write_norm_rs(float* R, const float* bo, const float* inj, int64_t inj_ld, const float* w_norm_next, float eps,
2403                      float* rs, uint16_t* xn16, int64_t T, void* stream, uint16_t* xn16_lo, int64_t ldx,
2404                      bool /*f16img*/) {
2405    {
2406        auto exp_props = sycl::ext::oneapi::experimental::properties{
2407            sycl::ext::oneapi::experimental::use_root_sync};
2408
2409        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
2410            ->submit([&](sycl::handler &cgh) {
2411                auto ldx_ldx_D_ct9 = ldx > 0 ? ldx : D;
2412
2413                cgh.parallel_for<
2414                    dpct_kernel_name<class gr_write_norm_rs_kernel_85f8e9>>(
2415                    sycl::nd_range<3>(sycl::range(1, 1, (unsigned)(T * HC)) *
2416                                          sycl::range(1, 1, 256),
2417                                      sycl::range(1, 1, 256)),
2418                    exp_props,
2419                    [=](sycl::nd_item<3> item_ct1)
2420                        [[sycl::reqd_sub_group_size(32)]] {
2421                            gr_write_norm_rs_kernel(R, bo, inj, inj_ld,
2422                                                    w_norm_next, eps, rs, xn16,
2423                                                    xn16_lo, ldx_ldx_D_ct9);
2424                        });
2425            });
2426    }
2427    check("gr_write_norm_rs");
2428}
2429void gr_write_cvec_norm_rs(float* R, const float* bo, const float* inj, int64_t inj_ld, const float* v_l,
2430                           const float* s_l, const int* on, int mode, const float* w_norm_next, float eps, float* rs,
2431                           uint16_t* xn16, int64_t T, void* stream, uint16_t* xn16_lo, int64_t ldx, bool /*f16img*/) {
2432    {
2433        auto exp_props = sycl::ext::oneapi::experimental::properties{
2434            sycl::ext::oneapi::experimental::use_root_sync};
2435
2436        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
2437            ->submit([&](sycl::handler &cgh) {
2438                auto ldx_ldx_D_ct13 = ldx > 0 ? ldx : D;
2439
2440                cgh.parallel_for<dpct_kernel_name<
2441                    class gr_write_cvec_norm_rs_kernel_abf888>>(
2442                    sycl::nd_range<3>(sycl::range(1, 1, (unsigned)(T * HC)) *
2443                                          sycl::range(1, 1, 256),
2444                                      sycl::range(1, 1, 256)),
2445                    exp_props,
2446                    [=](sycl::nd_item<3> item_ct1)
2447                        [[sycl::reqd_sub_group_size(32)]] {
2448                            gr_write_cvec_norm_rs_kernel(
2449                                R, bo, inj, inj_ld, v_l, s_l, on, mode,
2450                                w_norm_next, eps, rs, xn16, xn16_lo,
2451                                ldx_ldx_D_ct13);
2452                        });
2453            });
2454    }
2455    check("gr_write_cvec_norm_rs");
2456}
2457void gr_silu(const float* lo, uint16_t* lo16, int64_t T, void* stream, uint16_t* lo16_lo) {
2458    {
2459        auto exp_props = sycl::ext::oneapi::experimental::properties{
2460            sycl::ext::oneapi::experimental::use_root_sync};
2461
2462        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
2463            ->submit([&](sycl::handler &cgh) {
2464                auto T_LR_ct3 = T * LR;
2465
2466                cgh.parallel_for<dpct_kernel_name<class gr_silu_kernel_f26d34>>(
2467                    sycl::nd_range<3>(sycl::range(1, 1, blocks_for(T * LR)) *
2468                                          sycl::range(1, 1, 256),
2469                                      sycl::range(1, 1, 256)),
2470                    exp_props, [=](sycl::nd_item<3> item_ct1) {
2471                        gr_silu_kernel(lo, lo16, lo16_lo, T_LR_ct3);
2472                    });
2473            });
2474    }
2475    check("gr_silu");
2476}
2477void gr_mix(const float* xn, const float* gated, float* mixed, uint16_t* mixed16, int64_t T, void* stream,
2478            uint16_t* mixed_h, uint16_t* mixed16_lo) {
2479    {
2480        auto exp_props = sycl::ext::oneapi::experimental::properties{
2481            sycl::ext::oneapi::experimental::use_root_sync};
2482
2483        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
2484            ->template parallel_for<dpct_kernel_name<class gr_mix_kernel_d9dd98>>(
2485                sycl::nd_range<3>(sycl::range(1, 1, blocks_for(T * N)) *
2486                                      sycl::range(1, 1, 256),
2487                                  sycl::range(1, 1, 256)),
2488                exp_props, [=](sycl::nd_item<3> item_ct1) {
2489                    gr_mix_kernel(xn, gated, mixed, mixed16, T, mixed_h,
2490                                  mixed16_lo);
2491                });
2492    }
2493    check("gr_mix");
2494}
2495void gr_write(float* R, const float* bo, const float* inj, int64_t inj_ld, int64_t T, void* stream) {
2496    {
2497        auto exp_props = sycl::ext::oneapi::experimental::properties{
2498            sycl::ext::oneapi::experimental::use_root_sync};
2499
2500        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
2501            ->template parallel_for<dpct_kernel_name<class gr_write_kernel_b96cec>>(
2502                sycl::nd_range<3>(sycl::range(1, 1, blocks_for(T * D)) *
2503                                      sycl::range(1, 1, 256),
2504                                  sycl::range(1, 1, 256)),
2505                exp_props, [=](sycl::nd_item<3> item_ct1) {
2506                    gr_write_kernel(R, bo, inj, inj_ld, T);
2507                });
2508    }
2509    check("gr_write");
2510}
2511void gr_broadcast(const float* e, float* R, int64_t T, void* stream) {
2512    {
2513        auto exp_props = sycl::ext::oneapi::experimental::properties{
2514            sycl::ext::oneapi::experimental::use_root_sync};
2515
2516        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
2517            ->template parallel_for<dpct_kernel_name<class gr_broadcast_kernel_3dedc6>>(
2518                sycl::nd_range<3>(sycl::range(1, 1, blocks_for(T * D)) *
2519                                      sycl::range(1, 1, 256),
2520                                  sycl::range(1, 1, 256)),
2521                exp_props, [=](sycl::nd_item<3> item_ct1) {
2522                    gr_broadcast_kernel(e, R, T);
2523                });
2524    }
2525    check("gr_broadcast");
2526}
2527void gdn_gates(const float* ab, const float* dt, const float* ssm_a, float* gate, float* beta, int64_t T, void* stream) {
2528    {
2529        auto exp_props = sycl::ext::oneapi::experimental::properties{
2530            sycl::ext::oneapi::experimental::use_root_sync};
2531
2532        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
2533            ->template parallel_for<dpct_kernel_name<class gdn_gates_kernel_e66d35>>(
2534                sycl::nd_range<3>(sycl::range(1, 1, blocks_for(T * HV)) *
2535                                      sycl::range(1, 1, 256),
2536                                  sycl::range(1, 1, 256)),
2537                exp_props, [=](sycl::nd_item<3> item_ct1) {
2538                    gdn_gates_kernel(ab, dt, ssm_a, gate, beta, T);
2539                });
2540    }
2541    check("gdn_gates");
2542}
2543void gdn_conv(float* history, const float* qkv, const float* conv_w, float* h, int64_t T, float eps, void* stream) {
2544    static const bool serial = std::getenv("STRATA_GDN_CONV_SERIAL") != nullptr;   // the old walk (A/B)
2545    if (serial || T <= CONV_TILE) {
2546        auto exp_props = sycl::ext::oneapi::experimental::properties{
2547            sycl::ext::oneapi::experimental::use_root_sync};
2548
2549        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
2550            ->template parallel_for<dpct_kernel_name<class gdn_conv_kernel_df787b>>(
2551                sycl::nd_range<3>(sycl::range(1, 1, C / 128) *
2552                                      sycl::range(1, 1, 128),
2553                                  sycl::range(1, 1, 128)),
2554                exp_props, [=](sycl::nd_item<3> item_ct1) {
2555                    gdn_conv_kernel(history, qkv, conv_w, h, T);
2556                });
2557    } else {
2558        static const bool fused = [] { const char* v = std::getenv("STRATA_GDN_CONVL2"); return v && std::atoi(v) != 0; }();
2559        if (fused) {
2560            {
2561                auto exp_props = sycl::ext::oneapi::experimental::properties{
2562                    sycl::ext::oneapi::experimental::use_root_sync};
2563
2564                strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
2565                    ->template parallel_for<
2566                        dpct_kernel_name<class gdn_conv_l2_kernel_8e7204>>(
2567                        sycl::nd_range<3>(
2568                            sycl::range(
2569                                1, (unsigned)((T + CONV_TILE - 1) / CONV_TILE),
2570                                C / 128) *
2571                                sycl::range(1, 1, 128),
2572                            sycl::range(1, 1, 128)),
2573                        exp_props,
2574                        [=](sycl::nd_item<3> item_ct1)
2575                            [[sycl::reqd_sub_group_size(32)]] {
2576                                gdn_conv_l2_kernel(history, qkv, conv_w, h, T,
2577                                                   eps);
2578                            });
2579            }
2580            {
2581                auto exp_props = sycl::ext::oneapi::experimental::properties{
2582                    sycl::ext::oneapi::experimental::use_root_sync};
2583
2584                strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
2585                    ->template parallel_for<
2586                        dpct_kernel_name<class gdn_conv_hist_kernel_e391a1>>(
2587                        sycl::nd_range<3>(sycl::range(1, 1, C / 128) *
2588                                              sycl::range(1, 1, 128),
2589                                          sycl::range(1, 1, 128)),
2590                        exp_props, [=](sycl::nd_item<3> item_ct1) {
2591                            gdn_conv_hist_kernel(history, qkv, T);
2592                        });
2593            }
2594            check("gdn_conv");
2595            return;
2596        }
2597        {
2598            auto exp_props = sycl::ext::oneapi::experimental::properties{
2599                sycl::ext::oneapi::experimental::use_root_sync};
2600
2601            strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
2602                ->template parallel_for<
2603                    dpct_kernel_name<class gdn_conv_tiled_kernel_532f01>>(
2604                    sycl::nd_range<3>(
2605                        sycl::range(1,
2606                                    (unsigned)((T + CONV_TILE - 1) / CONV_TILE),
2607                                    C / 128) *
2608                            sycl::range(1, 1, 128),
2609                        sycl::range(1, 1, 128)),
2610                    exp_props, [=](sycl::nd_item<3> item_ct1) {
2611                        gdn_conv_tiled_kernel(history, qkv, conv_w, h, T);
2612                    });
2613        }
2614        {
2615            auto exp_props = sycl::ext::oneapi::experimental::properties{
2616                sycl::ext::oneapi::experimental::use_root_sync};
2617
2618            strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
2619                ->template parallel_for<
2620                    dpct_kernel_name<class gdn_conv_hist_kernel_e391a2>>(
2621                    sycl::nd_range<3>(sycl::range(1, 1, C / 128) *
2622                                          sycl::range(1, 1, 128),
2623                                      sycl::range(1, 1, 128)),
2624                    exp_props, [=](sycl::nd_item<3> item_ct1) {
2625                        gdn_conv_hist_kernel(history, qkv, T);
2626                    });
2627        }
2628    }
2629    {
2630        auto exp_props = sycl::ext::oneapi::experimental::properties{
2631            sycl::ext::oneapi::experimental::use_root_sync};
2632
2633        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
2634            ->template parallel_for<dpct_kernel_name<class gdn_l2_kernel_d82250>>(
2635                sycl::nd_range<3>(sycl::range(1, (unsigned)T, 2 * HK) *
2636                                      sycl::range(1, 1, S),
2637                                  sycl::range(1, 1, S)),
2638                exp_props,
2639                [=](sycl::nd_item<3> item_ct1)
2640                    [[sycl::reqd_sub_group_size(32)]] {
2641                        gdn_l2_kernel(h, eps);
2642                    });
2643    }
2644    check("gdn_conv");
2645}
2646// Variant 6, the Xe sub-group recurrence (gdn_xe.hpp): one barrier per token instead of five, the same bits.  Arc A770
2647// (Coder IQ1_M, 128K context, int8 KV): recurrence 1.83 -> 0.92 s on an 8K prompt (+5% prompt tok/s), 7.3 -> 3.65 s on
2648// 32K (+8%), the same output tokens.  On by default on Alchemist only (not measured on other cards).
2649// STRATA_GDN_XE=0: the column kernels everywhere; STRATA_GDN_XE=1: variant 6 on any Intel GPU with 16-lane sub-groups.
2650static bool gdn_xe_device(void* stream) {
2651    const auto device = strata::q_of(stream)->get_device();
2652    const auto subgroups = device.get_info<sycl::info::device::sub_group_sizes>();
2653    const bool sg16 = std::find(subgroups.begin(), subgroups.end(), size_t(16)) != subgroups.end();
2654    return sg16 && device.is_gpu() && device.get_info<sycl::info::device::vendor_id>() == 0x8086;
2655}
2656static bool gdn_xe_on(void* stream) {
2657    static const bool on = [stream] {
2658        const char* v = std::getenv("STRATA_GDN_XE");
2659        if (v && *v) return std::atoi(v) != 0 && gdn_xe_device(stream);
2660        return strata::intel_gpu_gen(strata::q_of(stream)->get_device()) == strata::IntelGpuGen::Alchemist &&
2661               gdn_xe_device(stream);
2662    }();
2663    return on;
2664}
2665void gdn_recurrence_variant(int variant, float* state, const float* h, const float* gate, const float* beta,
2666                            const float* z, const float* gamma, float eps, float* y, uint16_t* y16, int64_t T,
2667                            void* stream, int64_t ld16) {
2668    if (ld16 <= 0) ld16 = (int64_t) HV * S;
2669#if defined(__HIPCC__)
2670    if (variant == 3) {   // diagnostics: the quad recurrence + the old norm kernel
2671        if (T > 0) {
2672            gdn_rec_quad_kernel<<<HV * (S / QCB), QTH, 0, (cudaStream_t) stream>>>(state, h, gate, beta, y, T);
2673            gdn_out_norm_kernel<<<dim3((unsigned) T, HV), S, 0, (cudaStream_t) stream>>>(z, gamma, eps, y, y16, ld16);
2674        }
2675        return;
2676    }
2677    if (variant == 4 || variant == 5) {   // diagnostics: the quad recurrence's PP / two-column kernels + the norm
2678        if (T > 0) {
2679            if (variant == 5)
2680                gdn_rec_quad2c_kernel<<<HV * (S / C2CB), QTH, 0, (cudaStream_t) stream>>>(state, h, gate, beta, y, T);
2681            else
2682                gdn_rec_quad_pp_kernel<<<HV * (S / QCB), QTH, 0, (cudaStream_t) stream>>>(state, h, gate, beta, y, T);
2683            gdn_out_norm_loop_kernel<true><<<(unsigned) std::min<int64_t>(T * HV, 4096), S, 0, (cudaStream_t) stream>>>(
2684                z, gamma, eps, y, y16, T * HV, ld16);
2685        }
2686        check("gdn_recurrence (quad pp)");
2687        return;
2688    }
2689    if (variant == 1) {
2690        if (T > 0) {
2691            static const int pp = [] { const char* v = std::getenv("STRATA_GDN_PP"); return v ? std::atoi(v) : 0; }();
2692            if (pp == 2)
2693                gdn_rec_quad2c_kernel<<<HV * (S / C2CB), QTH, 0, (cudaStream_t) stream>>>(state, h, gate, beta, y, T);
2694            else if (pp)
2695                gdn_rec_quad_pp_kernel<<<HV * (S / QCB), QTH, 0, (cudaStream_t) stream>>>(state, h, gate, beta, y, T);
2696            else
2697                gdn_rec_quad_kernel<<<HV * (S / QCB), QTH, 0, (cudaStream_t) stream>>>(state, h, gate, beta, y, T);
2698            static const bool noy = [] { const char* v = std::getenv("STRATA_GDN_NOY"); return v && std::atoi(v) != 0; }();
2699            if (noy)
2700                gdn_out_norm_loop_kernel<false><<<(unsigned) std::min<int64_t>(T * HV, 4096), S, 0, (cudaStream_t) stream>>>(
2701                    z, gamma, eps, y, y16, T * HV, ld16);
2702            else
2703                gdn_out_norm_loop_kernel<true><<<(unsigned) std::min<int64_t>(T * HV, 4096), S, 0, (cudaStream_t) stream>>>(
2704                    z, gamma, eps, y, y16, T * HV, ld16);
2705        }
2706        check("gdn_recurrence (quad)");
2707        return;
2708    }
2709#else
2710    (void) variant;   // the quad recurrence kernels are AMD-only
2711#endif
2712    static const bool serial = std::getenv("STRATA_GDN_REC_HEADS") != nullptr;   // the one-block-per-head kernel (A/B)
2713    // variant 6 = the Xe sub-group recurrence + the unchanged norm kernel (gdn_recurrence: gdn_xe_on)
2714    const bool xe = T > 0 && !serial && variant == 6;
2715    if (xe && !gdn_xe_device(stream)) throw std::runtime_error("GDN Xe variant requires an Intel GPU with 16-lane sub-groups");
2716    if (!xe && (serial || T <= 0 || variant == 2)) {
2717        /*
2718        DPCT1049: The work-group size passed to the SYCL kernel may exceed
2719        the limit. To get the device limit, query
2720        info::device::max_work_group_size. Adjust the work-group size if needed.
2721        */
2722        auto exp_props = sycl::ext::oneapi::experimental::properties{
2723            sycl::ext::oneapi::experimental::use_root_sync};
2724
2725        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
2726            ->template parallel_for<dpct_kernel_name<class gdn_rec_kernel_923fed>>(
2727                sycl::nd_range<3>(sycl::range(1, 1, HV) * sycl::range(1, RG, S),
2728                                  sycl::range(1, RG, S)),
2729                exp_props,
2730                [=](sycl::nd_item<3> item_ct1)
2731                    [[sycl::reqd_sub_group_size(32)]] {
2732                        gdn_rec_kernel(state, h, gate, beta, z, gamma, eps, y,
2733                                       y16, T, ld16);
2734                    });
2735    } else {
2736        static const bool pipe = [] { const char* v = std::getenv("STRATA_GDN_PIPELINE"); return v == nullptr || std::atoi(v) != 0; }();
2737        if (xe) {
2738            detail::gdn_xe_launch(*strata::q_of(stream), state, h, gate, beta, y, T);
2739        } else
2740#if !defined(__HIPCC__)
2741        if (pipe && gdn_keyhead_ok())   // the value heads of a key head in one thread (same bits)
2742        {
2743            auto exp_props = sycl::ext::oneapi::experimental::properties{
2744                sycl::ext::oneapi::experimental::use_root_sync};
2745
2746            strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
2747                ->template parallel_for<
2748                    dpct_kernel_name<class gdn_rec_kh_kernel_c88399>>(
2749                    sycl::nd_range<3>(sycl::range(1, 1, HK * NCB) *
2750                                          sycl::range(1, RG, CB),
2751                                      sycl::range(1, RG, CB)),
2752                    exp_props, [=](sycl::nd_item<3> item_ct1) {
2753                        gdn_rec_kh_kernel(state, h, gate, beta, y, T);
2754                    });
2755        } else
2756#endif
2757            if (pipe) // the software-pipelined loads (same bits)
2758        {
2759            auto exp_props = sycl::ext::oneapi::experimental::properties{
2760                sycl::ext::oneapi::experimental::use_root_sync};
2761
2762            if([]{const char* e=std::getenv("STRATA_SYCL_GDN_PREFILL_REG_QK");return e&&e[0]=='1';}()){
2763                strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class gdn_rec_cols_pipe_local_probe>>(
2764                    sycl::nd_range<3>(sycl::range(1,1,HV*NCB)*sycl::range(1,RG,CB),sycl::range(1,RG,CB)),exp_props,
2765                    [=](sycl::nd_item<3>) [[sycl::reqd_sub_group_size(16)]] {gdn_rec_cols_pipe_local_kernel(state,h,gate,beta,y,T);});
2766            }else
2767            strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
2768                ->template parallel_for<
2769                    dpct_kernel_name<class gdn_rec_cols_pipe_kernel_c6cea3>>(
2770                    sycl::nd_range<3>(sycl::range(1, 1, HV * NCB) *
2771                                          sycl::range(1, RG, CB),
2772                                      sycl::range(1, RG, CB)),
2773                    exp_props, [=](sycl::nd_item<3> item_ct1) {
2774                        gdn_rec_cols_pipe_kernel(state, h, gate, beta, y, T);
2775                    });
2776        } else {
2777            auto exp_props = sycl::ext::oneapi::experimental::properties{
2778                sycl::ext::oneapi::experimental::use_root_sync};
2779
2780            strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
2781                ->template parallel_for<
2782                    dpct_kernel_name<class gdn_rec_cols_kernel_496541>>(
2783                    sycl::nd_range<3>(sycl::range(1, 1, HV * NCB) *
2784                                          sycl::range(1, RG, CB),
2785                                      sycl::range(1, RG, CB)),
2786                    exp_props, [=](sycl::nd_item<3> item_ct1) {
2787                        gdn_rec_cols_kernel(state, h, gate, beta, y, T);
2788                    });
2789        }
2790        {
2791            auto exp_props = sycl::ext::oneapi::experimental::properties{
2792                sycl::ext::oneapi::experimental::use_root_sync};
2793
2794            strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
2795                ->template parallel_for<
2796                    dpct_kernel_name<class gdn_out_norm_kernel_43e92c>>(
2797                    sycl::nd_range<3>(sycl::range(1, HV, (unsigned)T) *
2798                                          sycl::range(1, 1, S),
2799                                      sycl::range(1, 1, S)),
2800                    exp_props,
2801                    [=](sycl::nd_item<3> item_ct1)
2802                        [[sycl::reqd_sub_group_size(32)]] {
2803                            gdn_out_norm_kernel(z, gamma, eps, y, y16, ld16);
2804                        });
2805        }
2806    }
2807    check("gdn_recurrence");
2808}
2809void gdn_recurrence(float* state, const float* h, const float* gate, const float* beta, const float* z,
2810                    const float* gamma, float eps, float* y, uint16_t* y16, int64_t T, void* stream, int64_t ld16) {
2811    // Aurora (S23): four lanes per column + the grid-stride norm, the same bits (tests/hip/gdn_rec_head.cpp);
2812    // STRATA_GDN_HEAD=1 (on by default on gfx1151; off with STRATA_GDN_HEAD=0 or STRATA_GDN_REC_HEADS) takes them
2813    // (AMD builds only; the arch defaults set STRATA_GDN_HEAD=1 on gfx1151 and leave other cards on the earlier kernels)
2814    static const bool head = [] { const char* v = std::getenv("STRATA_GDN_HEAD"); return v != nullptr && std::atoi(v) != 0; }();
2815    static const bool serial = std::getenv("STRATA_GDN_REC_HEADS") != nullptr;
2816    const int v = head && !serial ? 1 : (!serial && gdn_xe_on(stream)) ? 6 : 0;
2817    gdn_recurrence_variant(v, state, h, gate, beta, z, gamma, eps, y, y16, T, stream, ld16);
2818}
2819void route(const float* logits, int32_t* ids, float* weights, int64_t T, int64_t n_expert, void* stream) {
2820    if (n_expert == 512)
2821    {
2822        auto exp_props = sycl::ext::oneapi::experimental::properties{
2823            sycl::ext::oneapi::experimental::use_root_sync};
2824
2825        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
2826            ->template parallel_for<dpct_kernel_name<class route_kernel_ceb296,
2827                                            dpct_kernel_scalar<16>>>(
2828                sycl::nd_range<3>(sycl::range(1, 1, (unsigned)((T + 7) / 8)) *
2829                                      sycl::range(1, 1, 256),
2830                                  sycl::range(1, 1, 256)),
2831                exp_props,
2832                [=](sycl::nd_item<3> item_ct1)
2833                    [[sycl::reqd_sub_group_size(32)]] {
2834                        route_kernel<16>(logits, ids, weights, T);
2835                    });
2836    } else if (n_expert == 256)
2837    {
2838        auto exp_props = sycl::ext::oneapi::experimental::properties{
2839            sycl::ext::oneapi::experimental::use_root_sync};
2840
2841        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
2842            ->template parallel_for<dpct_kernel_name<class route_kernel_4c3133,
2843                                            dpct_kernel_scalar<8>>>(
2844                sycl::nd_range<3>(sycl::range(1, 1, (unsigned)((T + 7) / 8)) *
2845                                      sycl::range(1, 1, 256),
2846                                  sycl::range(1, 1, 256)),
2847                exp_props,
2848                [=](sycl::nd_item<3> item_ct1)
2849                    [[sycl::reqd_sub_group_size(32)]] {
2850                        route_kernel<8>(logits, ids, weights, T);
2851                    });
2852    } else
2853        strata::kernels::router_top10(logits, (int) T, (int) n_expert, KU, ids, weights, stream);
2854    check("route");
2855}
2856void blob_dequant(const uint8_t* blob, uint16_t* gu16, uint16_t* down16, void* stream) {
2857    {
2858        auto exp_props = sycl::ext::oneapi::experimental::properties{
2859            sycl::ext::oneapi::experimental::use_root_sync};
2860
2861        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
2862            ->template parallel_for<dpct_kernel_name<class blob_dequant_kernel_252bb1,
2863                                            dpct_kernel_scalar<false>>>(
2864                sycl::nd_range<3>(
2865                    sycl::range(1, 1, blocks_for(1280LL * 640 + 2560LL * 160)) *
2866                        sycl::range(1, 1, 256),
2867                    sycl::range(1, 1, 256)),
2868                exp_props, [=](sycl::nd_item<3> item_ct1) {
2869                    blob_dequant_kernel<false>(blob, gu16, down16);
2870                });
2871    }
2872    check("blob_dequant");
2873}
2874void blob_dequant_f16(const uint8_t* blob, uint16_t* gu16, uint16_t* down16, void* stream) {
2875    {
2876        auto exp_props = sycl::ext::oneapi::experimental::properties{
2877            sycl::ext::oneapi::experimental::use_root_sync};
2878
2879        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
2880            ->template parallel_for<dpct_kernel_name<class blob_dequant_kernel_1d812a,
2881                                            dpct_kernel_scalar<true>>>(
2882                sycl::nd_range<3>(
2883                    sycl::range(1, 1, blocks_for(1280LL * 640 + 2560LL * 160)) *
2884                        sycl::range(1, 1, 256),
2885                    sycl::range(1, 1, 256)),
2886                exp_props, [=](sycl::nd_item<3> item_ct1) {
2887                    blob_dequant_kernel<true>(blob, gu16, down16);
2888                });
2889    }
2890    check("blob_dequant_f16");
2891}
2892void swiglu_interleaved(const float* gu, uint16_t* h16, int64_t n, void* stream) {
2893    if (n <= 0) return;
2894    {
2895        auto exp_props = sycl::ext::oneapi::experimental::properties{
2896            sycl::ext::oneapi::experimental::use_root_sync};
2897
2898        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
2899            ->template parallel_for<dpct_kernel_name<class swiglu_il_kernel_98d495>>(
2900                sycl::nd_range<3>(sycl::range(1, 1, blocks_for(n * FFC)) *
2901                                      sycl::range(1, 1, 256),
2902                                  sycl::range(1, 1, 256)),
2903                exp_props, [=](sycl::nd_item<3> item_ct1) {
2904                    swiglu_il_kernel(gu, h16, n);
2905                });
2906    }
2907    check("swiglu_interleaved");
2908}
2909void swiglu_pair(const float* g, const float* u, uint16_t* h16, int64_t n, void* stream) {
2910    {
2911        auto exp_props = sycl::ext::oneapi::experimental::properties{
2912            sycl::ext::oneapi::experimental::use_root_sync};
2913
2914        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
2915            ->template parallel_for<dpct_kernel_name<class swiglu_pair_kernel_ab28da>>(
2916                sycl::nd_range<3>(sycl::range(1, 1, blocks_for(n * FFC)) *
2917                                      sycl::range(1, 1, 256),
2918                                  sycl::range(1, 1, 256)),
2919                exp_props, [=](sycl::nd_item<3> item_ct1) {
2920                    swiglu_pair_kernel(g, u, h16, n);
2921                });
2922    }
2923    check("swiglu_pair");
2924}
2925namespace {
2926__dpct_inline__ void copy_i32_kernel(int32_t *__restrict__ dst,
2927                                     const int32_t *__restrict__ src,
2928                                     int64_t n) {
2929    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
2930#pragma unroll
2931    for (int64_t i =
2932             (int64_t)item_ct1.get_group(2) * item_ct1.get_local_range(2) +
2933             item_ct1.get_local_id(2);
2934         i < n; i += (int64_t)item_ct1.get_group_range(2) *
2935                     item_ct1.get_local_range(2))
2936        dst[i] = src[i];
2937}
2938}  // namespace
2939namespace {
2940__dpct_inline__ void copy_f4_kernel(sycl::float4 *__restrict__ dst,
2941                                    const sycl::float4 *__restrict__ src,
2942                                    int64_t n4) {
2943    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
2944#pragma unroll
2945    for (int64_t i =
2946             (int64_t)item_ct1.get_group(2) * item_ct1.get_local_range(2) +
2947             item_ct1.get_local_id(2);
2948         i < n4; i += (int64_t)item_ct1.get_group_range(2) *
2949                      item_ct1.get_local_range(2))
2950        dst[i] = src[i];
2951}
2952}  // namespace
2953void copy_f32_wide(float* dst, const float* src, int64_t n, void* stream) {
2954    if (n <= 0) return;
2955    const int64_t n4 = n / 4, b = std::min<int64_t>((n4 + 255) / 256, 4096);
2956    if (n4 > 0) {
2957        auto exp_props = sycl::ext::oneapi::experimental::properties{
2958            sycl::ext::oneapi::experimental::use_root_sync};
2959
2960        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
2961            ->template parallel_for<dpct_kernel_name<class copy_f4_kernel_bb4110>>(
2962                sycl::nd_range<3>(sycl::range(1, 1, (unsigned)b) *
2963                                      sycl::range(1, 1, 256),
2964                                  sycl::range(1, 1, 256)),
2965                exp_props, [=](sycl::nd_item<3> item_ct1) {
2966                    copy_f4_kernel((sycl::float4 *)dst,
2967                                   (const sycl::float4 *)src, n4);
2968                });
2969    }
2970    if (n % 4) copy_i32((int32_t*) dst + n4 * 4, (const int32_t*) src + n4 * 4, n % 4, stream);
2971    check("copy_f32_wide");
2972}
2973void copy_i32(int32_t* dst, const int32_t* src, int64_t n, void* stream) {
2974    if (n <= 0) return;
2975    const int64_t b = (n + 255) / 256;
2976    {
2977        auto exp_props = sycl::ext::oneapi::experimental::properties{
2978            sycl::ext::oneapi::experimental::use_root_sync};
2979
2980        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
2981            ->template parallel_for<dpct_kernel_name<class copy_i32_kernel_1c95ea>>(
2982                sycl::nd_range<3>(
2983                    sycl::range(1, 1, (unsigned)(b < 256 ? b : 256)) *
2984                        sycl::range(1, 1, 256),
2985                    sycl::range(1, 1, 256)),
2986                exp_props, [=](sycl::nd_item<3> item_ct1) {
2987                    copy_i32_kernel(dst, src, n);
2988                });
2989    }
2990    check("copy_i32");
2991}
2992void gather_rows16(const uint16_t* x16, const int32_t* src, uint16_t* dst16, int64_t n, int64_t width, void* stream) {
2993    if (n <= 0) return;
2994    {
2995        auto exp_props = sycl::ext::oneapi::experimental::properties{
2996            sycl::ext::oneapi::experimental::use_root_sync};
2997
2998        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
2999            ->template parallel_for<dpct_kernel_name<class gather_rows16_kernel_d9d697>>(
3000                sycl::nd_range<3>(
3001                    sycl::range(1, 1, blocks_for(n * (width / 8))) *
3002                        sycl::range(1, 1, 256),
3003                    sycl::range(1, 1, 256)),
3004                exp_props, [=](sycl::nd_item<3> item_ct1) {
3005                    gather_rows16_kernel(x16, src, dst16, n, width);
3006                });
3007    }
3008    check("gather_rows16");
3009}
3010void moe_combine(const float* Dm, const int32_t* slot, const float* w, const float* shared, const float* sg, float* bo,
3011                 int64_t T, void* stream, const float* row_sd) {
3012    if (row_sd != nullptr) { std::fprintf(stderr, "moe_combine: per-row scales (NVFP4) are CUDA only\n"); std::exit(1); }
3013#ifndef STRATA_W_NO_COMB
3014    if (((reinterpret_cast<uintptr_t>(Dm) | reinterpret_cast<uintptr_t>(shared) | reinterpret_cast<uintptr_t>(bo)) & 15) == 0) {
3015        {
3016            auto exp_props = sycl::ext::oneapi::experimental::properties{
3017                sycl::ext::oneapi::experimental::use_root_sync};
3018
3019            strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
3020                ->template parallel_for<
3021                    dpct_kernel_name<class moe_combine4_kernel_1c986f>>(
3022                    sycl::nd_range<3>(
3023                        sycl::range(1, 1, blocks_for(T * (N / 4))) *
3024                            sycl::range(1, 1, 256),
3025                        sycl::range(1, 1, 256)),
3026                    exp_props, [=](sycl::nd_item<3> item_ct1) {
3027                        moe_combine4_kernel(
3028                            Dm, slot, w,
3029                            reinterpret_cast<const sycl::float4 *>(shared), sg,
3030                            reinterpret_cast<sycl::float4 *>(bo), T);
3031                    });
3032        }
3033        check("moe_combine");
3034        return;
3035    }
3036#endif
3037    {
3038        auto exp_props = sycl::ext::oneapi::experimental::properties{
3039            sycl::ext::oneapi::experimental::use_root_sync};
3040
3041        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
3042            ->template parallel_for<dpct_kernel_name<class moe_combine_kernel_60f865>>(
3043                sycl::nd_range<3>(sycl::range(1, 1, blocks_for(T * N)) *
3044                                      sycl::range(1, 1, 256),
3045                                  sycl::range(1, 1, 256)),
3046                exp_props, [=](sycl::nd_item<3> item_ct1) {
3047                    moe_combine_kernel(Dm, slot, w, shared, sg, bo, T);
3048                });
3049    }
3050    check("moe_combine");
3051}
3052void rms_rows(float* x, const float* w, int64_t rows, int64_t cols, int64_t ld, float eps, void* stream) {
3053    if (rows <= 0) return;
3054    {
3055        auto exp_props = sycl::ext::oneapi::experimental::properties{
3056            sycl::ext::oneapi::experimental::use_root_sync};
3057
3058        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
3059            ->template parallel_for<dpct_kernel_name<class rms_rows_kernel_c88408>>(
3060                sycl::nd_range<3>(sycl::range(1, 1, (unsigned)rows) *
3061                                      sycl::range(1, 1, 256),
3062                                  sycl::range(1, 1, 256)),
3063                exp_props,
3064                [=](sycl::nd_item<3> item_ct1)
3065                    [[sycl::reqd_sub_group_size(32)]] {
3066                        rms_rows_kernel(x, w, cols, ld, eps);
3067                    });
3068    }
3069    check("rms_rows");
3070}
3071void rope(float* x, int64_t T, int64_t heads, int64_t dim, int64_t ld, int64_t pos0,
3072          const strata::kernels::RopeScaling& scaling, void* stream) {
3073    // The engine validates the resolved config at startup with the same rule (generate.cpp), so this only
3074    // fires for a caller that bypassed it; the prompt path has no error return here, so it stops the process.
3075    if (const char* why = strata::kernels::rope_scaling_invalid(scaling)) {
3076        std::fprintf(stderr, "prefill rope: invalid rope scaling: %s\n", why);
3077        std::exit(1);
3078    }
3079    const float theta_scale = powf((float) scaling.freq_base, -2.0f / 64.0f);
3080    const strata::kernels::RopeKernelArgs k = scaling.kernel_args(64);   // none: the identity constants
3081    const strata::kernels::RopeTab rt = strata::kernels::rope_table_for(scaling);
3082    if (rt.cos != nullptr)
3083    {
3084        auto exp_props = sycl::ext::oneapi::experimental::properties{
3085            sycl::ext::oneapi::experimental::use_root_sync};
3086
3087        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
3088            ->submit([&](sycl::handler &cgh) {
3089                auto strata_kernels_mrope_table_ct11 =
3090                    strata::kernels::mrope_table();
3091
3092                cgh.parallel_for<dpct_kernel_name<class rope_kernel_4d58b9,
3093                                                  dpct_kernel_scalar<true>>>(
3094                    sycl::nd_range<3>(sycl::range(1, 1, (unsigned)(T * heads)) *
3095                                          sycl::range(1, 1, 32),
3096                                      sycl::range(1, 1, 32)),
3097                    exp_props, [=](sycl::nd_item<3> item_ct1) {
3098                        rope_kernel<true>(x, heads, dim, ld, pos0, theta_scale,
3099                                          k.freq_scale, k.corr_low, k.corr_high,
3100                                          k.ext_factor, k.attn_factor,
3101                                          strata_kernels_mrope_table_ct11, rt);
3102                    });
3103            });
3104    } else {
3105        auto exp_props = sycl::ext::oneapi::experimental::properties{
3106            sycl::ext::oneapi::experimental::use_root_sync};
3107
3108        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
3109            ->submit([&](sycl::handler &cgh) {
3110                auto strata_kernels_mrope_table_ct11 =
3111                    strata::kernels::mrope_table();
3112
3113                cgh.parallel_for<dpct_kernel_name<class rope_kernel_4d58b9,
3114                                                  dpct_kernel_scalar<false>>>(
3115                    sycl::nd_range<3>(sycl::range(1, 1, (unsigned)(T * heads)) *
3116                                          sycl::range(1, 1, 32),
3117                                      sycl::range(1, 1, 32)),
3118                    exp_props, [=](sycl::nd_item<3> item_ct1) {
3119                        rope_kernel<false>(
3120                            x, heads, dim, ld, pos0, theta_scale, k.freq_scale,
3121                            k.corr_low, k.corr_high, k.ext_factor,
3122                            k.attn_factor, strata_kernels_mrope_table_ct11, rt);
3123                    });
3124            });
3125    }
3126    check("rope");
3127}
3128void split_q(const float* q_full, float* q, int64_t T, void* stream) {
3129    {
3130        auto exp_props = sycl::ext::oneapi::experimental::properties{
3131            sycl::ext::oneapi::experimental::use_root_sync};
3132
3133        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
3134            ->template parallel_for<dpct_kernel_name<class split_q_kernel_83c16c>>(
3135                sycl::nd_range<3>(sycl::range(1, 1, blocks_for(T * NHQ * 256)) *
3136                                      sycl::range(1, 1, 256),
3137                                  sycl::range(1, 1, 256)),
3138                exp_props, [=](sycl::nd_item<3> item_ct1) {
3139                    split_q_kernel(q_full, q, T);
3140                });
3141    }
3142    check("split_q");
3143}
3144void gate_attn(const float* attn, const float* q_full, uint16_t* out16, int64_t T, void* stream, int64_t ld16) {
3145    {
3146        auto exp_props = sycl::ext::oneapi::experimental::properties{
3147            sycl::ext::oneapi::experimental::use_root_sync};
3148
3149        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
3150            ->submit([&](sycl::handler &cgh) {
3151                auto ld16_ld16_ct4 = ld16 > 0 ? ld16 : NHQ * 256;
3152
3153                cgh.parallel_for<
3154                    dpct_kernel_name<class gate_attn_kernel_3fc329>>(
3155                    sycl::nd_range<3>(
3156                        sycl::range(1, 1, blocks_for(T * NHQ * 256)) *
3157                            sycl::range(1, 1, 256),
3158                        sycl::range(1, 1, 256)),
3159                    exp_props, [=](sycl::nd_item<3> item_ct1) {
3160                        gate_attn_kernel(attn, q_full, out16, T, ld16_ld16_ct4);
3161                    });
3162            });
3163    }
3164    check("gate_attn");
3165}
3166
3167}  // namespace strata::prefill