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
405.5 KiB7960 linesraw
1#include "b60_weight_cache.hpp"
2#include "b60_layout_state.hpp"
3#include <sycl/ext/intel/esimd.hpp>
4#include <sycl/ext/intel/esimd/xmx/dpas.hpp>
5// src/kernels/cuda/iq_kernels.cu - see include/strata/kernels/iq_kernels.hpp.
6//
7// The dot products (vec_dot_*_q8_1), the dequantizers and the q8_1 quantizer are transcribed from llama.cpp
8// (ggml/src/ggml-cuda/vecdotq.cuh, dequantize.cuh, quantize.cu at the commit in third_party/ggml/VERSION.txt;
9// MIT license, third_party/ggml/LICENSE).  The block structs and codebook grids come from its ggml-common.h,
10// included unchanged.
11#define DPCT_PROFILING_ENABLED
12#include <sycl/sycl.hpp>
13#include "strata/kprof.hpp"
14#include <sycl/ext/oneapi/matrix/matrix-intel.hpp>
15#include <dpct/dpct.hpp>
16#include "strata/sycl_math.hpp"
17#include "strata/sycl_queue.hpp"
18#include "strata/workload_trace.hpp"
19#include "strata/kernels/iq_kernels.hpp"
20#include "strata/kernels/iq_dequant_expert.hpp"
21#include "strata/kernels/dp4a.hpp"
22#include "strata/kernels/q8_1_finite.hpp"
23#include "strata/kernels/iq4_lut.hpp"
24#include "s26_tsum.dp.hpp"
25#include "strata/kernels/iq_dequant.hpp"
26#include "strata/kernels/q2_0_decode.hpp"
27#include "strata/kernels/expert_staging.hpp"
28#include "strata/kernels/verify_kernels.hpp"
29#include "strata/kernels/iq_signed_grid.hpp"
30
31#define GGML_COMMON_DECL_SYCL
32#define GGML_COMMON_IMPL_SYCL
33#include "ggml-common.h"
34#include "ggml-common-tq.h"                   // APR trellis types (agention llama.cpp fork)
35#include "strata/kernels/tq_lut_i8_sycl.hpp"   // int8 copy of the trellis codebook (one global scale) for the dp4a dot
36
37#include <sycl/ext/oneapi/matrix/matrix.hpp>
38#include <sycl/ext/intel/experimental/grf_size_properties.hpp>
39// BEGIN PRIVATE IQ3 XMX REUSE INCLUDES
40#include "strata/kernels/iq_signed_grid.hpp"
41#include <stdexcept>
42// END PRIVATE IQ3 XMX REUSE INCLUDES
43#include <algorithm>
44#include <type_traits>
45#include <cstdio>
46#include <utility>
47#include <optional>
48#include <cstdlib>
49#include <type_traits>
50#include <map>
51#include <mutex>
52#include <tuple>
53#include <cmath>
54
55namespace strata::kernels {
56namespace {
57
58// Four adjacent two-bit codes become four signed bytes {-1,0,1,2}.
59// Every byte before addition is 0..3: adding 0x7f cannot carry into
60// its neighbor. This replaces a byte-permute lookup, without requantizing.
61inline uint32_t q2_0_decode4(uint32_t codes) {
62    codes &= 255;
63    codes = (codes | (codes << 12)) & 0x000f000fu;
64    codes = (codes | (codes << 6)) & 0x03030303u;
65    return (codes + 0x7f7f7f7fu) ^ 0x80808080u;
66}
67inline sycl::int2 q2_0_decode8(uint32_t codes) {
68    return {(int)q2_0_decode4(codes), (int)q2_0_decode4(codes >> 8)};
69}
70
71void check(const char* what) {
72    /*
73    DPCT1010: SYCL uses exceptions to report errors and does not use the
74    error codes. The cudaGetLastError function call was replaced with 0. You
75    need to rewrite this code.
76    */
77    const dpct::err0 e = 0;
78    /*
79    DPCT1009: SYCL reports errors using exceptions and does not use error
80    codes. Please replace the "get_error_string_dummy(...)" with a real
81    error-handling function.
82    */
83}
84
85// ---------------------------------------------------------------- llama.cpp helpers (vecdotq.cuh)
86__dpct_inline__ int get_int_b2(const void *x, const int &i32) {
87    const uint16_t* x16 = (const uint16_t*) x;
88    int x32 = x16[2 * i32 + 0] << 0;
89    x32 |= x16[2 * i32 + 1] << 16;
90    return x32;
91}
92__dpct_inline__ int get_int_b4(const void *x, const int &i32) {
93    return ((const int *)x)[i32];
94}
95__dpct_inline__ uint32_t unpack_ksigns(const uint8_t v) {
96    const uint32_t p = sycl::popcount(v) & 1;
97    const uint32_t s = v ^ p << 7;
98    return s * 0x01010101;
99}
100__dpct_inline__ sycl::int2 get_int_from_table_16(const int &q4,
101                                                 const int8_t *table) {
102#if defined(STRATA_HIP_GFX906)
103    // AMD: llama.cpp's HIP lookup (vecdotq.cuh) - v_perm_b32 takes 3-bit byte indices, so the low and high halves
104    // of the table are looked up and the index MSB picks between them: 4 perms per 8 values.
105    const uint32_t* v32 = reinterpret_cast<const uint32_t*>(table);
106    const uint32_t q_even = (uint32_t) q4, q_odd = (uint32_t) q4 >> 4;
107    const uint32_t el = __builtin_amdgcn_perm(v32[1], v32[0], q_even & 0x07070707u);
108    const uint32_t ol = __builtin_amdgcn_perm(v32[1], v32[0], q_odd & 0x07070707u);
109    const uint32_t eh = __builtin_amdgcn_perm(v32[3], v32[2], q_even & 0x07070707u);
110    const uint32_t oh = __builtin_amdgcn_perm(v32[3], v32[2], q_odd & 0x07070707u);
111    return make_int2((int) __builtin_amdgcn_perm(eh, el, 0x03020100u | ((q_even & 0x08080808u) >> 1)),
112                     (int) __builtin_amdgcn_perm(oh, ol, 0x03020100u | ((q_odd & 0x08080808u) >> 1)));
113#else
114    const uint32_t* table32 = (const uint32_t*) table;
115    uint32_t tmp[2];
116    const uint32_t low_high_selection_indices = (0x32103210 | ((q4 & 0x88888888) >> 1));
117#pragma unroll
118    for (uint32_t i = 0; i < 2; ++i) {
119        const uint32_t shift = 16 * i;
120        const uint32_t low =
121            dpct::byte_level_permute(table32[0], table32[1], q4 >> shift);
122        const uint32_t high =
123            dpct::byte_level_permute(table32[2], table32[3], q4 >> shift);
124        tmp[i] = dpct::byte_level_permute(low, high,
125                                          low_high_selection_indices >> shift);
126    }
127    return sycl::int2(dpct::byte_level_permute(tmp[0], tmp[1], 0x6420),
128                      dpct::byte_level_permute(tmp[0], tmp[1], 0x7531));
129#endif
130}
131#define ggml_cuda_dp4a(a, b, c) strata::dp4a((a), (b), (c))   // SYCL port: the one dp4a (strata/sycl_math.hpp)
132
133// ---------------------------------------------------------------- the dot products (vecdotq.cuh)
134#ifndef STRATA_Q2_WORD_FAST
135#define STRATA_Q2_WORD_FAST 0
136#endif
137__dpct_inline__ sycl::int2 q2_decode8(uint16_t q) {
138#if STRATA_Q2_WORD_FAST
139    const auto decode4 = [](uint32_t c) {
140        c &= 0xFFu;
141        c = (c | (c << 12)) & 0x000F000Fu;
142        c = (c | (c << 6)) & 0x03030303u;
143        return (int) ((c + 0x7F7F7F7Fu) ^ 0x80808080u);
144    };
145    return sycl::int2(decode4(q), decode4(q >> 8));
146#else
147    const int qe = dpct::byte_level_permute(0x020100FF, 0x020100FF, q);
148    const int qo = dpct::byte_level_permute(0x020100FF, 0x020100FF, q >> 2);
149    return sycl::int2(dpct::byte_level_permute(qe, qo, 0x5140),
150                      dpct::byte_level_permute(qe, qo, 0x7362));
151#endif
152}
153
154__dpct_inline__ float vec_dot_q2_0_q8_1(const void *__restrict__ vbq,
155                                        const block_q8_1 *__restrict__ bq8_1,
156                                        const int &kbx, const int &iqs) {
157    const block_q2_0* bq2_0 = (const block_q2_0*) vbq + kbx;
158    const float d2 = bq2_0->d;
159    const int16_t* qs = (const int16_t*) bq2_0->qs + iqs * 4;
160    const block_q8_1* bq8_1_chunk = bq8_1 + iqs;
161    int sumi = 0;
162#pragma unroll
163    for (int j = 0; j < 4; ++j) {
164        const int q = qs[j];
165        const int u = get_int_b4(bq8_1_chunk->qs, j * 2 + 0);
166        const int v = get_int_b4(bq8_1_chunk->qs, j * 2 + 1);
167        const sycl::int2 w = q2_decode8((uint16_t) q);
168        sumi = ggml_cuda_dp4a(u, w.x(), sumi);
169        sumi = ggml_cuda_dp4a(v, w.y(), sumi);
170    }
171    const float d8 = bq8_1_chunk->ds[0];
172    return d2 * d8 * sumi;
173}
174
175// SYCL port: ggml's __vcmpne4 / __vsub4 came out of dpct as per-byte loops (extract, compare, insert, x4); on Xe the
176// expert dot kernels were ALU-bound with them (77% XVE active, metrics 2026-09-30). SWAR forms of the two uses:
177//   swar_ne4(x): 0xFF in every byte of x that is non-zero (the sign masks: at most one bit per byte)
178//   swar_sub4(a, s) with s from swar_ne4: per byte a - s, i.e. a + 1 where the sign byte is set (two's complement
179//   of the grid value after the xor: the same bits as __vsub4(a, s) for s in {0x00, 0xFF})
180#ifndef STRATA_SWAR
181#define STRATA_SWAR 1   // 1: the SWAR forms; 0: dpct's per-byte loops (A/B 2026-09-30: both correct)
182#endif
183#if STRATA_SWAR
184__dpct_inline__ int swar_ne4(unsigned x) {
185    x = (x | (x >> 4)) & 0x0F0F0F0Fu;
186    x = (x | (x >> 2)) & 0x03030303u;
187    x = (x | (x >> 1)) & 0x01010101u;
188    return (int) (x * 0xFFu);
189}
190__dpct_inline__ int swar_sub4(unsigned a, unsigned s) {
191    return (int) (((a & 0x7F7F7F7Fu) + (s & 0x01010101u)) ^ (a & 0x80808080u));
192}
193#else
194__dpct_inline__ int swar_ne4(unsigned x) { return dpct::vectorized_binary<sycl::uchar4>(x, 0, std::not_equal_to<>()); }
195__dpct_inline__ int swar_sub4(unsigned a, unsigned s) { return dpct::vectorized_binary<sycl::uchar4>(a, s, std::minus<>()); }
196#endif
197
198#ifndef STRATA_IQ3S_SIGN_FAST
199#define STRATA_IQ3S_SIGN_FAST 0
200#endif
201#ifndef STRATA_IQ3S_SIGN_APPLY_FAST
202#define STRATA_IQ3S_SIGN_APPLY_FAST 0
203#endif
204__dpct_inline__ int iq3s_sign_mask(unsigned nibble) {
205#if STRATA_IQ3S_SIGN_FAST
206    const unsigned bits = (nibble & 0x0Fu) * 0x00204081u & 0x01010101u;
207    return (int) ((bits << 8) - bits);
208#else
209    return swar_ne4((nibble & 1u) | ((nibble & 2u) << 8) |
210                    ((nibble & 4u) << 16) | ((nibble & 8u) << 24));
211#endif
212}
213__dpct_inline__ int iq3s_apply_sign(unsigned grid, unsigned sign) {
214#if STRATA_IQ3S_SIGN_APPLY_FAST
215    return (int) ((grid ^ sign) + (sign & 0x01010101u));
216#else
217    return swar_sub4(grid ^ sign, sign);
218#endif
219}
220
221template <bool PackedSigns = false>
222__dpct_inline__ float vec_dot_iq2_xxs_q8_1(const void *__restrict__ vbq,
223                                           const block_q8_1 *__restrict__ bq8_1,
224                                           const int &kbx, const int &iqs) {
225    const block_iq2_xxs* bq2 = PackedSigns ? iq_signed_grid::block_at<block_iq2_xxs>(vbq, uint32_t(kbx)) : (const block_iq2_xxs*) vbq + kbx;
226    const int q2 = get_int_b2(bq2->qs, iqs);
227    const uint8_t* aux8 = (const uint8_t*) &q2;
228    const uint32_t aux32 = get_int_b2(bq2->qs, iqs + 1);
229    int sumi = 0;
230#pragma unroll
231    for (int k0 = 0; k0 < 8; k0 += 2) {
232        const sycl::uint2 grid_pos =
233            ((const sycl::uint2 *)iq2xxs_grid)[aux8[k0 / 2]];
234        const uint32_t signs = unpack_ksigns(aux32 >> (7 * k0 / 2));
235        const int signs0 = swar_ne4(signs & 0x08040201);
236        const int grid0 = PackedSigns ? iq_signed_grid::apply(grid_pos.x(), signs) : swar_sub4(grid_pos.x() ^ signs0, signs0);
237        const int u0 = get_int_b4(bq8_1[iqs / 2].qs, k0 + 0);
238        sumi = ggml_cuda_dp4a(grid0, u0, sumi);
239        const int signs1 = swar_ne4(signs & 0x80402010);
240        const int grid1 = PackedSigns ? iq_signed_grid::apply(grid_pos.y(), signs >> 4) : swar_sub4(grid_pos.y() ^ signs1, signs1);
241        const int u1 = get_int_b4(bq8_1[iqs / 2].qs, k0 + 1);
242        sumi = ggml_cuda_dp4a(grid1, u1, sumi);
243    }
244    const int ls = aux32 >> 27 | 1;
245    sumi = sumi * ls / 8;
246    const float d = sycl::vec<sycl::half, 1>(bq2->d)
247                        .convert<float, sycl::rounding_mode::automatic>()[0] *
248                    bq8_1[iqs / 2].ds[0];
249    return d * sumi;
250}
251
252__dpct_inline__ float vec_dot_iq2_xs_q8_1(const void *__restrict__ vbq,
253                                          const block_q8_1 *__restrict__ bq8_1,
254                                          const int &kbx, const int &iqs) {
255    const block_iq2_xs* bq2 = (const block_iq2_xs*) vbq + kbx;
256    // SYCL port: the four 16-bit codes by shifts. ggml reads them through a uint16_t* to an int2, which is type
257    // punning the SYCL device compiler does not honour (non-char aliasing): IQ2_XS products came out garbage
258    // (iq_multi_parity, Swift 1.5 IQ2_XS) while the dequantizer, reading the codes directly, was exact.
259    const uint32_t q2_lo = (uint32_t) get_int_b2(bq2->qs, iqs + 0), q2_hi = (uint32_t) get_int_b2(bq2->qs, iqs + 1);
260    const uint16_t q2[4] = {(uint16_t) q2_lo, (uint16_t) (q2_lo >> 16), (uint16_t) q2_hi, (uint16_t) (q2_hi >> 16)};
261    const int ls0 = bq2->scales[iqs / 2] & 0x0F;
262    const int ls1 = bq2->scales[iqs / 2] >> 4;
263    int sumi0 = 0, sumi1 = 0;
264#pragma unroll
265    for (int l0 = 0; l0 < 8; l0 += 2) {
266        const sycl::uint2 grid_pos =
267            ((const sycl::uint2 *)iq2xs_grid)[q2[l0 / 2] & 0x1FF];
268        const uint32_t signs = unpack_ksigns(q2[l0 / 2] >> 9);
269#if STRATA_IQ3S_SIGN_FAST
270        const int signs0 = iq3s_sign_mask(signs);
271#else
272        const int signs0 = swar_ne4(signs & 0x08040201);
273#endif
274        const int grid_l = iq3s_apply_sign(grid_pos.x(), signs0);
275        const int u0 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 0);
276#if STRATA_IQ3S_SIGN_FAST
277        const int signs1 = iq3s_sign_mask(signs >> 4);
278#else
279        const int signs1 = swar_ne4(signs & 0x80402010);
280#endif
281        const int grid_h = iq3s_apply_sign(grid_pos.y(), signs1);
282        const int u1 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 1);
283        if (l0 < 4) {
284            sumi0 = ggml_cuda_dp4a(grid_l, u0, sumi0);
285            sumi0 = ggml_cuda_dp4a(grid_h, u1, sumi0);
286        } else {
287            sumi1 = ggml_cuda_dp4a(grid_l, u0, sumi1);
288            sumi1 = ggml_cuda_dp4a(grid_h, u1, sumi1);
289        }
290    }
291    const int sumi = (sumi0 * ls0 + sumi1 * ls1 + (sumi0 + sumi1) / 2) / 4;
292    const float d = sycl::vec<sycl::half, 1>(bq2->d)
293                        .convert<float, sycl::rounding_mode::automatic>()[0] *
294                    bq8_1[iqs / 2].ds[0];
295    return d * sumi;
296}
297
298template <bool PackedSigns = false>
299__dpct_inline__ float vec_dot_iq2_s_q8_1(const void *__restrict__ vbq,
300                                         const block_q8_1 *__restrict__ bq8_1,
301                                         const int &kbx, const int &iqs) {
302    const block_iq2_s* bq2 = PackedSigns ? iq_signed_grid::block_at<block_iq2_s>(vbq, uint32_t(kbx)) : (const block_iq2_s*) vbq + kbx;
303    const int qs_packed = get_int_b2(bq2->qs, iqs / 2);
304    const uint8_t* qs = (const uint8_t*) &qs_packed;
305    const int qh = bq2->qh[iqs / 2];
306    const int signs_packed_32 = get_int_b2(bq2->qs, QK_K / 32 + iqs / 2);
307    const uint8_t* signs_packed_8 = (const uint8_t*) &signs_packed_32;
308    const int ls0 = bq2->scales[iqs / 2] & 0x0F;
309    const int ls1 = bq2->scales[iqs / 2] >> 4;
310    int sumi0 = 0, sumi1 = 0;
311#pragma unroll
312    for (int l0 = 0; l0 < 8; l0 += 2) {
313        const int* grid_pos = (const int*) (iq2s_grid + (qs[l0 / 2] | ((qh << (8 - l0)) & 0x300)));
314#if STRATA_IQ3S_SIGN_FAST
315        const int signs0 = iq3s_sign_mask(signs_packed_8[l0 / 2]);
316        const int signs1 = iq3s_sign_mask(signs_packed_8[l0 / 2] >> 4);
317#else
318        const int signs0 = swar_ne4(((signs_packed_8[l0 / 2] & 0x03) << 7) |
319                ((signs_packed_8[l0 / 2] & 0x0C) << 21));
320        const int signs1 = swar_ne4(((signs_packed_8[l0 / 2] & 0x30) << 3) |
321                ((signs_packed_8[l0 / 2] & 0xC0) << 17));
322#endif
323        const int grid_l = PackedSigns ? iq_signed_grid::apply(grid_pos[0], signs_packed_8[l0 / 2]) : iq3s_apply_sign(grid_pos[0], signs0);
324        const int grid_h = PackedSigns ? iq_signed_grid::apply(grid_pos[1], signs_packed_8[l0 / 2] >> 4) : iq3s_apply_sign(grid_pos[1], signs1);
325        const int u0 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 0);
326        const int u1 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 1);
327        if (l0 < 4) {
328            sumi0 = ggml_cuda_dp4a(grid_l, u0, sumi0);
329            sumi0 = ggml_cuda_dp4a(grid_h, u1, sumi0);
330        } else {
331            sumi1 = ggml_cuda_dp4a(grid_l, u0, sumi1);
332            sumi1 = ggml_cuda_dp4a(grid_h, u1, sumi1);
333        }
334    }
335    const int sumi = (sumi0 * ls0 + sumi1 * ls1 + (sumi0 + sumi1) / 2) / 4;
336    const float d = sycl::vec<sycl::half, 1>(bq2->d)
337                        .convert<float, sycl::rounding_mode::automatic>()[0] *
338                    bq8_1[iqs / 2].ds[0];
339    return d * sumi;
340}
341
342__dpct_inline__ float vec_dot_iq3_xxs_q8_1(const void *__restrict__ vbq,
343                                           const block_q8_1 *__restrict__ bq8_1,
344                                           const int &kbx, const int &iqs) {
345    const block_iq3_xxs* bq3 = (const block_iq3_xxs*) vbq + kbx;
346    const sycl::int2 q3_packed =
347        sycl::int2(get_int_b2(bq3->qs, iqs), get_int_b2(bq3->qs, iqs + 1));
348    const uint8_t* q3 = (const uint8_t*) &q3_packed;
349    const uint32_t aux32 = get_int_b2(bq3->qs, QK_K / 16 + iqs / 2);
350    int sumi = 0;
351#pragma unroll
352    for (int l0 = 0; l0 < 8; l0 += 2) {
353        const sycl::int2 grid_pos =
354            sycl::int2(iq3xxs_grid[q3[l0 + 0]], iq3xxs_grid[q3[l0 + 1]]);
355        const uint32_t signs = unpack_ksigns(aux32 >> (7 * l0 / 2));
356        const int signs0 = swar_ne4(signs & 0x08040201);
357        const int grid_l = swar_sub4(grid_pos.x() ^ signs0, signs0);
358        const int u0 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 0);
359        const int signs1 = swar_ne4(signs & 0x80402010);
360        const int grid_h = swar_sub4(grid_pos.y() ^ signs1, signs1);
361        const int u1 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 1);
362        sumi = ggml_cuda_dp4a(grid_l, u0, sumi);
363        sumi = ggml_cuda_dp4a(grid_h, u1, sumi);
364    }
365    const int ls = aux32 >> 28;
366    sumi = (ls * sumi + sumi / 2) / 2;
367    const float d = sycl::vec<sycl::half, 1>(bq3->d)
368                        .convert<float, sycl::rounding_mode::automatic>()[0] *
369                    bq8_1[iqs / 2].ds[0];
370    return d * sumi;
371}
372
373__dpct_inline__ float vec_dot_iq3_s_q8_1(const void *__restrict__ vbq,
374                                         const block_q8_1 *__restrict__ bq8_1,
375                                         const int &kbx, const int &iqs) {
376    const block_iq3_s* bq3 = (const block_iq3_s*) vbq + kbx;
377    const sycl::int2 qs_packed =
378        sycl::int2(get_int_b2(bq3->qs, iqs + 0), get_int_b2(bq3->qs, iqs + 1));
379    const uint8_t* qs = (const uint8_t*) &qs_packed;
380    const int qh = bq3->qh[iqs / 2];
381    const int signs_packed_32 = get_int_b2(bq3->signs, iqs / 2);
382    const uint8_t* signs_packed_8 = (const uint8_t*) &signs_packed_32;
383    int sumi = 0;
384#pragma unroll
385    for (int l0 = 0; l0 < 8; l0 += 2) {
386        const sycl::int2 grid_pos =
387            sycl::int2(iq3s_grid[qs[l0 + 0] | ((qh << (8 - l0)) & 0x100)],
388                       iq3s_grid[qs[l0 + 1] | ((qh << (7 - l0)) & 0x100)]);
389        const int signs0 = swar_ne4(((signs_packed_8[l0 / 2] & 0x03) << 7) |
390                ((signs_packed_8[l0 / 2] & 0x0C) << 21));
391        const int signs1 = swar_ne4(((signs_packed_8[l0 / 2] & 0x30) << 3) |
392                ((signs_packed_8[l0 / 2] & 0xC0) << 17));
393        const int grid_l = swar_sub4(grid_pos.x() ^ signs0, signs0);
394        const int grid_h = swar_sub4(grid_pos.y() ^ signs1, signs1);
395        const int u0 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 0);
396        const int u1 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 1);
397        sumi = ggml_cuda_dp4a(grid_l, u0, sumi);
398        sumi = ggml_cuda_dp4a(grid_h, u1, sumi);
399    }
400    sumi *= 1 + 2 * ((bq3->scales[iqs / 4] >> ((iqs << 1) & 0x04)) & 0x0F);
401    const float d = sycl::vec<sycl::half, 1>(bq3->d)
402                        .convert<float, sycl::rounding_mode::automatic>()[0] *
403                    bq8_1[iqs / 2].ds[0];
404    return d * sumi;
405}
406
407__dpct_inline__ float vec_dot_iq1_m_q8_1(const void *__restrict__ vbq,
408                                         const block_q8_1 *__restrict__ bq8_1,
409                                         const int &kbx, const int &iqs) {
410    const block_iq1_m* bq1 = (const block_iq1_m*) vbq + kbx;
411    const int qs_packed = get_int_b4(bq1->qs, iqs);
412    const uint8_t* qs = (const uint8_t*) &qs_packed;
413    int sumi[2] = {0, 0};
414    float sumf[2] = {0.0f, 0.0f};
415#pragma unroll
416    for (int l0 = 0; l0 < 8; l0 += 2) {
417        const int qhl = bq1->qh[2 * iqs + l0 / 4] >> (4 * ((l0 / 2) % 2));
418        const int grid = iq1s_grid_gpu[qs[l0 / 2] | ((qhl & 0x07) << 8)];
419        const int grid0 = (grid >> 0) & 0x0F0F0F0F;
420        const int grid1 = (grid >> 4) & 0x0F0F0F0F;
421        const int u0 = get_int_b4(bq8_1[iqs].qs, l0 + 0);
422        const int u1 = get_int_b4(bq8_1[iqs].qs, l0 + 1);
423        sumi[l0 / 4] = ggml_cuda_dp4a(grid0, u0, sumi[l0 / 4]);
424        sumi[l0 / 4] = ggml_cuda_dp4a(grid1, u1, sumi[l0 / 4]);
425        const float delta = -1.0f + IQ1M_DELTA - (qhl & 0x08) * (2.0f * IQ1M_DELTA / 0x08);
426        int sumy = 0;
427        sumy = ggml_cuda_dp4a(u0, 0x01010101, sumy);
428        sumy = ggml_cuda_dp4a(u1, 0x01010101, sumy);
429        sumf[l0 / 4] += delta * sumy;
430    }
431    const uint16_t* sc = (const uint16_t*) bq1->scales;
432    iq1m_scale_t scale;
433    scale.u16 = (sc[0] >> 12) | ((sc[1] >> 8) & 0x00F0) | ((sc[2] >> 4) & 0x0F00) | (sc[3] & 0xF000);
434    const float d = sycl::vec<sycl::half, 1>(scale.f16)
435                        .convert<float, sycl::rounding_mode::automatic>()[0] *
436                    bq8_1[iqs].ds[0];
437    const int tmp = sc[iqs / 2] >> (6 * (iqs % 2));
438    const int sc0 = 2 * ((tmp >> 0) & 0x07) + 1;
439    const int sc1 = 2 * ((tmp >> 3) & 0x07) + 1;
440    return d * ((sumi[0] + sumf[0]) * sc0 + (sumi[1] + sumf[1]) * sc1);
441}
442
443// SYCL port: the IQ4_NL codebook in registers and its 2-byte-aligned weights as aligned loads. ggml reads 4 uint32 of
444// the codebook from global memory per lookup and each weight int as two 16-bit loads (block_iq4_nl is 18 bytes, its
445// qs 2-byte aligned); the expert down projection (IQ4_NL in 39 of 48 layers) was the largest expert kernel. Same ints
446// out, so the dots are bitwise unchanged.
447#ifndef STRATA_IQ4NL_LUT_SWAR
448#define STRATA_IQ4NL_LUT_SWAR 0
449#endif
450__dpct_inline__ uint32_t iq4nl_lut4(uint32_t q4) {   // four nibbles -> four kvalues_iq4nl bytes
451#if STRATA_IQ4NL_LUT_SWAR
452    return iq4_lut4_swar(q4);
453#else
454    constexpr uint32_t t0 = 0xBFAD9881u, t1 = 0xF6EADDCFu, t2 = 0x26190D01u, t3 = 0x71594535u;
455    uint32_t r = 0;
456#pragma unroll
457    for (int i = 0; i < 4; ++i) {
458        const uint32_t n = (q4 >> (8 * i)) & 0xF;
459        const uint32_t t = n < 4 ? t0 : n < 8 ? t1 : n < 12 ? t2 : t3;
460        r |= ((t >> (8 * (n & 3))) & 0xFF) << (8 * i);
461    }
462    return r;
463#endif
464}
465__dpct_inline__ sycl::int2 iq4nl_pair(int aux) {   // = get_int_from_table_16(aux)
466    return sycl::int2((int) iq4nl_lut4((uint32_t) aux & 0x0f0f0f0fu), (int) iq4nl_lut4(((uint32_t) aux >> 4) & 0x0f0f0f0fu));
467}
468__dpct_inline__ sycl::int2 load8_a2(const uint8_t* p) {   // 8 bytes at a 2-byte-aligned address, as two ints
469    const uintptr_t a = reinterpret_cast<uintptr_t>(p);
470    const uint32_t* q = reinterpret_cast<const uint32_t*>(a & ~uintptr_t(3));
471    const uint32_t w0 = q[0], w1 = q[1];
472    if (!(a & 2)) return sycl::int2((int) w0, (int) w1);
473    const uint32_t w2 = q[2];   // only when unaligned: it then holds needed bytes, so it cannot cross a page
474    return sycl::int2((int) ((w0 >> 16) | (w1 << 16)), (int) ((w1 >> 16) | (w2 << 16)));
475}
476__dpct_inline__ int load4_a2(const uint8_t* p) {   // 4 bytes at a 2-byte-aligned address (= get_int_b2)
477    const uintptr_t a = reinterpret_cast<uintptr_t>(p);
478    const uint32_t* q = reinterpret_cast<const uint32_t*>(a & ~uintptr_t(3));
479    const uint32_t w0 = q[0];
480    if (!(a & 2)) return (int) w0;
481    return (int) ((w0 >> 16) | (q[1] << 16));   // the second word holds needed bytes: page-safe
482}
483// SYCL port: the gate/up kernels can stage their format's codebook grid in local memory (STRATA_GRID_SLM=1, compile
484// time). Measured slower and off: copying the grid into each of ~1,200 work-groups per call costs more than the
485// lookups save (IQ2_S 52.5 -> 62.7 us, IQ3_S 60.8 -> 70.0, IQ3_XXS 60.3 -> 62.1 per call; unitrace 2026-10-01).
486#ifndef STRATA_GRID_SLM
487#define STRATA_GRID_SLM 0
488#endif
489#ifndef STRATA_IQ4NL_FAST
490#define STRATA_IQ4NL_FAST 1   // compile-time: -DSTRATA_IQ4NL_FAST=0 for ggml's table/16-bit-load path
491#endif
492
493__dpct_inline__ float vec_dot_iq4_nl_q8_1(const void *__restrict__ vbq,
494                                          const block_q8_1 *__restrict__ bq8_1,
495                                          const int &kbx, const int &iqs) {
496    const block_iq4_nl* bq4 = (const block_iq4_nl*) vbq + kbx;
497    const int* q8 = (const int*) bq8_1->qs + iqs;
498    int sumi = 0;
499#if STRATA_IQ4NL_FAST
500    const sycl::int2 qq = load8_a2(bq4->qs + 4 * iqs);
501#endif
502#pragma unroll
503    for (int l = 0; l < 2; ++l) {
504#if STRATA_IQ4NL_FAST
505        const sycl::int2 v = iq4nl_pair(l ? qq.y() : qq.x());
506#else
507        const int aux_q4 = get_int_b2(bq4->qs, iqs + l);
508        const sycl::int2 v = get_int_from_table_16(aux_q4, kvalues_iq4nl);
509#endif
510        sumi = ggml_cuda_dp4a(v.x(), q8[l + 0], sumi);
511        sumi = ggml_cuda_dp4a(v.y(), q8[l + 4], sumi);
512    }
513    const float d = sycl::vec<sycl::half, 1>(bq4->d)
514                        .convert<float, sycl::rounding_mode::automatic>()[0] *
515                    bq8_1->ds[0];
516    return d * sumi;
517}
518
519#ifndef STRATA_IQ4XS_LUT_SWAR
520#define STRATA_IQ4XS_LUT_SWAR 0
521#endif
522// IQ4_XS: 256 values as 8 sub-blocks of 32 (6-bit scale each); one call covers one sub-block (iqs = 4 * sub-block),
523// and `bq8_1` is the super-block's first q8_1 block, so the call's activation is bq8_1[iqs / 4].  The GSQ-RCO IQ3_S
524// file keeps one layer's routed gate/up experts in this format.
525__dpct_inline__ float vec_dot_iq4_xs_q8_1(const void *__restrict__ vbq,
526                                          const block_q8_1 *__restrict__ bq8_1,
527                                          const int &kbx, const int &iqs) {
528    const block_iq4_xs* bq4 = (const block_iq4_xs*) vbq + kbx;
529    int sumi = 0;
530#pragma unroll
531    for (int j = 0; j < 4; ++j) {
532        const int aux_q4 = get_int_b4(bq4->qs, iqs + j);
533#if STRATA_IQ4XS_LUT_SWAR
534        const sycl::int2 v = iq4nl_pair(aux_q4);
535#else
536        const sycl::int2 v = get_int_from_table_16(aux_q4, kvalues_iq4nl);
537#endif
538        const int u0 = get_int_b4(bq8_1[iqs / 4].qs, j + 0);
539        const int u1 = get_int_b4(bq8_1[iqs / 4].qs, j + 4);
540        sumi = ggml_cuda_dp4a(v.x(), u0, sumi);
541        sumi = ggml_cuda_dp4a(v.y(), u1, sumi);
542    }
543    const int ls = ((bq4->scales_l[iqs / 8] >> (iqs & 0x04)) & 0x0F) | (((bq4->scales_h >> (iqs / 2)) & 0x03) << 4);
544    sumi *= ls - 32;
545    const float d = sycl::vec<sycl::half, 1>(bq4->d)
546                        .convert<float, sycl::rounding_mode::automatic>()[0] *
547                    bq8_1[iqs / 4].ds[0];
548    return d * sumi;
549}
550
551// ---------------------------------------------------------------- Unsloth's UD-Q4_K_XL experts
552// Q4_K / Q5_K gate/up and Q5_1 / Q8_0 down: llama.cpp's vec_dot_*_q8_1 (vecdotq.cuh, VDR 2 each), transcribed; the
553// Q5_1 min term is the one departure (below).  Via eddoursul/Strata 8029fa9 (iq_dot.cuh) and #255 (Q8_0,
554// gopinath87607), which agree with llama.cpp and with each other.
555constexpr int VDR_Q4_K = 2, VDR_Q5_K = 2, VDR_Q5_1 = 2, VDR_Q5_0 = 2, VDR_Q4_1 = 2, VDR_Q4_0 = 2, VDR_Q8_0 = 2, VDR_Q6_K = 1;
556
557__dpct_inline__ float vec_dot_q4_K_q8_1_impl_vmmq(
558    const int *__restrict__ v, const int *__restrict__ u,
559    const uint8_t *__restrict__ sc, const uint8_t *__restrict__ m,
560    const sycl::half2 &dm4, const float *__restrict__ d8) {
561    float sumf_d = 0.0f;
562    float sumf_m = 0.0f;
563#pragma unroll
564    for (int i = 0; i < QR4_K; ++i) {
565        const int v0i = (v[0] >> (4 * i)) & 0x0F0F0F0F;
566        const int v1i = (v[1] >> (4 * i)) & 0x0F0F0F0F;
567        const int dot1 = ggml_cuda_dp4a(v1i, u[2 * i + 1], ggml_cuda_dp4a(v0i, u[2 * i + 0], 0));
568        const int dot2 = ggml_cuda_dp4a(0x01010101, u[2 * i + 1], ggml_cuda_dp4a(0x01010101, u[2 * i + 0], 0));
569        sumf_d += d8[i] * (dot1 * sc[i]);
570        sumf_m += d8[i] * (dot2 * m[i]);   // the min times the sum of the QUANTIZED activations
571    }
572    const sycl::float2 dm4f =
573        dm4.template convert<float, sycl::rounding_mode::automatic>();
574    return dm4f.x() * sumf_d - dm4f.y() * sumf_m;
575}
576__dpct_inline__ float vec_dot_q5_K_q8_1_impl_vmmq(
577    const int *__restrict__ vl, const int *__restrict__ vh,
578    const int *__restrict__ u, const uint8_t *__restrict__ sc,
579    const uint8_t *__restrict__ m, const sycl::half2 &dm5,
580    const float *__restrict__ d8) {
581    float sumf_d = 0.0f;
582    float sumf_m = 0.0f;
583#pragma unroll
584    for (int i = 0; i < QR5_K; ++i) {
585        const int vl0i = (vl[0] >> (4 * i)) & 0x0F0F0F0F;
586        const int vl1i = (vl[1] >> (4 * i)) & 0x0F0F0F0F;
587        const int vh0i = ((vh[0] >> i) << 4) & 0x10101010;
588        const int vh1i = ((vh[1] >> i) << 4) & 0x10101010;
589        const int v0i = vl0i | vh0i;
590        const int v1i = vl1i | vh1i;
591        const int dot1 = ggml_cuda_dp4a(v0i, u[2 * i + 0], ggml_cuda_dp4a(v1i, u[2 * i + 1], 0));
592        const int dot2 = ggml_cuda_dp4a(0x01010101, u[2 * i + 0], ggml_cuda_dp4a(0x01010101, u[2 * i + 1], 0));
593        sumf_d += d8[i] * (dot1 * sc[i]);
594        sumf_m += d8[i] * (dot2 * m[i]);
595    }
596    const sycl::float2 dm5f =
597        dm5.template convert<float, sycl::rounding_mode::automatic>();
598    return dm5f.x() * sumf_d - dm5f.y() * sumf_m;
599}
600// the 6-bit scales and mins of the 32-value group pair bq8_offset / 2, branchless (llama.cpp; shared by Q4_K, Q5_K)
601__dpct_inline__ void k_scale_min(const uint8_t *scales8, int bq8_offset,
602                                 uint16_t aux[2]) {
603    const uint16_t* scales = (const uint16_t*) scales8;
604    const int j = bq8_offset / 2;
605    const int jm = j & 1;
606    const uint32_t s0 = scales[jm + 0];
607    const uint32_t s2 = scales[jm + 2];
608    const uint32_t s4 = scales[jm + 4];
609    const uint32_t hi = (uint32_t) -(int32_t) (j >= 2);
610    aux[0] = (uint16_t) (((s0 & 0x3f3f) & ~hi) | ((((s4 >> 0) & 0x0f0f) | ((s0 & 0xc0c0) >> 2)) & hi));
611    aux[1] = (uint16_t) (((s2 & 0x3f3f) & ~hi) | ((((s4 >> 4) & 0x0f0f) | ((s2 & 0xc0c0) >> 2)) & hi));
612}
613__dpct_inline__ float vec_dot_q4_K_q8_1(const void *__restrict__ vbq,
614                                        const block_q8_1 *__restrict__ bq8_1,
615                                        const int &kbx, const int &iqs) {
616    const block_q4_K* bq4_K = (const block_q4_K*) vbq + kbx;
617    int v[2];
618    int u[2 * QR4_K];
619    float d8[QR4_K];
620    const int bq8_offset = QR4_K * ((iqs / 2) / (QI8_1 / 2));
621    const int* q4 = (const int*) (bq4_K->qs + 16 * bq8_offset + 4 * ((iqs / 2) % 4));
622    v[0] = q4[0];
623    v[1] = q4[4];
624    uint16_t aux[2];
625    k_scale_min(bq4_K->scales, bq8_offset, aux);
626    const uint8_t* sc = (const uint8_t*) aux;
627    const uint8_t* m = sc + 2;
628#pragma unroll
629    for (int i = 0; i < QR4_K; ++i) {
630        const block_q8_1* bq8i = bq8_1 + bq8_offset + i;
631        d8[i] = bq8i->ds[0];
632        const int* q8 = (const int*) bq8i->qs + ((iqs / 2) % 4);
633        u[2 * i + 0] = q8[0];
634        u[2 * i + 1] = q8[4];
635    }
636    return vec_dot_q4_K_q8_1_impl_vmmq(v, u, sc, m, bq4_K->dm, d8);
637}
638__dpct_inline__ float vec_dot_q5_K_q8_1(const void *__restrict__ vbq,
639                                        const block_q8_1 *__restrict__ bq8_1,
640                                        const int &kbx, const int &iqs) {
641    const block_q5_K* bq5_K = (const block_q5_K*) vbq + kbx;
642    int vl[2];
643    int vh[2];
644    int u[2 * QR5_K];
645    float d8[QR5_K];
646    const int bq8_offset = QR5_K * ((iqs / 2) / (QI8_1 / 2));
647    const int* ql = (const int*) (bq5_K->qs + 16 * bq8_offset + 4 * ((iqs / 2) % 4));
648    const int* qh = (const int*) (bq5_K->qh + 4 * ((iqs / 2) % 4));
649    vl[0] = ql[0];
650    vl[1] = ql[4];
651    vh[0] = qh[0] >> bq8_offset;
652    vh[1] = qh[4] >> bq8_offset;
653    uint16_t aux[2];
654    k_scale_min(bq5_K->scales, bq8_offset, aux);
655    const uint8_t* sc = (const uint8_t*) aux;
656    const uint8_t* m = sc + 2;
657#pragma unroll
658    for (int i = 0; i < QR5_K; ++i) {
659        const block_q8_1* bq8i = bq8_1 + bq8_offset + i;
660        d8[i] = bq8i->ds[0];
661        const int* q8 = (const int*) bq8i->qs + ((iqs / 2) % 4);
662        u[2 * i + 0] = q8[0];
663        u[2 * i + 1] = q8[4];
664    }
665    return vec_dot_q5_K_q8_1_impl_vmmq(vl, vh, u, sc, m, bq5_K->dm, d8);
666}
667// Q5_1: llama.cpp's integer chain, but the min term multiplies the sum of the QUANTIZED activations (dp4a with
668// 0x01010101, times d8) instead of the q8_1 block's `ds.y`, which our quantizer (like llama.cpp's) fills with the sum
669// of the ORIGINAL activations.  That is ggml-cpu's convention (its q8_1 `s` is d * sum(q)) and the one the K-quant
670// mins above use; the scaled and the min term then see the same activation (eddoursul/Strata measured 1.1-1.2%
671// against 1.9% relative error per expert).  Result: sumi * (d5 * d8) + sumu * (m5 * d8).
672// Q5_0: llama.cpp's integer chain (vecdotq.cuh vec_dot_q5_0_q8_1_impl), but the constant -16 per-weight offset multiplies
673// the sum of the QUANTIZED activations (dp4a with 0x01010101, times d8), like the Q5_1 and Q4_0 paths and ggml-cpu's q8_0
674// dot, instead of the q8_1 block's `ds.y` (the sum of the ORIGINAL activations, upstream CUDA).  Round 0214 (owner's yes,
675// 11-05): the original sum does not see the activations' rounding, which the experts' SwiGLU outputs (not zero-mean)
676// make large: the whole-expert error with Q5_0 down was 2.1e-2 .. 3.1e-2 against 1.2e-2 for every other down type, and the
677// GPU now agrees with the CPU path (UD-IQ4_XS, UD-Q3_K_XL).  Result: d5 * d8 * (sumi - 16 * sumu).
678__dpct_inline__ float vec_dot_q5_0_q8_1(const void *__restrict__ vbq,
679                                        const block_q8_1 *__restrict__ bq8_1,
680                                        const int &kbx, const int &iqs) {
681    const block_q5_0* bq5_0 = (const block_q5_0*) vbq + kbx;
682    int sumi = 0, sumu = 0;
683#pragma unroll
684    for (int i = 0; i < VDR_Q5_0; ++i) {
685        const int vl = get_int_b2(bq5_0->qs, iqs + i);
686        const int vh = get_int_b2(bq5_0->qh, 0) >> (4 * (iqs + i));
687        const int u0 = get_int_b4(bq8_1->qs, iqs + i), u1 = get_int_b4(bq8_1->qs, iqs + i + QI5_0);
688        int vi0 = (vl >> 0) & 0x0F0F0F0F;
689        vi0 |= (vh << 4) & 0x00000010;
690        vi0 |= (vh << 11) & 0x00001000;
691        vi0 |= (vh << 18) & 0x00100000;
692        vi0 |= (vh << 25) & 0x10000000;
693        sumi = ggml_cuda_dp4a(vi0, u0, sumi);
694        int vi1 = (vl >> 4) & 0x0F0F0F0F;
695        vi1 |= (vh >> 12) & 0x00000010;
696        vi1 |= (vh >> 5) & 0x00001000;
697        vi1 |= (vh << 2) & 0x00100000;
698        vi1 |= (vh << 9) & 0x10000000;
699        sumi = ggml_cuda_dp4a(vi1, u1, sumi);
700        sumu = ggml_cuda_dp4a(0x01010101, u1, ggml_cuda_dp4a(0x01010101, u0, sumu));
701    }
702    const float d5 = sycl::vec<sycl::half, 1>(bq5_0->d)
703                         .convert<float, sycl::rounding_mode::automatic>()[0];
704    const float d8 = bq8_1->ds[0];
705    return d5 * d8 * (float) (sumi - 16 * sumu);
706}
707// Q4_0 (plain llama-quantize Q4_0 files, e.g. bartowski's: gate/up and most down projections): the codes are centred
708// (q - 8 as signed bytes) before the dot, the exact integer form ggml-cpu's q4_0 x q8_0 dot uses, rather than
709// llama.cpp's CUDA chain (uncentred codes minus 8 x the q8_1 block's float sum `ds.y`).  On a real Q4_0 expert
710// (2560 x 640) the CUDA chain measured 1.4e-2 relative error against the float product, the centred form 5.3e-3;
711// with the CUDA chain native_expert_parity failed its 3e-2 limit on two layers of a Q4_0 Flash-Next file.  The
712// centring is the same idea as the Q5_1 min term above: the offset is applied to the activations' own int8 codes.
713__dpct_inline__ int q4_0_centred(const int v) {
714    // Unsigned: (b & 0x08080808) * 0x1E reaches 0xF0F0F0F0, which overflows a signed int - undefined behaviour the
715    // sm_60 build (no __dp4a, strata_dp4a fallback) optimised into a wrong value (native_expert_parity gpu rel 1.7e4).
716    const uint32_t b = (uint32_t) v ^ 0x08080808u;   // per byte: 0..15 -> (q - 8) as a 4-bit two's complement value
717    return (int) (b | ((b & 0x08080808u) * 0x1Eu));  // sign-extend each nibble into its byte (0x08 * 0x1E = 0xF0)
718}
719__dpct_inline__ float vec_dot_q4_0_q8_1(const void *__restrict__ vbq,
720                                        const block_q8_1 *__restrict__ bq8_1,
721                                        const int &kbx, const int &iqs) {
722    const block_q4_0* bq4 = (const block_q4_0*) vbq + kbx;
723    int sumi = 0;
724#pragma unroll
725    for (int i = 0; i < VDR_Q4_0; ++i) {
726        const int v = get_int_b2(bq4->qs, iqs + i);
727        sumi = ggml_cuda_dp4a(q4_0_centred((v >> 0) & 0x0F0F0F0F), get_int_b4(bq8_1->qs, iqs + i), sumi);
728        sumi = ggml_cuda_dp4a(q4_0_centred((v >> 4) & 0x0F0F0F0F), get_int_b4(bq8_1->qs, iqs + i + QI4_0), sumi);
729    }
730    return sycl::vec<sycl::half, 1>(bq4->d)
731               .convert<float, sycl::rounding_mode::automatic>()[0] *
732           bq8_1->ds[0] * sumi;
733}
734// Q4_1 (llama-quantize puts it on a few down projections of its Q4_0 files): the Q5_1 chain above without the fifth
735// bit, the same min-term choice (the activations' own int8 codes): sumi * (d4 * d8) + sumu * (m4 * d8).
736__dpct_inline__ float vec_dot_q4_1_q8_1(const void *__restrict__ vbq,
737                                        const block_q8_1 *__restrict__ bq8_1,
738                                        const int &kbx, const int &iqs) {
739    const block_q4_1* bq4_1 = (const block_q4_1*) vbq + kbx;
740    int sumi = 0, sumu = 0;
741#pragma unroll
742    for (int i = 0; i < VDR_Q4_1; ++i) {
743        const int v = get_int_b4(bq4_1->qs, iqs + i);
744        const int u0 = get_int_b4(bq8_1->qs, iqs + i), u1 = get_int_b4(bq8_1->qs, iqs + i + QI4_1);
745        sumi = ggml_cuda_dp4a((v >> 0) & 0x0F0F0F0F, u0, sumi);
746        sumi = ggml_cuda_dp4a((v >> 4) & 0x0F0F0F0F, u1, sumi);
747        sumu = ggml_cuda_dp4a(0x01010101, u1, ggml_cuda_dp4a(0x01010101, u0, sumu));
748    }
749    const sycl::float2 dm4 =
750        (bq4_1->dm).template convert<float, sycl::rounding_mode::automatic>();
751    const float d8 = bq8_1->ds[0];
752    return sumi * (dm4.x() * d8) + sumu * (dm4.y() * d8);
753}
754__dpct_inline__ float vec_dot_q5_1_q8_1(const void *__restrict__ vbq,
755                                        const block_q8_1 *__restrict__ bq8_1,
756                                        const int &kbx, const int &iqs) {
757    const block_q5_1* bq5_1 = (const block_q5_1*) vbq + kbx;
758    int sumi = 0, sumu = 0;
759#pragma unroll
760    for (int i = 0; i < VDR_Q5_1; ++i) {
761        const int vl = get_int_b4(bq5_1->qs, iqs + i);
762        const int vh = get_int_b4(bq5_1->qh, 0) >> (4 * (iqs + i));
763        const int u0 = get_int_b4(bq8_1->qs, iqs + i), u1 = get_int_b4(bq8_1->qs, iqs + i + QI5_1);
764        int vi0 = (vl >> 0) & 0x0F0F0F0F;
765        vi0 |= (vh << 4) & 0x00000010;
766        vi0 |= (vh << 11) & 0x00001000;
767        vi0 |= (vh << 18) & 0x00100000;
768        vi0 |= (vh << 25) & 0x10000000;
769        sumi = ggml_cuda_dp4a(vi0, u0, sumi);
770        int vi1 = (vl >> 4) & 0x0F0F0F0F;
771        vi1 |= (vh >> 12) & 0x00000010;
772        vi1 |= (vh >> 5) & 0x00001000;
773        vi1 |= (vh << 2) & 0x00100000;
774        vi1 |= (vh << 9) & 0x10000000;
775        sumi = ggml_cuda_dp4a(vi1, u1, sumi);
776        sumu = ggml_cuda_dp4a(0x01010101, u1, ggml_cuda_dp4a(0x01010101, u0, sumu));
777    }
778    const sycl::float2 dm5 =
779        (bq5_1->dm).template convert<float, sycl::rounding_mode::automatic>();
780    const float d8 = bq8_1->ds[0];
781    return sumi * (dm5.x() * d8) + sumu * (dm5.y() * d8);
782}
783// Q6_K: llama.cpp's integer chain verbatim (vecdotq.cuh vec_dot_q6_K_q8_1_impl_mmvq / vec_dot_q6_K_q8_1) -- signed
784// per-16-element scales, the -32 offset folded into the per-byte value, the q8_1 block's ds.low for the scales,
785// upstream exactly as pulled (no min-term choice exists: Q6_K has no learned min).
786__dpct_inline__ float
787vec_dot_q6_K_q8_1_impl_mmvq(const int vl, const int vh,
788                            const int *__restrict__ u,
789                            const int8_t *__restrict__ scales, const float d,
790                            const float *__restrict__ d8) {
791    float sumf = 0.0f;
792#pragma unroll
793    for (int i = 0; i < QR6_K; ++i) {
794        const int sc = scales[4 * i];
795        const int vil = (vl >> (4 * i)) & 0x0F0F0F0F;
796        const int vih = ((vh >> (4 * i)) << 4) & 0x30303030;
797        const int vi = dpct::vectorized_binary<sycl::char4>(
798            vil | vih, 0x20202020, dpct::sub_sat()); // vi = (vil | vih) - 32
799        sumf += d8[i] * (STRATA_DP4A(vi, u[i], 0) * sc);
800    }
801    return d * sumf;
802}
803__dpct_inline__ float vec_dot_q6_K_q8_1(const void *__restrict__ vbq,
804                                        const block_q8_1 *__restrict__ bq8_1,
805                                        const int &kbx, const int &iqs) {
806    const block_q6_K* bq6_K = (const block_q6_K*) vbq + kbx;
807    const int bq8_offset = 2 * QR6_K * (iqs / (QI6_K / 2)) + (iqs % (QI6_K / 2)) / (QI6_K / 4);
808    const int scale_offset = (QI6_K / 4) * (iqs / (QI6_K / 2)) + (iqs % (QI6_K / 2)) / (QI6_K / 8);
809    const int vh_shift = 2 * ((iqs % (QI6_K / 2)) / (QI6_K / 4));
810    const int vl = get_int_b2(bq6_K->ql, iqs);
811    const int vh = get_int_b2(bq6_K->qh, (QI6_K / 4) * (iqs / (QI6_K / 2)) + iqs % (QI6_K / 4)) >> vh_shift;
812    const int8_t* scales = bq6_K->scales + scale_offset;
813    int u[QR6_K];
814    float d8[QR6_K];
815#pragma unroll
816    for (int i = 0; i < QR6_K; ++i) {
817        u[i] = get_int_b4(bq8_1[bq8_offset + 2 * i].qs, iqs % QI8_1);
818        d8[i] = bq8_1[bq8_offset + 2 * i].ds[0];
819    }
820    return vec_dot_q6_K_q8_1_impl_mmvq(
821        vl, vh, u, scales,
822        sycl::vec<sycl::half, 1>(bq6_K->d)
823            .convert<float, sycl::rounding_mode::automatic>()[0],
824        d8);
825}
826__dpct_inline__ float vec_dot_q8_0_q8_1(const void *__restrict__ vbq,
827                                        const block_q8_1 *__restrict__ bq8_1,
828                                        const int &kbx, const int &iqs) {
829    const block_q8_0* bq8_0 = (const block_q8_0*) vbq + kbx;
830    int sumi = 0;
831#pragma unroll
832    for (int i = 0; i < VDR_Q8_0; ++i)
833        sumi = ggml_cuda_dp4a(get_int_b2(bq8_0->qs, iqs + i), get_int_b4(bq8_1->qs, iqs + i), sumi);
834    const float d8_0 = sycl::vec<sycl::half, 1>(bq8_0->d)
835                           .convert<float, sycl::rounding_mode::automatic>()[0],
836                d8_1 = bq8_1->ds[0];
837    return d8_0 * d8_1 * ((float) sumi);
838}
839
840// ---------------------------------------------------------------- APR trellis types (ggml 144 TQ2_T, 145 TQK6, 146 TQK7)
841// Transcribed from src/kernels/cuda/iq_kernels.cu (which has them from the agention llama.cpp fork's ggml-cuda/tq.cuh,
842// 6d3f2b1b8; format in ggml-common-tq.h).  A 128-value block is 8 lanes of 4 trellis steps (16 values); the dot of lane l
843// reads q8_1 block l/2, ints 4(l&1)..  Same integer and float operations in the same order as the CUDA kernels: the
844// decode reads the int8 codebook tq_lut_i8 (one global scale) against q8_1 activations.
845template<int TY> struct TqInfo;
846template<> struct TqInfo<144> { using block_t = block_tq2_t; };   // byte-aligned, no K
847template<> struct TqInfo<145> { using block_t = block_tqk6; static constexpr int K = 6; };
848template<> struct TqInfo<146> { using block_t = block_tqk7; static constexpr int K = 7; };
849__dpct_inline__ float tq_h2f(uint32_t bits) { return (float) sycl::bit_cast<sycl::half>((uint16_t) bits); }
850// the four unscaled weights of the step with state s: (a.x, a.y, b.x, b.y)
851__dpct_inline__ void tq_step(uint32_t s, float (&w)[4]) {
852    const uint32_t* lut = (const uint32_t*) tq_lut_f16;
853    const uint32_t x = (s & TQ_STATE_MASK) * 0x9e3779b1u;
854    const uint32_t pa = lut[x >> 21], pb = lut[(x >> 10) & 2047u];
855    w[0] = tq_h2f(pa & 0xFFFFu);
856    w[1] = tq_h2f(pa >> 16);
857    w[2] = tq_h2f(pb & 0xFFFFu);
858    w[3] = tq_h2f(pb >> 16);
859}
860// the states of steps 4l..4l+3 of one block (qs is 2-byte aligned: every trellis block has an even size)
861template<int TY>
862__dpct_inline__ void tq_states4(const uint8_t* qs, int l, uint32_t s[4]) {
863    const uint16_t* qs16 = (const uint16_t*) qs;
864    if constexpr (TY == 144) {   // s_t = qs[(t + 31) % 32] << 8 | qs[t]
865        const uint32_t w01 = qs16[2 * l + 0], w23 = qs16[2 * l + 1];
866        const uint32_t prev = qs[(4 * l + 31) & 31];
867        const uint32_t b0 = w01 & 0xFF, b1 = w01 >> 8, b2 = w23 & 0xFF, b3 = w23 >> 8;
868        s[0] = (prev << 8) | b0;
869        s[1] = (b0 << 8) | b1;
870        s[2] = (b1 << 8) | b2;
871        s[3] = (b2 << 8) | b3;
872    } else {
873        // step t's state: the 16 stream bits from bit (31 - t)*K, circular over 2K u16 words; steps 4l..4l+3 all
874        // lie in the four words from (28 - 4l)*K >> 4
875        constexpr int K = TqInfo<TY>::K, nwords = 2 * K;
876        const int off3 = (28 - 4 * l) * K, wb = off3 >> 4, r = off3 & 15;
877        const int wi1 = wb + 1 >= nwords ? wb + 1 - nwords : wb + 1;
878        const int wi2 = wb + 2 >= nwords ? wb + 2 - nwords : wb + 2;
879        const int wi3 = wb + 3 >= nwords ? wb + 3 - nwords : wb + 3;
880        const uint64_t v = (uint64_t) qs16[wb] | ((uint64_t) qs16[wi1] << 16) | ((uint64_t) qs16[wi2] << 32) |
881                           ((uint64_t) qs16[wi3] << 48);
882#pragma unroll
883        for (int i = 0; i < 4; ++i) s[i] = (uint32_t) (v >> (r + (3 - i) * K)) & 0xFFFFu;
884    }
885}
886// The lane's 16 codebook values as 4 ints of packed int8 (tq_load: the weight side only), the activation side in
887// tq_apply; vec_dot_tq_q8_1 is apply(load()).  Numerics as in the CUDA file: the int8 codebook is within 0.85% RMS of
888// the fp16 one; the prompt path decodes through the fp16 codebook (dq_tq below).
889struct TqLane { int q[4]; float d; };
890template<int TY>
891__dpct_inline__ TqLane tq_load(const void* __restrict__ vbq, int kbx, int iqs) {
892    const auto* b = (const typename TqInfo<TY>::block_t*) vbq + kbx;
893    uint32_t s[4];
894    tq_states4<TY>(b->qs, iqs / 4, s);
895    TqLane r;
896#pragma unroll
897    for (int i = 0; i < 4; ++i) {
898        const uint32_t x = (s[i] & TQ_STATE_MASK) * 0x9e3779b1u;
899        r.q[i] = (int) ((uint32_t) tq_lut_i8[x >> 21] | ((uint32_t) tq_lut_i8[(x >> 10) & 2047u] << 16));
900    }
901    r.d = tq_h2f(b->d);
902    return r;
903}
904__dpct_inline__ float tq_apply(const TqLane& r, const block_q8_1* __restrict__ bq8_1, int iqs) {
905    const int l = iqs / 4;
906    const block_q8_1* b8 = bq8_1 + l / 2;
907    const int* q8 = (const int*) b8->qs + 4 * (l & 1);
908    int sumi = 0;
909#pragma unroll
910    for (int i = 0; i < 4; ++i) sumi = ggml_cuda_dp4a(r.q[i], q8[i], sumi);
911    return r.d * ((float) b8->ds[0] * TQ_LUT_I8_SCALE) * (float) sumi;
912}
913template<int TY>
914__dpct_inline__ float vec_dot_tq_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1,
915                                      const int& kbx, const int& iqs) {
916    return tq_apply(tq_load<TY>(vbq, kbx, iqs), bq8_1, iqs);
917}
918
919// ---------------------------------------------------------------- the formats
920// qk = values per block, ipb = dot calls per block (qi / vdr), step = the iqs stride between calls.
921template<int TY> 
922struct Fmt;
923template<> struct Fmt<16> { static constexpr int qk = 256, ipb = 8, step = 2;
924    static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_iq2_xxs_q8_1(v, y, kbx, iqs); } };
925template<> struct Fmt<17> { static constexpr int qk = 256, ipb = 8, step = 2;
926    static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_iq2_xs_q8_1(v, y, kbx, iqs); } };
927template<> struct Fmt<18> { static constexpr int qk = 256, ipb = 8, step = 2;
928    static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_iq3_xxs_q8_1(v, y, kbx, iqs); } };
929template<> struct Fmt<20> { static constexpr int qk = 32, ipb = 2, step = 2;
930    static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_iq4_nl_q8_1(v, y, kbx, iqs); } };
931template<> struct Fmt<21> { static constexpr int qk = 256, ipb = 8, step = 2;
932    static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_iq3_s_q8_1(v, y, kbx, iqs); } };
933template<> struct Fmt<23> { static constexpr int qk = 256, ipb = 8, step = 4;
934    static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_iq4_xs_q8_1(v, y, kbx, iqs); } };
935template<> struct Fmt<22> { static constexpr int qk = 256, ipb = 8, step = 2;
936    static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_iq2_s_q8_1(v, y, kbx, iqs); } };
937// Private template dispatch key; GGUF still uses format 22.
938template<> struct Fmt<10022> : Fmt<22> {
939    static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_iq2_s_q8_1<true>(v, y, kbx, iqs); } };
940template<> struct Fmt<10016> : Fmt<16> {
941    static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_iq2_xxs_q8_1<true>(v, y, kbx, iqs); } };
942template<> struct Fmt<29> { static constexpr int qk = 256, ipb = 8, step = 1;
943    static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_iq1_m_q8_1(v, y, kbx, iqs); } };
944template<> struct Fmt<42> { static constexpr int qk = 64, ipb = 2, step = 1;
945    static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_q2_0_q8_1(v, y, kbx, iqs); }
946    static float dot_word_expand(const void* v, const block_q8_1* y, int kbx, int iqs) {
947        const auto* b = (const block_q2_0*)v + kbx;
948        const float d2 = b->d;
949        const auto* qs = (const int16_t*)b->qs + iqs * 4;
950        const auto* a = y + iqs;
951        int sumi = 0;
952#pragma unroll
953        for (int j = 0; j < 4; ++j) {
954            const auto w = q2_0_decode8((uint32_t)qs[j]);
955            const int u = get_int_b4(a->qs, j * 2), z = get_int_b4(a->qs, j * 2 + 1);
956            sumi = ggml_cuda_dp4a(u, w.x(), sumi);
957            sumi = ggml_cuda_dp4a(z, w.y(), sumi);
958        }
959        const float d8 = a->ds[0];
960        return d2 * d8 * sumi;
961    }
962};
963// Private diagnostic trait, never a GGUF format or a production switch entry.
964template<> struct Fmt<10042> {
965    static constexpr int qk = 64, ipb = 2, step = 1;
966    static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) {
967        const auto* b = (const block_q2_0*)v + kbx;
968        const float d2 = b->d;
969        const auto* qs = (const int16_t*)b->qs + iqs * 4;
970        const auto* a = y + iqs;
971        int sumi = 0;
972#pragma unroll
973        for (int j = 0; j < 4; ++j) {
974            const auto w = q2_0_decode8((uint32_t)qs[j]);
975            const int u = get_int_b4(a->qs, j * 2), z = get_int_b4(a->qs, j * 2 + 1);
976            sumi = ggml_cuda_dp4a(u, w.x(), sumi);
977            sumi = ggml_cuda_dp4a(z, w.y(), sumi);
978        }
979        const float d8 = a->ds[0];
980        return d2 * d8 * sumi;
981    }
982};
983template<> struct Fmt<12> { static constexpr int qk = 256, ipb = QI4_K / VDR_Q4_K, step = VDR_Q4_K;
984    static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_q4_K_q8_1(v, y, kbx, iqs); } };
985template<> struct Fmt<13> { static constexpr int qk = 256, ipb = QI5_K / VDR_Q5_K, step = VDR_Q5_K;
986    static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_q5_K_q8_1(v, y, kbx, iqs); } };
987template<> struct Fmt<14> { static constexpr int qk = 256, ipb = QI6_K / VDR_Q6_K, step = VDR_Q6_K;
988    static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_q6_K_q8_1(v, y, kbx, iqs); } };
989template<> struct Fmt<7> { static constexpr int qk = 32, ipb = QI5_1 / VDR_Q5_1, step = VDR_Q5_1;
990    static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_q5_1_q8_1(v, y, kbx, iqs); } };
991template<> struct Fmt<2> { static constexpr int qk = 32, ipb = QI4_0 / VDR_Q4_0, step = VDR_Q4_0;
992    static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_q4_0_q8_1(v, y, kbx, iqs); } };
993template<> struct Fmt<3> { static constexpr int qk = 32, ipb = QI4_1 / VDR_Q4_1, step = VDR_Q4_1;
994    static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_q4_1_q8_1(v, y, kbx, iqs); } };
995template<> struct Fmt<6> { static constexpr int qk = 32, ipb = QI5_0 / VDR_Q5_0, step = VDR_Q5_0;
996    static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_q5_0_q8_1(v, y, kbx, iqs); } };
997template<> struct Fmt<8> { static constexpr int qk = 32, ipb = QI8_0 / VDR_Q8_0, step = VDR_Q8_0;
998    static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_q8_0_q8_1(v, y, kbx, iqs); } };
999// APR trellis types: 8 lanes of 4 steps per 128-value block, iqs = 4 * lane
1000template<> struct Fmt<144> { static constexpr int qk = 128, ipb = 8, step = 4;
1001    static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_tq_q8_1<144>(v, y, kbx, iqs); } };
1002template<> struct Fmt<145> { static constexpr int qk = 128, ipb = 8, step = 4;
1003    static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_tq_q8_1<145>(v, y, kbx, iqs); } };
1004template<> struct Fmt<146> { static constexpr int qk = 128, ipb = 8, step = 4;
1005    static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_tq_q8_1<146>(v, y, kbx, iqs); } };
1006
1007// The formats of each role, one list each so a type cannot be in one switch and missing from another.  Every
1008// entry is a kernel template for each CUDA architecture of the build, hence two lists rather than one.
1009#ifdef STRATA_Q6K_EXPERTS   // opt-in build (-DSTRATA_Q6K_EXPERTS=ON): one more instance per kernel, loaded at start
1010#define STRATA_GU_FMTS(X) X(16) X(17) X(18) X(21) X(22) X(23) X(29) X(42) X(12) X(13) X(14) X(6) X(2) X(3) X(8) X(144) X(145)
1011#else
1012#define STRATA_GU_FMTS(X) X(16) X(17) X(18) X(21) X(22) X(23) X(29) X(42) X(12) X(13) X(6) X(2) X(3) X(8) X(144) X(145)
1013#endif
1014// Q5_K (and Q6_K with the option) downs: what a UD file carries at an expert width divisible by 256 (512, 1024; Qwen3.6's UD-Q4_K_XL
1015// has Q5_K / Q6_K downs), as the CUDA list has had them; the lane kernels are the gate/up's (Fmt / KqSplit of 13 and 14)
1016#ifdef STRATA_Q6K_EXPERTS
1017#define STRATA_D_FMTS(X) X(20) X(23) X(42) X(7) X(6) X(2) X(3) X(8) X(13) X(14) X(144) X(146)
1018#else
1019#define STRATA_D_FMTS(X) X(20) X(23) X(42) X(7) X(6) X(2) X(3) X(8) X(13) X(144) X(146)
1020#endif
1021#define STRATA_MMVQ_FMTS(X) X(16) X(17) X(18) X(20) X(21) X(22) X(23) X(29) X(42) X(12) X(13) X(7) X(6) X(2) X(3) X(8) X(144) X(145) X(146)
1022
1023__dpct_inline__ float warp_sum(float v) {
1024#pragma unroll
1025    /*
1026    DPCT1108: '__shfl_xor_sync' was migrated with the experimental feature
1027    masked sub_group function which may not be supported by all compilers or
1028    runtimes. You may need to adjust the code.
1029    */
1030    for (int o = 16; o > 0; o >>= 1) v +=
1031        dpct::experimental::permute_sub_group_by_xor(
1032            0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(), v,
1033            o);
1034    return v;
1035}
1036
1037struct IQ3SLMSplit {   // IQ3_S
1038    struct W { int g[8]; int ls; float dw; };
1039    static W load(const void* __restrict__ vbq, int kbx, int iqs, const uint32_t* grid) {
1040        const block_iq3_s* bq3 = iq_signed_grid::block_at<block_iq3_s>(vbq, uint32_t(kbx));
1041        const sycl::int2 qs_packed = sycl::int2(get_int_b2(bq3->qs, iqs + 0),
1042                                                get_int_b2(bq3->qs, iqs + 1));
1043        const uint8_t* qs = (const uint8_t*) &qs_packed;
1044        const int qh = bq3->qh[iqs / 2];
1045        const int signs_packed_32 = get_int_b2(bq3->signs, iqs / 2);
1046        const uint8_t* signs_packed_8 = (const uint8_t*) &signs_packed_32;
1047        W r;
1048#pragma unroll
1049        for (int l0 = 0; l0 < 8; l0 += 2) {
1050            const sycl::int2 grid_pos =
1051                sycl::int2(grid[qs[l0 + 0] | ((qh << (8 - l0)) & 0x100)],
1052                           grid[qs[l0 + 1] | ((qh << (7 - l0)) & 0x100)]);
1053            r.g[l0 + 0] = iq_signed_grid::apply(grid_pos.x(), signs_packed_8[l0 / 2]);
1054            r.g[l0 + 1] = iq_signed_grid::apply(grid_pos.y(), signs_packed_8[l0 / 2] >> 4);
1055        }
1056        r.ls = 1 + 2 * ((bq3->scales[iqs / 4] >> ((iqs << 1) & 0x04)) & 0x0F);
1057        r.dw = sycl::vec<sycl::half, 1>(bq3->d)
1058                   .convert<float, sycl::rounding_mode::automatic>()[0];
1059        return r;
1060    }
1061};
1062namespace iq3jm=sycl::ext::oneapi::experimental::matrix;
1063inline float iq3_xmx_float_finish(const IQ3SLMSplit::W& pw,const block_q8_1* activation,int sumi){
1064    sumi*=pw.ls;const float d=pw.dw*activation->ds[0];return d*sumi;
1065}
1066template<int NT,int KB>class IQ3XmxRegisterKernel;
1067template<int NT,int KB>
1068void iq3_xmx_register_launch(const uint8_t* w,const block_q8_1* x,float* y,int N,sycl::queue* q){
1069    constexpr int NR=16,NS=32,XB=KB*8,RB=KB*sizeof(block_iq3_s);
1070    q->parallel_for<IQ3XmxRegisterKernel<NT,KB>>(sycl::nd_range<1>((N+NR-1)/NR*512,512),
1071      [=](sycl::nd_item<1> it)[[sycl::reqd_sub_group_size(16)]]{
1072        auto group=it.get_group();auto sg=it.get_sub_group();int lid=it.get_local_linear_id(),sid=lid/16,lane=lid%16,base=it.get_group_linear_id()*NR,row=base+lane;
1073        auto& table=*sycl::ext::oneapi::group_local_memory_for_overwrite<uint32_t[512]>(group);
1074        auto& partial=*sycl::ext::oneapi::group_local_memory_for_overwrite<float[NS*NT*NR]>(group);
1075        table[lid]=iq3s_grid[lid];it.barrier(sycl::access::fence_space::local_space);
1076        float acc[NT]={};
1077        for(int seg=sid;seg<XB;seg+=NS){
1078            IQ3SLMSplit::W pw{};if(row<N)pw=IQ3SLMSplit::load(w+uint32_t(row)*uint32_t(RB),seg/8,2*(seg%8),table);
1079            iq3jm::joint_matrix<sycl::sub_group,int8_t,iq3jm::use::a,NT,32,iq3jm::layout::row_major> A;
1080            iq3jm::joint_matrix<sycl::sub_group,int8_t,iq3jm::use::b,32,NR,iq3jm::layout::ext_intel_packed> B;
1081            iq3jm::joint_matrix<sycl::sub_group,int32_t,iq3jm::use::accumulator,NT,NR> C;
1082
1083                auto pa=sycl::address_space_cast<sycl::access::address_space::global_space,sycl::access::decorated::no>(x[seg].qs);
1084                iq3jm::joint_matrix_load(sg,A,pa,XB*sizeof(block_q8_1));
1085                iq3jm::joint_matrix_fill(sg,B,0);
1086
1087                    int kr=0;
1088                    iq3jm::joint_matrix_apply(sg,B,[&](auto& element){
1089                        const int word=kr<4?pw.g[0]:kr<8?pw.g[1]:kr<12?pw.g[2]:kr<16?pw.g[3]:kr<20?pw.g[4]:kr<24?pw.g[5]:kr<28?pw.g[6]:pw.g[7];
1090                        element=int8_t(uint32_t(word)>>(8*(kr%4)));++kr;
1091                    });
1092
1093
1094            iq3jm::joint_matrix_fill(sg,C,0);iq3jm::joint_matrix_mad(sg,C,A,B,C);
1095
1096                int mr=0;
1097                iq3jm::joint_matrix_apply(sg,C,[&](auto& element){
1098                    acc[mr]+=iq3_xmx_float_finish(pw,x+mr*XB+seg,int(element));++mr;
1099                });
1100
1101
1102        }
1103#pragma unroll
1104        for(int j=0;j<NT;++j)partial[sid*NT*NR+j*NR+lane]=acc[j];
1105        it.barrier(sycl::access::fence_space::local_space);
1106        const int rr=lid/32,vl=lid%32;
1107#pragma unroll
1108        for(int j=0;j<NT;++j){float v=partial[vl*NT*NR+j*NR+rr];v+=partial[(vl^16)*NT*NR+j*NR+rr];
1109#pragma unroll
1110            for(int off=8;off;off>>=1)v+=sycl::permute_group_by_xor(sg,v,off);
1111            if(vl==0&&base+rr<N)y[uint32_t(j)*uint32_t(N)+uint32_t(base+rr)]=v;
1112        }
1113    });
1114}
1115template<int KB>void iq3_xmx_register_T(int T,const uint8_t* w,const block_q8_1* x,float* y,int N,sycl::queue* q){
1116#define IQ3_XMX_T(t) case t:iq3_xmx_register_launch<t,KB>(w,x,y,N,q);break
1117    switch(T){IQ3_XMX_T(1);IQ3_XMX_T(2);IQ3_XMX_T(3);IQ3_XMX_T(4);IQ3_XMX_T(5);IQ3_XMX_T(6);IQ3_XMX_T(7);IQ3_XMX_T(8);}
1118#undef IQ3_XMX_T
1119}
1120
1121// SYCL port: lanes per row for the grouped expert kernels. A 2560-wide row is 80 (block, part) calls; over 32
1122// lanes that is 2.5 calls each and a 5-step reduction - the work per sub-group is too small for the fixed cost.
1123// STRATA_EXPERT_LANES (compile time) lanes share a row; 256 / that many rows per work-group.
1124#ifndef STRATA_EXPERT_LANES
1125#define STRATA_EXPERT_LANES 8
1126#endif
1127constexpr int kExpertLanes = STRATA_EXPERT_LANES;
1128constexpr int kExpertRows = 256 / kExpertLanes;
1129template <int LANES>
1130__dpct_inline__ float lanes_sum(float v) {
1131#pragma unroll
1132    for (int o = LANES / 2; o > 0; o >>= 1)
1133        v += dpct::experimental::permute_sub_group_by_xor(0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(), v, o);
1134    return v;
1135}
1136template <int TY, int LANES, bool Q2_WORD_EXPAND = false>
1137__dpct_inline__ float row_dot_lanes(const uint8_t *row, const block_q8_1 *x, int nb, int sub) {
1138    using F = Fmt<TY>;
1139    float s = 0.0f;
1140    for (int k = sub; k < nb * F::ipb; k += LANES) {
1141        const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb);
1142        if constexpr (TY == 42 && Q2_WORD_EXPAND)
1143            s += F::dot_word_expand(row, x + kbx * (F::qk / 32), kbx, iqs);
1144        else
1145            s += F::dot(row, (TY == 10016 || TY == 10022) ? iq_signed_grid::block_at<block_q8_1>(x, uint32_t(kbx * (F::qk / 32))) : x + kbx * (F::qk / 32), kbx, iqs);
1146    }
1147    return lanes_sum<LANES>(s);
1148}
1149
1150// One row against one q8_1 activation, the whole warp: call k = (block, part) is lane-strided.
1151template <int TY>
1152__dpct_inline__ float row_dot(const uint8_t *row, const block_q8_1 *x, int nb,
1153                              int lane) {
1154    using F = Fmt<TY>;
1155    float s = 0.0f;
1156    for (int k = lane; k < nb * F::ipb; k += 32) {
1157        const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb);
1158        /*
1159        DPCT1084: The function call "Fmt::dot" has multiple migration
1160        results in different template instantiations that could not be unified.
1161        You may need to adjust the code.
1162        */
1163        s += F::dot(row, x + kbx * (F::qk / 32), kbx, iqs);
1164    }
1165    return warp_sum(s);
1166}
1167
1168template <int TY>
1169__dpct_inline__ void
1170mmvq_kernel(const uint8_t *__restrict__ w, size_t row_bytes,
1171            const block_q8_1 *__restrict__ x, float *__restrict__ y, int n_in,
1172            int n_out, int ncols) {
1173    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
1174    const int row = item_ct1.get_group(2) * 4 + item_ct1.get_local_id(1);
1175    if (row >= n_out) return;
1176    const int lane = item_ct1.get_local_id(2);
1177    const int nb = n_in / Fmt<TY>::qk;
1178    const uint8_t* wr = w + (size_t) row * row_bytes;
1179    for (int c = 0; c < ncols; ++c) {
1180        const float s =
1181            row_dot<TY>(wr, x + (size_t)c * (n_in / 32), nb, lane);
1182        if (lane == 0) y[(size_t) c * n_out + row] = s;
1183    }
1184}
1185
1186// ---------------------------------------------------------------- decode once, apply to every column
1187// The kernels above call Fmt<TY>::dot once per (call, column): each column re-reads the weight words and redoes
1188// the grid lookups and sign unpacking.  Here each dot is split, as native_mmvq.cu's multi-column traits are, into
1189// `load` (everything that depends only on the weight: the signed grid words, the integer scales, the fp16 block
1190// scale as a float) and `apply` (the activation loads, the dp4a chain in the same order, the same integer scale
1191// step and the same float expression).  `apply(load(...))` does the dot's integer and float operations in the same
1192// order on the same values, so a column of the kernels below is BITWISE equal to the same column of mmvq_kernel /
1193// native_gu_kernel / native_down_kernel (iq_multi_parity checks it; STRATA_OLD_IQ_MMVQ=1 keeps the old kernels).
1194template<int TY> struct Split;
1195// Formats with a Split below take the decode-once kernels; the others (Q4_K, Q5_K, Q5_1, Q8_0: UD-Q4_K_XL) the
1196// per-entry ones, which call Fmt<TY>::dot per column exactly as before #242 (the launchers test kSplit at compile
1197// time, so the multi kernels are never instantiated for a type without a Split).
1198template<int TY> inline constexpr bool kSplit = false;
1199template<int TY> inline constexpr bool kStageIqGrid = (TY == 16 || TY == 17 || TY == 22 || TY == 29);
1200
1201template<> inline constexpr bool kSplit<16> = true;
1202template<> struct Split<16> {   // IQ2_XXS
1203    struct W { int g[8]; int ls; float dw; };
1204    template<bool STAGE_GRID = false>
1205    static W load(const void* __restrict__ vbq, int kbx, int iqs, const uint32_t* __restrict__ s_grid = nullptr) {
1206        const block_iq2_xxs* bq2 = (const block_iq2_xxs*) vbq + kbx;
1207        const int q2 = get_int_b2(bq2->qs, iqs);
1208        const uint8_t* aux8 = (const uint8_t*) &q2;
1209        const uint32_t aux32 = get_int_b2(bq2->qs, iqs + 1);
1210        const sycl::uint2 *grid_lut;
1211        if constexpr (STAGE_GRID) grid_lut = (const sycl::uint2 *)s_grid;
1212        else grid_lut = (const sycl::uint2 *)iq2xxs_grid;
1213        W r;
1214#pragma unroll
1215        for (int k0 = 0; k0 < 8; k0 += 2) {
1216            const sycl::uint2 grid_pos = grid_lut[aux8[k0 / 2]];
1217            const uint32_t signs = unpack_ksigns(aux32 >> (7 * k0 / 2));
1218            const int signs0 = dpct::vectorized_binary<sycl::uchar4>(
1219                signs & 0x08040201, 0, std::not_equal_to<>());
1220            r.g[k0 + 0] = dpct::vectorized_binary<sycl::uchar4>(
1221                grid_pos.x() ^ signs0, signs0, std::minus<>());
1222            const int signs1 = dpct::vectorized_binary<sycl::uchar4>(
1223                signs & 0x80402010, 0, std::not_equal_to<>());
1224            r.g[k0 + 1] = dpct::vectorized_binary<sycl::uchar4>(
1225                grid_pos.y() ^ signs1, signs1, std::minus<>());
1226        }
1227        r.ls = aux32 >> 27 | 1;
1228        r.dw = sycl::vec<sycl::half, 1>(bq2->d)
1229                   .convert<float, sycl::rounding_mode::automatic>()[0];
1230        return r;
1231    }
1232    static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) {
1233        int sumi = 0;
1234#pragma unroll
1235        for (int j = 0; j < 8; ++j) sumi = ggml_cuda_dp4a(r.g[j], get_int_b4(bq8_1[iqs / 2].qs, j), sumi);
1236        sumi = sumi * r.ls / 8;
1237        const float d = r.dw * bq8_1[iqs / 2].ds[0];
1238        return d * sumi;
1239    }
1240};
1241// IQ2_XS and IQ2_S share the apply: two half sums, two 4-bit scales
1242struct SplitLs2 {
1243    struct W { int g[8]; int ls0, ls1; float dw; };
1244    static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) {
1245        int sumi0 = 0, sumi1 = 0;
1246#pragma unroll
1247        for (int j = 0; j < 4; ++j) sumi0 = ggml_cuda_dp4a(r.g[j], get_int_b4(bq8_1[iqs / 2].qs, j), sumi0);
1248#pragma unroll
1249        for (int j = 4; j < 8; ++j) sumi1 = ggml_cuda_dp4a(r.g[j], get_int_b4(bq8_1[iqs / 2].qs, j), sumi1);
1250        const int sumi = (sumi0 * r.ls0 + sumi1 * r.ls1 + (sumi0 + sumi1) / 2) / 4;
1251        const float d = r.dw * bq8_1[iqs / 2].ds[0];
1252        return d * sumi;
1253    }
1254};
1255template<> inline constexpr bool kSplit<17> = true;
1256template<> struct Split<17> : SplitLs2 {   // IQ2_XS
1257    template<bool STAGE_GRID = false>
1258    static W load(const void* __restrict__ vbq, int kbx, int iqs, const uint32_t* __restrict__ s_grid = nullptr) {
1259        const block_iq2_xs* bq2 = (const block_iq2_xs*) vbq + kbx;
1260        // SYCL port: the codes by shifts, not through a uint16_t* to an int2 (see vec_dot_iq2_xs_q8_1)
1261        const uint32_t q2_lo = (uint32_t) get_int_b2(bq2->qs, iqs + 0), q2_hi = (uint32_t) get_int_b2(bq2->qs, iqs + 1);
1262        const uint16_t q2[4] = {(uint16_t) q2_lo, (uint16_t) (q2_lo >> 16), (uint16_t) q2_hi, (uint16_t) (q2_hi >> 16)};
1263        const sycl::uint2 *grid_lut;
1264        if constexpr (STAGE_GRID) grid_lut = (const sycl::uint2 *)s_grid;
1265        else grid_lut = (const sycl::uint2 *)iq2xs_grid;
1266        W r;
1267        r.ls0 = bq2->scales[iqs / 2] & 0x0F;
1268        r.ls1 = bq2->scales[iqs / 2] >> 4;
1269#pragma unroll
1270        for (int l0 = 0; l0 < 8; l0 += 2) {
1271            const sycl::uint2 grid_pos = grid_lut[q2[l0 / 2] & 0x1FF];
1272            const uint32_t signs = unpack_ksigns(q2[l0 / 2] >> 9);
1273#if STRATA_IQ3S_SIGN_FAST
1274            const int signs0 = iq3s_sign_mask(signs);
1275            const int signs1 = iq3s_sign_mask(signs >> 4);
1276#else
1277            const int signs0 = dpct::vectorized_binary<sycl::uchar4>(
1278                signs & 0x08040201, 0, std::not_equal_to<>());
1279            const int signs1 = dpct::vectorized_binary<sycl::uchar4>(
1280                signs & 0x80402010, 0, std::not_equal_to<>());
1281#endif
1282#if STRATA_IQ3S_SIGN_APPLY_FAST
1283            r.g[l0 + 0] = iq3s_apply_sign(grid_pos.x(), signs0);
1284            r.g[l0 + 1] = iq3s_apply_sign(grid_pos.y(), signs1);
1285#else
1286            r.g[l0 + 0] = dpct::vectorized_binary<sycl::uchar4>(
1287                grid_pos.x() ^ signs0, signs0, std::minus<>());
1288            r.g[l0 + 1] = dpct::vectorized_binary<sycl::uchar4>(
1289                grid_pos.y() ^ signs1, signs1, std::minus<>());
1290#endif
1291        }
1292        r.dw = sycl::vec<sycl::half, 1>(bq2->d)
1293                   .convert<float, sycl::rounding_mode::automatic>()[0];
1294        return r;
1295    }
1296};
1297template<> inline constexpr bool kSplit<22> = true;
1298template<> struct Split<22> : SplitLs2 {   // IQ2_S
1299    template<bool STAGE_GRID = false>
1300    static W load(const void* __restrict__ vbq, int kbx, int iqs, const uint32_t* __restrict__ s_grid = nullptr) {
1301        const block_iq2_s* bq2 = (const block_iq2_s*) vbq + kbx;
1302        const int qs_packed = get_int_b2(bq2->qs, iqs / 2);
1303        const uint8_t* qs = (const uint8_t*) &qs_packed;
1304        const int qh = bq2->qh[iqs / 2];
1305        const int signs_packed_32 = get_int_b2(bq2->qs, QK_K / 32 + iqs / 2);
1306        const uint8_t* signs_packed_8 = (const uint8_t*) &signs_packed_32;
1307        const uint64_t* grid_lut;
1308        if constexpr (STAGE_GRID) grid_lut = (const uint64_t*) s_grid;
1309        else grid_lut = iq2s_grid;
1310        W r;
1311        r.ls0 = bq2->scales[iqs / 2] & 0x0F;
1312        r.ls1 = bq2->scales[iqs / 2] >> 4;
1313#pragma unroll
1314        for (int l0 = 0; l0 < 8; l0 += 2) {
1315            const int* grid_pos = (const int*) (grid_lut + (qs[l0 / 2] | ((qh << (8 - l0)) & 0x300)));
1316#if STRATA_IQ3S_SIGN_FAST
1317            const int signs0 = iq3s_sign_mask(signs_packed_8[l0 / 2]);
1318            const int signs1 = iq3s_sign_mask(signs_packed_8[l0 / 2] >> 4);
1319#else
1320            const int signs0 = dpct::vectorized_binary<sycl::uchar4>(
1321                ((signs_packed_8[l0 / 2] & 0x03) << 7) |
1322                    ((signs_packed_8[l0 / 2] & 0x0C) << 21),
1323                0x00000000, std::not_equal_to<>());
1324            const int signs1 = dpct::vectorized_binary<sycl::uchar4>(
1325                ((signs_packed_8[l0 / 2] & 0x30) << 3) |
1326                    ((signs_packed_8[l0 / 2] & 0xC0) << 17),
1327                0x00000000, std::not_equal_to<>());
1328#endif
1329#if STRATA_IQ3S_SIGN_APPLY_FAST
1330            r.g[l0 + 0] = iq3s_apply_sign(grid_pos[0], signs0);
1331            r.g[l0 + 1] = iq3s_apply_sign(grid_pos[1], signs1);
1332#else
1333            r.g[l0 + 0] = dpct::vectorized_binary<sycl::uchar4>(
1334                grid_pos[0] ^ signs0, signs0, std::minus<>());
1335            r.g[l0 + 1] = dpct::vectorized_binary<sycl::uchar4>(
1336                grid_pos[1] ^ signs1, signs1, std::minus<>());
1337#endif
1338        }
1339        r.dw = sycl::vec<sycl::half, 1>(bq2->d)
1340                   .convert<float, sycl::rounding_mode::automatic>()[0];
1341        return r;
1342    }
1343};
1344template<> inline constexpr bool kSplit<18> = true;
1345template<> struct Split<18> {   // IQ3_XXS
1346    struct W { int g[8]; int ls; float dw; };
1347    template<bool STAGE_GRID = false>
1348    static W load(const void* __restrict__ vbq, int kbx, int iqs, const uint32_t* __restrict__ = nullptr) {
1349        const block_iq3_xxs* bq3 = (const block_iq3_xxs*) vbq + kbx;
1350        const sycl::int2 q3_packed =
1351            sycl::int2(get_int_b2(bq3->qs, iqs), get_int_b2(bq3->qs, iqs + 1));
1352        const uint8_t* q3 = (const uint8_t*) &q3_packed;
1353        const uint32_t aux32 = get_int_b2(bq3->qs, QK_K / 16 + iqs / 2);
1354        W r;
1355#pragma unroll
1356        for (int l0 = 0; l0 < 8; l0 += 2) {
1357            const sycl::int2 grid_pos =
1358                sycl::int2(iq3xxs_grid[q3[l0 + 0]], iq3xxs_grid[q3[l0 + 1]]);
1359            const uint32_t signs = unpack_ksigns(aux32 >> (7 * l0 / 2));
1360            const int signs0 = dpct::vectorized_binary<sycl::uchar4>(
1361                signs & 0x08040201, 0, std::not_equal_to<>());
1362            r.g[l0 + 0] = dpct::vectorized_binary<sycl::uchar4>(
1363                grid_pos.x() ^ signs0, signs0, std::minus<>());
1364            const int signs1 = dpct::vectorized_binary<sycl::uchar4>(
1365                signs & 0x80402010, 0, std::not_equal_to<>());
1366            r.g[l0 + 1] = dpct::vectorized_binary<sycl::uchar4>(
1367                grid_pos.y() ^ signs1, signs1, std::minus<>());
1368        }
1369        r.ls = aux32 >> 28;
1370        r.dw = sycl::vec<sycl::half, 1>(bq3->d)
1371                   .convert<float, sycl::rounding_mode::automatic>()[0];
1372        return r;
1373    }
1374    static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) {
1375        int sumi = 0;
1376#pragma unroll
1377        for (int j = 0; j < 8; ++j) sumi = ggml_cuda_dp4a(r.g[j], get_int_b4(bq8_1[iqs / 2].qs, j), sumi);
1378        sumi = (r.ls * sumi + sumi / 2) / 2;
1379        const float d = r.dw * bq8_1[iqs / 2].ds[0];
1380        return d * sumi;
1381    }
1382};
1383template<> inline constexpr bool kSplit<21> = true;
1384template<> struct Split<21> {   // IQ3_S
1385    struct W { int g[8]; int ls; float dw; };
1386    template<bool STAGE_GRID = false>
1387    static W load(const void* __restrict__ vbq, int kbx, int iqs, const uint32_t* __restrict__ = nullptr) {
1388        const block_iq3_s* bq3 = (const block_iq3_s*) vbq + kbx;
1389        const sycl::int2 qs_packed = sycl::int2(get_int_b2(bq3->qs, iqs + 0),
1390                                                get_int_b2(bq3->qs, iqs + 1));
1391        const uint8_t* qs = (const uint8_t*) &qs_packed;
1392        const int qh = bq3->qh[iqs / 2];
1393        const int signs_packed_32 = get_int_b2(bq3->signs, iqs / 2);
1394        const uint8_t* signs_packed_8 = (const uint8_t*) &signs_packed_32;
1395        W r;
1396#pragma unroll
1397        for (int l0 = 0; l0 < 8; l0 += 2) {
1398            const sycl::int2 grid_pos =
1399                sycl::int2(iq3s_grid[qs[l0 + 0] | ((qh << (8 - l0)) & 0x100)],
1400                           iq3s_grid[qs[l0 + 1] | ((qh << (7 - l0)) & 0x100)]);
1401            const int signs0 = dpct::vectorized_binary<sycl::uchar4>(
1402                ((signs_packed_8[l0 / 2] & 0x03) << 7) |
1403                    ((signs_packed_8[l0 / 2] & 0x0C) << 21),
1404                0x00000000, std::not_equal_to<>());
1405            const int signs1 = dpct::vectorized_binary<sycl::uchar4>(
1406                ((signs_packed_8[l0 / 2] & 0x30) << 3) |
1407                    ((signs_packed_8[l0 / 2] & 0xC0) << 17),
1408                0x00000000, std::not_equal_to<>());
1409            r.g[l0 + 0] = dpct::vectorized_binary<sycl::uchar4>(
1410                grid_pos.x() ^ signs0, signs0, std::minus<>());
1411            r.g[l0 + 1] = dpct::vectorized_binary<sycl::uchar4>(
1412                grid_pos.y() ^ signs1, signs1, std::minus<>());
1413        }
1414        r.ls = 1 + 2 * ((bq3->scales[iqs / 4] >> ((iqs << 1) & 0x04)) & 0x0F);
1415        r.dw = sycl::vec<sycl::half, 1>(bq3->d)
1416                   .convert<float, sycl::rounding_mode::automatic>()[0];
1417        return r;
1418    }
1419    static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) {
1420        int sumi = 0;
1421#pragma unroll
1422        for (int j = 0; j < 8; ++j) sumi = ggml_cuda_dp4a(r.g[j], get_int_b4(bq8_1[iqs / 2].qs, j), sumi);
1423        sumi *= r.ls;
1424        const float d = r.dw * bq8_1[iqs / 2].ds[0];
1425        return d * sumi;
1426    }
1427};
1428template<> inline constexpr bool kSplit<29> = true;
1429template<> struct Split<29> {   // IQ1_M
1430    struct W { int g[8]; float delta[4]; int sc0, sc1; float dw; };
1431    template<bool STAGE_GRID = false>
1432    static W load(const void* __restrict__ vbq, int kbx, int iqs, const uint32_t* __restrict__ s_grid = nullptr) {
1433        const block_iq1_m* bq1 = (const block_iq1_m*) vbq + kbx;
1434        const int qs_packed = get_int_b4(bq1->qs, iqs);
1435        const uint8_t* qs = (const uint8_t*) &qs_packed;
1436        const uint32_t* grid_lut;
1437        if constexpr (STAGE_GRID) grid_lut = s_grid;
1438        else grid_lut = iq1s_grid_gpu;
1439        W r;
1440#pragma unroll
1441        for (int l0 = 0; l0 < 8; l0 += 2) {
1442            const int qhl = bq1->qh[2 * iqs + l0 / 4] >> (4 * ((l0 / 2) % 2));
1443            const int grid = grid_lut[qs[l0 / 2] | ((qhl & 0x07) << 8)];
1444            r.g[l0 + 0] = (grid >> 0) & 0x0F0F0F0F;
1445            r.g[l0 + 1] = (grid >> 4) & 0x0F0F0F0F;
1446            r.delta[l0 / 2] = -1.0f + IQ1M_DELTA - (qhl & 0x08) * (2.0f * IQ1M_DELTA / 0x08);
1447        }
1448        const uint16_t* sc = (const uint16_t*) bq1->scales;
1449        iq1m_scale_t scale;
1450        scale.u16 = (sc[0] >> 12) | ((sc[1] >> 8) & 0x00F0) | ((sc[2] >> 4) & 0x0F00) | (sc[3] & 0xF000);
1451        r.dw = sycl::vec<sycl::half, 1>(scale.f16)
1452                   .convert<float, sycl::rounding_mode::automatic>()[0];
1453        const int tmp = sc[iqs / 2] >> (6 * (iqs % 2));
1454        r.sc0 = 2 * ((tmp >> 0) & 0x07) + 1;
1455        r.sc1 = 2 * ((tmp >> 3) & 0x07) + 1;
1456        return r;
1457    }
1458    static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) {
1459        int sumi[2] = {0, 0};
1460        float sumf[2] = {0.0f, 0.0f};
1461#pragma unroll
1462        for (int l0 = 0; l0 < 8; l0 += 2) {
1463            const int u0 = get_int_b4(bq8_1[iqs].qs, l0 + 0);
1464            const int u1 = get_int_b4(bq8_1[iqs].qs, l0 + 1);
1465            sumi[l0 / 4] = ggml_cuda_dp4a(r.g[l0 + 0], u0, sumi[l0 / 4]);
1466            sumi[l0 / 4] = ggml_cuda_dp4a(r.g[l0 + 1], u1, sumi[l0 / 4]);
1467            int sumy = 0;
1468            sumy = ggml_cuda_dp4a(u0, 0x01010101, sumy);
1469            sumy = ggml_cuda_dp4a(u1, 0x01010101, sumy);
1470            sumf[l0 / 4] += r.delta[l0 / 2] * sumy;
1471        }
1472        const float d = r.dw * bq8_1[iqs].ds[0];
1473        return d * ((sumi[0] + sumf[0]) * r.sc0 + (sumi[1] + sumf[1]) * r.sc1);
1474    }
1475};
1476template<> inline constexpr bool kSplit<20> = true;
1477template<> struct Split<20> {   // IQ4_NL
1478    struct W { sycl::int2 v[2]; float dw; };
1479    template<bool STAGE_GRID = false>
1480    static W load(const void* __restrict__ vbq, int kbx, int iqs, const uint32_t* __restrict__ = nullptr) {
1481        const block_iq4_nl* bq4 = (const block_iq4_nl*) vbq + kbx;
1482        W r;
1483#pragma unroll
1484        for (int l = 0; l < 2; ++l) r.v[l] = iq4nl_pair(get_int_b2(bq4->qs, iqs + l));   // SYCL port: = get_int_from_table_16(q)
1485        r.dw = sycl::vec<sycl::half, 1>(bq4->d)
1486                   .convert<float, sycl::rounding_mode::automatic>()[0];
1487        return r;
1488    }
1489    static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) {
1490        const int* q8 = (const int*) bq8_1->qs + iqs;
1491        int sumi = 0;
1492#pragma unroll
1493        for (int l = 0; l < 2; ++l) {
1494            sumi = ggml_cuda_dp4a(r.v[l].x(), q8[l + 0], sumi);
1495            sumi = ggml_cuda_dp4a(r.v[l].y(), q8[l + 4], sumi);
1496        }
1497        const float d = r.dw * bq8_1->ds[0];
1498        return d * sumi;
1499    }
1500};
1501template<> inline constexpr bool kSplit<23> = true;
1502template<> struct Split<23> {   // IQ4_XS
1503    struct W { sycl::int2 v[4]; int ls; float dw; };
1504    template<bool STAGE_GRID = false>
1505    static W load(const void* __restrict__ vbq, int kbx, int iqs, const uint32_t* __restrict__ = nullptr) {
1506        const block_iq4_xs* bq4 = (const block_iq4_xs*) vbq + kbx;
1507        W r;
1508#pragma unroll
1509        for (int j = 0; j < 4; ++j) r.v[j] = iq4nl_pair(get_int_b4(bq4->qs, iqs + j));   // SYCL port: = get_int_from_table_16(q)
1510        r.ls = ((bq4->scales_l[iqs / 8] >> (iqs & 0x04)) & 0x0F) | (((bq4->scales_h >> (iqs / 2)) & 0x03) << 4);
1511        r.dw = sycl::vec<sycl::half, 1>(bq4->d)
1512                   .convert<float, sycl::rounding_mode::automatic>()[0];
1513        return r;
1514    }
1515    static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) {
1516        int sumi = 0;
1517#pragma unroll
1518        for (int j = 0; j < 4; ++j) {
1519            const int u0 = get_int_b4(bq8_1[iqs / 4].qs, j + 0);
1520            const int u1 = get_int_b4(bq8_1[iqs / 4].qs, j + 4);
1521            sumi = ggml_cuda_dp4a(r.v[j].x(), u0, sumi);
1522            sumi = ggml_cuda_dp4a(r.v[j].y(), u1, sumi);
1523        }
1524        sumi *= r.ls - 32;
1525        const float d = r.dw * bq8_1[iqs / 4].ds[0];
1526        return d * sumi;
1527    }
1528};
1529template<> inline constexpr bool kSplit<42> = true;
1530template<> struct Split<42> {   // Q2_0
1531    struct W { int qx[4], qy[4]; float d2; };
1532    template<bool STAGE_GRID = false>
1533    static W load(const void* __restrict__ vbq, int kbx, int iqs, const uint32_t* __restrict__ = nullptr) {
1534        const block_q2_0* bq2_0 = (const block_q2_0*) vbq + kbx;
1535        W r;
1536        r.d2 = bq2_0->d;
1537        const int16_t* qs = (const int16_t*) bq2_0->qs + iqs * 4;
1538#pragma unroll
1539        for (int j = 0; j < 4; ++j) {
1540            const int q = qs[j];
1541            const sycl::int2 w = q2_decode8((uint16_t) q);
1542            r.qx[j] = w.x();
1543            r.qy[j] = w.y();
1544        }
1545        return r;
1546    }
1547    static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) {
1548        const block_q8_1* bq8_1_chunk = bq8_1 + iqs;
1549        int sumi = 0;
1550#pragma unroll
1551        for (int j = 0; j < 4; ++j) {
1552            const int u = get_int_b4(bq8_1_chunk->qs, j * 2 + 0);
1553            const int v = get_int_b4(bq8_1_chunk->qs, j * 2 + 1);
1554            sumi = ggml_cuda_dp4a(u, r.qx[j], sumi);
1555            sumi = ggml_cuda_dp4a(v, r.qy[j], sumi);
1556        }
1557        const float d8 = bq8_1_chunk->ds[0];
1558        return r.d2 * d8 * sumi;
1559    }
1560};
1561
1562// APR trellis types: the lane's 16 decoded codebook values (tq_load / tq_apply above)
1563template<> inline constexpr bool kSplit<144> = true;
1564template<> inline constexpr bool kSplit<145> = true;
1565template<> inline constexpr bool kSplit<146> = true;
1566template<int TY> struct SplitTq {
1567    using W = TqLane;
1568    template<bool STAGE_GRID = false>   // (no grid table to stage: the codebook is read where it is)
1569    static W load(const void* __restrict__ vbq, int kbx, int iqs, const uint32_t* __restrict__ = nullptr) {
1570        return tq_load<TY>(vbq, kbx, iqs);
1571    }
1572    static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) { return tq_apply(r, bq8_1, iqs); }
1573};
1574template<> struct Split<144> : SplitTq<144> {};
1575template<> struct Split<145> : SplitTq<145> {};
1576template<> struct Split<146> : SplitTq<146> {};
1577
1578// One row against the n <= NC activations x + off[0..n) (n >= 1, warp-uniform; offsets in q8_1 blocks, 32-bit to
1579// spare registers), the whole warp.  Per activation this is row_dot: the same calls k, lane-strided the same way,
1580// summed in the same order, then the same warp_sum.  Only the weight side moves out of the per-activation loop.
1581template <int TY, int NC, bool EXACT_N = false, bool STAGE_GRID = false>
1582__dpct_inline__ void
1583row_dot_multi(const uint8_t *row, const block_q8_1 *x, const int (&off)[NC],
1584              int n, int nb, int lane, float (&s)[NC],
1585              const uint32_t *__restrict__ s_grid = nullptr) {
1586    using F = Fmt<TY>;
1587    using S = Split<TY>;
1588#pragma unroll
1589    for (int c = 0; c < NC; ++c) s[c] = 0.0f;
1590    for (int k = lane; k < nb * F::ipb; k += 32) {
1591        const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb);
1592        /*
1593        DPCT1084: The function call "Split::load" has multiple migration
1594        results in different template instantiations that could not be unified.
1595        You may need to adjust the code.
1596        */
1597        const typename S::W w =
1598            S::template load<STAGE_GRID>(row, kbx, iqs, s_grid);
1599#pragma unroll
1600        for (int c = 0; c < NC; ++c)
1601            if (EXACT_N || c < n) s[c] += S::apply(w, x + off[c] + kbx * (F::qk / 32), iqs);
1602    }
1603#pragma unroll
1604    for (int c = 0; c < NC; ++c)
1605        if (EXACT_N || c < n) s[c] = warp_sum(s[c]);
1606}
1607
1608// 8-lane sub-warp row dot for K = nb * ipb == 40 (TD == 20, IQ4_NL with n_ff == 640):
1609// 4 rows per warp (32 rows per 256-thread block), 100% active lanes, bitwise identical addition tree to row_dot_multi.
1610template <int TY, int NC, bool EXACT_N = false>
1611/*
1612DPCT1110: The total declared local variable size in device function
1613row_dot_40_sub8 exceeds 128 bytes and may cause high register pressure. Consult
1614with your hardware vendor to find the total register size available and adjust
1615the code, or use smaller sub-group size to avoid high register pressure.
1616*/
1617__dpct_inline__ void row_dot_40_sub8(const uint8_t *row, const block_q8_1 *x,
1618                                     const int (&off)[NC], int n, int t,
1619                                     float (&s)[NC]) {
1620    using F = Fmt<TY>;
1621    using S = Split<TY>;
1622#pragma unroll
1623    for (int c = 0; c < NC; ++c) s[c] = 0.0f;
1624    for (int k = t; k < 40; k += 32) {
1625        const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb);
1626        const typename S::W w = S::load(row, kbx, iqs);
1627#pragma unroll
1628        for (int c = 0; c < NC; ++c)
1629            if (EXACT_N || c < n) s[c] += S::apply(w, x + off[c] + kbx * (F::qk / 32), iqs);
1630    }
1631    {
1632        const int k = t + 16, kbx = k / F::ipb, iqs = F::step * (k % F::ipb);
1633        const typename S::W w = S::load(row, kbx, iqs);
1634#pragma unroll
1635        for (int c = 0; c < NC; ++c) {
1636            if (EXACT_N || c < n) {
1637                float s16 = 0.0f;
1638                s16 += S::apply(w, x + off[c] + kbx * (F::qk / 32), iqs);
1639                /*
1640                DPCT1013: The rounding mode could not be specified and the
1641                generated code may have different accuracy than the original
1642                code. Verify the correctness. SYCL math built-in function
1643                rounding mode is aligned with OpenCL C 1.2 standard.
1644                */
1645                s[c] = s[c] + s16;
1646            }
1647        }
1648    }
1649    float s8[NC];
1650#pragma unroll
1651    for (int c = 0; c < NC; ++c) s8[c] = 0.0f;
1652    {
1653        const int k = t + 8, kbx = k / F::ipb, iqs = F::step * (k % F::ipb);
1654        const typename S::W w = S::load(row, kbx, iqs);
1655#pragma unroll
1656        for (int c = 0; c < NC; ++c)
1657            if (EXACT_N || c < n) s8[c] += S::apply(w, x + off[c] + kbx * (F::qk / 32), iqs);
1658    }
1659    {
1660        const int k = t + 24, kbx = k / F::ipb, iqs = F::step * (k % F::ipb);
1661        const typename S::W w = S::load(row, kbx, iqs);
1662#pragma unroll
1663        for (int c = 0; c < NC; ++c) {
1664            if (EXACT_N || c < n) {
1665                float s24 = 0.0f;
1666                s24 += S::apply(w, x + off[c] + kbx * (F::qk / 32), iqs);
1667                /*
1668                DPCT1013: The rounding mode could not be specified and the
1669                generated code may have different accuracy than the original
1670                code. Verify the correctness. SYCL math built-in function
1671                rounding mode is aligned with OpenCL C 1.2 standard.
1672                */
1673                s[c] = s[c] + s8[c] + s24;
1674            }
1675        }
1676    }
1677#pragma unroll
1678    for (int c = 0; c < NC; ++c) {
1679        if (EXACT_N || c < n) {
1680#pragma unroll
1681            /*
1682            DPCT1108: '__shfl_xor_sync' was migrated with the experimental
1683            feature masked sub_group function which may not be supported by all
1684            compilers or runtimes. You may need to adjust the code.
1685            */
1686            for (int o = 4; o > 0; o >>= 1) s[c] +=
1687                dpct::experimental::permute_sub_group_by_xor(
1688                    0xffffffffu,
1689                    sycl::ext::oneapi::this_work_item::get_sub_group(), s[c],
1690                    o);
1691        }
1692    }
1693}
1694
1695// 16-lane sub-warp row dot for K = nb * ipb == 20 (TD == 42, Q2_0 with n_ff == 640):
1696// 2 rows per warp (16 rows per 256-thread block), bitwise identical addition tree to row_dot_multi.
1697template <int TY, int NC, bool EXACT_N = false>
1698/*
1699DPCT1110: The total declared local variable size in device function
1700row_dot_20_sub16 exceeds 128 bytes and may cause high register pressure. Consult
1701with your hardware vendor to find the total register size available and adjust
1702the code, or use smaller sub-group size to avoid high register pressure.
1703*/
1704__dpct_inline__ void row_dot_20_sub16(const uint8_t *row, const block_q8_1 *x,
1705                                      const int (&off)[NC], int n, int t,
1706                                      float (&s)[NC]) {
1707    using F = Fmt<TY>;
1708    using S = Split<TY>;
1709#pragma unroll
1710    for (int c = 0; c < NC; ++c) s[c] = 0.0f;
1711    {
1712        const int k = t, kbx = k / F::ipb, iqs = F::step * (k % F::ipb);
1713        const typename S::W w = S::load(row, kbx, iqs);
1714#pragma unroll
1715        for (int c = 0; c < NC; ++c)
1716            if (EXACT_N || c < n) s[c] += S::apply(w, x + off[c] + kbx * (F::qk / 32), iqs);
1717    }
1718    float s16[NC];
1719#pragma unroll
1720    for (int c = 0; c < NC; ++c) s16[c] = 0.0f;
1721    if (t < 4) {
1722        const int k = t + 16, kbx = k / F::ipb, iqs = F::step * (k % F::ipb);
1723        const typename S::W w = S::load(row, kbx, iqs);
1724#pragma unroll
1725        for (int c = 0; c < NC; ++c)
1726            if (EXACT_N || c < n) s16[c] += S::apply(w, x + off[c] + kbx * (F::qk / 32), iqs);
1727    }
1728#pragma unroll
1729    for (int c = 0; c < NC; ++c) {
1730        if (EXACT_N || c < n) {
1731            /*
1732            DPCT1013: The rounding mode could not be specified and the
1733            generated code may have different accuracy than the original code.
1734            Verify the correctness. SYCL math built-in function rounding mode is
1735            aligned with OpenCL C 1.2 standard.
1736            */
1737            s[c] = s[c] + s16[c];
1738#pragma unroll
1739            /*
1740            DPCT1108: '__shfl_xor_sync' was migrated with the experimental
1741            feature masked sub_group function which may not be supported by all
1742            compilers or runtimes. You may need to adjust the code.
1743            */
1744            for (int o = 8; o > 0; o >>= 1) s[c] +=
1745                dpct::experimental::permute_sub_group_by_xor(
1746                    0xffffffffu,
1747                    sycl::ext::oneapi::this_work_item::get_sub_group(), s[c],
1748                    o);
1749        }
1750    }
1751}
1752
1753// 16-lane sub-warp row dot for K = nb * ipb == 80 (all kSplit gate/up formats with n_embd == 2560):
1754// 2 rows per warp (16 rows per 256-thread block), 100% active lanes, bitwise identical addition tree to row_dot_multi.
1755template <int TY, int NC, bool EXACT_N = false, bool STAGE_GRID = false>
1756/*
1757DPCT1110: The total declared local variable size in device function
1758row_dot_80_sub16 exceeds 128 bytes and may cause high register pressure. Consult
1759with your hardware vendor to find the total register size available and adjust
1760the code, or use smaller sub-group size to avoid high register pressure.
1761*/
1762__dpct_inline__ void
1763row_dot_80_sub16(const uint8_t *row, const block_q8_1 *x, const int (&off)[NC],
1764                 int n, int t, float (&s)[NC],
1765                 const uint32_t *__restrict__ s_grid = nullptr) {
1766    using F = Fmt<TY>;
1767    using S = Split<TY>;
1768#pragma unroll
1769    for (int c = 0; c < NC; ++c) s[c] = 0.0f;
1770    for (int k = t; k < 80; k += 32) {
1771        const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb);
1772        /*
1773        DPCT1084: The function call "Split::load" has multiple migration
1774        results in different template instantiations that could not be unified.
1775        You may need to adjust the code.
1776        */
1777        const typename S::W w =
1778            S::template load<STAGE_GRID>(row, kbx, iqs, s_grid);
1779#pragma unroll
1780        for (int c = 0; c < NC; ++c)
1781            if (EXACT_N || c < n) s[c] += S::apply(w, x + off[c] + kbx * (F::qk / 32), iqs);
1782    }
1783    float s16[NC];
1784#pragma unroll
1785    for (int c = 0; c < NC; ++c) s16[c] = 0.0f;
1786    for (int k = t + 16; k < 64; k += 32) {
1787        const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb);
1788        /*
1789        DPCT1084: The function call "Split::load" has multiple migration
1790        results in different template instantiations that could not be unified.
1791        You may need to adjust the code.
1792        */
1793        const typename S::W w =
1794            S::template load<STAGE_GRID>(row, kbx, iqs, s_grid);
1795#pragma unroll
1796        for (int c = 0; c < NC; ++c)
1797            if (EXACT_N || c < n) s16[c] += S::apply(w, x + off[c] + kbx * (F::qk / 32), iqs);
1798    }
1799#pragma unroll
1800    for (int c = 0; c < NC; ++c) {
1801        if (EXACT_N || c < n) {
1802            /*
1803            DPCT1013: The rounding mode could not be specified and the
1804            generated code may have different accuracy than the original code.
1805            Verify the correctness. SYCL math built-in function rounding mode is
1806            aligned with OpenCL C 1.2 standard.
1807            */
1808            s[c] = s[c] + s16[c];
1809#pragma unroll
1810            /*
1811            DPCT1108: '__shfl_xor_sync' was migrated with the experimental
1812            feature masked sub_group function which may not be supported by all
1813            compilers or runtimes. You may need to adjust the code.
1814            */
1815            for (int o = 8; o > 0; o >>= 1) s[c] +=
1816                dpct::experimental::permute_sub_group_by_xor(
1817                    0xffffffffu,
1818                    sycl::ext::oneapi::this_work_item::get_sub_group(), s[c],
1819                    o);
1820        }
1821    }
1822}
1823
1824template <int TY, bool STAGE_GRID = kStageIqGrid<TY>>
1825__dpct_inline__ const uint32_t *
1826stage_iq_grid(uint32_t *s_buf, int tid, int nthreads) {
1827    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
1828    if constexpr (!STAGE_GRID) {
1829        return nullptr;
1830    } else if constexpr (TY == 16) {
1831        sycl::uint2 *dst = (sycl::uint2 *)s_buf;
1832        const sycl::uint2 *src = (const sycl::uint2 *)iq2xxs_grid;
1833#pragma unroll
1834        for (int i = tid; i < 256; i += nthreads) dst[i] = src[i];
1835        /*
1836        DPCT1065: Consider replacing sycl::nd_item::barrier() with
1837        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
1838        better performance if there is no access to global memory.
1839        */
1840        item_ct1.barrier();
1841        return s_buf;
1842    } else if constexpr (TY == 17) {
1843        sycl::uint2 *dst = (sycl::uint2 *)s_buf;
1844        const sycl::uint2 *src = (const sycl::uint2 *)iq2xs_grid;
1845#pragma unroll
1846        for (int i = tid; i < 512; i += nthreads) dst[i] = src[i];
1847        /*
1848        DPCT1065: Consider replacing sycl::nd_item::barrier() with
1849        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
1850        better performance if there is no access to global memory.
1851        */
1852        item_ct1.barrier();
1853        return s_buf;
1854    } else if constexpr (TY == 22) {
1855        sycl::uint2 *dst = (sycl::uint2 *)s_buf;
1856        const sycl::uint2 *src = (const sycl::uint2 *)iq2s_grid;
1857#pragma unroll
1858        for (int i = tid; i < 1024; i += nthreads) dst[i] = src[i];
1859        /*
1860        DPCT1065: Consider replacing sycl::nd_item::barrier() with
1861        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
1862        better performance if there is no access to global memory.
1863        */
1864        item_ct1.barrier();
1865        return s_buf;
1866    } else if constexpr (TY == 29) {
1867        sycl::uint2 *dst = (sycl::uint2 *)s_buf;
1868        const sycl::uint2 *src = (const sycl::uint2 *)iq1s_grid_gpu;
1869#pragma unroll
1870        for (int i = tid; i < 1024; i += nthreads) dst[i] = src[i];
1871        /*
1872        DPCT1065: Consider replacing sycl::nd_item::barrier() with
1873        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
1874        better performance if there is no access to global memory.
1875        */
1876        item_ct1.barrier();
1877        return s_buf;
1878    } else {
1879        return nullptr;
1880    }
1881}
1882
1883template<int TY, bool STAGE_GRID = kStageIqGrid<TY>>
1884struct IqGridWords {
1885    static constexpr int value = !STAGE_GRID ? 4 : (TY == 22 || TY == 29) ? 2048 : (TY == 17) ? 1024 : (TY == 16) ? 512 : 4;
1886};
1887
1888// mmvq_kernel with the columns taken NC at a time.  After warp_sum every lane holds the same sum, so lane c stores
1889// column c.
1890// #778: `__shared__ alignas(16)` does not compile for gfx1030 (HIP); the attribute after the declarator does, but nvcc
1891// with MSVC as host does not take it.  Same layout either way.
1892#if defined(__HIPCC__)
1893#define STRATA_SHARED_ALIGN16_U32(name, ...) __shared__ uint32_t name[__VA_ARGS__] __attribute__((aligned(16)))
1894#else
1895#define STRATA_SHARED_ALIGN16_U32(name, ...) alignas(16) uint32_t name[__VA_ARGS__]
1896#endif
1897template <int TY, int NC, bool STAGE_GRID = kStageIqGrid<TY>,
1898          bool EXACT_N = false>
1899__dpct_inline__ void
1900mmvq_multi_kernel(const uint8_t *__restrict__ w, size_t row_bytes,
1901                  const block_q8_1 *__restrict__ x, float *__restrict__ y,
1902                  int n_in, int n_out, int ncols) {
1903    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
1904auto &s_grid_buf = *sycl::ext::oneapi::group_local_memory_for_overwrite<
1905    uint32_t[IqGridWords<TY, STAGE_GRID>::value]>(
1906    sycl::ext::oneapi::this_work_item::get_work_group<3>());
1907    const uint32_t *s_grid = stage_iq_grid<TY, STAGE_GRID>(
1908        s_grid_buf, item_ct1.get_local_id(1) * 32 + item_ct1.get_local_id(2),
1909        128);
1910    const int row = item_ct1.get_group(2) * 4 + item_ct1.get_local_id(1);
1911    if (row >= n_out) return;
1912    const int lane = item_ct1.get_local_id(2);
1913    const int nb = n_in / Fmt<TY>::qk, xb = n_in / 32;
1914    const uint8_t* wr = w + (size_t) row * row_bytes;
1915    if constexpr (EXACT_N) {
1916        int off[NC];
1917#pragma unroll
1918        for (int c = 0; c < NC; ++c) off[c] = c * xb;
1919        float s[NC];
1920        row_dot_multi<TY, NC, true, STAGE_GRID>(wr, x, off, NC, nb, lane, s, s_grid);
1921#pragma unroll
1922        for (int c = 0; c < NC; ++c)
1923            if (lane == c) y[(size_t) c * n_out + row] = s[c];
1924    } else {
1925        for (int c0 = 0; c0 < ncols; c0 += NC) {
1926            const int n = sycl::min(NC, ncols - c0);
1927            int off[NC];
1928#pragma unroll
1929            for (int c = 0; c < NC; ++c)
1930                off[c] = (c0 + sycl::min(c, n - 1)) * xb;
1931            float s[NC];
1932            row_dot_multi<TY, NC, false, STAGE_GRID>(wr, x, off, n, nb, lane, s, s_grid);
1933#pragma unroll
1934            for (int c = 0; c < NC; ++c)
1935                if (c < n && lane == c) y[(size_t) (c0 + c) * n_out + row] = s[c];
1936        }
1937    }
1938}
1939
1940// ---------------------------------------------------------------- grouped native experts
1941
1942// ---------------------------------------------------------------- SYCL port: multi-entry dots
1943//
1944// A window routes the same expert for several tokens (up to 6). The single-entry dot above recomputes the
1945// dequantised weights - grid lookups, sign unpacking, the byte-wise compare/xor/subtract emulations - once per
1946// token; only the dp4a against the activation and the scale differ. Multi<TY> splits each format into `prep`
1947// (weights, once) and `acts` + `finish` (per token). NW packed int32s of weights per call.
1948struct MultiW { int w[8]; int a = 0, b = 0; float d = 0.f; };
1949
1950template <int TY> struct Multi { static constexpr bool has = false; static constexpr int NW = 0; };
1951
1952template <> struct Multi<16> {   // IQ2_XXS: same decoded weights for each activation
1953    static constexpr bool has = true; static constexpr int NW = 8;
1954    __dpct_inline__ static void prep(const void* vbq, int kbx, int iqs, MultiW& m, const void* = nullptr) {
1955        const auto* block = static_cast<const block_iq2_xxs*>(vbq) + kbx;
1956        const int q2 = get_int_b2(block->qs, iqs);
1957        const auto* codes = reinterpret_cast<const uint8_t*>(&q2);
1958        const uint32_t aux = get_int_b2(block->qs, iqs + 1);
1959#pragma unroll
1960        for (int j = 0; j < 8; j += 2) {
1961            const sycl::uint2 grid = reinterpret_cast<const sycl::uint2*>(iq2xxs_grid)[codes[j / 2]];
1962            const uint32_t signs = unpack_ksigns(aux >> (7 * j / 2));
1963            const int s0 = swar_ne4(signs & 0x08040201), s1 = swar_ne4(signs & 0x80402010);
1964            m.w[j] = swar_sub4(grid.x() ^ s0, s0);
1965            m.w[j + 1] = swar_sub4(grid.y() ^ s1, s1);
1966        }
1967        m.a = aux >> 27 | 1;
1968        m.d = sycl::vec<sycl::half, 1>(block->d).convert<float, sycl::rounding_mode::automatic>()[0];
1969    }
1970    __dpct_inline__ static void acts(const block_q8_1* y, int iqs, int* u, float& ds) {
1971#pragma unroll
1972        for (int j = 0; j < 8; ++j) u[j] = get_int_b4(y[iqs / 2].qs, j);
1973        ds = y[iqs / 2].ds[0];
1974    }
1975    __dpct_inline__ static float finish(int s0, int s1, const MultiW& m, float ds) {
1976        const int sum = (s0 + s1) * m.a / 8; // original integer scaling/truncation
1977        const float scale = m.d * ds;
1978        return scale * sum;
1979    }
1980};
1981
1982template <> struct Multi<18> {   // iq3_xxs
1983    static constexpr bool has = true; static constexpr int NW = 8;
1984    __dpct_inline__ static void prep(const void* vbq, int kbx, int iqs, MultiW& m, const void* grid = nullptr) {
1985        const block_iq3_xxs* bq3 = (const block_iq3_xxs*) vbq + kbx;
1986#if STRATA_IQ4NL_FAST
1987        const sycl::int2 q3_packed = load8_a2(bq3->qs + 4 * iqs);
1988        const uint32_t aux32 = (uint32_t) load4_a2(bq3->qs + 4 * (QK_K / 16 + iqs / 2));
1989#else
1990        const sycl::int2 q3_packed = sycl::int2(get_int_b2(bq3->qs, iqs), get_int_b2(bq3->qs, iqs + 1));
1991        const uint32_t aux32 = get_int_b2(bq3->qs, QK_K / 16 + iqs / 2);
1992#endif
1993        const uint8_t* q3 = (const uint8_t*) &q3_packed;
1994        const uint32_t* G = (const uint32_t*) grid;
1995#pragma unroll
1996        for (int l0 = 0; l0 < 8; l0 += 2) {
1997            const sycl::int2 grid_pos = G ? sycl::int2(G[q3[l0 + 0]], G[q3[l0 + 1]])
1998                                          : sycl::int2(iq3xxs_grid[q3[l0 + 0]], iq3xxs_grid[q3[l0 + 1]]);
1999            const uint32_t signs = unpack_ksigns(aux32 >> (7 * l0 / 2));
2000#if STRATA_IQ3S_SIGN_FAST
2001            const int signs0 = iq3s_sign_mask(signs);
2002            const int signs1 = iq3s_sign_mask(signs >> 4);
2003#else
2004            const int signs0 = swar_ne4(signs & 0x08040201);
2005            const int signs1 = swar_ne4(signs & 0x80402010);
2006#endif
2007            m.w[l0 + 0] = iq3s_apply_sign(grid_pos.x(), signs0);
2008            m.w[l0 + 1] = iq3s_apply_sign(grid_pos.y(), signs1);
2009        }
2010        m.a = (int) (aux32 >> 28);
2011        m.d = sycl::vec<sycl::half, 1>(bq3->d).convert<float, sycl::rounding_mode::automatic>()[0];
2012    }
2013    __dpct_inline__ static void acts(const block_q8_1* y, int iqs, int* u, float& ds) {
2014#pragma unroll
2015        for (int j = 0; j < 8; ++j) u[j] = get_int_b4(y[iqs / 2].qs, j);
2016        ds = y[iqs / 2].ds[0];
2017    }
2018    __dpct_inline__ static float finish(int s0, int s1, const MultiW& m, float ds) {
2019        const int sumi = s0 + s1;
2020        return m.d * ds * (float) ((m.a * sumi + sumi / 2) / 2);
2021    }
2022};
2023
2024template <bool PackedSigns> struct IQ2SMulti {   // iq2_s
2025    static constexpr bool has = true; static constexpr int NW = 8;
2026    __dpct_inline__ static void prep(const void* vbq, int kbx, int iqs, MultiW& m, const void* grid = nullptr) {
2027        const block_iq2_s* bq2 = PackedSigns ? iq_signed_grid::block_at<block_iq2_s>(vbq, uint32_t(kbx)) : (const block_iq2_s*) vbq + kbx;
2028#if STRATA_IQ4NL_FAST
2029        const int qs_packed = load4_a2(bq2->qs + 4 * (iqs / 2));
2030        const int signs_packed_32 = load4_a2(bq2->qs + 4 * (QK_K / 32 + iqs / 2));
2031#else
2032        const int qs_packed = get_int_b2(bq2->qs, iqs / 2);
2033        const int signs_packed_32 = get_int_b2(bq2->qs, QK_K / 32 + iqs / 2);
2034#endif
2035        const uint8_t* qs = (const uint8_t*) &qs_packed;
2036        const int qh = bq2->qh[iqs / 2];
2037        const uint8_t* sp = (const uint8_t*) &signs_packed_32;
2038        const uint64_t* G = (const uint64_t*) grid;
2039#pragma unroll
2040        for (int l0 = 0; l0 < 8; l0 += 2) {
2041            const int gi = qs[l0 / 2] | ((qh << (8 - l0)) & 0x300);
2042            const int* grid_pos = G ? (const int*) (G + gi) : (const int*) (iq2s_grid + gi);
2043#if STRATA_IQ3S_SIGN_FAST
2044            const int signs0 = iq3s_sign_mask(sp[l0 / 2]);
2045            const int signs1 = iq3s_sign_mask(sp[l0 / 2] >> 4);
2046#else
2047            const int signs0 = swar_ne4(((sp[l0 / 2] & 0x03) << 7) | ((sp[l0 / 2] & 0x0C) << 21));
2048            const int signs1 = swar_ne4(((sp[l0 / 2] & 0x30) << 3) | ((sp[l0 / 2] & 0xC0) << 17));
2049#endif
2050            m.w[l0 + 0] = PackedSigns ? iq_signed_grid::apply(grid_pos[0], sp[l0 / 2]) : iq3s_apply_sign(grid_pos[0], signs0);
2051            m.w[l0 + 1] = PackedSigns ? iq_signed_grid::apply(grid_pos[1], sp[l0 / 2] >> 4) : iq3s_apply_sign(grid_pos[1], signs1);
2052        }
2053        m.a = bq2->scales[iqs / 2] & 0x0F;
2054        m.b = bq2->scales[iqs / 2] >> 4;
2055        m.d = sycl::vec<sycl::half, 1>(bq2->d).convert<float, sycl::rounding_mode::automatic>()[0];
2056    }
2057    __dpct_inline__ static void acts(const block_q8_1* y, int iqs, int* u, float& ds) {
2058#pragma unroll
2059        for (int j = 0; j < 8; ++j) u[j] = get_int_b4(y[iqs / 2].qs, j);
2060        ds = y[iqs / 2].ds[0];
2061    }
2062    __dpct_inline__ static float finish(int s0, int s1, const MultiW& m, float ds) {
2063        return m.d * ds * (float) ((s0 * m.a + s1 * m.b + (s0 + s1) / 2) / 4);
2064    }
2065};
2066
2067template <> struct Multi<22> : IQ2SMulti<false> {};
2068template <> struct Multi<10022> : IQ2SMulti<true> {};
2069
2070template <> struct Multi<21> {   // iq3_s
2071    static constexpr bool has = true; static constexpr int NW = 8;
2072    __dpct_inline__ static void prep(const void* vbq, int kbx, int iqs, MultiW& m, const void* grid = nullptr) {
2073        const block_iq3_s* bq3 = (const block_iq3_s*) vbq + kbx;
2074#if STRATA_IQ4NL_FAST
2075        const sycl::int2 qs_packed = load8_a2(bq3->qs + 4 * iqs);
2076        const int signs_packed_32 = load4_a2(bq3->signs + 4 * (iqs / 2));
2077#else
2078        const sycl::int2 qs_packed = sycl::int2(get_int_b2(bq3->qs, iqs + 0), get_int_b2(bq3->qs, iqs + 1));
2079        const int signs_packed_32 = get_int_b2(bq3->signs, iqs / 2);
2080#endif
2081        const uint8_t* qs = (const uint8_t*) &qs_packed;
2082        const int qh = bq3->qh[iqs / 2];
2083        const uint8_t* sp = (const uint8_t*) &signs_packed_32;
2084        const uint32_t* G = (const uint32_t*) grid;
2085#pragma unroll
2086        for (int l0 = 0; l0 < 8; l0 += 2) {
2087            const int i0 = qs[l0 + 0] | ((qh << (8 - l0)) & 0x100), i1 = qs[l0 + 1] | ((qh << (7 - l0)) & 0x100);
2088            const sycl::int2 grid_pos = G ? sycl::int2(G[i0], G[i1]) : sycl::int2(iq3s_grid[i0], iq3s_grid[i1]);
2089#if STRATA_IQ3S_SIGN_FAST
2090            const int signs0 = iq3s_sign_mask(sp[l0 / 2]);
2091            const int signs1 = iq3s_sign_mask(sp[l0 / 2] >> 4);
2092#else
2093            const int signs0 = swar_ne4(((sp[l0 / 2] & 0x03) << 7) | ((sp[l0 / 2] & 0x0C) << 21));
2094            const int signs1 = swar_ne4(((sp[l0 / 2] & 0x30) << 3) | ((sp[l0 / 2] & 0xC0) << 17));
2095#endif
2096#if STRATA_IQ3S_SIGN_APPLY_FAST
2097            m.w[l0 + 0] = iq3s_apply_sign(grid_pos.x(), signs0);
2098            m.w[l0 + 1] = iq3s_apply_sign(grid_pos.y(), signs1);
2099#else
2100            m.w[l0 + 0] = swar_sub4(grid_pos.x() ^ signs0, signs0);
2101            m.w[l0 + 1] = swar_sub4(grid_pos.y() ^ signs1, signs1);
2102#endif
2103        }
2104        m.a = 1 + 2 * ((bq3->scales[iqs / 4] >> ((iqs << 1) & 0x04)) & 0x0F);
2105        m.d = sycl::vec<sycl::half, 1>(bq3->d).convert<float, sycl::rounding_mode::automatic>()[0];
2106    }
2107    __dpct_inline__ static void acts(const block_q8_1* y, int iqs, int* u, float& ds) {
2108#pragma unroll
2109        for (int j = 0; j < 8; ++j) u[j] = get_int_b4(y[iqs / 2].qs, j);
2110        ds = y[iqs / 2].ds[0];
2111    }
2112    __dpct_inline__ static float finish(int s0, int s1, const MultiW& m, float ds) {
2113        return m.d * ds * (float) ((s0 + s1) * m.a);
2114    }
2115};
2116
2117template <> struct Multi<20> {   // iq4_nl (down)
2118    static constexpr bool has = true; static constexpr int NW = 4;
2119    __dpct_inline__ static void prep(const void* vbq, int kbx, int iqs, MultiW& m, const void* = nullptr) {
2120        const block_iq4_nl* bq4 = (const block_iq4_nl*) vbq + kbx;
2121#if STRATA_IQ4NL_FAST
2122        const sycl::int2 qq = load8_a2(bq4->qs + 4 * iqs);
2123#endif
2124#pragma unroll
2125        for (int l = 0; l < 2; ++l) {
2126#if STRATA_IQ4NL_FAST
2127            const sycl::int2 v = iq4nl_pair(l ? qq.y() : qq.x());
2128#else
2129            const int aux_q4 = get_int_b2(bq4->qs, iqs + l);
2130            const sycl::int2 v = get_int_from_table_16(aux_q4, kvalues_iq4nl);
2131#endif
2132            m.w[2 * l + 0] = v.x();
2133            m.w[2 * l + 1] = v.y();
2134        }
2135        m.d = sycl::vec<sycl::half, 1>(bq4->d).convert<float, sycl::rounding_mode::automatic>()[0];
2136    }
2137    __dpct_inline__ static void acts(const block_q8_1* y, int iqs, int* u, float& ds) {
2138        const int* q8 = (const int*) y->qs + iqs;
2139#pragma unroll
2140        for (int l = 0; l < 2; ++l) { u[2 * l + 0] = q8[l + 0]; u[2 * l + 1] = q8[l + 4]; }
2141        ds = y->ds[0];
2142    }
2143    __dpct_inline__ static float finish(int s0, int s1, const MultiW& m, float ds) { return m.d * ds * (float) (s0 + s1); }
2144};
2145
2146template <> struct Multi<42> {   // q2_0 (down)
2147    static constexpr bool has = true; static constexpr int NW = 8;
2148    __dpct_inline__ static void prep(const void* vbq, int kbx, int iqs, MultiW& m, const void* = nullptr) {
2149        const block_q2_0* bq2_0 = (const block_q2_0*) vbq + kbx;
2150        const int16_t* qs = (const int16_t*) bq2_0->qs + iqs * 4;
2151#pragma unroll
2152        for (int j = 0; j < 4; ++j) {
2153            const int q = qs[j];
2154            const sycl::int2 w = q2_decode8((uint16_t) q);
2155            m.w[2 * j + 0] = w.x();
2156            m.w[2 * j + 1] = w.y();
2157        }
2158        m.d = bq2_0->d;
2159    }
2160    __dpct_inline__ static void acts(const block_q8_1* y, int iqs, int* u, float& ds) {
2161        const block_q8_1* chunk = y + iqs;
2162#pragma unroll
2163        for (int j = 0; j < 4; ++j) { u[2 * j + 0] = get_int_b4(chunk->qs, j * 2 + 0); u[2 * j + 1] = get_int_b4(chunk->qs, j * 2 + 1); }
2164        ds = chunk->ds[0];
2165    }
2166    __dpct_inline__ static float finish(int s0, int s1, const MultiW& m, float ds) { return m.d * ds * (float) (s0 + s1); }
2167    __dpct_inline__ static void prep_word_expand(const void* vbq, int kbx, int iqs, MultiW& m) {
2168        const auto* b = (const block_q2_0*)vbq + kbx;
2169        const auto* qs = (const int16_t*)b->qs + iqs * 4;
2170#pragma unroll
2171        for (int j = 0; j < 4; ++j) {
2172            const auto w = q2_0_decode8((uint32_t)qs[j]);
2173            m.w[2*j] = w.x(); m.w[2*j+1] = w.y();
2174        }
2175        m.d = b->d;
2176    }
2177};
2178
2179template<> struct Multi<10042> : Multi<42> {
2180    __dpct_inline__ static void prep(const void* vbq, int kbx, int iqs, MultiW& m, const void* = nullptr) {
2181        const auto* b = (const block_q2_0*)vbq + kbx;
2182        const auto* qs = (const int16_t*)b->qs + iqs * 4;
2183#pragma unroll
2184        for (int j = 0; j < 4; ++j) {
2185            const auto w = q2_0_decode8((uint32_t)qs[j]);
2186            m.w[2*j] = w.x(); m.w[2*j+1] = w.y();
2187        }
2188        m.d = b->d;
2189    }
2190};
2191
2192// MODEL-UPDATE (Intel): Unsloth's formats in the lane kernels' multi-entry path.  Each Fmt<TY>::dot of the K-quants,
2193// Q5_1 and Q8_0 split into `load` (every read of the weight block and what is computed from it alone) and `apply`
2194// (the activation reads and the rest of the dot), the same statements in the same order as vec_dot_*_q8_1 above, so
2195// apply(load(...)) is the dot's value bit for bit; a group's 2-4 entries then read and decode each weight word once
2196// instead of once per entry.  Every entry keeps its own lane-strided k order and lanes_sum: the outputs are bitwise
2197// those of row_dot_lanes (native_grouped_parity --kq checks it).  STRATA_KQ_SPLIT=0: the per-entry kernels.
2198template <int TY> struct KqSplit { static constexpr bool has = false; };
2199// APR trellis types: tq_load decodes the lane's 16 codebook values once, tq_apply is the activation side per entry (the same
2200// operations as vec_dot_tq_q8_1, so the outputs are the per-entry kernels' bits)
2201template <int TY> struct KqSplitTq {
2202    static constexpr bool has = true;
2203    using W = TqLane;
2204    __dpct_inline__ static W load(const void* __restrict__ vbq, int kbx, int iqs) { return tq_load<TY>(vbq, kbx, iqs); }
2205    __dpct_inline__ static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) { return tq_apply(r, bq8_1, iqs); }
2206};
2207template <> struct KqSplit<144> : KqSplitTq<144> {};
2208template <> struct KqSplit<145> : KqSplitTq<145> {};
2209template <> struct KqSplit<146> : KqSplitTq<146> {};
2210#if STRATA_IQ4XS_LUT_SWAR
2211template <> struct KqSplit<23> : Split<23> { static constexpr bool has = true; };
2212#endif
2213template <> struct KqSplit<12> {   // Q4_K (vec_dot_q4_K_q8_1)
2214    static constexpr bool has = true;
2215    struct W { int v[2]; uint16_t aux[2]; sycl::half2 dm; };
2216    __dpct_inline__ static W load(const void* __restrict__ vbq, int kbx, int iqs) {
2217        const block_q4_K* b = (const block_q4_K*) vbq + kbx;
2218        W r;
2219        const int bq8_offset = QR4_K * ((iqs / 2) / (QI8_1 / 2));
2220        const int* q4 = (const int*) (b->qs + 16 * bq8_offset + 4 * ((iqs / 2) % 4));
2221        r.v[0] = q4[0];
2222        r.v[1] = q4[4];
2223        k_scale_min(b->scales, bq8_offset, r.aux);
2224        r.dm = b->dm;
2225        return r;
2226    }
2227    __dpct_inline__ static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) {
2228        const int bq8_offset = QR4_K * ((iqs / 2) / (QI8_1 / 2));
2229        int u[2 * QR4_K];
2230        float d8[QR4_K];
2231#pragma unroll
2232        for (int i = 0; i < QR4_K; ++i) {
2233            const block_q8_1* bq8i = bq8_1 + bq8_offset + i;
2234            d8[i] = bq8i->ds[0];
2235            const int* q8 = (const int*) bq8i->qs + ((iqs / 2) % 4);
2236            u[2 * i + 0] = q8[0];
2237            u[2 * i + 1] = q8[4];
2238        }
2239        const uint8_t* sc = (const uint8_t*) r.aux;
2240        const uint8_t* m = sc + 2;
2241        return vec_dot_q4_K_q8_1_impl_vmmq(r.v, u, sc, m, r.dm, d8);
2242    }
2243};
2244template <> struct KqSplit<13> {   // Q5_K (vec_dot_q5_K_q8_1)
2245    static constexpr bool has = true;
2246    struct W { int vl[2]; int vh[2]; uint16_t aux[2]; sycl::half2 dm; };
2247    __dpct_inline__ static W load(const void* __restrict__ vbq, int kbx, int iqs) {
2248        const block_q5_K* b = (const block_q5_K*) vbq + kbx;
2249        W r;
2250        const int bq8_offset = QR5_K * ((iqs / 2) / (QI8_1 / 2));
2251        const int* ql = (const int*) (b->qs + 16 * bq8_offset + 4 * ((iqs / 2) % 4));
2252        const int* qh = (const int*) (b->qh + 4 * ((iqs / 2) % 4));
2253        r.vl[0] = ql[0];
2254        r.vl[1] = ql[4];
2255        r.vh[0] = qh[0] >> bq8_offset;
2256        r.vh[1] = qh[4] >> bq8_offset;
2257        k_scale_min(b->scales, bq8_offset, r.aux);
2258        r.dm = b->dm;
2259        return r;
2260    }
2261    __dpct_inline__ static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) {
2262        const int bq8_offset = QR5_K * ((iqs / 2) / (QI8_1 / 2));
2263        int u[2 * QR5_K];
2264        float d8[QR5_K];
2265#pragma unroll
2266        for (int i = 0; i < QR5_K; ++i) {
2267            const block_q8_1* bq8i = bq8_1 + bq8_offset + i;
2268            d8[i] = bq8i->ds[0];
2269            const int* q8 = (const int*) bq8i->qs + ((iqs / 2) % 4);
2270            u[2 * i + 0] = q8[0];
2271            u[2 * i + 1] = q8[4];
2272        }
2273        const uint8_t* sc = (const uint8_t*) r.aux;
2274        const uint8_t* m = sc + 2;
2275        return vec_dot_q5_K_q8_1_impl_vmmq(r.vl, r.vh, u, sc, m, r.dm, d8);
2276    }
2277};
2278template <> struct KqSplit<14> {   // Q6_K (vec_dot_q6_K_q8_1)
2279    static constexpr bool has = true;
2280    struct W { int vl, vh; int8_t sc[5]; float d; };
2281    __dpct_inline__ static W load(const void* __restrict__ vbq, int kbx, int iqs) {
2282        const block_q6_K* bq6_K = (const block_q6_K*) vbq + kbx;
2283        const int scale_offset = (QI6_K / 4) * (iqs / (QI6_K / 2)) + (iqs % (QI6_K / 2)) / (QI6_K / 8);
2284        const int vh_shift = 2 * ((iqs % (QI6_K / 2)) / (QI6_K / 4));
2285        W r;
2286        r.vl = get_int_b2(bq6_K->ql, iqs);
2287        r.vh = get_int_b2(bq6_K->qh, (QI6_K / 4) * (iqs / (QI6_K / 2)) + iqs % (QI6_K / 4)) >> vh_shift;
2288        const int8_t* scales = bq6_K->scales + scale_offset;
2289        r.sc[0] = scales[0];
2290        r.sc[4] = scales[4];   // the impl reads scales[4 * i], i < QR6_K = 2
2291        r.d = sycl::vec<sycl::half, 1>(bq6_K->d).convert<float, sycl::rounding_mode::automatic>()[0];
2292        return r;
2293    }
2294    __dpct_inline__ static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) {
2295        const int bq8_offset = 2 * QR6_K * (iqs / (QI6_K / 2)) + (iqs % (QI6_K / 2)) / (QI6_K / 4);
2296        int u[QR6_K];
2297        float d8[QR6_K];
2298#pragma unroll
2299        for (int i = 0; i < QR6_K; ++i) {
2300            u[i] = get_int_b4(bq8_1[bq8_offset + 2 * i].qs, iqs % QI8_1);
2301            d8[i] = bq8_1[bq8_offset + 2 * i].ds[0];
2302        }
2303        return vec_dot_q6_K_q8_1_impl_mmvq(r.vl, r.vh, u, r.sc, r.d, d8);
2304    }
2305};
2306template <> struct KqSplit<7> {   // Q5_1 (vec_dot_q5_1_q8_1)
2307    static constexpr bool has = true;
2308    struct W { int vl[VDR_Q5_1]; int qh; sycl::half2 dm; };
2309    __dpct_inline__ static W load(const void* __restrict__ vbq, int kbx, int iqs) {
2310        const block_q5_1* b = (const block_q5_1*) vbq + kbx;
2311        W r;
2312#pragma unroll
2313        for (int i = 0; i < VDR_Q5_1; ++i) r.vl[i] = get_int_b4(b->qs, iqs + i);
2314        r.qh = get_int_b4(b->qh, 0);
2315        r.dm = b->dm;
2316        return r;
2317    }
2318    __dpct_inline__ static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) {
2319        int sumi = 0, sumu = 0;
2320#pragma unroll
2321        for (int i = 0; i < VDR_Q5_1; ++i) {
2322            const int vl = r.vl[i];
2323            const int vh = r.qh >> (4 * (iqs + i));
2324            const int u0 = get_int_b4(bq8_1->qs, iqs + i), u1 = get_int_b4(bq8_1->qs, iqs + i + QI5_1);
2325            int vi0 = (vl >> 0) & 0x0F0F0F0F;
2326            vi0 |= (vh << 4) & 0x00000010;
2327            vi0 |= (vh << 11) & 0x00001000;
2328            vi0 |= (vh << 18) & 0x00100000;
2329            vi0 |= (vh << 25) & 0x10000000;
2330            sumi = ggml_cuda_dp4a(vi0, u0, sumi);
2331            int vi1 = (vl >> 4) & 0x0F0F0F0F;
2332            vi1 |= (vh >> 12) & 0x00000010;
2333            vi1 |= (vh >> 5) & 0x00001000;
2334            vi1 |= (vh << 2) & 0x00100000;
2335            vi1 |= (vh << 9) & 0x10000000;
2336            sumi = ggml_cuda_dp4a(vi1, u1, sumi);
2337            sumu = ggml_cuda_dp4a(0x01010101, u1, ggml_cuda_dp4a(0x01010101, u0, sumu));
2338        }
2339        const sycl::float2 dm5 = (r.dm).template convert<float, sycl::rounding_mode::automatic>();
2340        const float d8 = bq8_1->ds[0];
2341        return sumi * (dm5.x() * d8) + sumu * (dm5.y() * d8);
2342    }
2343};
2344template <> struct KqSplit<8> {   // Q8_0 (vec_dot_q8_0_q8_1)
2345    static constexpr bool has = true;
2346    struct W { int q[VDR_Q8_0]; float d; };
2347    __dpct_inline__ static W load(const void* __restrict__ vbq, int kbx, int iqs) {
2348        const block_q8_0* b = (const block_q8_0*) vbq + kbx;
2349        W r;
2350#pragma unroll
2351        for (int i = 0; i < VDR_Q8_0; ++i) r.q[i] = get_int_b2(b->qs, iqs + i);
2352        r.d = sycl::vec<sycl::half, 1>(b->d).convert<float, sycl::rounding_mode::automatic>()[0];
2353        return r;
2354    }
2355    __dpct_inline__ static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) {
2356        int sumi = 0;
2357#pragma unroll
2358        for (int i = 0; i < VDR_Q8_0; ++i) sumi = ggml_cuda_dp4a(r.q[i], get_int_b4(bq8_1->qs, iqs + i), sumi);
2359        const float d8_1 = bq8_1->ds[0];
2360        return r.d * d8_1 * ((float) sumi);
2361    }
2362};
2363// the lane kernels' multi-entry path: the IQ formats' Multi always, the K-quant splits unless KM is false
2364template <int TY, bool KM> inline constexpr bool kEntryMulti = Multi<TY>::has || (KM && KqSplit<TY>::has);
2365
2366// One row against E activations at once, LANES lanes per row: the K-quant / Q5_1 / Q8_0 split (KqSplit).
2367template <int TY, int LANES, int E>
2368__dpct_inline__ void row_dot_ksplit(const uint8_t* row, const block_q8_1* const* xs, int nb, int sub, float* out) {
2369    using F = Fmt<TY>;
2370    using K = KqSplit<TY>;
2371    float s[E];
2372#pragma unroll
2373    for (int e = 0; e < E; ++e) s[e] = 0.f;
2374    for (int k = sub; k < nb * F::ipb; k += LANES) {
2375        const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb);
2376        const typename K::W w = K::load(row, kbx, iqs);
2377#pragma unroll
2378        for (int e = 0; e < E; ++e) s[e] += K::apply(w, xs[e] + kbx * (F::qk / 32), iqs);
2379    }
2380#pragma unroll
2381    for (int e = 0; e < E; ++e) out[e] = lanes_sum<LANES>(s[e]);
2382}
2383
2384// One row against E activations at once, LANES lanes per row: the IQ formats' Multi.
2385template <int TY, int LANES, int E, bool Q2_WORD_EXPAND = false>
2386__dpct_inline__ void row_dot_multi_iq(const uint8_t* row, const block_q8_1* const* xs, int nb, int sub, float* out,
2387                                      const void* grid = nullptr) {
2388    using F = Fmt<TY>;
2389    using M = Multi<TY>;
2390    float s[E];
2391#pragma unroll
2392    for (int e = 0; e < E; ++e) s[e] = 0.f;
2393    for (int k = sub; k < nb * F::ipb; k += LANES) {
2394        const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb);
2395        MultiW m;
2396        if constexpr (TY == 42 && Q2_WORD_EXPAND)
2397            M::prep_word_expand(row, kbx, iqs, m);
2398        else
2399            M::prep(row, kbx, iqs, m, grid);
2400#pragma unroll
2401        for (int e = 0; e < E; ++e) {
2402            int u[8];
2403            float ds;
2404            M::acts(TY == 10022 ? iq_signed_grid::block_at<block_q8_1>(xs[e], uint32_t(kbx * (F::qk / 32))) : xs[e] + kbx * (F::qk / 32), iqs, u, ds);
2405            int s0 = 0, s1 = 0;
2406#pragma unroll
2407            for (int j = 0; j < M::NW / 2; ++j) s0 = ggml_cuda_dp4a(m.w[j], u[j], s0);
2408#pragma unroll
2409            for (int j = M::NW / 2; j < M::NW; ++j) s1 = ggml_cuda_dp4a(m.w[j], u[j], s1);
2410            s[e] += M::finish(s0, s1, m, ds);
2411        }
2412    }
2413#pragma unroll
2414    for (int e = 0; e < E; ++e) out[e] = lanes_sum<LANES>(s[e]);
2415}
2416
2417template <int TY, int LANES, int E, bool Q2_WORD_EXPAND = false>
2418__dpct_inline__ void row_dot_multi(const uint8_t* row, const block_q8_1* const* xs, int nb, int sub, float* out,
2419                                   const void* grid = nullptr) {
2420    if constexpr (KqSplit<TY>::has) row_dot_ksplit<TY, LANES, E>(row, xs, nb, sub, out);
2421    else row_dot_multi_iq<TY, LANES, E, Q2_WORD_EXPAND>(row, xs, nb, sub, out, grid);
2422}
2423
2424// The entries e0..e1 of one row: chunks of 4 through the multi-entry dot, the rest one at a time.
2425template <int TY, int LANES, bool ReuseIQ2XXS = false, bool Bounded = false, bool KM = true>
2426__dpct_inline__ void row_entries(const uint8_t* wr, const block_q8_1* x, int x_stride, const int32_t* ent_idx,
2427                                 int e0, int e1, int nb, int sub, float* dst, size_t dst_stride,
2428                                 const void* grid = nullptr) {
2429    const auto activation = [=](int e) {
2430        if constexpr (Bounded) return iq_signed_grid::block_at<block_q8_1>(x, uint32_t(ent_idx[e]) * uint32_t(x_stride));
2431        else return x + (size_t) ent_idx[e] * x_stride;
2432    };
2433    const auto output_offset = [=](int e) -> size_t {
2434        if constexpr (Bounded) return uint32_t(e) * uint32_t(dst_stride);
2435        else return (size_t)e * dst_stride;
2436    };
2437    int e = e0;
2438    if constexpr ((Multi<TY>::has && (TY != 16 || ReuseIQ2XXS)) || (KM && KqSplit<TY>::has)) {
2439        for (; e + 4 <= e1; e += 4) {
2440            const block_q8_1* xs[4] = {activation(e), activation(e + 1),
2441                                       activation(e + 2), activation(e + 3)};
2442            float o[4];
2443            row_dot_multi<TY, LANES, 4>(wr, xs, nb, sub, o, grid);
2444            if (sub == 0)
2445#pragma unroll
2446                for (int i = 0; i < 4; ++i) dst[output_offset(e + i)] = o[i];
2447        }
2448        if (e + 2 <= e1) {
2449            const block_q8_1* xs[2] = {activation(e), activation(e + 1)};
2450            float o[2];
2451            row_dot_multi<TY, LANES, 2>(wr, xs, nb, sub, o, grid);
2452            if (sub == 0) { dst[output_offset(e)] = o[0]; dst[output_offset(e + 1)] = o[1]; }
2453            e += 2;
2454        }
2455    }
2456    for (; e < e1; ++e) {
2457        const float v = row_dot_lanes<TY, LANES>(wr, activation(e), nb, sub);
2458        if (sub == 0) dst[output_offset(e)] = v;
2459    }
2460}
2461
2462constexpr int GU_ROWS = 8;     // rows per block (one warp each)
2463
2464template <int TG, int LN = kExpertLanes, bool ReuseIQ2XXS = false, bool FixedShape = false, bool KM = true>
2465__dpct_inline__ void native_gu_kernel(
2466    const unsigned long long *__restrict__ grp_ptr,
2467    const int32_t *__restrict__ grp_start, const int32_t *__restrict__ n_groups,
2468    const int32_t *__restrict__ ent_tok, const block_q8_1 *__restrict__ xq,
2469    NativeExpertLayout L, float *__restrict__ gate, float *__restrict__ up) {
2470    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
2471    // #363: group g is computed by block row g % gridDim.y (a launch sized for fewer rows than possible groups strides);
2472    // a block row with no group returns before the barrier below (uniform over the work-group)
2473    const int ng = *n_groups;
2474    if ((int) item_ct1.get_group(1) >= ng) return;
2475    const void* grid = nullptr;
2476#if STRATA_GRID_SLM
2477    if constexpr (TG == 18 || TG == 21 || TG == 22) {
2478        using GT = std::conditional_t<TG == 22, uint64_t, uint32_t>;
2479        constexpr int GN = TG == 22 ? 1024 : TG == 21 ? 512 : 256;
2480        auto& sg = *sycl::ext::oneapi::group_local_memory_for_overwrite<GT[GN]>(item_ct1.get_group());
2481        for (int i = (int) item_ct1.get_local_id(2); i < GN; i += (int) item_ct1.get_local_range(2)) {
2482            if constexpr (TG == 22) sg[i] = iq2s_grid[i];
2483            else if constexpr (TG == 21) sg[i] = iq3s_grid[i];
2484            else sg[i] = iq3xxs_grid[i];
2485        }
2486        item_ct1.barrier(sycl::access::fence_space::local_space);
2487        grid = &sg[0];
2488    }
2489#endif
2490    const int rib = item_ct1.get_local_id(2) / LN,
2491              sub = item_ct1.get_local_id(2) % LN;
2492    const int row = item_ct1.get_group(2) * (256 / LN) + rib; // 0 .. 2*n_ff
2493    const int64_t ff = FixedShape ? 640 : L.n_ff;
2494    if (row >= 2 * ff) return;
2495    const bool is_up = row >= ff;
2496    const int r = is_up ? row - (int) ff : row;
2497    const size_t off = FixedShape ? uint32_t((is_up ? 640 : 0) + r) * uint32_t(TG == 10022 ? 820 : 660) : (is_up ? L.up_off : 0) + (size_t) r * L.gu_row;
2498    const int nb = FixedShape ? 10 : (int) (L.n_embd / Fmt<TG>::qk), xb = FixedShape ? 80 : (int) (L.n_embd / 32);
2499    for (int g = (int) item_ct1.get_group(1); g < ng; g += (int) item_ct1.get_group_range(1)) {
2500        const uint8_t* wr = (const uint8_t*) grp_ptr[g] + off;
2501        const int e0 = grp_start[g], e1 = grp_start[g + 1];
2502        row_entries<TG, LN, ReuseIQ2XXS, FixedShape, KM>(wr, xq, xb, ent_tok, e0, e1, nb, sub, (is_up ? up : gate) + r, (size_t) ff, grid);
2503    }
2504}
2505
2506// native_gu_kernel with the group's entries taken GRP_NC at a time, each weight part decoded once per pass.
2507// A group has at most one entry per token of the window (kVerifyMaxT = 8; setup writes --spec 4, and a split window
2508// has halves of <= 4), so 4 takes such windows in one pass; 8 would take ~64-80 registers against ~48 (ptxas -v).
2509constexpr int GRP_NC = 4;
2510
2511__dpct_inline__ void native_gu_iq3s_slm_kernel(
2512    const unsigned long long *__restrict__ grp_ptr,
2513    const int32_t *__restrict__ grp_start, const int32_t *__restrict__ n_groups,
2514    const int32_t *__restrict__ ent_tok, const block_q8_1 *__restrict__ xq,
2515    NativeExpertLayout L, float *__restrict__ gate, float *__restrict__ up) {
2516    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
2517    auto &s_x_words = *sycl::ext::oneapi::group_local_memory_for_overwrite<
2518        uint32_t[GRP_NC * 80 * 9]>(item_ct1.get_group());
2519    const int ng = *n_groups;
2520    const int rib = item_ct1.get_local_id(2) / 8;
2521    const int sub = item_ct1.get_local_id(2) % 8;
2522    const int row = item_ct1.get_group(2) * 32 + rib;
2523    const bool is_up = row >= L.n_ff;
2524    const int r = is_up ? row - (int) L.n_ff : row;
2525    const size_t off = (is_up ? L.up_off : 0) + (size_t) r * L.gu_row;
2526    const int nb = (int) (L.n_embd / Fmt<21>::qk);
2527    const int xb = (int) (L.n_embd / 32);
2528    auto *s_x = reinterpret_cast<const block_q8_1 *>(s_x_words);
2529    for (int g = (int) item_ct1.get_group(1); g < ng; g += (int) item_ct1.get_group_range(1)) {
2530        const uint8_t *wr = (const uint8_t *) grp_ptr[g] + off;
2531        const int e0 = grp_start[g], e1 = grp_start[g + 1];
2532        for (int e = e0; e < e1; e += GRP_NC) {
2533            const int n = sycl::min(GRP_NC, e1 - e);
2534            item_ct1.barrier(sycl::access::fence_space::local_space);
2535            for (int j = 0; j < n; ++j) {
2536                const auto *src = reinterpret_cast<const uint32_t *>(xq + (size_t) ent_tok[e + j] * xb);
2537                for (int i = (int) item_ct1.get_local_id(2); i < xb * 9; i += 256)
2538                    s_x_words[j * xb * 9 + i] = src[i];
2539            }
2540            item_ct1.barrier(sycl::access::fence_space::local_space);
2541            float *dst = (is_up ? up : gate) + r;
2542            if (n == 1) {
2543                const block_q8_1 *xs[1] = {s_x};
2544                float v[1];
2545                row_dot_multi<21, 8, 1>(wr, xs, nb, sub, v);
2546                if (sub == 0) dst[(size_t) e * L.n_ff] = v[0];
2547            } else if (n == 2) {
2548                const block_q8_1 *xs[2] = {s_x, s_x + xb};
2549                float v[2];
2550                row_dot_multi<21, 8, 2>(wr, xs, nb, sub, v);
2551                if (sub == 0) {
2552                    dst[(size_t) e * L.n_ff] = v[0];
2553                    dst[(size_t) (e + 1) * L.n_ff] = v[1];
2554                }
2555            } else if (n == 3) {
2556                const block_q8_1 *xs[3] = {s_x, s_x + xb, s_x + 2 * xb};
2557                float v[3];
2558                row_dot_multi<21, 8, 3>(wr, xs, nb, sub, v);
2559                if (sub == 0) {
2560                    dst[(size_t) e * L.n_ff] = v[0];
2561                    dst[(size_t) (e + 1) * L.n_ff] = v[1];
2562                    dst[(size_t) (e + 2) * L.n_ff] = v[2];
2563                }
2564            } else {
2565                const block_q8_1 *xs[4] = {s_x, s_x + xb, s_x + 2 * xb, s_x + 3 * xb};
2566                float v[4];
2567                row_dot_multi<21, 8, 4>(wr, xs, nb, sub, v);
2568                if (sub == 0)
2569#pragma unroll
2570                    for (int i = 0; i < 4; ++i) dst[(size_t) (e + i) * L.n_ff] = v[i];
2571            }
2572        }
2573    }
2574}
2575
2576template <int TG, bool STAGE_GRID = kStageIqGrid<TG>, bool SUB16 = true>
2577/*
2578DPCT1110: The total declared local variable size in device function
2579native_gu_multi_kernel exceeds 128 bytes and may cause high register pressure.
2580Consult with your hardware vendor to find the total register size available and
2581adjust the code, or use smaller sub-group size to avoid high register pressure.
2582*/
2583__dpct_inline__ void native_gu_multi_kernel(
2584    const unsigned long long *__restrict__ grp_ptr,
2585    const int32_t *__restrict__ grp_start, const int32_t *__restrict__ n_groups,
2586    const int32_t *__restrict__ ent_tok, const block_q8_1 *__restrict__ xq,
2587    NativeExpertLayout L, float *__restrict__ gate, float *__restrict__ up) {
2588    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
2589    const int ng = *n_groups;
2590    if (item_ct1.get_group(1) >= ng) return;
2591    auto &s_grid_buf = *sycl::ext::oneapi::group_local_memory_for_overwrite<
2592        uint32_t[IqGridWords<TG, STAGE_GRID>::value]>(
2593        sycl::ext::oneapi::this_work_item::get_work_group<3>());
2594    const uint32_t *s_grid = stage_iq_grid<TG, STAGE_GRID>(
2595        s_grid_buf, item_ct1.get_local_id(2), 256);
2596    const int nb = (int) (L.n_embd / Fmt<TG>::qk), xb = (int) (L.n_embd / 32);
2597    if constexpr (SUB16) {
2598        if (xb == 80 && nb * Fmt<TG>::ipb == 80) {   // row_dot_80_sub16 covers exactly 80 dots (not the 128-value TQ blocks)
2599            const int subwarp = item_ct1.get_local_id(2) >> 4,
2600                      t = item_ct1.get_local_id(2) & 15;
2601            const int row = item_ct1.get_group(2) * 16 + subwarp; // 0 .. 2*n_ff
2602            if (row >= 2 * L.n_ff) return;
2603            const bool is_up = row >= L.n_ff;
2604            const int r = is_up ? row - (int) L.n_ff : row;
2605            const size_t w_off = (is_up ? L.up_off : 0) + (size_t) r * L.gu_row;
2606            float* dst = is_up ? up : gate;
2607            for (int g = item_ct1.get_group(1); g < ng;
2608                 g += item_ct1.get_group_range(1)) {
2609                const uint8_t* wr = (const uint8_t*) grp_ptr[g] + w_off;
2610                const int e0 = grp_start[g], e1 = grp_start[g + 1];
2611                for (int e = e0; e < e1; e += GRP_NC) {
2612                    const int n = sycl::min(GRP_NC, e1 - e);
2613                    if (n == 1) {
2614                        const int off1[1] = { ent_tok[e] * 80 };
2615                        float s1[1];
2616                        row_dot_80_sub16<TG, 1, true, STAGE_GRID>(
2617                            wr, xq, off1, 1, t, s1, s_grid);
2618                        if (t == 0) dst[(size_t) e * L.n_ff + r] = s1[0];
2619                    } else if (n == 2) {
2620                        const int off2[2] = { ent_tok[e] * 80, ent_tok[e + 1] * 80 };
2621                        float s2[2];
2622                        row_dot_80_sub16<TG, 2, true, STAGE_GRID>(
2623                            wr, xq, off2, 2, t, s2, s_grid);
2624                        if (t < 2) dst[(size_t) (e + t) * L.n_ff + r] = s2[t];
2625                    } else if (n == 3) {
2626                        const int off3[3] = { ent_tok[e] * 80, ent_tok[e + 1] * 80, ent_tok[e + 2] * 80 };
2627                        float s3[3];
2628                        row_dot_80_sub16<TG, 3, true, STAGE_GRID>(
2629                            wr, xq, off3, 3, t, s3, s_grid);
2630                        if (t < 3) dst[(size_t) (e + t) * L.n_ff + r] = s3[t];
2631                    } else {
2632                        const int off4[4] = { ent_tok[e] * 80, ent_tok[e + 1] * 80, ent_tok[e + 2] * 80, ent_tok[e + 3] * 80 };
2633                        float s4[4];
2634                        row_dot_80_sub16<TG, 4, true, STAGE_GRID>(
2635                            wr, xq, off4, 4, t, s4, s_grid);
2636                        if (t < 4) dst[(size_t) (e + t) * L.n_ff + r] = s4[t];
2637                    }
2638                }
2639            }
2640            return;
2641        }
2642    }
2643    const int warp = item_ct1.get_local_id(2) >> 5,
2644              lane = item_ct1.get_local_id(2) & 31;
2645    const int row = item_ct1.get_group(2) * GU_ROWS + warp; // 0 .. 2*n_ff
2646    if (row >= 2 * L.n_ff) return;
2647    const bool is_up = row >= L.n_ff;
2648    const int r = is_up ? row - (int) L.n_ff : row;
2649    const size_t w_off = (is_up ? L.up_off : 0) + (size_t) r * L.gu_row;
2650    float* dst = is_up ? up : gate;
2651    for (int g = item_ct1.get_group(1); g < ng;
2652         g +=
2653         item_ct1.get_group_range(1)) { // the group stride, as native_gu_kernel
2654        const uint8_t* wr = (const uint8_t*) grp_ptr[g] + w_off;
2655        const int e0 = grp_start[g], e1 = grp_start[g + 1];
2656        for (int e = e0; e < e1; e += GRP_NC) {
2657            const int n = sycl::min(GRP_NC, e1 - e);
2658            if (n == 1) {
2659                const int off1[1] = { ent_tok[e] * xb };
2660                float s1[1];
2661                row_dot_multi<TG, 1, true, STAGE_GRID>(
2662                    wr, xq, off1, 1, nb, lane, s1, s_grid);
2663                if (lane == 0) dst[(size_t) e * L.n_ff + r] = s1[0];
2664            } else if (n == 2) {
2665                const int off2[2] = { ent_tok[e] * xb, ent_tok[e + 1] * xb };
2666                float s2[2];
2667                row_dot_multi<TG, 2, true, STAGE_GRID>(
2668                    wr, xq, off2, 2, nb, lane, s2, s_grid);
2669                if (lane < 2) dst[(size_t) (e + lane) * L.n_ff + r] = s2[lane];
2670            } else if (n == 3) {
2671                const int off3[3] = { ent_tok[e] * xb, ent_tok[e + 1] * xb, ent_tok[e + 2] * xb };
2672                float s3[3];
2673                row_dot_multi<TG, 3, true, STAGE_GRID>(
2674                    wr, xq, off3, 3, nb, lane, s3, s_grid);
2675                if (lane < 3) dst[(size_t) (e + lane) * L.n_ff + r] = s3[lane];
2676            } else {
2677                const int off4[4] = { ent_tok[e] * xb, ent_tok[e + 1] * xb, ent_tok[e + 2] * xb, ent_tok[e + 3] * xb };
2678                float s4[4];
2679                row_dot_multi<TG, 4, true, STAGE_GRID>(
2680                    wr, xq, off4, 4, nb, lane, s4, s_grid);
2681                if (lane < 4) dst[(size_t) (e + lane) * L.n_ff + r] = s4[lane];
2682            }
2683        }
2684    }
2685}
2686
2687// APR (prism.hadamard): y = H_block (signs * x) per block of each row, block = the work-group size (a power of two <= 1024),
2688// one work-group per (row block, row).  The butterflies are the CPU's (hadamard.cpp) in the same order, so the
2689// rotated values are the same floats.
2690template <typename T> __dpct_inline__ float ld_f(const T* p) { return (float) *p; }
2691template <> __dpct_inline__ float ld_f<sycl::half>(const sycl::half* p) { return (float) *p; }
2692template <typename T> __dpct_inline__ void st_f(T* p, float v) { *p = v; }
2693template <> __dpct_inline__ void st_f<sycl::half>(sycl::half* p, float v) {
2694    *p = sycl::vec<float, 1>(v).convert<sycl::half, sycl::rounding_mode::automatic>()[0];
2695}
2696template <typename T>
2697__dpct_inline__ void hadamard_rows_kernel(const T* __restrict__ x, T* __restrict__ y, int64_t width,
2698                                          const float* __restrict__ signs, float scale) {
2699    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
2700    auto& hbuf = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[1024]>(item_ct1.get_group());
2701    const int n = (int) item_ct1.get_local_range(2), i = (int) item_ct1.get_local_id(2);
2702    const int64_t col = (int64_t) item_ct1.get_group(2) * n + i, at = (int64_t) item_ct1.get_group(1) * width + col;
2703    float v = ld_f<T>(x + at);
2704    if (signs) v *= signs[col];
2705    hbuf[i] = v;
2706    for (int len = 1; len < n; len <<= 1) {
2707        sycl::group_barrier(item_ct1.get_group());
2708        if ((i & len) == 0) {
2709            const float a = hbuf[i], c = hbuf[i + len];
2710            hbuf[i] = a + c;
2711            hbuf[i + len] = a - c;
2712        }
2713    }
2714    sycl::group_barrier(item_ct1.get_group());
2715    st_f<T>(y + at, hbuf[i] * scale);
2716}
2717template <typename T> class hadamard_rows_name;
2718template <typename T>
2719void launch_hadamard_rows(const T* x, T* y, int64_t rows, int64_t width, int block, const float* signs, dpct::queue_ptr s) {
2720    const float scale = 1.0f / std::sqrt((float) block);
2721    strata::kprof::kp(s, __FILE__, __func__, __LINE__)->template parallel_for<hadamard_rows_name<T>>(
2722        sycl::nd_range<3>(sycl::range<3>(1, (size_t) rows, (size_t) (width / block) * (size_t) block),
2723                          sycl::range<3>(1, 1, (size_t) block)),
2724        [=](sycl::nd_item<3>) [[sycl::reqd_sub_group_size(32)]] { hadamard_rows_kernel<T>(x, y, width, signs, scale); });
2725}
2726
2727__dpct_inline__ void swiglu_entries_kernel(const float *__restrict__ gate,
2728                                           const float *__restrict__ up,
2729                                           float *__restrict__ h, long long n) {
2730    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
2731    const long long i =
2732        (long long)item_ct1.get_group(2) * item_ct1.get_local_range(2) +
2733        item_ct1.get_local_id(2);
2734    if (i >= n) return;
2735    const float g = gate[i];
2736    h[i] = (g / (1.0f + sycl::native::exp(-g))) * up[i];
2737}
2738
2739template <int TD, int LN = kExpertLanes, bool KM = true, bool Q2_WORD_EXPAND = false>
2740__dpct_inline__ void native_down_kernel(
2741    const unsigned long long *__restrict__ grp_ptr,
2742    const int32_t *__restrict__ grp_start, const int32_t *__restrict__ n_groups,
2743    const int32_t *__restrict__ ent_dst, const block_q8_1 *__restrict__ hq,
2744    NativeExpertLayout L, float *__restrict__ out) {
2745    static_assert(!Q2_WORD_EXPAND || (TD == 42 && LN == 8));
2746    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
2747    const int ng = *n_groups;   // #363: the group stride, as native_gu_kernel
2748    const int rib = item_ct1.get_local_id(2) / LN,
2749              sub = item_ct1.get_local_id(2) % LN;
2750    const int r = item_ct1.get_group(2) * (256 / LN) + rib;
2751    if (r >= L.n_embd) return;
2752    const size_t off = L.down_off + (size_t) r * L.d_row;
2753    const int nb = (int) (L.n_ff / Fmt<TD>::qk), hb = (int) (L.n_ff / 32);
2754    // down: entry e's activation is row e of hq (identity index), its output row is ent_dst[e]
2755    for (int g = (int) item_ct1.get_group(1); g < ng; g += (int) item_ct1.get_group_range(1)) {
2756        const uint8_t* wr = (const uint8_t*) grp_ptr[g] + off;
2757        const int e0 = grp_start[g], e1 = grp_start[g + 1];
2758        int e = e0;
2759        if constexpr (kEntryMulti<TD, KM> && TD != 16) { // IQ2_XXS reuse remains GU-only and opt-in
2760            for (; e + 4 <= e1; e += 4) {
2761                const block_q8_1* xs[4] = {hq + (size_t) e * hb, hq + (size_t) (e + 1) * hb, hq + (size_t) (e + 2) * hb, hq + (size_t) (e + 3) * hb};
2762                float o[4];
2763                row_dot_multi<TD, LN, 4, Q2_WORD_EXPAND>(wr, xs, nb, sub, o);
2764                if (sub == 0)
2765#pragma unroll
2766                    for (int i = 0; i < 4; ++i) out[(size_t) ent_dst[e + i] * L.n_embd + r] = o[i];
2767            }
2768            if (e + 2 <= e1) {
2769                const block_q8_1* xs[2] = {hq + (size_t) e * hb, hq + (size_t) (e + 1) * hb};
2770                float o[2];
2771                row_dot_multi<TD, LN, 2, Q2_WORD_EXPAND>(wr, xs, nb, sub, o);
2772                if (sub == 0) { out[(size_t) ent_dst[e] * L.n_embd + r] = o[0]; out[(size_t) ent_dst[e + 1] * L.n_embd + r] = o[1]; }
2773                e += 2;
2774            }
2775        }
2776        for (; e < e1; ++e) {
2777            const float v = row_dot_lanes<TD, LN, Q2_WORD_EXPAND>(wr, hq + (size_t) e * hb, nb, sub);
2778            if (sub == 0) out[(size_t) ent_dst[e] * L.n_embd + r] = v;
2779        }
2780    }
2781}
2782
2783__dpct_inline__ void native_down_iq4nl_slm_kernel(
2784    const unsigned long long *__restrict__ grp_ptr,
2785    const int32_t *__restrict__ grp_start, const int32_t *__restrict__ n_groups,
2786    const int32_t *__restrict__ ent_dst, const block_q8_1 *__restrict__ hq,
2787    NativeExpertLayout L, float *__restrict__ out) {
2788    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
2789    auto &s_hq_words = *sycl::ext::oneapi::group_local_memory_for_overwrite<
2790        uint32_t[GRP_NC * 20 * 9]>(item_ct1.get_group());
2791    const int ng = *n_groups;
2792    const int rib = item_ct1.get_local_id(2) / 8;
2793    const int sub = item_ct1.get_local_id(2) % 8;
2794    const int r = item_ct1.get_group(2) * 32 + rib;
2795    const size_t off = L.down_off + (size_t) r * L.d_row;
2796    const int nb = (int) (L.n_ff / Fmt<20>::qk);
2797    const int hb = (int) (L.n_ff / 32);
2798    auto *s_hq = reinterpret_cast<const block_q8_1 *>(s_hq_words);
2799    for (int g = (int) item_ct1.get_group(1); g < ng; g += (int) item_ct1.get_group_range(1)) {
2800        const uint8_t *wr = (const uint8_t *) grp_ptr[g] + off;
2801        const int e0 = grp_start[g], e1 = grp_start[g + 1];
2802        for (int e = e0; e < e1; e += GRP_NC) {
2803            const int n = sycl::min(GRP_NC, e1 - e);
2804            const auto *src = reinterpret_cast<const uint32_t *>(hq + (size_t) e * hb);
2805            const int words = n * hb * 9;
2806            item_ct1.barrier(sycl::access::fence_space::local_space);
2807            for (int i = (int) item_ct1.get_local_id(2); i < words; i += 256) s_hq_words[i] = src[i];
2808            item_ct1.barrier(sycl::access::fence_space::local_space);
2809            if (n == 1) {
2810                const block_q8_1 *xs[1] = {s_hq};
2811                float v[1];
2812                row_dot_multi<20, 8, 1>(wr, xs, nb, sub, v);
2813                if (sub == 0) out[(size_t) ent_dst[e] * L.n_embd + r] = v[0];
2814            } else if (n == 2) {
2815                const block_q8_1 *xs[2] = {s_hq, s_hq + hb};
2816                float v[2];
2817                row_dot_multi<20, 8, 2>(wr, xs, nb, sub, v);
2818                if (sub == 0) {
2819                    out[(size_t) ent_dst[e] * L.n_embd + r] = v[0];
2820                    out[(size_t) ent_dst[e + 1] * L.n_embd + r] = v[1];
2821                }
2822            } else if (n == 3) {
2823                const block_q8_1 *xs[3] = {s_hq, s_hq + hb, s_hq + 2 * hb};
2824                float v[3];
2825                row_dot_multi<20, 8, 3>(wr, xs, nb, sub, v);
2826                if (sub == 0) {
2827                    out[(size_t) ent_dst[e] * L.n_embd + r] = v[0];
2828                    out[(size_t) ent_dst[e + 1] * L.n_embd + r] = v[1];
2829                    out[(size_t) ent_dst[e + 2] * L.n_embd + r] = v[2];
2830                }
2831            } else {
2832                const block_q8_1 *xs[4] = {s_hq, s_hq + hb, s_hq + 2 * hb, s_hq + 3 * hb};
2833                float v[4];
2834                row_dot_multi<20, 8, 4>(wr, xs, nb, sub, v);
2835                if (sub == 0)
2836#pragma unroll
2837                    for (int i = 0; i < 4; ++i) out[(size_t) ent_dst[e + i] * L.n_embd + r] = v[i];
2838            }
2839        }
2840    }
2841}
2842
2843// native_down_kernel with the entries taken GRP_NC at a time
2844template <int TD, bool SUB_DOWN = true>
2845/*
2846DPCT1110: The total declared local variable size in device function
2847native_down_multi_kernel exceeds 128 bytes and may cause high register pressure.
2848Consult with your hardware vendor to find the total register size available and
2849adjust the code, or use smaller sub-group size to avoid high register pressure.
2850*/
2851__dpct_inline__ void native_down_multi_kernel(
2852    const unsigned long long *__restrict__ grp_ptr,
2853    const int32_t *__restrict__ grp_start, const int32_t *__restrict__ n_groups,
2854    const int32_t *__restrict__ ent_dst, const block_q8_1 *__restrict__ hq,
2855    NativeExpertLayout L, float *__restrict__ out) {
2856    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
2857    const int ng = *n_groups;
2858    if (item_ct1.get_group(1) >= ng) return;
2859    auto &s_hq_buf = *sycl::ext::oneapi::group_local_memory_for_overwrite<
2860        uint32_t[GRP_NC * 20 * 9]>(
2861        sycl::ext::oneapi::this_work_item::get_work_group<3>());
2862    const int nb = (int) (L.n_ff / Fmt<TD>::qk), hb = (int) (L.n_ff / 32);
2863    if constexpr (SUB_DOWN && TD == 20) {
2864        if (hb == 20) {
2865            const int r =
2866                item_ct1.get_group(2) * 32 + (item_ct1.get_local_id(2) >> 3);
2867            const int t = item_ct1.get_local_id(2) & 7;
2868            const bool valid_r = (r < L.n_embd);
2869            const size_t w_off = L.down_off + (size_t) (valid_r ? r : 0) * L.d_row;
2870            const block_q8_1* s_hq = reinterpret_cast<const block_q8_1*>(s_hq_buf);
2871            for (int g = item_ct1.get_group(1); g < ng;
2872                 g += item_ct1.get_group_range(1)) {
2873                const uint8_t* wr = (const uint8_t*) grp_ptr[g] + w_off;
2874                const int e0 = grp_start[g], e1 = grp_start[g + 1];
2875                for (int e = e0; e < e1; e += GRP_NC) {
2876                    const int n = sycl::min(GRP_NC, e1 - e);
2877                    const uint32_t* src = reinterpret_cast<const uint32_t*>(hq + (size_t) e * 20);
2878                    const int words = n * (20 * 9);
2879                    /*
2880                    DPCT1118: SYCL group functions and algorithms must be
2881                    encountered in converged control flow. You may need to
2882                    adjust the code.
2883                    */
2884                    /*
2885                    DPCT1065: Consider replacing sycl::nd_item::barrier()
2886                    with
2887                    sycl::nd_item::barrier(sycl::access::fence_space::local_space)
2888                    for better performance if there is no access to global
2889                    memory.
2890                    */
2891                    item_ct1.barrier();
2892#pragma unroll
2893                    for (int i = item_ct1.get_local_id(2); i < words; i += 256)
2894                        s_hq_buf[i] = src[i];
2895                    /*
2896                    DPCT1118: SYCL group functions and algorithms must be
2897                    encountered in converged control flow. You may need to
2898                    adjust the code.
2899                    */
2900                    /*
2901                    DPCT1065: Consider replacing sycl::nd_item::barrier()
2902                    with
2903                    sycl::nd_item::barrier(sycl::access::fence_space::local_space)
2904                    for better performance if there is no access to global
2905                    memory.
2906                    */
2907                    item_ct1.barrier();
2908                    if (valid_r) {
2909                        if (n == 1) {
2910                            const int off1[1] = { 0 };
2911                            float s1[1];
2912                            row_dot_40_sub8<TD, 1, true>(wr, s_hq, off1, 1, t,
2913                                                         s1);
2914                            if (t == 0) out[(size_t) ent_dst[e] * L.n_embd + r] = s1[0];
2915                        } else if (n == 2) {
2916                            const int off2[2] = { 0, 20 };
2917                            float s2[2];
2918                            row_dot_40_sub8<TD, 2, true>(wr, s_hq, off2, 2, t,
2919                                                         s2);
2920                            if (t < 2) out[(size_t) ent_dst[e + t] * L.n_embd + r] = s2[t];
2921                        } else if (n == 3) {
2922                            const int off3[3] = { 0, 20, 40 };
2923                            float s3[3];
2924                            row_dot_40_sub8<TD, 3, true>(wr, s_hq, off3, 3, t,
2925                                                         s3);
2926                            if (t < 3) out[(size_t) ent_dst[e + t] * L.n_embd + r] = s3[t];
2927                        } else {
2928                            const int off4[4] = { 0, 20, 40, 60 };
2929                            float s4[4];
2930                            row_dot_40_sub8<TD, 4, true>(wr, s_hq, off4, 4, t,
2931                                                         s4);
2932                            if (t < 4) out[(size_t) ent_dst[e + t] * L.n_embd + r] = s4[t];
2933                        }
2934                    }
2935                }
2936            }
2937            return;
2938        }
2939    } else if constexpr (SUB_DOWN && TD == 42) {
2940        if (hb == 20) {
2941            const int r =
2942                item_ct1.get_group(2) * 16 + (item_ct1.get_local_id(2) >> 4);
2943            const int t = item_ct1.get_local_id(2) & 15;
2944            const bool valid_r = (r < L.n_embd);
2945            const size_t w_off = L.down_off + (size_t) (valid_r ? r : 0) * L.d_row;
2946            const block_q8_1* s_hq = reinterpret_cast<const block_q8_1*>(s_hq_buf);
2947            for (int g = item_ct1.get_group(1); g < ng;
2948                 g += item_ct1.get_group_range(1)) {
2949                const uint8_t* wr = (const uint8_t*) grp_ptr[g] + w_off;
2950                const int e0 = grp_start[g], e1 = grp_start[g + 1];
2951                for (int e = e0; e < e1; e += GRP_NC) {
2952                    const int n = sycl::min(GRP_NC, e1 - e);
2953                    const uint32_t* src = reinterpret_cast<const uint32_t*>(hq + (size_t) e * 20);
2954                    const int words = n * (20 * 9);
2955                    /*
2956                    DPCT1118: SYCL group functions and algorithms must be
2957                    encountered in converged control flow. You may need to
2958                    adjust the code.
2959                    */
2960                    /*
2961                    DPCT1065: Consider replacing sycl::nd_item::barrier()
2962                    with
2963                    sycl::nd_item::barrier(sycl::access::fence_space::local_space)
2964                    for better performance if there is no access to global
2965                    memory.
2966                    */
2967                    item_ct1.barrier();
2968#pragma unroll
2969                    for (int i = item_ct1.get_local_id(2); i < words; i += 256)
2970                        s_hq_buf[i] = src[i];
2971                    /*
2972                    DPCT1118: SYCL group functions and algorithms must be
2973                    encountered in converged control flow. You may need to
2974                    adjust the code.
2975                    */
2976                    /*
2977                    DPCT1065: Consider replacing sycl::nd_item::barrier()
2978                    with
2979                    sycl::nd_item::barrier(sycl::access::fence_space::local_space)
2980                    for better performance if there is no access to global
2981                    memory.
2982                    */
2983                    item_ct1.barrier();
2984                    if (valid_r) {
2985                        if (n == 1) {
2986                            const int off1[1] = { 0 };
2987                            float s1[1];
2988                            row_dot_20_sub16<TD, 1, true>(wr, s_hq, off1, 1, t, s1);
2989                            if (t == 0) out[(size_t) ent_dst[e] * L.n_embd + r] = s1[0];
2990                        } else if (n == 2) {
2991                            const int off2[2] = { 0, 20 };
2992                            float s2[2];
2993                            row_dot_20_sub16<TD, 2, true>(wr, s_hq, off2, 2, t, s2);
2994                            if (t < 2) out[(size_t) ent_dst[e + t] * L.n_embd + r] = s2[t];
2995                        } else if (n == 3) {
2996                            const int off3[3] = { 0, 20, 40 };
2997                            float s3[3];
2998                            row_dot_20_sub16<TD, 3, true>(wr, s_hq, off3, 3, t, s3);
2999                            if (t < 3) out[(size_t) ent_dst[e + t] * L.n_embd + r] = s3[t];
3000                        } else {
3001                            const int off4[4] = { 0, 20, 40, 60 };
3002                            float s4[4];
3003                            row_dot_20_sub16<TD, 4, true>(wr, s_hq, off4, 4, t, s4);
3004                            if (t < 4) out[(size_t) ent_dst[e + t] * L.n_embd + r] = s4[t];
3005                        }
3006                    }
3007                }
3008            }
3009            return;
3010        }
3011    }
3012    const int warp = item_ct1.get_local_id(2) >> 5,
3013              lane = item_ct1.get_local_id(2) & 31;
3014    const int r = item_ct1.get_group(2) * 8 + warp;
3015    const bool valid_r = (r < L.n_embd);
3016    const size_t w_off = L.down_off + (size_t) (valid_r ? r : 0) * L.d_row;
3017    for (int g = item_ct1.get_group(1); g < ng;
3018         g +=
3019         item_ct1.get_group_range(1)) { // the group stride, as native_gu_kernel
3020        const uint8_t* wr = (const uint8_t*) grp_ptr[g] + w_off;
3021        const int e0 = grp_start[g], e1 = grp_start[g + 1];
3022        if (hb == 20) {
3023            const block_q8_1* s_hq = reinterpret_cast<const block_q8_1*>(s_hq_buf);
3024            for (int e = e0; e < e1; e += GRP_NC) {
3025                const int n = sycl::min(GRP_NC, e1 - e);
3026                const uint32_t* src = reinterpret_cast<const uint32_t*>(hq + (size_t) e * 20);
3027                const int words = n * (20 * 9);
3028                /*
3029                DPCT1118: SYCL group functions and algorithms must be
3030                encountered in converged control flow. You may need to adjust
3031                the code.
3032                */
3033                /*
3034                DPCT1065: Consider replacing sycl::nd_item::barrier() with
3035                sycl::nd_item::barrier(sycl::access::fence_space::local_space)
3036                for better performance if there is no access to global memory.
3037                */
3038                item_ct1.barrier();
3039#pragma unroll
3040                for (int i = item_ct1.get_local_id(2); i < words; i += 256)
3041                    s_hq_buf[i] = src[i];
3042                /*
3043                DPCT1118: SYCL group functions and algorithms must be
3044                encountered in converged control flow. You may need to adjust
3045                the code.
3046                */
3047                /*
3048                DPCT1065: Consider replacing sycl::nd_item::barrier() with
3049                sycl::nd_item::barrier(sycl::access::fence_space::local_space)
3050                for better performance if there is no access to global memory.
3051                */
3052                item_ct1.barrier();
3053                if (valid_r) {
3054                    if (n == 1) {
3055                        const int off1[1] = { 0 };
3056                        float s1[1];
3057                        row_dot_multi<TD, 1, true>(wr, s_hq, off1, 1, nb, lane,
3058                                                   s1);
3059                        if (lane == 0) out[(size_t) ent_dst[e] * L.n_embd + r] = s1[0];
3060                    } else if (n == 2) {
3061                        const int off2[2] = { 0, 20 };
3062                        float s2[2];
3063                        row_dot_multi<TD, 2, true>(wr, s_hq, off2, 2, nb, lane,
3064                                                   s2);
3065                        if (lane < 2) out[(size_t) ent_dst[e + lane] * L.n_embd + r] = s2[lane];
3066                    } else {
3067                        int off[GRP_NC];
3068#pragma unroll
3069                        for (int c = 0; c < GRP_NC; ++c)
3070                            off[c] = sycl::min(c, n - 1) * 20;
3071                        float s[GRP_NC];
3072                        row_dot_multi<TD, GRP_NC>(wr, s_hq, off, n, nb, lane, s);
3073#pragma unroll
3074                        for (int c = 0; c < GRP_NC; ++c)
3075                            if (c < n && lane == c) out[(size_t) ent_dst[e + c] * L.n_embd + r] = s[c];
3076                    }
3077                }
3078            }
3079        } else if (valid_r) {
3080            for (int e = e0; e < e1; e += GRP_NC) {
3081                const int n = sycl::min(GRP_NC, e1 - e);
3082                int off[GRP_NC];
3083#pragma unroll
3084                for (int c = 0; c < GRP_NC; ++c)
3085                    off[c] = (e + sycl::min(c, n - 1)) * hb;
3086                float s[GRP_NC];
3087                row_dot_multi<TD, GRP_NC>(wr, hq, off, n, nb, lane, s);
3088#pragma unroll
3089                for (int c = 0; c < GRP_NC; ++c)
3090                    if (c < n && lane == c) out[(size_t) ent_dst[e + c] * L.n_embd + r] = s[c];
3091            }
3092        }
3093    }
3094}
3095
3096// ---------------------------------------------------------------- q8_1 (quantize.cu)
3097// value i of a q8_1 row set (the warp holds block i / 32, lane = i % 32)
3098__dpct_inline__ void q8_1_store(const float xi, block_q8_1 *__restrict__ y,
3099                                const long long i) {
3100    float amax = sycl::fabs(xi), sum = xi;
3101#pragma unroll
3102    for (int o = 16; o > 0; o >>= 1) {
3103        /*
3104        DPCT1108: '__shfl_xor_sync' was migrated with the experimental
3105        feature masked sub_group function which may not be supported by all
3106        compilers or runtimes. You may need to adjust the code.
3107        */
3108        amax = sycl::fmax(
3109            amax,
3110            dpct::experimental::permute_sub_group_by_xor(
3111                0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(),
3112                amax, o));
3113        /*
3114        DPCT1108: '__shfl_xor_sync' was migrated with the experimental
3115        feature masked sub_group function which may not be supported by all
3116        compilers or runtimes. You may need to adjust the code.
3117        */
3118        sum += dpct::experimental::permute_sub_group_by_xor(
3119            0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(),
3120            sum, o);
3121    }
3122    const float d = q8_1_finite(amax / 127.0f);   // #606: q8_1_finite.hpp - the same bits for every finite block
3123    const int8_t q = q8_1_quant(xi, d, amax);
3124    const long long ib = i / 32, iqs = i % 32;
3125    y[ib].qs[iqs] = q;
3126    if (iqs == 0) y[ib].ds = q8_1_ds(d, sum);
3127}
3128
3129__dpct_inline__ void quantize_q8_1_kernel(const float *__restrict__ x,
3130                                          block_q8_1 *__restrict__ y,
3131                                          long long n) {
3132    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
3133    const long long i =
3134        (long long)item_ct1.get_group(2) * item_ct1.get_local_range(2) +
3135        item_ct1.get_local_id(2);
3136    if (i >= n) return;
3137    q8_1_store(x[i], y, i);
3138}
3139
3140// swiglu_entries_kernel and quantize_q8_1_kernel in one pass, over the call's own entries only:
3141// [grp_start[0], grp_start[*n_groups]) (a call's entries are contiguous; the verify window's PCIe call starts after
3142// its VRAM call) instead of all cap_entries twice - nothing reads the others: the down kernel reads its groups'.
3143// n_ff is a multiple of 32, so a warp is one q8_1 block and the bounds are warp-uniform.  The values are the two
3144// kernels': the SwiGLU product is rounded on its own - it must not contract into the first add of q8_1_store's block
3145// sum, as it could not when it went through memory (CUDA: __fmul_rn; HIP's __fmul_rn is a plain product, so there
3146// the product is written here under contract(off)) - then q8_1_store unchanged: the same blocks, bit for bit.
3147__dpct_inline__ void swiglu_q8_1_entries_kernel(
3148    const float *__restrict__ gate, const float *__restrict__ up,
3149    const int32_t *__restrict__ grp_start, const int32_t *__restrict__ n_groups,
3150    int n_ff, block_q8_1 *__restrict__ hq) {
3151    // the product rounded on its own (no contraction into q8_1_store's block sum), as through memory in the v1 kernels
3152    // - HIP's form; icpx is clang too (SYCL port)
3153#pragma clang fp contract(off)
3154    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
3155    const long long lo = (long long)grp_start[0] * n_ff,
3156                    hi = (long long)grp_start[*n_groups] * n_ff;
3157    for (long long i =
3158             lo +
3159             (long long)item_ct1.get_group(2) * item_ct1.get_local_range(2) +
3160             item_ct1.get_local_id(2);
3161         i < hi; i += (long long)item_ct1.get_group_range(2) *
3162                      item_ct1.get_local_range(2)) {
3163        const float g = gate[i];
3164#if defined(__HIPCC__)
3165        const float h = (g / (1.0f + __expf(-g))) * up[i];
3166#else
3167        /*
3168        DPCT1013: The rounding mode could not be specified and the generated
3169        code may have different accuracy than the original code. Verify the
3170        correctness. SYCL math built-in function rounding mode is aligned with
3171        OpenCL C 1.2 standard.
3172        */
3173        const float h = (g / (1.0f + sycl::native::exp(-g))) * up[i];
3174#endif
3175        q8_1_store(h, hq, i);
3176    }
3177}
3178
3179// ---------------------------------------------------------------- dequant (dequantize.cuh)
3180template <typename dst_t> __dpct_inline__ dst_t cvt(float v);
3181template <> __dpct_inline__ float cvt<float>(float v) { return v; }
3182template <>
3183__dpct_inline__ sycl::half cvt<sycl::half>(float v) {
3184    return sycl::vec<float, 1>(v)
3185        .convert<sycl::half, sycl::rounding_mode::automatic>()[0];
3186}
3187
3188// SYCL port: the dequant functions below wrote one 2-byte value at a time (dq_* = llama.cpp's per-thread loops); on Xe
3189// the FP16 expert dequant ran at ~80 GB/s of writes, 40% of the prompt path. Each thread's run of values goes out as one
3190// vector store instead (the offsets are multiples of the run length, so the stores are aligned).
3191template <typename dst_t, int N>
3192__dpct_inline__ void store_run(dst_t* y, const float* v) {
3193    if constexpr (std::is_same_v<dst_t, sycl::half> && (N == 4 || N == 8)) {
3194        sycl::vec<sycl::half, N> h;
3195#pragma unroll
3196        for (int j = 0; j < N; ++j) h[j] = sycl::half(v[j]);
3197        *reinterpret_cast<sycl::vec<sycl::half, N>*>(y) = h;
3198    } else {
3199#pragma unroll
3200        for (int j = 0; j < N; ++j) y[j] = cvt<dst_t>(v[j]);
3201    }
3202}
3203template <typename dst_t>
3204inline void dq_iq2_xxs(const void *vx, int64_t ibs, dst_t *yy, int tid) {
3205    const block_iq2_xxs* x = (const block_iq2_xxs*) vx;
3206    const int64_t il = tid % 4, ib = tid / 4;   // consecutive lanes write consecutive 16-byte runs (coalesced stores)
3207    dst_t* y = yy + 32 * ib + 8 * il;
3208    const uint16_t* q2 = x[ibs].qs + 4 * ib;
3209    const uint8_t* aux8 = (const uint8_t*) q2;
3210    const uint8_t* grid = (const uint8_t*) (iq2xxs_grid + aux8[il]);
3211    const uint32_t aux32 = q2[2] | (q2[3] << 16);
3212    const float d = (float) x[ibs].d * (0.5f + (aux32 >> 28)) * 0.25f;
3213    const uint8_t signs = ksigns_iq2xs[(aux32 >> 7 * il) & 127];
3214    float v[8];
3215#pragma unroll
3216    for (int j = 0; j < 8; ++j) v[j] = d * grid[j] * (signs & kmask_iq2xs[j] ? -1.f : 1.f);
3217    store_run<dst_t, 8>(y, v);
3218}
3219template <typename dst_t>
3220inline void dq_iq2_xxs_metadata(const void *vx, int64_t ibs, dst_t *yy, int tid, sycl::sub_group sg) {
3221    const block_iq2_xxs* x = (const block_iq2_xxs*) vx;
3222    const int64_t il = tid / 8, ib = tid % 8;
3223    dst_t* y = yy + 32 * ib + 8 * il;
3224    const uint16_t* q2 = x[ibs].qs + 4 * ib;
3225    const uint8_t* aux8 = (const uint8_t*) q2;
3226    const uint8_t* grid = (const uint8_t*) (iq2xxs_grid + aux8[il]);
3227    const uint32_t lane = sg.get_local_linear_id();
3228    uint32_t aux32 = 0;
3229    if((lane & 3u) == 0u) aux32 = q2[2] | (q2[3] << 16);
3230    aux32 = sycl::select_from_group(sg, aux32, lane & ~3u);
3231    const float d = (float) x[ibs].d * (0.5f + (aux32 >> 28)) * 0.25f;
3232    const uint8_t signs = ksigns_iq2xs[(aux32 >> 7 * il) & 127];
3233    float v[8];
3234#pragma unroll
3235    for (int j = 0; j < 8; ++j) v[j] = d * grid[j] * (signs & kmask_iq2xs[j] ? -1.f : 1.f);
3236    store_run<dst_t, 8>(y, v);
3237}
3238template <typename dst_t>
3239inline void dq_iq2_xs(const void *vx, int64_t ibs, dst_t *yy, int tid) {
3240    const block_iq2_xs* x = (const block_iq2_xs*) vx;
3241    const int64_t il = tid % 4, ib = tid / 4;   // consecutive lanes write consecutive 16-byte runs (coalesced stores)
3242    dst_t* y = yy + 32 * ib + 8 * il;
3243    const uint16_t* q2 = x[ibs].qs + 4 * ib;
3244    const uint8_t* grid = (const uint8_t*) (iq2xs_grid + (q2[il] & 511));
3245    const float d = (float) x[ibs].d * (0.5f + ((x[ibs].scales[ib] >> 4 * (il / 2)) & 0xf)) * 0.25f;
3246    const uint8_t signs = ksigns_iq2xs[q2[il] >> 9];
3247    float v[8];
3248#pragma unroll
3249    for (int j = 0; j < 8; ++j) v[j] = d * grid[j] * (signs & kmask_iq2xs[j] ? -1.f : 1.f);
3250    store_run<dst_t, 8>(y, v);
3251}
3252template <typename dst_t>
3253inline void dq_iq2_s(const void *vx, int64_t ibs, dst_t *yy, int tid) {
3254    const block_iq2_s* x = (const block_iq2_s*) vx;
3255    const int64_t il = tid % 4, ib = tid / 4;   // consecutive lanes write consecutive 16-byte runs (coalesced stores)
3256    dst_t* y = yy + 32 * ib + 8 * il;
3257    const uint8_t* grid = (const uint8_t*) (iq2s_grid + (x[ibs].qs[4 * ib + il] | ((x[ibs].qh[ib] << (8 - 2 * il)) & 0x300)));
3258    const float d = (float) x[ibs].d * (0.5f + ((x[ibs].scales[ib] >> 4 * (il / 2)) & 0xf)) * 0.25f;
3259    const uint8_t signs = x[ibs].qs[QK_K / 8 + 4 * ib + il];
3260    float v[8];
3261#pragma unroll
3262    for (int j = 0; j < 8; ++j) v[j] = d * grid[j] * (signs & kmask_iq2xs[j] ? -1.f : 1.f);
3263    store_run<dst_t, 8>(y, v);
3264}
3265template <typename dst_t>
3266inline void dq_iq3_xxs(const void *vx, int64_t ibs, dst_t *yy, int tid) {
3267    const block_iq3_xxs* x = (const block_iq3_xxs*) vx;
3268    const int64_t il = tid % 4, ib = tid / 4;   // consecutive lanes write consecutive 16-byte runs (coalesced stores)
3269    dst_t* y = yy + 32 * ib + 8 * il;
3270    const uint8_t* q3 = x[ibs].qs + 8 * ib;
3271    const uint16_t* gas = (const uint16_t*) (x[ibs].qs + QK_K / 4) + 2 * ib;
3272    const uint8_t* grid1 = (const uint8_t*) (iq3xxs_grid + q3[2 * il + 0]);
3273    const uint8_t* grid2 = (const uint8_t*) (iq3xxs_grid + q3[2 * il + 1]);
3274    const uint32_t aux32 = gas[0] | (gas[1] << 16);
3275    const float d = (float) x[ibs].d * (0.5f + (aux32 >> 28)) * 0.5f;
3276    const uint8_t signs = ksigns_iq2xs[(aux32 >> 7 * il) & 127];
3277    float v[8];
3278#pragma unroll
3279    for (int j = 0; j < 4; ++j) {
3280        v[j + 0] = d * grid1[j] * (signs & kmask_iq2xs[j + 0] ? -1.f : 1.f);
3281        v[j + 4] = d * grid2[j] * (signs & kmask_iq2xs[j + 4] ? -1.f : 1.f);
3282    }
3283    store_run<dst_t, 8>(y, v);
3284}
3285template <typename dst_t>
3286inline void dq_iq3_s(const void *vx, int64_t ibs, dst_t *yy, int tid) {
3287    const block_iq3_s* x = (const block_iq3_s*) vx;
3288    const int64_t il = tid % 4, ib = tid / 4;   // consecutive lanes write consecutive 16-byte runs (coalesced stores)
3289    dst_t* y = yy + 32 * ib + 8 * il;
3290    const uint8_t* qs = x[ibs].qs + 8 * ib;
3291    const uint8_t* grid1 = (const uint8_t*) (iq3s_grid + (qs[2 * il + 0] | ((x[ibs].qh[ib] << (8 - 2 * il)) & 256)));
3292    const uint8_t* grid2 = (const uint8_t*) (iq3s_grid + (qs[2 * il + 1] | ((x[ibs].qh[ib] << (7 - 2 * il)) & 256)));
3293    const float d = (float) x[ibs].d * (1 + 2 * ((x[ibs].scales[ib / 2] >> 4 * (ib % 2)) & 0xf));
3294    const uint8_t signs = x[ibs].signs[4 * ib + il];
3295    float v[8];
3296#pragma unroll
3297    for (int j = 0; j < 4; ++j) {
3298        v[j + 0] = d * grid1[j] * (signs & kmask_iq2xs[j + 0] ? -1.f : 1.f);
3299        v[j + 4] = d * grid2[j] * (signs & kmask_iq2xs[j + 4] ? -1.f : 1.f);
3300    }
3301    store_run<dst_t, 8>(y, v);
3302}
3303template <typename dst_t>
3304inline void dq_iq1_m(const void *vx, int64_t ibs, dst_t *yy, int tid) {
3305    const block_iq1_m* x = (const block_iq1_m*) vx;
3306    const int64_t il = tid % 4, ib = tid / 4;   // consecutive lanes write consecutive 16-byte runs (coalesced stores)
3307    dst_t* y = yy + 32 * ib + 8 * il;
3308    const uint16_t* sc = (const uint16_t*) x[ibs].scales;
3309    iq1m_scale_t scale;
3310    scale.u16 = (sc[0] >> 12) | ((sc[1] >> 8) & 0x00f0) | ((sc[2] >> 4) & 0x0f00) | (sc[3] & 0xf000);
3311    const int64_t ib16 = 2 * ib + il / 2;
3312    const float d = (float) scale.f16 * (2 * ((sc[ib16 / 4] >> 3 * (ib16 % 4)) & 0x7) + 1);
3313    const float delta = x[ibs].qh[2 * ib + il / 2] & (0x08 << 4 * (il % 2)) ? -1 - IQ1M_DELTA : -1 + IQ1M_DELTA;
3314    uint32_t grid32[2];
3315    const int8_t* q = (const int8_t*) grid32;
3316    grid32[0] = iq1s_grid_gpu[x[ibs].qs[4 * ib + il] | (((x[ibs].qh[2 * ib + il / 2] >> 4 * (il % 2)) & 7) << 8)];
3317    grid32[1] = (grid32[0] >> 4) & 0x0f0f0f0f;
3318    grid32[0] &= 0x0f0f0f0f;
3319#pragma unroll
3320    for (int j = 0; j < 8; ++j) y[j] = cvt<dst_t>(d * (q[j] + delta));
3321}
3322template <typename dst_t>
3323inline void dq_iq4_nl(const void *vx, int64_t ibs, dst_t *yy, int tid) {
3324    const block_iq4_nl* x = (const block_iq4_nl*) vx + ibs * (QK_K / QK4_NL);
3325    // SYCL port: thread (ib, il) writes the block's values [8 il, 8 il + 8) as one run: il < 2 the low nibbles of
3326    // qs[8 il ..], il >= 2 the high nibbles of qs[8 (il - 2) ..] (the same values as llama.cpp's 4 + 4 split)
3327    const int64_t il = tid % 4, ib = tid / 4;   // consecutive lanes write consecutive 16-byte runs (coalesced stores)
3328    dst_t* y = yy + 32 * ib + 8 * il;
3329    const uint8_t* q4 = x[ib].qs + 8 * (il & 1);
3330    const float d = (float) x[ib].d;
3331    float v[8];
3332    if (il < 2) {
3333#pragma unroll
3334        for (int j = 0; j < 8; ++j) v[j] = d * kvalues_iq4nl[q4[j] & 0xf];
3335    } else {
3336#pragma unroll
3337        for (int j = 0; j < 8; ++j) v[j] = d * kvalues_iq4nl[q4[j] >> 4];
3338    }
3339    store_run<dst_t, 8>(y, v);
3340}
3341// Q3_K (the Q2_0 file's token_embd): llama.cpp's dequantize_block_q3_K, its 64 threads folded onto 32
3342template <typename dst_t>
3343inline void dq_q3_k(const void *vx, int64_t ibs, dst_t *yy, int tid) {
3344    const block_q3_K* x = (const block_q3_K*) vx + ibs;
3345    for (int tt = tid; tt < 64; tt += 32) {
3346        const int r = tt / 4, t2 = r / 2, is0 = r % 2;
3347        const int l0 = 16 * is0 + 4 * (tt % 4);
3348        const int n = t2 / 4, j = t2 - 4 * n;
3349        const uint8_t m = (uint8_t) (1 << (4 * n + j));
3350        const int is = 8 * n + 2 * j + is0;
3351        const int shift = 2 * j;
3352        const int8_t us = is < 4  ? (int8_t) ((x->scales[is - 0] & 0xF) | (((x->scales[is + 8] >> 0) & 3) << 4)) :
3353                          is < 8  ? (int8_t) ((x->scales[is - 0] & 0xF) | (((x->scales[is + 4] >> 2) & 3) << 4)) :
3354                          is < 12 ? (int8_t) ((x->scales[is - 8] >> 4) | (((x->scales[is + 0] >> 4) & 3) << 4)) :
3355                                    (int8_t) ((x->scales[is - 8] >> 4) | (((x->scales[is - 4] >> 6) & 3) << 4));
3356        const float dl = (float) x->d * (us - 32);
3357        dst_t* y = yy + 128 * n + 32 * j;
3358        const uint8_t* q = x->qs + 32 * n;
3359        const uint8_t* hm = x->hmask;
3360#pragma unroll
3361        for (int l = l0; l < l0 + 4; ++l) y[l] = cvt<dst_t>(
3362            dl * ((int8_t)((q[l] >> shift) & 3) - ((hm[l] & m) ? 0 : 4)));
3363    }
3364}
3365template <typename dst_t>
3366inline void dq_iq4_xs(const void *vx, int64_t ibs, dst_t *yy, int tid) {
3367    const block_iq4_xs* x = (const block_iq4_xs*) vx + ibs;
3368    const int il = tid / 8, ib = tid % 8;
3369    dst_t* y = yy + 32 * ib + 4 * il;
3370    const uint8_t* q4 = x->qs + 16 * ib + 4 * il;
3371    const float d = (float) x->d * ((((x->scales_l[ib / 2] >> 4 * (ib % 2)) & 0xf) | (((x->scales_h >> 2 * ib) & 3) << 4)) - 32);
3372    float lo[4], hi[4];
3373#pragma unroll
3374    for (int j = 0; j < 4; ++j) {
3375        lo[j] = d * kvalues_iq4nl[q4[j] & 0xf];
3376        hi[j] = d * kvalues_iq4nl[q4[j] >> 4];
3377    }
3378    store_run<dst_t, 4>(y, lo);
3379    store_run<dst_t, 4>(y + 16, hi);
3380}
3381template <typename dst_t>
3382inline void dq_q2_0(const void *vx, int64_t ibs, dst_t *yy, int tid) {
3383    // one "superblock" = 256 values = 4 blocks of 64; thread tid writes 8 values
3384    const block_q2_0* x = (const block_q2_0*) vx + ibs * 4;
3385    const int b = tid / 8, part = tid % 8;          // block 0..3, 8 values each
3386    const float d = (float) x[b].d;
3387    float v[8];
3388#pragma unroll
3389    for (int j = 0; j < 8; ++j) {
3390        const int i = part * 8 + j;
3391        const int code = (x[b].qs[i / 4] >> ((i % 4) * 2)) & 3;
3392        v[j] = d * (float) (code - 1);
3393    }
3394    store_run<dst_t, 8>(yy + b * 64 + part * 8, v);
3395}
3396
3397// llama.cpp's dequantize_q4_K / dequantize_q5_K (dequantize.cuh; q5_K's 64 threads folded onto 32) and the 32-value
3398// blocks of Q5_1 / Q8_0, 8 of them per 256-value "superblock" (thread tid writes 8 values of block tid / 4; it was block
3399// tid % 8, which scattered a sub-group's 2-byte stores 64 bytes apart: B70 Q5_1 / Q8_0 at 88-93 GB/s of FP16 against 250+).
3400__dpct_inline__ void get_scale_min_k4(int j, const uint8_t *q, uint8_t &d,
3401                                      uint8_t &m) {
3402    if (j < 4) {
3403        d = q[j] & 63; m = q[j + 4] & 63;
3404    } else {
3405        d = (q[j + 4] & 0xF) | ((q[j - 4] >> 6) << 4);
3406        m = (q[j + 4] >> 4) | ((q[j - 0] >> 6) << 4);
3407    }
3408}
3409template <typename dst_t>
3410inline void dq_q4_k(const void *vx, int64_t ibs, dst_t *yy, int tid) {
3411    const block_q4_K* x = (const block_q4_K*) vx;
3412    const int64_t il = tid / 8, ir = tid % 8, is = 2 * il;
3413    const int n = 4;
3414    dst_t* y = yy + 64 * il + n * ir;
3415    const float dall = x[ibs].dm[0];
3416    const float dmin = x[ibs].dm[1];
3417    const uint8_t* q = x[ibs].qs + 32 * il + n * ir;
3418    uint8_t sc, m;
3419    get_scale_min_k4((int) is + 0, x[ibs].scales, sc, m);
3420    const float d1 = dall * sc, m1 = dmin * m;
3421    get_scale_min_k4((int) is + 1, x[ibs].scales, sc, m);
3422    const float d2 = dall * sc, m2 = dmin * m;
3423#pragma unroll
3424    for (int l = 0; l < n; ++l) {
3425        y[l + 0] = cvt<dst_t>(d1 * (q[l] & 0xF) - m1);
3426        y[l + 32] = cvt<dst_t>(d2 * (q[l] >> 4) - m2);
3427    }
3428}
3429template <typename dst_t>
3430inline void dq_q5_k(const void *vx, int64_t ibs, dst_t *yy, int tid) {
3431    const block_q5_K* x = (const block_q5_K*) vx;
3432    for (int tt = tid; tt < 64; tt += 32) {
3433        const int il = tt / 16, ir = tt % 16, is = 2 * il;
3434        dst_t* y = yy + 64 * il + 2 * ir;
3435        const float dall = x[ibs].dm[0];
3436        const float dmin = x[ibs].dm[1];
3437        const uint8_t* ql = x[ibs].qs + 32 * il + 2 * ir;
3438        const uint8_t* qh = x[ibs].qh + 2 * ir;
3439        uint8_t sc, m;
3440        get_scale_min_k4(is + 0, x[ibs].scales, sc, m);
3441        const float d1 = dall * sc, m1 = dmin * m;
3442        get_scale_min_k4(is + 1, x[ibs].scales, sc, m);
3443        const float d2 = dall * sc, m2 = dmin * m;
3444        uint8_t hm = (uint8_t) (1 << (2 * il));
3445        y[0] = cvt<dst_t>(d1 * ((ql[0] & 0xF) + (qh[0] & hm ? 16 : 0)) - m1);
3446        y[1] = cvt<dst_t>(d1 * ((ql[1] & 0xF) + (qh[1] & hm ? 16 : 0)) - m1);
3447        hm <<= 1;
3448        y[32] = cvt<dst_t>(d2 * ((ql[0] >> 4) + (qh[0] & hm ? 16 : 0)) - m2);
3449        y[33] = cvt<dst_t>(d2 * ((ql[1] >> 4) + (qh[1] & hm ? 16 : 0)) - m2);
3450    }
3451}
3452template <typename dst_t>
3453inline void dq_q5_0(const void *vx, int64_t ibs, dst_t *yy, int tid) {
3454    // symmetric: one delta (no min), the high bit folded in then centered by the format's fixed -16 offset
3455    const block_q5_0* x = (const block_q5_0*) vx + ibs * (QK_K / QK5_0);
3456    const int ib = tid / 4, il = tid % 4;   // lanes 4b..4b+3 write block b: neighbouring lanes, neighbouring values
3457    const float d = sycl::vec<sycl::half, 1>(x[ib].d)
3458                        .convert<float, sycl::rounding_mode::automatic>()[0];
3459    uint32_t qh;
3460    memcpy(&qh, x[ib].qh, sizeof(qh));
3461    dst_t* y = yy + 32 * ib;
3462    float v0[4], v1[4];
3463#pragma unroll
3464    for (int j = 0; j < 4; ++j) {
3465        const int iqs = 4 * il + j;
3466        const int xh_0 = ((qh >> (iqs + 0)) << 4) & 0x10;
3467        const int xh_1 = ((qh >> (iqs + 12))) & 0x10;
3468        v0[j] = ((float) ((x[ib].qs[iqs] & 0xf) | xh_0) - 16.0f) * d;
3469        v1[j] = ((float) ((x[ib].qs[iqs] >> 4) | xh_1) - 16.0f) * d;
3470    }
3471    store_run<dst_t, 4>(y + 4 * il, v0);
3472    store_run<dst_t, 4>(y + 16 + 4 * il, v1);
3473}
3474template <typename dst_t>
3475inline void dq_q4_0(const void *vx, int64_t ibs, dst_t *yy, int tid) {
3476    const block_q4_0* x = (const block_q4_0*) vx + ibs * (QK_K / QK4_0);
3477    const int ib = tid / 4, il = tid % 4;   // lanes 4b..4b+3 write block b: neighbouring lanes, neighbouring values
3478    const float d = sycl::vec<sycl::half, 1>(x[ib].d)
3479                        .convert<float, sycl::rounding_mode::automatic>()[0];
3480    dst_t* y = yy + 32 * ib;
3481    float v0[4], v1[4];
3482#pragma unroll
3483    for (int j = 0; j < 4; ++j) {
3484        const int iqs = 4 * il + j;                   // llama.cpp's dequantize_q4_0 for value pairs iqs, iqs + 16
3485        v0[j] = ((float) (x[ib].qs[iqs] & 0xf) - 8.0f) * d;
3486        v1[j] = ((float) (x[ib].qs[iqs] >> 4) - 8.0f) * d;
3487    }
3488    store_run<dst_t, 4>(y + 4 * il, v0);
3489    store_run<dst_t, 4>(y + 16 + 4 * il, v1);
3490}
3491template <typename dst_t>
3492inline void dq_q4_1(const void *vx, int64_t ibs, dst_t *yy, int tid) {
3493    const block_q4_1* x = (const block_q4_1*) vx + ibs * (QK_K / QK4_1);
3494    const int ib = tid / 4, il = tid % 4;   // lanes 4b..4b+3 write block b: neighbouring lanes, neighbouring values
3495    const sycl::float2 dm =
3496        (x[ib].dm).template convert<float, sycl::rounding_mode::automatic>();
3497    dst_t* y = yy + 32 * ib;
3498    float v0[4], v1[4];
3499#pragma unroll
3500    for (int j = 0; j < 4; ++j) {
3501        const int iqs = 4 * il + j;                   // llama.cpp's dequantize_q4_1 for value pairs iqs, iqs + 16
3502        v0[j] = (float)(x[ib].qs[iqs] & 0xf) * dm.x() + dm.y();
3503        v1[j] = (float)(x[ib].qs[iqs] >> 4) * dm.x() + dm.y();
3504    }
3505    store_run<dst_t, 4>(y + 4 * il, v0);
3506    store_run<dst_t, 4>(y + 16 + 4 * il, v1);
3507}
3508template <typename dst_t>
3509inline void dq_q5_1(const void *vx, int64_t ibs, dst_t *yy, int tid) {
3510    const block_q5_1* x = (const block_q5_1*) vx + ibs * (QK_K / QK5_1);
3511    const int ib = tid / 4, il = tid % 4;   // lanes 4b..4b+3 write block b: neighbouring lanes, neighbouring values
3512    const sycl::float2 dm =
3513        (x[ib].dm).template convert<float, sycl::rounding_mode::automatic>();
3514    uint32_t qh;
3515    memcpy(&qh, x[ib].qh, sizeof(qh));
3516    dst_t* y = yy + 32 * ib;
3517    float v0[4], v1[4];
3518#pragma unroll
3519    for (int j = 0; j < 4; ++j) {
3520        const int iqs = 4 * il + j;                   // llama.cpp's dequantize_q5_1 for value pairs iqs, iqs + 16
3521        const int xh_0 = ((qh >> (iqs + 0)) << 4) & 0x10;
3522        const int xh_1 = ((qh >> (iqs + 12))) & 0x10;
3523        v0[j] = (float)((x[ib].qs[iqs] & 0xf) | xh_0) * dm.x() + dm.y();
3524        v1[j] = (float)((x[ib].qs[iqs] >> 4) | xh_1) * dm.x() + dm.y();
3525    }
3526    store_run<dst_t, 4>(y + 4 * il, v0);
3527    store_run<dst_t, 4>(y + 16 + 4 * il, v1);
3528}
3529template<typename dst_t>
3530void dq_q6_k(const void* vx, int64_t ibs, dst_t* yy, int tid) {
3531    // llama.cpp's dequantize_q6_K (dequantize.cuh, written for 64 threads) folded onto the kernel's 32: each of the
3532    // 64 thread roles runs at tid and tid + 32.
3533    const block_q6_K* x = (const block_q6_K*) vx;
3534    for (int tt = tid; tt < 64; tt += 32) {
3535        const int64_t ip = tt / 32;                 // 0 or 1
3536        const int64_t il = tt - 32 * ip;            // 0...31
3537        const int64_t is = 8 * ip + il / 16;
3538        dst_t* y = yy + 128 * ip + il;
3539        const float d =
3540            sycl::vec<sycl::half, 1>(x[ibs].d)
3541                .convert<float, sycl::rounding_mode::automatic>()[0];
3542        const uint8_t* ql = x[ibs].ql + 64 * ip + il;
3543        const uint8_t qh = x[ibs].qh[32 * ip + il];
3544        const int8_t* sc = x[ibs].scales + is;
3545        y[0]  = cvt<dst_t>(d * sc[0] * ((int8_t) ((ql[0]  & 0xF) | (((qh >> 0) & 3) << 4)) - 32));
3546        y[32] = cvt<dst_t>(d * sc[2] * ((int8_t) ((ql[32] & 0xF) | (((qh >> 2) & 3) << 4)) - 32));
3547        y[64] = cvt<dst_t>(d * sc[4] * ((int8_t) ((ql[0]  >> 4) | (((qh >> 4) & 3) << 4)) - 32));
3548        y[96] = cvt<dst_t>(d * sc[6] * ((int8_t) ((ql[32] >> 4) | (((qh >> 6) & 3) << 4)) - 32));
3549    }
3550}
3551template <typename dst_t>
3552inline void dq_q8_0(const void *vx, int64_t ibs, dst_t *yy, int tid) {
3553    const block_q8_0* x = (const block_q8_0*) vx + ibs * (QK_K / QK8_0);
3554    const int ib = tid / 4, il = tid % 4;   // lanes 4b..4b+3 write block b: neighbouring lanes, neighbouring values
3555    const float d = sycl::vec<sycl::half, 1>(x[ib].d)
3556                        .convert<float, sycl::rounding_mode::automatic>()[0];
3557    dst_t* y = yy + 32 * ib + 8 * il;
3558    float v[8];
3559#pragma unroll
3560    for (int j = 0; j < 8; ++j) v[j] = (float)x[ib].qs[8 * il + j] * d;
3561    store_run<dst_t, 8>(y, v);
3562}
3563
3564// BF16 (the token embedding as the checkpoint ships it, tools/embd_bf16_pack.py): 8 values per thread.
3565template <typename dst_t>
3566inline void dq_bf16(const void *vx, int64_t ibs, dst_t *yy, int tid) {
3567    const uint16_t* x = (const uint16_t*) vx + ibs * 256 + tid * 8;
3568#pragma unroll
3569    for (int j = 0; j < 8; ++j) yy[tid * 8 + j] =
3570        cvt<dst_t>(sycl::bit_cast<float>((uint32_t)x[j] << 16));
3571}
3572
3573// APR trellis types: one 256-value call = two 128-blocks; thread tid decodes block tid/16, lane (tid/2)%8, steps
3574// 2(tid%2)..2(tid%2)+1 (8 values)
3575template <int TY, typename dst_t>
3576inline void dq_tq(const void *vx, int64_t ibs, dst_t *yy, int tid) {
3577    const int blk = tid >> 4, l = (tid >> 1) & 7, half = tid & 1;
3578    const auto* b = (const typename TqInfo<TY>::block_t*) vx + 2 * ibs + blk;
3579    const float d = tq_h2f(b->d);
3580    uint32_t s[4];
3581    tq_states4<TY>(b->qs, l, s);
3582    dst_t* y = yy + blk * 128 + 16 * l + 8 * half;
3583    float v[8];
3584#pragma unroll
3585    for (int i = 0; i < 2; ++i) {
3586        float w[4];
3587        tq_step(s[2 * half + i], w);
3588        v[4 * i + 0] = d * w[0];
3589        v[4 * i + 1] = d * w[1];
3590        v[4 * i + 2] = d * w[2];
3591        v[4 * i + 3] = d * w[3];
3592    }
3593    store_run<dst_t, 8>(y, v);
3594}
3595
3596// Every type below must also be in is_iq() (BF16: embed_type_supported): the host entry points refuse the others,
3597// so the default is unreachable.
3598template <typename dst_t>
3599__dpct_inline__ void
3600dq_dispatch(int ty, const void *vx, int64_t ibs, dst_t *y, int tid) {
3601    switch (ty) {
3602        case 16: dq_iq2_xxs(vx, ibs, y, tid);
3603            break;
3604        case 17: dq_iq2_xs(vx, ibs, y, tid);
3605            break;
3606        case 18: dq_iq3_xxs(vx, ibs, y, tid);
3607            break;
3608        case 20: dq_iq4_nl(vx, ibs, y, tid); break;
3609        case 21: dq_iq3_s(vx, ibs, y, tid); break;
3610        case 22: dq_iq2_s(vx, ibs, y, tid); break;
3611        case 29: dq_iq1_m(vx, ibs, y, tid); break;
3612        case 23: dq_iq4_xs(vx, ibs, y, tid); break;
3613        case 11: dq_q3_k(vx, ibs, y, tid); break;
3614        case 42: dq_q2_0(vx, ibs, y, tid); break;
3615        case 12: dq_q4_k(vx, ibs, y, tid); break;
3616        case 13: dq_q5_k(vx, ibs, y, tid); break;
3617#ifdef STRATA_Q6K_EXPERTS
3618        case 14: dq_q6_k(vx, ibs, y, tid); break;
3619#endif
3620        case 7: dq_q5_1(vx, ibs, y, tid); break;
3621        case 6: dq_q5_0(vx, ibs, y, tid); break;
3622        case 2: dq_q4_0(vx, ibs, y, tid); break;
3623        case 3: dq_q4_1(vx, ibs, y, tid); break;
3624        case 8: dq_q8_0(vx, ibs, y, tid); break;
3625        case 30: dq_bf16(vx, ibs, y, tid); break;
3626        case 144: dq_tq<144>(vx, ibs, y, tid); break;
3627        case 145: dq_tq<145>(vx, ibs, y, tid); break;
3628        case 146: dq_tq<146>(vx, ibs, y, tid); break;
3629        default: break;
3630    }
3631}
3632
3633// flat: superblock i -> y + 256 i
3634template <typename dst_t>
3635__dpct_inline__ void dequant_flat_kernel(
3636    int ty, const void *__restrict__ vx, dst_t *__restrict__ y) {
3637    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
3638    const int64_t i = item_ct1.get_group(2);
3639    dq_dispatch<dst_t>(ty, vx, i, y + i * QK_K, item_ct1.get_local_id(2));
3640}
3641// gate/up: superblock i of a role matrix (n_embd/256 per row) -> interleaved row 2r + parity
3642__dpct_inline__ void dequant_gu_kernel(
3643    int ty, const void *__restrict__ gate, const void *__restrict__ up,
3644    int64_t per_row, sycl::half *__restrict__ y) {
3645    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
3646    const int64_t i = item_ct1.get_group(2);
3647    const int parity = item_ct1.get_group(1);
3648    const int64_t r = i / per_row, c = i % per_row;
3649    dq_dispatch<sycl::half>(ty, parity ? up : gate, i,
3650                            y + ((2 * r + parity) * per_row + c) * QK_K,
3651                            item_ct1.get_local_id(2));
3652}
3653
3654// the types dq_dispatch dequantizes
3655bool is_iq(int t) {
3656    return t == 144 || t == 145 || t == 146 || t == 16 || t == 17 || t == 18 || t == 20 || t == 21 || t == 22 || t == 23 || t == 29 || t == 42 || t == 11 ||
3657#ifdef STRATA_Q6K_EXPERTS
3658           t == 12 || t == 13 || t == 14 || t == 7 || t == 6 || t == 2 || t == 3 || t == 8;
3659#else
3660           t == 12 || t == 13 || t == 7 || t == 6 || t == 2 || t == 3 || t == 8;
3661#endif
3662}
3663// values per block of the types the grouped expert kernels take (0 = none)
3664int gu_qk(int t) {
3665    switch (t) {
3666#define STRATA_QK(T) case T: return Fmt<T>::qk;
3667        STRATA_GU_FMTS(STRATA_QK)
3668#undef STRATA_QK
3669        default: return 0;
3670    }
3671}
3672int d_qk(int t) {
3673    switch (t) {
3674#define STRATA_QK(T) case T: return Fmt<T>::qk;
3675        STRATA_D_FMTS(STRATA_QK)
3676#undef STRATA_QK
3677        default: return 0;
3678    }
3679}
3680bool gu_split(int t) {
3681    switch (t) {
3682#define STRATA_SP(T) case T: return kSplit<T>;
3683        STRATA_GU_FMTS(STRATA_SP)
3684#undef STRATA_SP
3685        default: return false;
3686    }
3687}
3688
3689bool env_on(const char* name) {
3690    const char* v = std::getenv(name);
3691    return v != nullptr && v[0] != '\0' && v[0] != '0';
3692}
3693// STRATA_OLD_IQ_MMVQ=1 keeps the per-column kernels (bitwise equal to the new ones; kept for A/B timing)
3694bool g_old_kernels = env_on("STRATA_OLD_IQ_MMVQ");
3695// SYCL port (0.1.31 merge): upstream sends the split formats (the i-quants) to native_gu/down_multi_kernel, one warp
3696// per row, 8 rows a group. On the B70 the port's grouped kernels (8 lanes a row, 32 rows a group, the multi-entry
3697// dots with aligned loads and the IQ4 codebook in registers) are the measured ones, so they stay the default for
3698// every format; STRATA_EXPERT_SPLIT=1 takes upstream's multi kernels, launched with their own grid (GU_ROWS rows).
3699bool g_split_multi = env_on("STRATA_EXPERT_SPLIT");
3700bool g_no_sub16_gu = env_on("STRATA_NO_SUB16_GU");
3701
3702// Keep the original decoder for diagnosis and for devices outside Battlemage.
3703// Cache by the actual SYCL device, not a process-wide first-device decision.
3704bool q2_word_expand_enabled(const sycl::device& device) {
3705    static const bool enabled = [] {
3706        const char* v = std::getenv("STRATA_SYCL_Q2_WORD_EXPAND");
3707        return !(v && v[0] == '0');
3708    }();
3709    if (!enabled) return false;
3710    thread_local std::optional<std::pair<sycl::device, bool>> cached;
3711    if (!cached || cached->first != device)
3712        cached.emplace(device, strata::intel_gpu_gen(device) == strata::IntelGpuGen::Battlemage);
3713    return cached->second;
3714}
3715
3716// PR #4185 controls: six are on by default for a Battlemage device (strata::bm_default_on), the rest are opt-in (measured neutral); =0 / =1 decides
3717// STRATA_IQ_STAGE_GRID=0 disables staging 64-bit i-quant codebook tables into shared memory
3718bool g_stage_grid = [] {
3719    const char* v = std::getenv("STRATA_IQ_STAGE_GRID");
3720    return v == nullptr || v[0] == '\0' || v[0] != '0';
3721}();
3722// The single-matrix mmvq (128-thread blocks, one per 4 rows) pays the 2-8 KB staging per block: on the RTX 5070 its
3723// IQ2_XS / IQ2_S / IQ1_M calls were 10-20% slower staged at 3-8 columns (iq_multi_parity --bench), while the grouped
3724// expert kernels gain.  So mmvq stages only with STRATA_IQ_STAGE_GRID_MMVQ=1 (bitwise the same either way).
3725bool g_stage_grid_mmvq = g_stage_grid && [] {
3726    const char* v = std::getenv("STRATA_IQ_STAGE_GRID_MMVQ");
3727    return v != nullptr && v[0] == '1';
3728}();
3729
3730template <int TY, bool STAGE_GRID = kStageIqGrid<TY>>
3731void launch_mmvq_multi_nc(dpct::dim3 grid, dpct::dim3 block, dpct::queue_ptr s,
3732                          const uint8_t *W, size_t rb, const block_q8_1 *X,
3733                          float *y, int n_in, int n_out, int ncols) {
3734    switch (ncols) {
3735        /*
3736        DPCT1049: The work-group size passed to the SYCL kernel may exceed
3737        the limit. To get the device limit, query
3738        info::device::max_work_group_size. Adjust the work-group size if needed.
3739        */
3740    case 1: {
3741
3742        auto exp_props = sycl::ext::oneapi::experimental::properties{
3743            sycl::ext::oneapi::experimental::use_root_sync};
3744
3745        strata::kprof::kp(s, __FILE__, __func__, __LINE__)->submit([&](sycl::handler &cgh) {
3746
3747            cgh.parallel_for<dpct_kernel_name<
3748                class mmvq_multi_kernel_8df6c9, dpct_kernel_scalar<TY>,
3749                dpct_kernel_scalar<1>, dpct_kernel_scalar<STAGE_GRID>,
3750                dpct_kernel_scalar<true>>>(
3751                sycl::nd_range<3>(grid * block, block), exp_props,
3752                [=](sycl::nd_item<3> item_ct1)
3753                    [[sycl::reqd_sub_group_size(32)]] {
3754                        mmvq_multi_kernel<TY, 1, STAGE_GRID, true>(
3755                            W, rb, X, y, n_in, n_out, 1);
3756                    });
3757        });
3758    } break;
3759        /*
3760        DPCT1049: The work-group size passed to the SYCL kernel may exceed
3761        the limit. To get the device limit, query
3762        info::device::max_work_group_size. Adjust the work-group size if needed.
3763        */
3764    case 2: {
3765
3766        auto exp_props = sycl::ext::oneapi::experimental::properties{
3767            sycl::ext::oneapi::experimental::use_root_sync};
3768
3769        strata::kprof::kp(s, __FILE__, __func__, __LINE__)->submit([&](sycl::handler &cgh) {
3770
3771            cgh.parallel_for<dpct_kernel_name<
3772                class mmvq_multi_kernel_9c43f2, dpct_kernel_scalar<TY>,
3773                dpct_kernel_scalar<2>, dpct_kernel_scalar<STAGE_GRID>,
3774                dpct_kernel_scalar<true>>>(
3775                sycl::nd_range<3>(grid * block, block), exp_props,
3776                [=](sycl::nd_item<3> item_ct1)
3777                    [[sycl::reqd_sub_group_size(32)]] {
3778                        mmvq_multi_kernel<TY, 2, STAGE_GRID, true>(
3779                            W, rb, X, y, n_in, n_out, 2);
3780                    });
3781        });
3782    } break;
3783        /*
3784        DPCT1049: The work-group size passed to the SYCL kernel may exceed
3785        the limit. To get the device limit, query
3786        info::device::max_work_group_size. Adjust the work-group size if needed.
3787        */
3788    case 3: {
3789
3790        auto exp_props = sycl::ext::oneapi::experimental::properties{
3791            sycl::ext::oneapi::experimental::use_root_sync};
3792
3793        strata::kprof::kp(s, __FILE__, __func__, __LINE__)->submit([&](sycl::handler &cgh) {
3794
3795            cgh.parallel_for<dpct_kernel_name<
3796                class mmvq_multi_kernel_f8d14a, dpct_kernel_scalar<TY>,
3797                dpct_kernel_scalar<3>, dpct_kernel_scalar<STAGE_GRID>,
3798                dpct_kernel_scalar<true>>>(
3799                sycl::nd_range<3>(grid * block, block), exp_props,
3800                [=](sycl::nd_item<3> item_ct1)
3801                    [[sycl::reqd_sub_group_size(32)]] {
3802                        mmvq_multi_kernel<TY, 3, STAGE_GRID, true>(
3803                            W, rb, X, y, n_in, n_out, 3);
3804                    });
3805        });
3806    } break;
3807        /*
3808        DPCT1049: The work-group size passed to the SYCL kernel may exceed
3809        the limit. To get the device limit, query
3810        info::device::max_work_group_size. Adjust the work-group size if needed.
3811        */
3812    case 4: {
3813
3814        auto exp_props = sycl::ext::oneapi::experimental::properties{
3815            sycl::ext::oneapi::experimental::use_root_sync};
3816
3817        strata::kprof::kp(s, __FILE__, __func__, __LINE__)->submit([&](sycl::handler &cgh) {
3818
3819            cgh.parallel_for<dpct_kernel_name<
3820                class mmvq_multi_kernel_88cd9a, dpct_kernel_scalar<TY>,
3821                dpct_kernel_scalar<4>, dpct_kernel_scalar<STAGE_GRID>,
3822                dpct_kernel_scalar<true>>>(
3823                sycl::nd_range<3>(grid * block, block), exp_props,
3824                [=](sycl::nd_item<3> item_ct1)
3825                    [[sycl::reqd_sub_group_size(32)]] {
3826                        mmvq_multi_kernel<TY, 4, STAGE_GRID, true>(
3827                            W, rb, X, y, n_in, n_out, 4);
3828                    });
3829        });
3830    } break;
3831        /*
3832        DPCT1049: The work-group size passed to the SYCL kernel may exceed
3833        the limit. To get the device limit, query
3834        info::device::max_work_group_size. Adjust the work-group size if needed.
3835        */
3836    case 5: {
3837
3838        auto exp_props = sycl::ext::oneapi::experimental::properties{
3839            sycl::ext::oneapi::experimental::use_root_sync};
3840
3841        strata::kprof::kp(s, __FILE__, __func__, __LINE__)->submit([&](sycl::handler &cgh) {
3842
3843            cgh.parallel_for<dpct_kernel_name<
3844                class mmvq_multi_kernel_d55b02, dpct_kernel_scalar<TY>,
3845                dpct_kernel_scalar<5>, dpct_kernel_scalar<STAGE_GRID>,
3846                dpct_kernel_scalar<true>>>(
3847                sycl::nd_range<3>(grid * block, block), exp_props,
3848                [=](sycl::nd_item<3> item_ct1)
3849                    [[sycl::reqd_sub_group_size(32)]] {
3850                        mmvq_multi_kernel<TY, 5, STAGE_GRID, true>(
3851                            W, rb, X, y, n_in, n_out, 5);
3852                    });
3853        });
3854    } break;
3855        /*
3856        DPCT1049: The work-group size passed to the SYCL kernel may exceed
3857        the limit. To get the device limit, query
3858        info::device::max_work_group_size. Adjust the work-group size if needed.
3859        */
3860    case 6: {
3861
3862        auto exp_props = sycl::ext::oneapi::experimental::properties{
3863            sycl::ext::oneapi::experimental::use_root_sync};
3864
3865        strata::kprof::kp(s, __FILE__, __func__, __LINE__)->submit([&](sycl::handler &cgh) {
3866
3867            cgh.parallel_for<dpct_kernel_name<
3868                class mmvq_multi_kernel_3404b2, dpct_kernel_scalar<TY>,
3869                dpct_kernel_scalar<6>, dpct_kernel_scalar<STAGE_GRID>,
3870                dpct_kernel_scalar<true>>>(
3871                sycl::nd_range<3>(grid * block, block), exp_props,
3872                [=](sycl::nd_item<3> item_ct1)
3873                    [[sycl::reqd_sub_group_size(32)]] {
3874                        mmvq_multi_kernel<TY, 6, STAGE_GRID, true>(
3875                            W, rb, X, y, n_in, n_out, 6);
3876                    });
3877        });
3878    } break;
3879        default:
3880            /*
3881            DPCT1049: The work-group size passed to the SYCL kernel may
3882            exceed the limit. To get the device limit, query
3883            info::device::max_work_group_size. Adjust the work-group size if
3884            needed.
3885            */
3886        if (ncols <= 1) {
3887
3888            auto exp_props = sycl::ext::oneapi::experimental::properties{
3889                sycl::ext::oneapi::experimental::use_root_sync};
3890
3891            strata::kprof::kp(s, __FILE__, __func__, __LINE__)->submit([&](sycl::handler &cgh) {
3892
3893                cgh.parallel_for<dpct_kernel_name<
3894                    class mmvq_multi_kernel_1f7e16, dpct_kernel_scalar<TY>,
3895                    dpct_kernel_scalar<1>, dpct_kernel_scalar<STAGE_GRID>,
3896                    dpct_kernel_scalar<false>>>(
3897                    sycl::nd_range<3>(grid * block, block), exp_props,
3898                    [=](sycl::nd_item<3> item_ct1)
3899                        [[sycl::reqd_sub_group_size(32)]] {
3900                            mmvq_multi_kernel<TY, 1, STAGE_GRID, false>(
3901                                W, rb, X, y, n_in, n_out, ncols);
3902                        });
3903            });
3904        }
3905        /*
3906        DPCT1049: The work-group size passed to the SYCL kernel may
3907        exceed the limit. To get the device limit, query
3908        info::device::max_work_group_size. Adjust the work-group size if
3909        needed.
3910        */
3911        else {
3912
3913            auto exp_props = sycl::ext::oneapi::experimental::properties{
3914                sycl::ext::oneapi::experimental::use_root_sync};
3915
3916            strata::kprof::kp(s, __FILE__, __func__, __LINE__)->submit([&](sycl::handler &cgh) {
3917
3918                cgh.parallel_for<dpct_kernel_name<
3919                    class mmvq_multi_kernel_95b544, dpct_kernel_scalar<TY>,
3920                    dpct_kernel_scalar<8>, dpct_kernel_scalar<STAGE_GRID>,
3921                    dpct_kernel_scalar<false>>>(
3922                    sycl::nd_range<3>(grid * block, block), exp_props,
3923                    [=](sycl::nd_item<3> item_ct1)
3924                        [[sycl::reqd_sub_group_size(32)]] {
3925                            mmvq_multi_kernel<TY, 8, STAGE_GRID, false>(
3926                                W, rb, X, y, n_in, n_out, ncols);
3927                        });
3928            });
3929        }
3930            break;
3931    }
3932}
3933bool g_q2_word_expand = env_on("STRATA_SYCL_Q2_WORD_EXPAND");
3934
3935
3936template <int TY>
3937void launch_mmvq(const uint8_t *W, size_t rb, const block_q8_1 *X, float *y,
3938                 int n_in, int n_out, int ncols, dpct::queue_ptr s) {
3939    const dpct::dim3 grid((unsigned)((n_out + 3) / 4)), block(32, 4);
3940    /*
3941    DPCT1049: The work-group size passed to the SYCL kernel may exceed the
3942    limit. To get the device limit, query info::device::max_work_group_size.
3943    Adjust the work-group size if needed.
3944    */
3945    if constexpr (!kSplit<TY>) {
3946
3947        auto exp_props = sycl::ext::oneapi::experimental::properties{
3948            sycl::ext::oneapi::experimental::use_root_sync};
3949
3950        strata::kprof::kp(s, __FILE__, __func__, __LINE__)->submit([&](sycl::handler &cgh) {
3951
3952            cgh.parallel_for<dpct_kernel_name<class mmvq_kernel_c04bb8,
3953                                              dpct_kernel_scalar<TY>>>(
3954                sycl::nd_range<3>(grid * block, block), exp_props,
3955                [=](sycl::nd_item<3> item_ct1)
3956                    [[sycl::reqd_sub_group_size(32)]] {
3957                        mmvq_kernel<TY>(W, rb, X, y, n_in, n_out, ncols);
3958                    });
3959        });
3960    }
3961    /*
3962    DPCT1049: The work-group size passed to the SYCL kernel may exceed the
3963    limit. To get the device limit, query info::device::max_work_group_size.
3964    Adjust the work-group size if needed.
3965    */
3966    else if (g_old_kernels) {
3967
3968        auto exp_props = sycl::ext::oneapi::experimental::properties{
3969            sycl::ext::oneapi::experimental::use_root_sync};
3970
3971        strata::kprof::kp(s, __FILE__, __func__, __LINE__)->submit([&](sycl::handler &cgh) {
3972
3973            cgh.parallel_for<dpct_kernel_name<class mmvq_kernel_18057f,
3974                                              dpct_kernel_scalar<TY>>>(
3975                sycl::nd_range<3>(grid * block, block), exp_props,
3976                [=](sycl::nd_item<3> item_ct1)
3977                    [[sycl::reqd_sub_group_size(32)]] {
3978                        mmvq_kernel<TY>(W, rb, X, y, n_in, n_out, ncols);
3979                    });
3980        });
3981    } else if constexpr (kStageIqGrid<TY>) {
3982        if (!g_stage_grid_mmvq) {
3983            launch_mmvq_multi_nc<TY, false>(grid, block, s, W, rb, X, y, n_in, n_out, ncols);
3984            return;
3985        }
3986        launch_mmvq_multi_nc<TY, true>(grid, block, s, W, rb, X, y, n_in, n_out, ncols);
3987    } else {
3988        launch_mmvq_multi_nc<TY, false>(grid, block, s, W, rb, X, y, n_in, n_out, ncols);
3989    }
3990}
3991
3992
3993// BEGIN PRIVATE IQ3 XMX REUSE HELPER
3994// Private reuse of the old B580 public REG35 candidate; not a production dispatch.
3995struct IQ3XmxWeightPrep {   // IQ3_S
3996    using W = Split<21>::W;
3997    static W load(const void* __restrict__ vbq, int kbx, int iqs, const uint32_t* grid) {
3998        const block_iq3_s* bq3 = iq_signed_grid::block_at<block_iq3_s>(vbq, uint32_t(kbx));
3999        const sycl::int2 qs_packed = sycl::int2(get_int_b2(bq3->qs, iqs + 0),
4000                                                get_int_b2(bq3->qs, iqs + 1));
4001        const uint8_t* qs = (const uint8_t*) &qs_packed;
4002        const int qh = bq3->qh[iqs / 2];
4003        const int signs_packed_32 = get_int_b2(bq3->signs, iqs / 2);
4004        const uint8_t* signs_packed_8 = (const uint8_t*) &signs_packed_32;
4005        W r;
4006#pragma unroll
4007        for (int l0 = 0; l0 < 8; l0 += 2) {
4008            const sycl::int2 grid_pos =
4009                sycl::int2(grid[qs[l0 + 0] | ((qh << (8 - l0)) & 0x100)],
4010                           grid[qs[l0 + 1] | ((qh << (7 - l0)) & 0x100)]);
4011            r.g[l0 + 0] = iq_signed_grid::apply(grid_pos.x(), signs_packed_8[l0 / 2]);
4012            r.g[l0 + 1] = iq_signed_grid::apply(grid_pos.y(), signs_packed_8[l0 / 2] >> 4);
4013        }
4014        r.ls = 1 + 2 * ((bq3->scales[iqs / 4] >> ((iqs << 1) & 0x04)) & 0x0F);
4015        r.dw = sycl::vec<sycl::half, 1>(bq3->d)
4016                   .convert<float, sycl::rounding_mode::automatic>()[0];
4017        return r;
4018    }
4019};
4020
4021namespace iq3jm=sycl::ext::oneapi::experimental::matrix;
4022inline float iq3_xmx_float_finish(const Split<21>::W& pw,const block_q8_1* activation,int sumi){
4023    sumi*=pw.ls;const float d=pw.dw*activation->ds[0];return d*sumi;
4024}
4025template<int NT,int KB>class IQ3PublicXmxKernel;
4026template<int NT,int KB>
4027void iq3_public_xmx_launch(const uint8_t* w,const block_q8_1* x,float* y,int N,sycl::queue* q){
4028    constexpr int NR=16,NS=32,XB=KB*8,RB=KB*sizeof(block_iq3_s);
4029    q->parallel_for<IQ3PublicXmxKernel<NT,KB>>(sycl::nd_range<1>((N+NR-1)/NR*512,512),
4030      [=](sycl::nd_item<1> it)[[sycl::reqd_sub_group_size(16)]]{
4031        auto group=it.get_group();auto sg=it.get_sub_group();int lid=it.get_local_linear_id(),sid=lid/16,lane=lid%16,base=it.get_group_linear_id()*NR,row=base+lane;
4032        auto& table=*sycl::ext::oneapi::group_local_memory_for_overwrite<uint32_t[512]>(group);
4033
4034
4035        auto& partial=*sycl::ext::oneapi::group_local_memory_for_overwrite<float[NS*NT*NR]>(group);
4036        table[lid]=iq3s_grid[lid];it.barrier(sycl::access::fence_space::local_space);
4037        float acc[NT]={};
4038        for(int seg=sid;seg<XB;seg+=NS){
4039            Split<21>::W pw{};if(row<N)pw=IQ3XmxWeightPrep::load(w+uint32_t(row)*uint32_t(RB),seg/8,2*(seg%8),table);
4040            iq3jm::joint_matrix<sycl::sub_group,int8_t,iq3jm::use::a,NT,32,iq3jm::layout::row_major> A;
4041            iq3jm::joint_matrix<sycl::sub_group,int8_t,iq3jm::use::b,32,NR,iq3jm::layout::ext_intel_packed> B;
4042            iq3jm::joint_matrix<sycl::sub_group,int32_t,iq3jm::use::accumulator,NT,NR> C;
4043
4044                auto pa=sycl::address_space_cast<sycl::access::address_space::global_space,sycl::access::decorated::no>(x[seg].qs);
4045                iq3jm::joint_matrix_load(sg,A,pa,XB*sizeof(block_q8_1));
4046                iq3jm::joint_matrix_fill(sg,B,0);
4047
4048                    int kr=0;
4049                    iq3jm::joint_matrix_apply(sg,B,[&](auto& element){
4050                        const int word=kr<4?pw.g[0]:kr<8?pw.g[1]:kr<12?pw.g[2]:kr<16?pw.g[3]:kr<20?pw.g[4]:kr<24?pw.g[5]:kr<28?pw.g[6]:pw.g[7];
4051                        element=int8_t(uint32_t(word)>>(8*(kr%4)));++kr;
4052                    });
4053
4054
4055            iq3jm::joint_matrix_fill(sg,C,0);iq3jm::joint_matrix_mad(sg,C,A,B,C);
4056
4057                int mr=0;
4058                iq3jm::joint_matrix_apply(sg,C,[&](auto& element){
4059                    acc[mr]+=iq3_xmx_float_finish(pw,x+mr*XB+seg,int(element));++mr;
4060                });
4061
4062
4063        }
4064#pragma unroll
4065        for(int j=0;j<NT;++j)partial[sid*NT*NR+j*NR+lane]=acc[j];
4066        it.barrier(sycl::access::fence_space::local_space);
4067        const int rr=lid/32,vl=lid%32;
4068#pragma unroll
4069        for(int j=0;j<NT;++j){float v=partial[vl*NT*NR+j*NR+rr];v+=partial[(vl^16)*NT*NR+j*NR+rr];
4070#pragma unroll
4071            for(int off=8;off;off>>=1)v+=sycl::permute_group_by_xor(sg,v,off);
4072            if(vl==0&&base+rr<N)y[uint32_t(j)*uint32_t(N)+uint32_t(base+rr)]=v;
4073        }
4074    });
4075}
4076template<int KB>void iq3_public_xmx_T(int T,const uint8_t* w,const block_q8_1* x,float* y,int N,sycl::queue* q){
4077#define IQ3_XMX_T(t) case t:iq3_public_xmx_launch<t,KB>(w,x,y,N,q);break
4078    switch(T){IQ3_XMX_T(1);IQ3_XMX_T(2);IQ3_XMX_T(3);IQ3_XMX_T(4);IQ3_XMX_T(5);IQ3_XMX_T(6);IQ3_XMX_T(7);IQ3_XMX_T(8);}
4079#undef IQ3_XMX_T
4080}
4081
4082// END PRIVATE IQ3 XMX REUSE HELPER
4083// SYCL port: upstream's opt-in AMD-tuned S26 (STRATA_EXPERT_V2) and S27 (STRATA_EXPERT_V2K) grouped-expert kernels are
4084// not migrated: dpct cannot name their instantiations and they are tuned for gfx1151. The port's lane kernels below are
4085// the measured ones for every format; the two switches only print a note.
4086// (the S26/S27 kernels and their launchers are not here: the canonical code is src/kernels/cuda/iq_kernels.cu, STRATA_EXPERT_V2 / STRATA_EXPERT_V2K; sycl/tools/fixups.py keeps this block out)
4087
4088template<int TY, int E>
4089__dpct_inline__ void rows_dot_reuse(const uintptr_t (&rows)[2],
4090                                   const block_q8_1* const* xs, int nb, int sub,
4091                                   float (&out)[2][E]) {
4092    static_assert(TY == 22 || TY == 18 || TY == 21);
4093    using F = Fmt<TY>;
4094    using M = Multi<TY>;
4095    static_assert(F::qk % 32 == 0 && 8 % F::ipb == 0 && M::NW == 8);
4096    constexpr int BS = TY == 22 ? sizeof(block_iq2_s) :
4097                       TY == 21 ? sizeof(block_iq3_s) : sizeof(block_iq3_xxs);
4098    constexpr int KSTEP = 8 / F::ipb, XB = F::qk / 32;
4099    const int iqs = F::step * (sub % F::ipb), kb0 = sub / F::ipb;
4100    uintptr_t wp[2] = {rows[0] + (size_t) kb0 * BS, rows[1] + (size_t) kb0 * BS};
4101    size_t xoff = (size_t) kb0 * XB * sizeof(block_q8_1);
4102    float sum[2][E];
4103#pragma unroll
4104    for (int r = 0; r < 2; ++r)
4105#pragma unroll
4106        for (int e = 0; e < E; ++e) sum[r][e] = 0.f;
4107    for (int kb = kb0; kb < nb; kb += KSTEP) {
4108        int u[E][M::NW];
4109        float ds[E];
4110#pragma unroll
4111        for (int e = 0; e < E; ++e)
4112            M::acts((const block_q8_1*) (uintptr_t(xs[e]) + xoff), iqs, u[e], ds[e]);
4113#pragma unroll
4114        for (int r = 0; r < 2; ++r) {
4115            MultiW m;
4116            M::prep((const void*) wp[r], 0, iqs, m);
4117#pragma unroll
4118            for (int e = 0; e < E; ++e) {
4119                int s0 = 0, s1 = 0;
4120#pragma unroll
4121                for (int j = 0; j < M::NW / 2; ++j) s0 = ggml_cuda_dp4a(m.w[j], u[e][j], s0);
4122#pragma unroll
4123                for (int j = M::NW / 2; j < M::NW; ++j) s1 = ggml_cuda_dp4a(m.w[j], u[e][j], s1);
4124                sum[r][e] += M::finish(s0, s1, m, ds[e]);
4125            }
4126            wp[r] += (size_t) KSTEP * BS;
4127        }
4128        xoff += (size_t) KSTEP * XB * sizeof(block_q8_1);
4129    }
4130#pragma unroll
4131    for (int r = 0; r < 2; ++r)
4132#pragma unroll
4133        for (int e = 0; e < E; ++e) out[r][e] = lanes_sum<8>(sum[r][e]);
4134}
4135
4136template<int TG, bool E3 = false>
4137__dpct_inline__ void native_gu_row_reuse_kernel(
4138    const unsigned long long* __restrict__ grp_ptr, const int32_t* __restrict__ grp_start,
4139    const int32_t* __restrict__ n_groups, const int32_t* __restrict__ ent_tok,
4140    const block_q8_1* __restrict__ xq, NativeExpertLayout L,
4141    float* __restrict__ gate, float* __restrict__ up) {
4142    auto it = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
4143    const int ng = *n_groups;
4144    if ((int) it.get_group(1) >= ng) return;
4145    const int rib = (int) it.get_local_id(2) / 8, sub = (int) it.get_local_id(2) % 8;
4146    const int row0 = (int) it.get_group(2) * 64 + rib, nrows = (int) (2 * L.n_ff);
4147    if (row0 >= nrows) return;
4148    const int nb = (int) (L.n_embd / Fmt<TG>::qk), xb = (int) (L.n_embd / 32);
4149    size_t off[2];
4150    float* dst[2];
4151    bool live[2];
4152#pragma unroll
4153    for (int r = 0; r < 2; ++r) {
4154        const int v = row0 + r * 32;
4155        live[r] = v < nrows;
4156        const int vv = live[r] ? v : row0;
4157        const bool is_up = vv >= L.n_ff;
4158        const int wr = is_up ? vv - (int) L.n_ff : vv;
4159        off[r] = (is_up ? L.up_off : 0) + (size_t) wr * L.gu_row;
4160        dst[r] = (is_up ? up : gate) + wr;
4161    }
4162    for (int g = (int) it.get_group(1); g < ng; g += (int) it.get_group_range(1)) {
4163        const uintptr_t base = uintptr_t(grp_ptr[g]);
4164        const uintptr_t rows[2] = {base + off[0], base + off[1]};
4165        const int e1 = grp_start[g + 1];
4166        int e = grp_start[g];
4167        auto pass = [&](auto ec) {
4168            constexpr int E = decltype(ec)::value;
4169            const block_q8_1* xs[E];
4170#pragma unroll
4171            for (int j = 0; j < E; ++j) xs[j] = xq + (size_t) ent_tok[e + j] * xb;
4172            float o[2][E];
4173            rows_dot_reuse<TG, E>(rows, xs, nb, sub, o);
4174            if (sub == 0)
4175#pragma unroll
4176                for (int r = 0; r < 2; ++r) if (live[r])
4177#pragma unroll
4178                    for (int j = 0; j < E; ++j) dst[r][(size_t) (e + j) * L.n_ff] = o[r][j];
4179            e += E;
4180        };
4181        for (; e + 4 <= e1;) pass(std::integral_constant<int, 4>{});
4182        if constexpr (E3) {
4183            if (e + 3 == e1) pass(std::integral_constant<int, 3>{});
4184        }
4185        if (e + 2 <= e1) pass(std::integral_constant<int, 2>{});
4186        if (e < e1) pass(std::integral_constant<int, 1>{});
4187    }
4188}
4189
4190template<int TG>
4191void launch_gu_row_reuse(unsigned groups, dpct::queue_ptr s,
4192                         const unsigned long long* ptr, const int32_t* start,
4193                         const int32_t* ng, const int32_t* tok,
4194                         const block_q8_1* xq, const NativeExpertLayout& L,
4195                         float* gate, float* up) {
4196    const unsigned gx = (unsigned) ((2 * L.n_ff + 63) / 64);
4197    auto props = sycl::ext::oneapi::experimental::properties{
4198        sycl::ext::oneapi::experimental::use_root_sync};
4199    static const bool e3 = TG == 21 || strata::bm_default_on("STRATA_EXPERT_ROW_E3", s->get_device(), false);
4200    if (e3) {
4201        static const bool logged = [] {
4202            std::fprintf(stderr, "strata: %s exact three-entry row reuse enabled\n",
4203                         TG == 22 ? "IQ2_S" : TG == 21 ? "IQ3_S" : "IQ3_XXS");
4204            return true;
4205        }();
4206        (void) logged;
4207        s->parallel_for<dpct_kernel_name<class native_gu_row_reuse_e3, dpct_kernel_scalar<TG>>>(
4208            sycl::nd_range<3>(sycl::range<3>(1, groups, (size_t) gx * 256),
4209                              sycl::range<3>(1, 1, 256)), props,
4210            [=](sycl::nd_item<3>) [[sycl::reqd_sub_group_size(16)]] {
4211                native_gu_row_reuse_kernel<TG, true>(ptr, start, ng, tok, xq, L, gate, up);
4212            });
4213        return;
4214    }
4215    s->parallel_for<dpct_kernel_name<class native_gu_row_reuse, dpct_kernel_scalar<TG>>>(
4216        sycl::nd_range<3>(sycl::range<3>(1, groups, (size_t) gx * 256),
4217                          sycl::range<3>(1, 1, 256)), props,
4218        [=](sycl::nd_item<3>) [[sycl::reqd_sub_group_size(16)]] {
4219            native_gu_row_reuse_kernel<TG>(ptr, start, ng, tok, xq, L, gate, up);
4220        });
4221}
4222
4223// BEGIN PRIVATE GU22 ROW REUSE ONLY
4224// Private, default OFF: GU22-only extraction from the frozen 51560d17 source.
4225bool gu22_row_reuse_enabled(const sycl::device& device) {
4226    static const bool enabled = [] {
4227        const char* v = std::getenv("STRATA_PRIVATE_GU_PREPARED");
4228        return v && v[0] == '1';
4229    }();
4230    if (!enabled) return false;
4231    thread_local std::optional<std::pair<sycl::device, bool>> cached;
4232    if (!cached || cached->first != device)
4233        cached.emplace(device, strata::intel_gpu_gen(device) == strata::IntelGpuGen::Battlemage);
4234    return cached->second;
4235}
4236// (the PR #3153 copy of rows_dot_reuse / native_gu_row_reuse_kernel / launch_gu_row_reuse for IQ2_S is the head's generalised
4237// version above: same two-row reuse, same arithmetic; its enable switch above keeps its name)
4238// END PRIVATE GU22 ROW REUSE ONLY
4239
4240// SYCL port: lanes per row of the port's grouped expert kernels at run time (STRATA_GU_LANES / STRATA_DOWN_LANES:
4241// 4, 8, 16 or 32; default STRATA_EXPERT_LANES), 256 / lanes rows per work-group. Gate/up rows are 80 dot calls
4242// (2560 wide), the IQ4_NL down rows 40 (640 wide), so the best split can differ by role.
4243inline int lanes_env(const char* name) {
4244    const char* v = std::getenv(name);
4245    const int n = v ? std::atoi(v) : kExpertLanes;
4246    return n == 4 || n == 8 || n == 16 || n == 32 ? n : kExpertLanes;
4247}
4248inline int gu_lanes() { static const int v = lanes_env("STRATA_GU_LANES"); return v; }
4249inline int down_lanes() { static const int v = lanes_env("STRATA_DOWN_LANES"); return v; }
4250bool g_iq2xxs_reuse = [] {
4251    const char* value = std::getenv("STRATA_SYCL_EXPERT_MULTI16");
4252    return value && std::atoi(value) != 0;
4253}();
4254
4255void launch_gu_iq2xxs_reuse(unsigned groups, dpct::queue_ptr stream, const unsigned long long* ptr,
4256                           const int32_t* start, const int32_t* count, const int32_t* tok,
4257                           const block_q8_1* x, const NativeExpertLayout& layout, float* gate, float* up) {
4258    constexpr int lanes = 8, rows = 256 / lanes;
4259    const unsigned columns = (unsigned)((2 * layout.n_ff + rows - 1) / rows);
4260    auto properties = sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};
4261    stream->parallel_for<dpct_kernel_name<class native_gu_iq2xxs_reuse_kernel>>(
4262        sycl::nd_range<3>(sycl::range<3>(1, groups, (size_t)columns * 256), sycl::range<3>(1, 1, 256)), properties,
4263        [=](sycl::nd_item<3>) [[sycl::reqd_sub_group_size(32)]] { native_gu_kernel<16, lanes, true>(ptr, start, count, tok, x, layout, gate, up); });
4264}
4265
4266
4267template <int TG>
4268void launch_gu_packed_fixed(unsigned groups, dpct::queue_ptr s, const unsigned long long* pointers,
4269                             const int32_t* starts, const int32_t* count, const int32_t* tokens,
4270                             const block_q8_1* x, NativeExpertLayout layout, float* gate, float* up) {
4271    auto properties = sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};
4272    s->parallel_for<dpct_kernel_name<class gu_packed_fixed, dpct_kernel_scalar<TG>>>(
4273        sycl::nd_range<3>(sycl::range<3>(1,groups,40*256),sycl::range<3>(1,1,256)),properties,
4274        [=](sycl::nd_item<3>) [[sycl::reqd_sub_group_size(32)]] { native_gu_kernel<TG,8,false,true>(pointers,starts,count,tokens,x,layout,gate,up); });
4275}
4276
4277// STRATA_KQ_GU_LANES (opt-in): the lane split of the K-quant / Q8_0 gate/up rows alone (Unsloth's files), default STRATA_GU_LANES.
4278// B70, 4-token windows, split on: 16 lanes reads Q4_K/Q5_1 experts at 439 GB/s against 426 at 8; the reduction order differs
4279// (other bits), so it stays opt-in.
4280inline int kq_gu_lanes() { static const int v = std::getenv("STRATA_KQ_GU_LANES") ? lanes_env("STRATA_KQ_GU_LANES") : gu_lanes(); return v; }
4281// Single output row, weight preparation shared across entries; original LN8.
4282// GU16 preparation is the already byte-tested IQ2_XXS preparation from R2,
4283// with no paired output row and no whole-packet Q8 staging array.
4284struct GuPrepared16 {
4285    using W=MultiW;
4286    static W load(const void* vbq,int kb,int iqs) {
4287        const auto* b=(const block_iq2_xxs*)vbq+kb;
4288        const int q2=get_int_b2(b->qs,iqs);
4289        const uint8_t* ids=(const uint8_t*)&q2;
4290        const uint32_t aux=get_int_b2(b->qs,iqs+1);
4291        W w;
4292#pragma unroll
4293        for(int j=0;j<4;++j) {
4294            const sycl::uint2 grid=((const sycl::uint2*)iq2xxs_grid)[ids[j]];
4295            const uint32_t signs=unpack_ksigns(aux>>(7*j));
4296            const int a=swar_ne4(signs&0x08040201),c=swar_ne4(signs&0x80402010);
4297            w.w[2*j]=swar_sub4(grid.x()^a,a);w.w[2*j+1]=swar_sub4(grid.y()^c,c);
4298        }
4299        w.a=aux>>27|1;
4300        w.d=sycl::vec<sycl::half,1>(b->d).convert<float,sycl::rounding_mode::automatic>()[0];
4301        return w;
4302    }
4303    static float apply(const W& w,const block_q8_1* x,int iqs) {
4304        int a=0,b=0;
4305#pragma unroll
4306        for(int j=0;j<4;++j)a=ggml_cuda_dp4a(w.w[j],get_int_b4(x[iqs/2].qs,j),a);
4307#pragma unroll
4308        for(int j=4;j<8;++j)b=ggml_cuda_dp4a(w.w[j],get_int_b4(x[iqs/2].qs,j),b);
4309        // Each32-coefficient dot is bounded by176128, scale<=31: no overflow.
4310        const int v=(a+b)*w.a/8;
4311        const float d=w.d*x[iqs/2].ds[0];
4312        return d*v;
4313    }
4314};
4315// Exact IQ1_M coefficients in eighth units: q+delta=(8*q-(7 or9))/8.
4316// The pinned2048-entry grid is ternary; prove_affine29.py checks every value.
4317struct GuPrepared29Affine {
4318    static_assert(IQ1M_DELTA==0.125f);
4319    struct W {int g[8];int16_t sc0,sc1;float dw;};
4320    static_assert(sizeof(W)==40);
4321    static_assert(sizeof(Split<29>::W)==60);
4322    static W load(const void* vbq,int kb,int iqs) {
4323        const auto* b=(const block_iq1_m*)vbq+kb;
4324        const int packed=get_int_b4(b->qs,iqs);
4325        const uint8_t* qs=(const uint8_t*)&packed;
4326        W w;
4327#pragma unroll
4328        for(int j=0;j<4;++j) {
4329            const int qh=b->qh[2*iqs+j/2]>>(4*(j%2));
4330            const uint32_t grid=iq1s_grid_gpu[qs[j]|((qh&7)<<8)];
4331            const uint32_t off=uint32_t(7+((qh&8)>>2))*0x01010101u;
4332            const uint32_t low=(grid&0x0f0f0f0fu)<<3,high=((grid>>4)&0x0f0f0f0fu)<<3;
4333            // Guarded byte subtraction: no cross-byte borrow for0..16 minus7/9.
4334            w.g[2*j]=sycl::bit_cast<int32_t>(((low|0x80808080u)-off)^0x80808080u);
4335            w.g[2*j+1]=sycl::bit_cast<int32_t>(((high|0x80808080u)-off)^0x80808080u);
4336        }
4337        const uint16_t* sc=(const uint16_t*)b->scales;
4338        iq1m_scale_t scale;
4339        scale.u16=(sc[0]>>12)|((sc[1]>>8)&0x00f0)|((sc[2]>>4)&0x0f00)|(sc[3]&0xf000);
4340        w.dw=sycl::vec<sycl::half,1>(scale.f16).convert<float,sycl::rounding_mode::automatic>()[0];
4341        const int tmp=sc[iqs/2]>>(6*(iqs%2));
4342        w.sc0=int16_t(2*(tmp&7)+1);w.sc1=int16_t(2*((tmp>>3)&7)+1);
4343        return w;
4344    }
4345    static float apply(const W& w,const block_q8_1* x,int iqs) {
4346        int a=0,b=0;
4347#pragma unroll
4348        for(int j=0;j<4;++j)a=ggml_cuda_dp4a(w.g[j],get_int_b4(x[iqs].qs,j),a);
4349#pragma unroll
4350        for(int j=4;j<8;++j)b=ggml_cuda_dp4a(w.g[j],get_int_b4(x[iqs].qs,j),b);
4351        const int scaled=int(int16_t(a))*int(w.sc0)+int(int16_t(b))*int(w.sc1);
4352        const float value=float(scaled)*0.125f;
4353        const float d=w.dw*x[iqs].ds[0];
4354        return d*value;
4355    }
4356};
4357
4358template<int TY,int E>
4359__dpct_inline__ void gu_prepared_dot(const uint8_t* row,const block_q8_1* const* xs,int nb,int sub,float* out) {
4360    using F=Fmt<TY>;
4361    float sum[E];
4362#pragma unroll
4363    for(int e=0;e<E;++e)sum[e]=0.f;
4364    for(int k=sub;k<nb*F::ipb;k+=8) {
4365        const int kb=k/F::ipb,iqs=F::step*(k%F::ipb);
4366        if constexpr(TY==16) {
4367            const auto w=GuPrepared16::load(row,kb,iqs);
4368#pragma unroll
4369            for(int e=0;e<E;++e)sum[e]+=GuPrepared16::apply(w,xs[e]+kb*(F::qk/32),iqs);
4370        } else {
4371            static_assert(TY==29);
4372            const auto w=GuPrepared29Affine::load(row,kb,iqs);
4373#pragma unroll
4374            for(int e=0;e<E;++e)sum[e]+=GuPrepared29Affine::apply(w,xs[e]+kb*(F::qk/32),iqs);
4375        }
4376    }
4377#pragma unroll
4378    for(int e=0;e<E;++e)out[e]=lanes_sum<8>(sum[e]);
4379}
4380template<int TY,int LN,bool KM>
4381__dpct_inline__ void gu_prepared_entries(const uint8_t* row,const block_q8_1* x,int stride,const int32_t* idx,
4382    int first,int last,int nb,int sub,float* dst,size_t dst_stride,const void* =nullptr) {
4383    static_assert((TY==16 || TY==29) && LN==8 && KM);
4384    int e=first;
4385    for(;e+4<=last;e+=4) {
4386        const block_q8_1* xs[4]={x+(size_t)idx[e]*stride,x+(size_t)idx[e+1]*stride,x+(size_t)idx[e+2]*stride,x+(size_t)idx[e+3]*stride};
4387        float out[4];gu_prepared_dot<TY,4>(row,xs,nb,sub,out);
4388        if(sub==0) {
4389#pragma unroll
4390            for(int j=0;j<4;++j)dst[(size_t)(e+j)*dst_stride]=out[j];
4391        }
4392    }
4393    if(e+2<=last) {
4394        const block_q8_1* xs[2]={x+(size_t)idx[e]*stride,x+(size_t)idx[e+1]*stride};
4395        float out[2];gu_prepared_dot<TY,2>(row,xs,nb,sub,out);
4396        if(sub==0){dst[(size_t)e*dst_stride]=out[0];dst[(size_t)(e+1)*dst_stride]=out[1];}e+=2;
4397    }
4398    for(;e<last;++e) {
4399        float v;
4400        {
4401            const block_q8_1* xs[1]={x+(size_t)idx[e]*stride};float out[1];gu_prepared_dot<TY,1>(row,xs,nb,sub,out);v=out[0];
4402        }
4403        if(sub==0)dst[(size_t)e*dst_stride]=v;
4404    }
4405}
4406
4407template <int TG, int LN = kExpertLanes, bool KM = true>
4408__dpct_inline__ void gu_prepared_kernel(
4409    const unsigned long long *__restrict__ grp_ptr,
4410    const int32_t *__restrict__ grp_start, const int32_t *__restrict__ n_groups,
4411    const int32_t *__restrict__ ent_tok, const block_q8_1 *__restrict__ xq,
4412    NativeExpertLayout L, float *__restrict__ gate, float *__restrict__ up) {
4413    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
4414    // #363: group g is computed by block row g % gridDim.y (a launch sized for fewer rows than possible groups strides);
4415    // a block row with no group returns before the barrier below (uniform over the work-group)
4416    const int ng = *n_groups;
4417    if ((int) item_ct1.get_group(1) >= ng) return;
4418    const void* grid = nullptr;
4419#if STRATA_GRID_SLM
4420    if constexpr (TG == 18 || TG == 21 || TG == 22) {
4421        using GT = std::conditional_t<TG == 22, uint64_t, uint32_t>;
4422        constexpr int GN = TG == 22 ? 1024 : TG == 21 ? 512 : 256;
4423        auto& sg = *sycl::ext::oneapi::group_local_memory_for_overwrite<GT[GN]>(item_ct1.get_group());
4424        for (int i = (int) item_ct1.get_local_id(2); i < GN; i += (int) item_ct1.get_local_range(2)) {
4425            if constexpr (TG == 22) sg[i] = iq2s_grid[i];
4426            else if constexpr (TG == 21) sg[i] = iq3s_grid[i];
4427            else sg[i] = iq3xxs_grid[i];
4428        }
4429        item_ct1.barrier(sycl::access::fence_space::local_space);
4430        grid = &sg[0];
4431    }
4432#endif
4433    const int rib = item_ct1.get_local_id(2) / LN,
4434              sub = item_ct1.get_local_id(2) % LN;
4435    const int row = item_ct1.get_group(2) * (256 / LN) + rib; // 0 .. 2*n_ff
4436    if (row >= 2 * L.n_ff) return;
4437    const bool is_up = row >= L.n_ff;
4438    const int r = is_up ? row - (int) L.n_ff : row;
4439    const size_t off = (is_up ? L.up_off : 0) + (size_t) r * L.gu_row;
4440    const int nb = (int) (L.n_embd / Fmt<TG>::qk), xb = (int) (L.n_embd / 32);
4441    for (int g = (int) item_ct1.get_group(1); g < ng; g += (int) item_ct1.get_group_range(1)) {
4442        const uint8_t* wr = (const uint8_t*) grp_ptr[g] + off;
4443        const int e0 = grp_start[g], e1 = grp_start[g + 1];
4444        gu_prepared_entries<TG, LN, KM>(wr, xq, xb, ent_tok, e0, e1, nb, sub, (is_up ? up : gate) + r, (size_t) L.n_ff, grid);
4445    }
4446}
4447
4448
4449
4450inline bool gu_prepared_enabled(const sycl::device& dev) {
4451    static const bool enabled=[] {const char* p=std::getenv("STRATA_PRIVATE_GU_PREPARED");return p&&std::atoi(p)!=0;}();
4452    return enabled && strata::intel_gpu_gen(dev)==strata::IntelGpuGen::Battlemage;
4453}
4454template<int TY> class GuPreparedKernel;
4455template<int TY> void launch_gu_prepared(unsigned groups,dpct::queue_ptr s,const unsigned long long* ptr,const int32_t* start,
4456    const int32_t* ng,const int32_t* tokens,const block_q8_1* x,const NativeExpertLayout& L,float* gate,float* up) {
4457    const unsigned gx=unsigned((2*L.n_ff+31)/32);
4458    const auto props=sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};
4459    s->parallel_for<GuPreparedKernel<TY>>(sycl::nd_range<3>(sycl::range<3>(1,groups,(size_t)gx*256),sycl::range<3>(1,1,256)),props,
4460        [=](sycl::nd_item<3>) [[sycl::reqd_sub_group_size(32)]] {gu_prepared_kernel<TY,8,true>(ptr,start,ng,tokens,x,L,gate,up);});
4461}
4462
4463// Same packed fields, original DP4A and eight independent FP32 chains.
4464// Each ESIMD item owns16rows; four independent items own64rows without SLM.
4465namespace pvr=sycl::ext::intel::esimd;
4466inline bool ps_enabled(const sycl::device& device){
4467 static const bool on=[] {const char* p=std::getenv("STRATA_PRIVATE_PACKED_REGISTER");return p&&p[0]=='1';}();
4468 return on&&b60_main_actor()&&b60_weights_packed()&&strata::intel_gpu_gen(device)==strata::IntelGpuGen::Battlemage;
4469}
4470SYCL_ESIMD_FUNCTION ESIMD_INLINE pvr::simd<int32_t,16>
4471pvr_sign(pvr::simd<uint32_t,16> positive,pvr::simd<uint32_t,16> sign){
4472 pvr::simd<uint32_t,16> bit=((sign&15u)*0x00204081u)&0x01010101u;
4473 return (positive^(bit*255u))+bit;
4474}
4475SYCL_ESIMD_FUNCTION ESIMD_INLINE pvr::simd<uint32_t,16>
4476pvr_q2(pvr::simd<uint32_t,16> code){
4477 code&=255u;code=(code|(code<<12))&0x000f000fu;
4478 code=(code|(code<<6))&0x03030303u;
4479 return (code+0x7f7f7f7fu)^0x80808080u;
4480}
4481template<int E>
4482SYCL_ESIMD_FUNCTION ESIMD_INLINE void pvr_gu_packet(
4483 const uint8_t* weights,int row,int first,const int32_t* tokens,
4484 const block_q8_1* xq,float* dst,int row_limit){
4485#pragma clang fp contract(off)
4486 pvr::simd<uint32_t,16> rows(row,1);auto valid=rows<uint32_t(row_limit);
4487 pvr::simd<float,16> sum[8][E];
4488#pragma unroll
4489 for(int p=0;p<8;++p){
4490#pragma unroll
4491  for(int e=0;e<E;++e)sum[p][e]=0.f;
4492 }
4493 const auto* tile=weights+size_t(row/16)*13120;
4494 for(int kb=0;kb<10;++kb){
4495  const auto* block=tile+kb*1312;
4496  auto bits=pvr::block_load<uint16_t,16>(reinterpret_cast<const uint16_t*>(block+1280));
4497  pvr::simd<float,16> d=bits.template bit_cast_view<sycl::half>().read();
4498#pragma unroll
4499  for(int p=0;p<8;++p){
4500   const auto* plane=block+p*160;
4501   auto qs=pvr::block_load<uint32_t,16>(reinterpret_cast<const uint32_t*>(plane));
4502   auto signs=pvr::block_load<uint32_t,16>(reinterpret_cast<const uint32_t*>(plane+64));
4503   auto aux=pvr::block_load<uint16_t,16>(reinterpret_cast<const uint16_t*>(plane+128));
4504   pvr::simd<uint32_t,16> qh=aux&255u,scale=aux>>8;
4505   pvr::simd<int32_t,16> w[8];
4506#pragma unroll
4507   for(int j=0;j<4;++j){
4508    pvr::simd<uint32_t,16> index=((qs>>(8*j))&255u)|((qh<<(8-2*j))&0x300u);
4509    auto grid=pvr::gather<uint64_t,16>(iq2s_grid,index*8u);
4510    pvr::simd<uint32_t,16> lo=grid,hi=grid>>32;
4511    w[2*j]=pvr_sign(lo,signs>>(8*j));w[2*j+1]=pvr_sign(hi,signs>>(8*j+4));
4512   }
4513   pvr::simd<int32_t,16> a=scale&15u,b=scale>>4;
4514#pragma unroll
4515   for(int e=0;e<E;++e){
4516    const auto* raw=reinterpret_cast<const uint8_t*>(xq+size_t(tokens[first+e])*80+kb*8+p);
4517    pvr::simd<uint32_t,8> offset(4,4);
4518    auto u=pvr::gather<int32_t,8>(reinterpret_cast<const int32_t*>(raw),offset);
4519    pvr::simd<uint32_t,1> zero=0;
4520    auto dsbits=pvr::gather<uint16_t,1>(reinterpret_cast<const uint16_t*>(raw),zero);
4521    pvr::simd<float,1> ds=dsbits.template bit_cast_view<sycl::half>().read();
4522    pvr::simd<int32_t,16> s0=0,s1=0;
4523#pragma unroll
4524    for(int j=0;j<4;++j)s0=pvr::dp4a<int32_t>(s0,w[j],pvr::simd<int32_t,16>(u[j]));
4525#pragma unroll
4526    for(int j=4;j<8;++j)s1=pvr::dp4a<int32_t>(s1,w[j],pvr::simd<int32_t,16>(u[j]));
4527    pvr::simd<int32_t,16> si=(s0*a+s1*b+(s0+s1)/2)/4;
4528    pvr::simd<float,16> dot=si;
4529    const float scalar_ds=ds[0];pvr::simd<float,16> factor=d*scalar_ds;
4530    pvr::simd<float,16> term=factor*dot;term.merge(0.f,!valid);
4531    sum[p][e]=sum[p][e]+term;
4532   }
4533  }
4534 }
4535#pragma unroll
4536 for(int e=0;e<E;++e){
4537  auto value=((sum[0][e]+sum[4][e])+(sum[2][e]+sum[6][e]))+
4538             ((sum[1][e]+sum[5][e])+(sum[3][e]+sum[7][e]));
4539  pvr::block_store<float,16>(dst+size_t(first+e)*640+row,value);
4540 }
4541}
4542
4543template<int E>
4544SYCL_ESIMD_FUNCTION ESIMD_INLINE void pvr_down_packet(
4545 const uint8_t* weights,int row,int first,const int32_t* destinations,
4546 const block_q8_1* xq,float* dst){
4547#pragma clang fp contract(off)
4548 pvr::simd<uint32_t,16> rows(row,1);auto valid=rows<2560u;
4549 pvr::simd<float,16> sum[8][E];
4550#pragma unroll
4551 for(int p=0;p<8;++p){
4552#pragma unroll
4553  for(int e=0;e<E;++e)sum[p][e]=0.f;
4554 }
4555 const auto* tile=weights+size_t(row/16)*2880;
4556 for(int step=0;step<3;++step){
4557#pragma unroll
4558  for(int p=0;p<8;++p){
4559   const int k=step*8+p;if(k>=20)continue;
4560   const auto* block=tile+(k/2)*288;
4561   auto q0=pvr::block_load<uint32_t,16>(reinterpret_cast<const uint32_t*>(block+(k%2)*128));
4562   auto q1=pvr::block_load<uint32_t,16>(reinterpret_cast<const uint32_t*>(block+(k%2)*128+64));
4563   auto bits=pvr::block_load<uint16_t,16>(reinterpret_cast<const uint16_t*>(block+256));
4564   pvr::simd<float,16> d=bits.template bit_cast_view<sycl::half>().read();
4565   pvr::simd<uint32_t,16> w[8];
4566#pragma unroll
4567   for(int j=0;j<4;++j){
4568    pvr::simd<uint32_t,16> v=(j<2?q0:q1)>>(16*(j%2));
4569    w[j*2]=pvr_q2(v);w[j*2+1]=pvr_q2(v>>8);
4570   }
4571#pragma unroll
4572   for(int e=0;e<E;++e){
4573    const auto* raw=reinterpret_cast<const uint8_t*>(xq+size_t(first+e)*20+k);
4574    pvr::simd<uint32_t,8> offset(4,4);
4575    auto u=pvr::gather<int32_t,8>(reinterpret_cast<const int32_t*>(raw),offset);
4576    pvr::simd<uint32_t,1> zero=0;
4577    auto dsbits=pvr::gather<uint16_t,1>(reinterpret_cast<const uint16_t*>(raw),zero);
4578    pvr::simd<float,1> ds=dsbits.template bit_cast_view<sycl::half>().read();
4579    pvr::simd<int32_t,16> si=0;
4580#pragma unroll
4581    for(int j=0;j<8;++j)si=pvr::dp4a<int32_t>(si,pvr::simd<int32_t,16>(w[j]),pvr::simd<int32_t,16>(u[j]));
4582    pvr::simd<float,16> dot=si;
4583    const float scalar_ds=ds[0];pvr::simd<float,16> factor=d*scalar_ds;
4584    pvr::simd<float,16> term=factor*dot;term.merge(0.f,!valid);
4585    sum[p][e]=sum[p][e]+term;
4586   }
4587  }
4588 }
4589#pragma unroll
4590 for(int e=0;e<E;++e){
4591  auto value=((sum[0][e]+sum[4][e])+(sum[2][e]+sum[6][e]))+
4592             ((sum[1][e]+sum[5][e])+(sum[3][e]+sum[7][e]));
4593  pvr::block_store<float,16>(dst+size_t(destinations[first+e])*2560+row,value);
4594 }
4595}
4596class GuPackedRegisterKernel;
4597class DownPackedRegisterKernel;
4598template<bool Down,class Kernel>
4599void launch_pvr(unsigned groups,dpct::queue_ptr queue,
4600 const unsigned long long* pointers,const int32_t* starts,const int32_t* count,
4601 const int32_t* entries,const block_q8_1* x,const NativeExpertLayout& L,
4602 float* first_output,float* second_output){
4603 queue->parallel_for<Kernel>(
4604  sycl::nd_range<3>(sycl::range<3>(1,groups,(Down?40:20)*4),sycl::range<3>(1,1,4)),
4605  [=](sycl::nd_item<3> it) [[intel::sycl_explicit_simd]] {
4606   const int ng=*count;if(int(it.get_group(1))>=ng)return;
4607   const int v=int(it.get_group(2))*64+int(it.get_local_id(2))*16;
4608   const bool high=!Down&&v>=640;const int row=high?v-640:v;
4609   float* dst=high?second_output:first_output;
4610   for(int g=int(it.get_group(1));g<ng;g+=int(it.get_group_range(1))){
4611    const auto* w=reinterpret_cast<const uint8_t*>(pointers[g])+(Down?L.down_off:(high?L.up_off:0));
4612    int e=starts[g],end=starts[g+1];
4613#define PVR_CALL(E) if constexpr(Down)pvr_down_packet<E>(w,row,e,entries,x,dst);else pvr_gu_packet<E>(w,row,e,entries,x,dst,int(L.n_ff))
4614    for(;end-e>=4;e+=4){PVR_CALL(4);}
4615    if(end-e>=2){PVR_CALL(2);e+=2;}
4616    for(;e<end;++e){PVR_CALL(1);}
4617#undef PVR_CALL
4618   }
4619  });
4620}
4621// IQ2_XXS: one ESIMD item retains the original four rows x eight K lanes.
4622inline bool p16_enabled(const sycl::device& dev){
4623 static const bool on=[] {const char*p=std::getenv("STRATA_PRIVATE_GU_XXS_PACKED");return p&&p[0]=='1';}();
4624 return on&&b60_main_actor()&&b60_weights_packed()&&strata::intel_gpu_gen(dev)==strata::IntelGpuGen::Battlemage;
4625}
4626SYCL_ESIMD_FUNCTION ESIMD_INLINE pvr::simd<int32_t,32>
4627p16_sign(pvr::simd<uint32_t,32> positive,pvr::simd<uint32_t,32> sign){
4628 pvr::simd<uint32_t,32> bit=((sign&15u)*0x00204081u)&0x01010101u;
4629 return (positive^(bit*255u))+bit;
4630}
4631template<int E>
4632SYCL_ESIMD_FUNCTION ESIMD_INLINE void p16_packet(
4633 const uint8_t* weights,int row,int first,const int32_t* tokens,
4634 const block_q8_1* xq,float* dst,int row_limit){
4635#pragma clang fp contract(off)
4636 pvr::simd<uint32_t,32> rows;
4637#pragma unroll
4638 for(int r=0;r<4;++r)rows.template select<8,1>(r*8)=uint32_t(row+r);
4639 auto valid=rows<uint32_t(row_limit);
4640 pvr::simd<float,32> sum[E];
4641#pragma unroll
4642 for(int e=0;e<E;++e)sum[e]=0.f;
4643 const auto* tile=weights+size_t(row/8)*5280;
4644 const int half=(row%8)/4;
4645#pragma unroll 1
4646 for(int kb=0;kb<10;++kb){
4647  const auto* block=tile+kb*528;
4648  auto qs=pvr::block_load<uint32_t,32>(reinterpret_cast<const uint32_t*>(block+half*128));
4649  auto aux=pvr::block_load<uint32_t,32>(reinterpret_cast<const uint32_t*>(block+256+half*128));
4650  pvr::simd<uint32_t,4> doff(0,2);
4651  auto dbits=pvr::gather<uint16_t,4>(reinterpret_cast<const uint16_t*>(block+512+half*8),doff);
4652  pvr::simd<float,4> d4=dbits.template bit_cast_view<sycl::half>().read();
4653  pvr::simd<float,32> d;
4654#pragma unroll
4655  for(int r=0;r<4;++r)d.template select<8,1>(r*8)=float(d4[r]);
4656  pvr::simd<int32_t,32> w[8];
4657#pragma unroll
4658  for(int j=0;j<4;++j){
4659   pvr::simd<uint32_t,32> index=(qs>>(8*j))&255u;
4660   auto grid=pvr::gather<uint64_t,32>(iq2xxs_grid,index*8u);
4661   pvr::simd<uint32_t,32> lo=grid,hi=grid>>32;
4662   pvr::simd<uint32_t,32> s7=(aux>>(7*j))&127u;
4663   pvr::simd<uint32_t,32> signs=s7|((pvr::cbit(s7)&1u)<<7);
4664   w[2*j]=p16_sign(lo,signs);w[2*j+1]=p16_sign(hi,signs>>4);
4665  }
4666  pvr::simd<int32_t,32> odd=(aux>>27)|1u;
4667#pragma unroll
4668  for(int e=0;e<E;++e){
4669   const auto* raw=reinterpret_cast<const uint8_t*>(xq+size_t(tokens[first+e])*80+kb*8);
4670   pvr::simd<uint32_t,8> offsets(0,36);
4671   auto u=pvr::gather<int32_t,64,8>(reinterpret_cast<const int32_t*>(raw),offsets+4u);
4672   auto dsbits=pvr::gather<uint16_t,8>(reinterpret_cast<const uint16_t*>(raw),offsets);
4673   pvr::simd<float,8> ds8=dsbits.template bit_cast_view<sycl::half>().read();
4674   pvr::simd<float,32> ds;
4675#pragma unroll
4676   for(int r=0;r<4;++r)ds.template select<8,1>(r*8)=ds8;
4677   pvr::simd<int32_t,32> s0=0,s1=0;
4678#pragma unroll
4679   for(int j=0;j<8;++j){
4680    pvr::simd<int32_t,32> word;
4681#pragma unroll
4682    for(int r=0;r<4;++r)word.template select<8,1>(r*8)=u.template select<8,1>(j*8);
4683    if(j<4)s0=pvr::dp4a<int32_t>(s0,w[j],word);else s1=pvr::dp4a<int32_t>(s1,w[j],word);
4684   }
4685   pvr::simd<int32_t,32> si=(s0+s1)*odd/8;
4686   pvr::simd<float,32> dot=si,factor=d*ds;
4687   pvr::simd<float,32> term=factor*dot;term.merge(0.f,!valid);
4688   sum[e]=sum[e]+term;
4689  }
4690 }
4691#pragma unroll
4692 for(int e=0;e<E;++e){
4693  pvr::simd<float,4> s[8];
4694#pragma unroll
4695  for(int p=0;p<8;++p)s[p]=sum[e].template select<4,8>(p);
4696  auto value=((s[0]+s[4])+(s[2]+s[6]))+((s[1]+s[5])+(s[3]+s[7]));
4697  pvr::block_store<float,4>(dst+size_t(first+e)*640+row,value);
4698 }
4699}
4700class GuXXSPackedKernel;
4701void launch_gu_xxs(unsigned groups,dpct::queue_ptr queue,
4702 const unsigned long long* pointers,const int32_t* starts,const int32_t* count,
4703 const int32_t* entries,const block_q8_1* x,const NativeExpertLayout& L,float* gate,float* up){
4704 queue->parallel_for<GuXXSPackedKernel>(
4705  sycl::nd_range<3>(sycl::range<3>(1,groups,80*4),sycl::range<3>(1,1,4)),
4706  [=](sycl::nd_item<3> it) [[intel::sycl_explicit_simd]] {
4707   const int ng=*count;if(int(it.get_group(1))>=ng)return;
4708   const int v=int(it.get_group(2))*16+int(it.get_local_id(2))*4;
4709   const bool high=v>=640;const int row=high?v-640:v;float* dst=high?up:gate;
4710   for(int g=int(it.get_group(1));g<ng;g+=int(it.get_group_range(1))){
4711    const auto* w=reinterpret_cast<const uint8_t*>(pointers[g])+(high?L.up_off:0);
4712    int e=starts[g],end=starts[g+1];
4713    for(;end-e>=4;e+=4)p16_packet<4>(w,row,e,entries,x,dst,int(L.n_ff));
4714    if(end-e>=2){p16_packet<2>(w,row,e,entries,x,dst,int(L.n_ff));e+=2;}
4715    for(;e<end;++e)p16_packet<1>(w,row,e,entries,x,dst,int(L.n_ff));
4716   }
4717  });
4718}
4719
4720
4721inline bool p4_enabled(){static const bool on=[] {const char*p=std::getenv("STRATA_PRIVATE_DOWN_S4");return p&&p[0]=='1';}();return on;}
4722SYCL_ESIMD_FUNCTION ESIMD_INLINE pvr::simd<uint32_t,16> p4_q2_eight(pvr::simd<uint32_t,16> q){
4723 q&=65535u;q=(q|(q<<8))&0x00ff00ffu;
4724 q=(q|(q<<4))&0x0f0f0f0fu;q=(q|(q<<2))&0x33333333u;
4725 return (q+0x77777777u)^0x88888888u;
4726}
4727template<int E>
4728SYCL_ESIMD_FUNCTION ESIMD_INLINE void p4_down_packet(
4729 const uint8_t* weights,int row,int first,const int32_t* destinations,
4730 const block_q8_1* xq,float* dst){
4731#pragma clang fp contract(off)
4732 pvr::simd<uint32_t,16> rows(row,1);auto valid=rows<2560u;
4733 pvr::simd<float,16> sum[8][E];
4734#pragma unroll
4735 for(int p=0;p<8;++p){
4736#pragma unroll
4737  for(int e=0;e<E;++e)sum[p][e]=0.f;
4738 }
4739 const auto* tile=weights+size_t(row/16)*2880;
4740 for(int step=0;step<3;++step){
4741#pragma unroll
4742  for(int p=0;p<8;++p){
4743   const int k=step*8+p;if(k>=20)continue;
4744   const auto* block=tile+(k/2)*288;
4745   auto q0=pvr::block_load<uint32_t,16>(reinterpret_cast<const uint32_t*>(block+(k%2)*128));
4746   auto q1=pvr::block_load<uint32_t,16>(reinterpret_cast<const uint32_t*>(block+(k%2)*128+64));
4747   auto bits=pvr::block_load<uint16_t,16>(reinterpret_cast<const uint16_t*>(block+256));
4748   pvr::simd<float,16> d=bits.template bit_cast_view<sycl::half>().read();
4749   pvr::simd<uint32_t,64> packed;
4750#pragma unroll
4751   for(int j=0;j<4;++j){
4752    pvr::simd<uint32_t,16> v=(j<2?q0:q1)>>(16*(j%2));
4753    packed.template select<16,1>(j*16)=p4_q2_eight(v);
4754   }
4755   // Keep the natural16-row dword order from the qualified IQ4 INT4 path.
4756   pvr::simd<uint16_t,128> B=packed.template bit_cast_view<uint16_t>().read();
4757   pvr::simd<uint32_t,E*8> aw;
4758   float scales[E];
4759#pragma unroll
4760   for(int e=0;e<E;++e){
4761    const auto* raw=reinterpret_cast<const uint8_t*>(xq+size_t(first+e)*20+k);
4762    pvr::simd<uint32_t,8> offset(4,4);
4763    aw.template select<8,1>(e*8)=pvr::gather<uint32_t,8>(reinterpret_cast<const uint32_t*>(raw),offset);
4764    pvr::simd<uint32_t,1> zero_offset=0;
4765    auto dsbits=pvr::gather<uint16_t,1>(reinterpret_cast<const uint16_t*>(raw),zero_offset);
4766    pvr::simd<float,1> ds=dsbits.template bit_cast_view<sycl::half>().read();scales[e]=ds[0];
4767   }
4768   pvr::simd<int8_t,E*32> A=aw.template bit_cast_view<int8_t>();
4769   pvr::simd<int32_t,E*16> zero=0;
4770   using P=pvr::xmx::dpas_argument_type;
4771   // Q2 nibbles have natural K order. IQ4 GGML's K0/K16 interleave is not used.
4772   auto product=pvr::xmx::dpas<8,E,int32_t,int32_t,uint16_t,int8_t,P::s4,P::s8>(zero,B,A);
4773#pragma unroll
4774   for(int e=0;e<E;++e){
4775    pvr::simd<int32_t,16> si=product.template select<16,1>(e*16);
4776    pvr::simd<float,16> dot=si;
4777    const float scalar_ds=scales[e];pvr::simd<float,16> factor=d*scalar_ds;
4778    pvr::simd<float,16> term=factor*dot;term.merge(0.f,!valid);
4779    sum[p][e]=sum[p][e]+term;
4780   }
4781  }
4782 }
4783#pragma unroll
4784 for(int e=0;e<E;++e){
4785  auto value=((sum[0][e]+sum[4][e])+(sum[2][e]+sum[6][e]))+
4786             ((sum[1][e]+sum[5][e])+(sum[3][e]+sum[7][e]));
4787  pvr::block_store<float,16>(dst+size_t(destinations[first+e])*2560+row,value);
4788 }
4789}
4790
4791class DownPackedS4Kernel;
4792template<bool Down,class Kernel>
4793void launch_pvr_s4(unsigned groups,dpct::queue_ptr queue,
4794 const unsigned long long* pointers,const int32_t* starts,const int32_t* count,
4795 const int32_t* entries,const block_q8_1* x,const NativeExpertLayout& L,
4796 float* first_output,float* second_output){
4797 queue->parallel_for<Kernel>(
4798  sycl::nd_range<3>(sycl::range<3>(1,groups,(Down?40:20)*4),sycl::range<3>(1,1,4)),
4799  [=](sycl::nd_item<3> it) [[intel::sycl_explicit_simd]] {
4800   const int ng=*count;if(int(it.get_group(1))>=ng)return;
4801   const int v=int(it.get_group(2))*64+int(it.get_local_id(2))*16;
4802   const bool high=!Down&&v>=640;const int row=high?v-640:v;
4803   float* dst=high?second_output:first_output;
4804   for(int g=int(it.get_group(1));g<ng;g+=int(it.get_group_range(1))){
4805    const auto* w=reinterpret_cast<const uint8_t*>(pointers[g])+(Down?L.down_off:(high?L.up_off:0));
4806    int e=starts[g],end=starts[g+1];
4807#define PVR_CALL(E) if constexpr(Down)p4_down_packet<E>(w,row,e,entries,x,dst);else pvr_gu_packet<E>(w,row,e,entries,x,dst,int(L.n_ff))
4808    for(;end-e>=4;e+=4){PVR_CALL(4);}
4809    if(end-e>=2){PVR_CALL(2);e+=2;}
4810    for(;e<end;++e){PVR_CALL(1);}
4811#undef PVR_CALL
4812   }
4813  });
4814}
4815
4816inline bool grid64_enabled(){static const bool on=[] {const char*p=std::getenv("STRATA_PRIVATE_GU_GRID64");return p&&p[0]=='1';}();return on;}
4817template<int E>
4818SYCL_ESIMD_FUNCTION ESIMD_INLINE void grid64_gu_packet(
4819 const uint8_t* weights,int row,int first,const int32_t* tokens,
4820 const block_q8_1* xq,float* dst,int row_limit){
4821#pragma clang fp contract(off)
4822 pvr::simd<uint32_t,16> rows(row,1);auto valid=rows<uint32_t(row_limit);
4823 pvr::simd<float,16> sum[8][E];
4824#pragma unroll
4825 for(int p=0;p<8;++p){
4826#pragma unroll
4827  for(int e=0;e<E;++e)sum[p][e]=0.f;
4828 }
4829 const auto* tile=weights+size_t(row/16)*13120;
4830 for(int kb=0;kb<10;++kb){
4831  const auto* block=tile+kb*1312;
4832  auto bits=pvr::block_load<uint16_t,16>(reinterpret_cast<const uint16_t*>(block+1280));
4833  pvr::simd<float,16> d=bits.template bit_cast_view<sycl::half>().read();
4834#pragma unroll
4835  for(int p=0;p<8;++p){
4836   const auto* plane=block+p*160;
4837   auto qs=pvr::block_load<uint32_t,16>(reinterpret_cast<const uint32_t*>(plane));
4838   auto signs=pvr::block_load<uint32_t,16>(reinterpret_cast<const uint32_t*>(plane+64));
4839   auto aux=pvr::block_load<uint16_t,16>(reinterpret_cast<const uint16_t*>(plane+128));
4840   pvr::simd<uint32_t,16> qh=aux&255u,scale=aux>>8;
4841   pvr::simd<uint32_t,64> indices,signs_all;
4842#pragma unroll
4843   for(int j=0;j<4;++j){
4844    indices.template select<16,1>(j*16)=((qs>>(8*j))&255u)|((qh<<(8-2*j))&0x300u);
4845    signs_all.template select<16,1>(j*16)=signs>>(8*j);
4846   }
4847   auto grid=pvr::gather<uint64_t,64>(iq2s_grid,indices*8u);
4848   pvr::simd<uint32_t,64> lo=grid,hi=grid>>32;
4849   pvr::simd<uint32_t,64> bit0=((signs_all&15u)*0x00204081u)&0x01010101u;
4850   pvr::simd<uint32_t,64> bit1=(((signs_all>>4)&15u)*0x00204081u)&0x01010101u;
4851   pvr::simd<int32_t,64> low_words=(lo^(bit0*255u))+bit0,high_words=(hi^(bit1*255u))+bit1;
4852   pvr::simd<int32_t,16> w[8];
4853#pragma unroll
4854   for(int j=0;j<4;++j){
4855    w[2*j]=low_words.template select<16,1>(j*16);
4856    w[2*j+1]=high_words.template select<16,1>(j*16);
4857   }
4858   pvr::simd<int32_t,16> a=scale&15u,b=scale>>4;
4859#pragma unroll
4860   for(int e=0;e<E;++e){
4861    const auto* raw=reinterpret_cast<const uint8_t*>(xq+size_t(tokens[first+e])*80+kb*8+p);
4862    pvr::simd<uint32_t,8> offset(4,4);
4863    auto u=pvr::gather<int32_t,8>(reinterpret_cast<const int32_t*>(raw),offset);
4864    pvr::simd<uint32_t,1> zero=0;
4865    auto dsbits=pvr::gather<uint16_t,1>(reinterpret_cast<const uint16_t*>(raw),zero);
4866    pvr::simd<float,1> ds=dsbits.template bit_cast_view<sycl::half>().read();
4867    pvr::simd<int32_t,16> s0=0,s1=0;
4868#pragma unroll
4869    for(int j=0;j<4;++j)s0=pvr::dp4a<int32_t>(s0,w[j],pvr::simd<int32_t,16>(u[j]));
4870#pragma unroll
4871    for(int j=4;j<8;++j)s1=pvr::dp4a<int32_t>(s1,w[j],pvr::simd<int32_t,16>(u[j]));
4872    pvr::simd<int32_t,16> si=(s0*a+s1*b+(s0+s1)/2)/4;
4873    pvr::simd<float,16> dot=si;
4874    const float scalar_ds=ds[0];pvr::simd<float,16> factor=d*scalar_ds;
4875    pvr::simd<float,16> term=factor*dot;term.merge(0.f,!valid);
4876    sum[p][e]=sum[p][e]+term;
4877   }
4878  }
4879 }
4880#pragma unroll
4881 for(int e=0;e<E;++e){
4882  auto value=((sum[0][e]+sum[4][e])+(sum[2][e]+sum[6][e]))+
4883             ((sum[1][e]+sum[5][e])+(sum[3][e]+sum[7][e]));
4884  pvr::block_store<float,16>(dst+size_t(first+e)*640+row,value);
4885 }
4886}
4887
4888class GuGrid64Kernel;
4889template<bool Down,class Kernel>
4890void launch_grid64(unsigned groups,dpct::queue_ptr queue,
4891 const unsigned long long* pointers,const int32_t* starts,const int32_t* count,
4892 const int32_t* entries,const block_q8_1* x,const NativeExpertLayout& L,
4893 float* first_output,float* second_output){
4894 queue->parallel_for<Kernel>(
4895  sycl::nd_range<3>(sycl::range<3>(1,groups,(Down?40:20)*4),sycl::range<3>(1,1,4)),
4896  [=](sycl::nd_item<3> it) [[intel::sycl_explicit_simd]] {
4897   const int ng=*count;if(int(it.get_group(1))>=ng)return;
4898   const int v=int(it.get_group(2))*64+int(it.get_local_id(2))*16;
4899   const bool high=!Down&&v>=640;const int row=high?v-640:v;
4900   float* dst=high?second_output:first_output;
4901   for(int g=int(it.get_group(1));g<ng;g+=int(it.get_group_range(1))){
4902    const auto* w=reinterpret_cast<const uint8_t*>(pointers[g])+(Down?L.down_off:(high?L.up_off:0));
4903    int e=starts[g],end=starts[g+1];
4904#define PVR_CALL(E) if constexpr(Down)pvr_down_packet<E>(w,row,e,entries,x,dst);else grid64_gu_packet<E>(w,row,e,entries,x,dst,int(L.n_ff))
4905    for(;end-e>=4;e+=4){PVR_CALL(4);}
4906    if(end-e>=2){PVR_CALL(2);e+=2;}
4907    for(;e<end;++e){PVR_CALL(1);}
4908#undef PVR_CALL
4909   }
4910  });
4911}
4912
4913inline bool grid_s4_enabled(){static const bool on=[] {const char*p=std::getenv("STRATA_PRIVATE_GU_GRID_S4");return p&&p[0]=='1';}();return on;}
4914static const uint32_t b60_s4_grid[1024]={
4915 0x11111111,0x11111115,0x11111133,0x11111151,0x11111155,0x11111313,0x11111331,0x11111335,0x11111353,0x11111511,0x11111515,0x11111533,0x11111551,0x11113113,0x11113131,0x11113135,
4916 0x11113153,0x11113311,0x11113315,0x11113333,0x11113351,0x11113513,0x11113531,0x11113535,0x11113553,0x11115111,0x11115115,0x11115133,0x11115151,0x11115313,0x11115331,0x11115511,
4917 0x11115533,0x11115555,0x11131113,0x11131131,0x11131135,0x11131153,0x11131311,0x11131315,0x11131333,0x11131351,0x11131513,0x11131531,0x11133111,0x11133115,0x11133133,0x11133151,
4918 0x11133313,0x11133331,0x11133335,0x11133353,0x11133511,0x11133533,0x11133551,0x11135113,0x11135131,0x11135311,0x11135315,0x11135333,0x11135513,0x11135531,0x11151111,0x11151115,
4919 0x11151133,0x11151151,0x11151313,0x11151331,0x11151511,0x11151555,0x11153113,0x11153131,0x11153135,0x11153153,0x11153311,0x11153333,0x11155111,0x11155133,0x11155155,0x11155331,
4920 0x11155515,0x11311113,0x11311131,0x11311135,0x11311153,0x11311311,0x11311315,0x11311333,0x11311351,0x11311513,0x11311531,0x11311535,0x11311553,0x11313111,0x11313115,0x11313133,
4921 0x11313151,0x11313155,0x11313313,0x11313331,0x11313335,0x11313353,0x11313511,0x11313515,0x11313533,0x11315113,0x11315131,0x11315135,0x11315153,0x11315311,0x11315333,0x11315351,
4922 0x11315513,0x11315531,0x11331111,0x11331115,0x11331133,0x11331151,0x11331155,0x11331313,0x11331331,0x11331335,0x11331353,0x11331511,0x11331533,0x11331551,0x11333113,0x11333131,
4923 0x11333135,0x11333153,0x11333311,0x11333315,0x11333333,0x11333351,0x11333513,0x11333531,0x11335111,0x11335115,0x11335133,0x11335151,0x11335313,0x11335331,0x11335511,0x11351113,
4924 0x11351131,0x11351135,0x11351153,0x11351311,0x11351333,0x11353111,0x11353133,0x11353151,0x11353313,0x11353331,0x11353511,0x11355113,0x11355131,0x11355311,0x11511111,0x11511115,
4925 0x11511133,0x11511151,0x11511313,0x11511331,0x11511335,0x11511353,0x11511511,0x11511533,0x11511555,0x11513113,0x11513131,0x11513135,0x11513153,0x11513311,0x11513315,0x11513333,
4926 0x11513351,0x11513513,0x11513531,0x11515111,0x11515133,0x11515331,0x11515555,0x11531113,0x11531131,0x11531311,0x11531315,0x11531333,0x11531351,0x11531513,0x11533111,0x11533133,
4927 0x11533151,0x11533313,0x11533331,0x11533511,0x11535113,0x11535311,0x11551111,0x11551313,0x11551331,0x11551515,0x11551551,0x11551555,0x11553311,0x11555353,0x13111113,0x13111131,
4928 0x13111135,0x13111153,0x13111311,0x13111315,0x13111333,0x13111351,0x13111513,0x13111531,0x13111535,0x13113111,0x13113115,0x13113133,0x13113151,0x13113313,0x13113331,0x13113335,
4929 0x13113353,0x13113511,0x13113515,0x13113533,0x13113551,0x13115113,0x13115131,0x13115135,0x13115311,0x13115333,0x13115351,0x13115513,0x13115531,0x13131111,0x13131115,0x13131133,
4930 0x13131151,0x13131155,0x13131313,0x13131331,0x13131335,0x13131353,0x13131511,0x13131515,0x13131533,0x13131551,0x13133113,0x13133131,0x13133135,0x13133153,0x13133311,0x13133315,
4931 0x13133333,0x13133351,0x13133513,0x13133531,0x13135111,0x13135115,0x13135133,0x13135151,0x13135313,0x13135331,0x13151113,0x13151131,0x13151153,0x13151311,0x13151333,0x13151513,
4932 0x13151531,0x13153111,0x13153133,0x13153313,0x13153331,0x13155113,0x13155131,0x13155311,0x13311111,0x13311115,0x13311133,0x13311151,0x13311313,0x13311331,0x13311335,0x13311353,
4933 0x13311511,0x13311533,0x13311551,0x13313113,0x13313131,0x13313135,0x13313153,0x13313311,0x13313315,0x13313333,0x13313351,0x13313513,0x13313531,0x13315111,0x13315115,0x13315133,
4934 0x13315151,0x13315313,0x13315331,0x13315511,0x13331113,0x13331131,0x13331135,0x13331153,0x13331311,0x13331315,0x13331333,0x13331351,0x13331513,0x13331531,0x13333111,0x13333115,
4935 0x13333133,0x13333151,0x13333313,0x13333331,0x13333511,0x13335113,0x13335131,0x13335311,0x13351111,0x13351133,0x13351151,0x13351313,0x13351331,0x13351511,0x13353113,0x13353131,
4936 0x13353311,0x13355111,0x13355555,0x13511113,0x13511131,0x13511135,0x13511153,0x13511311,0x13511333,0x13511351,0x13511513,0x13513111,0x13513115,0x13513133,0x13513151,0x13513313,
4937 0x13513331,0x13513511,0x13515113,0x13515131,0x13531111,0x13531115,0x13531133,0x13531151,0x13531313,0x13531331,0x13531511,0x13533113,0x13533131,0x13533311,0x13533553,0x13535515,
4938 0x13551131,0x13551311,0x13553111,0x13553335,0x15111111,0x15111115,0x15111133,0x15111151,0x15111313,0x15111331,0x15111335,0x15111353,0x15111511,0x15111533,0x15111555,0x15113113,
4939 0x15113131,0x15113311,0x15113315,0x15113333,0x15113531,0x15115111,0x15115155,0x15115331,0x15115555,0x15131113,0x15131131,0x15131311,0x15131315,0x15131333,0x15131513,0x15133111,
4940 0x15133115,0x15133133,0x15133313,0x15133331,0x15133511,0x15135113,0x15135131,0x15135311,0x15151111,0x15151155,0x15151515,0x15151551,0x15151555,0x15153131,0x15153311,0x15155151,
4941 0x15155155,0x15155551,0x15311113,0x15311131,0x15311135,0x15311153,0x15311311,0x15311333,0x15311351,0x15311513,0x15311531,0x15313111,0x15313115,0x15313133,0x15313151,0x15313313,
4942 0x15313331,0x15313511,0x15315113,0x15315131,0x15315311,0x15331111,0x15331133,0x15331151,0x15331313,0x15331331,0x15331511,0x15333113,0x15333131,0x15333311,0x15333535,0x15335111,
4943 0x15351113,0x15351131,0x15351311,0x15353111,0x15353353,0x15511111,0x15511133,0x15511313,0x15511331,0x15513113,0x15513131,0x15513311,0x15515155,0x15515555,0x15531113,0x15531131,
4944 0x15531311,0x15535333,0x15551155,0x15551515,0x15553531,0x15555151,0x15555155,0x31111113,0x31111131,0x31111135,0x31111153,0x31111311,0x31111315,0x31111333,0x31111351,0x31111355,
4945 0x31111513,0x31111531,0x31111535,0x31113111,0x31113115,0x31113133,0x31113151,0x31113155,0x31113313,0x31113331,0x31113335,0x31113353,0x31113511,0x31113515,0x31113533,0x31115113,
4946 0x31115131,0x31115311,0x31115333,0x31115351,0x31115513,0x31115531,0x31131111,0x31131115,0x31131133,0x31131151,0x31131313,0x31131331,0x31131335,0x31131353,0x31131511,0x31131515,
4947 0x31131533,0x31133113,0x31133131,0x31133135,0x31133153,0x31133311,0x31133315,0x31133333,0x31133351,0x31133513,0x31133531,0x31135111,0x31135115,0x31135133,0x31135151,0x31135313,
4948 0x31135331,0x31135511,0x31151113,0x31151131,0x31151311,0x31151315,0x31151333,0x31151351,0x31151531,0x31153111,0x31153133,0x31153151,0x31153313,0x31153331,0x31153511,0x31155113,
4949 0x31155131,0x31311111,0x31311115,0x31311133,0x31311151,0x31311155,0x31311313,0x31311331,0x31311335,0x31311353,0x31311511,0x31311515,0x31311533,0x31311551,0x31313113,0x31313131,
4950 0x31313135,0x31313153,0x31313311,0x31313315,0x31313333,0x31313351,0x31313513,0x31313531,0x31315111,0x31315115,0x31315133,0x31315151,0x31315313,0x31315331,0x31315511,0x31331113,
4951 0x31331131,0x31331135,0x31331153,0x31331311,0x31331315,0x31331333,0x31331351,0x31331513,0x31331531,0x31333111,0x31333115,0x31333133,0x31333151,0x31333313,0x31333331,0x31333511,
4952 0x31333555,0x31335113,0x31335131,0x31335311,0x31351111,0x31351115,0x31351133,0x31351151,0x31351313,0x31351331,0x31351511,0x31353113,0x31353131,0x31353311,0x31355111,0x31355533,
4953 0x31511113,0x31511131,0x31511153,0x31511311,0x31511315,0x31511333,0x31511351,0x31511513,0x31511531,0x31513111,0x31513115,0x31513133,0x31513151,0x31513313,0x31513331,0x31513511,
4954 0x31515131,0x31515311,0x31531111,0x31531115,0x31531133,0x31531151,0x31531313,0x31531331,0x31531511,0x31533113,0x31533131,0x31533311,0x31535111,0x31535335,0x31551113,0x31551131,
4955 0x31551311,0x31553111,0x33111111,0x33111115,0x33111133,0x33111151,0x33111313,0x33111331,0x33111335,0x33111353,0x33111511,0x33111515,0x33111533,0x33111551,0x33113113,0x33113131,
4956 0x33113135,0x33113153,0x33113311,0x33113315,0x33113333,0x33113351,0x33113513,0x33113531,0x33115111,0x33115115,0x33115133,0x33115151,0x33115313,0x33115331,0x33131113,0x33131131,
4957 0x33131135,0x33131153,0x33131311,0x33131315,0x33131333,0x33131351,0x33131513,0x33131531,0x33133111,0x33133115,0x33133133,0x33133151,0x33133313,0x33133331,0x33133511,0x33135113,
4958 0x33135131,0x33135311,0x33151111,0x33151133,0x33151151,0x33151313,0x33151331,0x33151511,0x33153113,0x33153131,0x33153311,0x33153553,0x33155111,0x33311113,0x33311131,0x33311135,
4959 0x33311153,0x33311311,0x33311315,0x33311333,0x33311351,0x33311513,0x33311531,0x33313111,0x33313115,0x33313133,0x33313151,0x33313313,0x33313331,0x33313511,0x33315113,0x33315131,
4960 0x33315311,0x33331111,0x33331115,0x33331133,0x33331151,0x33331313,0x33331331,0x33331511,0x33333113,0x33333131,0x33333311,0x33335111,0x33351113,0x33351131,0x33351311,0x33351535,
4961 0x33353111,0x33511111,0x33511115,0x33511133,0x33511151,0x33511313,0x33511331,0x33511511,0x33513113,0x33513131,0x33513311,0x33513355,0x33515111,0x33531113,0x33531131,0x33531311,
4962 0x33533111,0x33551111,0x33551353,0x33555133,0x33555551,0x35111113,0x35111131,0x35111135,0x35111311,0x35111315,0x35111333,0x35111351,0x35111513,0x35111531,0x35113111,0x35113133,
4963 0x35113151,0x35113313,0x35113331,0x35113511,0x35115131,0x35115311,0x35131111,0x35131115,0x35131133,0x35131151,0x35131313,0x35131331,0x35131511,0x35133113,0x35133131,0x35133311,
4964 0x35135111,0x35135353,0x35151131,0x35151311,0x35153111,0x35153335,0x35155513,0x35311111,0x35311133,0x35311151,0x35311313,0x35311331,0x35311511,0x35313113,0x35313131,0x35313311,
4965 0x35315111,0x35331113,0x35331131,0x35331311,0x35333111,0x35333155,0x35333551,0x35335315,0x35351111,0x35355331,0x35511113,0x35511131,0x35511311,0x35513533,0x35515351,0x35531111,
4966 0x35531555,0x35553115,0x35555513,0x51111111,0x51111115,0x51111133,0x51111151,0x51111313,0x51111331,0x51111353,0x51111511,0x51111533,0x51113113,0x51113131,0x51113311,0x51113315,
4967 0x51113333,0x51113351,0x51113513,0x51115111,0x51115133,0x51115313,0x51115331,0x51131113,0x51131131,0x51131153,0x51131311,0x51131315,0x51131333,0x51131351,0x51131513,0x51131531,
4968 0x51133111,0x51133115,0x51133133,0x51133151,0x51133313,0x51133331,0x51135113,0x51135131,0x51135311,0x51135553,0x51151111,0x51151133,0x51151155,0x51151313,0x51151331,0x51153113,
4969 0x51153131,0x51153311,0x51311113,0x51311131,0x51311135,0x51311153,0x51311311,0x51311315,0x51311333,0x51311351,0x51311513,0x51313111,0x51313115,0x51313133,0x51313151,0x51313313,
4970 0x51313331,0x51313511,0x51315113,0x51315131,0x51315311,0x51331111,0x51331115,0x51331133,0x51331151,0x51331313,0x51331331,0x51331511,0x51333113,0x51333131,0x51333311,0x51335111,
4971 0x51335155,0x51351113,0x51351131,0x51351311,0x51351553,0x51353111,0x51511111,0x51511133,0x51511313,0x51511331,0x51513113,0x51513131,0x51513311,0x51515515,0x51531113,0x51531131,
4972 0x51533111,0x51533533,0x51551515,0x51553351,0x51553355,0x51555115,0x51555515,0x53111113,0x53111131,0x53111153,0x53111311,0x53111315,0x53111333,0x53111351,0x53111531,0x53113111,
4973 0x53113115,0x53113133,0x53113151,0x53113313,0x53113331,0x53113511,0x53115113,0x53115131,0x53115311,0x53131111,0x53131133,0x53131313,0x53131331,0x53133113,0x53133131,0x53133311,
4974 0x53133355,0x53151113,0x53151131,0x53151311,0x53153111,0x53155535,0x53311111,0x53311115,0x53311133,0x53311151,0x53311313,0x53311331,0x53311511,0x53313113,0x53313131,0x53313311,
4975 0x53315111,0x53315335,0x53331113,0x53331131,0x53331311,0x53333111,0x53335351,0x53335513,0x53351111,0x53353135,0x53353531,0x53511113,0x53511131,0x53511311,0x53511535,0x53513111,
4976 0x53515553,0x53531111,0x53533153,0x53533315,0x53555311,0x55111111,0x55111133,0x55111155,0x55111331,0x55111515,0x55111555,0x55113113,0x55113131,0x55113311,0x55115515,0x55115555,
4977 0x55133111,0x55133533,0x55151115,0x55151155,0x55151515,0x55151551,0x55151555,0x55155115,0x55155151,0x55155155,0x55155551,0x55311113,0x55311131,0x55311311,0x55313111,0x55315153,
4978 0x55315531,0x55331111,0x55331353,0x55353313,0x55511155,0x55511551,0x55515515,0x55533331,0x55535135,0x55551151,0x55551155,0x55551511,0x55551515,0x55551551,0x55555151,0x55555555,
4979};
4980template<int E>
4981SYCL_ESIMD_FUNCTION ESIMD_INLINE void grid_s4_packet(
4982 const uint8_t* weights,int row,int first,const int32_t* tokens,
4983 const block_q8_1* xq,float* dst,int row_limit){
4984#pragma clang fp contract(off)
4985 pvr::simd<uint32_t,16> rows(row,1);auto valid=rows<uint32_t(row_limit);
4986 pvr::simd<float,16> sum[8][E];
4987#pragma unroll
4988 for(int p=0;p<8;++p){
4989#pragma unroll
4990  for(int e=0;e<E;++e)sum[p][e]=0.f;
4991 }
4992 const auto* tile=weights+size_t(row/16)*13120;
4993 for(int kb=0;kb<10;++kb){
4994  const auto* block=tile+kb*1312;
4995  auto bits=pvr::block_load<uint16_t,16>(reinterpret_cast<const uint16_t*>(block+1280));
4996  pvr::simd<float,16> d=bits.template bit_cast_view<sycl::half>().read();
4997#pragma unroll
4998  for(int p=0;p<8;++p){
4999   const auto* plane=block+p*160;
5000   auto qs=pvr::block_load<uint32_t,16>(reinterpret_cast<const uint32_t*>(plane));
5001   auto signs=pvr::block_load<uint32_t,16>(reinterpret_cast<const uint32_t*>(plane+64));
5002   auto aux=pvr::block_load<uint16_t,16>(reinterpret_cast<const uint16_t*>(plane+128));
5003   pvr::simd<uint32_t,16> qh=aux&255u,scale=aux>>8;
5004   pvr::simd<uint32_t,64> indices,signs_all;
5005#pragma unroll
5006   for(int j=0;j<4;++j){
5007    indices.template select<16,1>(j*16)=((qs>>(8*j))&255u)|((qh<<(8-2*j))&0x300u);
5008    signs_all.template select<16,1>(j*16)=signs>>(8*j);
5009   }
5010   auto packed=pvr::gather<uint32_t,64>(b60_s4_grid,indices*4u);
5011   pvr::simd<uint32_t,64> residual=((packed>>1)&0x33333333u)+((packed>>2)&0x11111111u);
5012   pvr::simd<uint32_t,64> bits=signs_all&255u;
5013   bits=(bits|(bits<<12))&0x000f000fu;
5014   bits=(bits|(bits<<6))&0x03030303u;
5015   bits=(bits|(bits<<3))&0x11111111u;
5016   pvr::simd<uint32_t,64> mask=bits*15u;
5017   pvr::simd<uint32_t,64> coarse=(packed^mask)+bits;
5018   pvr::simd<uint32_t,64> negative=((0x88888888u-residual)^0x88888888u);
5019   residual=residual^((residual^negative)&mask);
5020   pvr::simd<uint16_t,128> Bc=coarse.template bit_cast_view<uint16_t>().read();
5021   pvr::simd<uint16_t,128> Br=residual.template bit_cast_view<uint16_t>().read();
5022   pvr::simd<int32_t,16> a=scale&15u,b=scale>>4;
5023   pvr::simd<int32_t,E*16> aw=0;
5024   pvr::simd<float,E> activation_scale;
5025#pragma unroll
5026   for(int e=0;e<E;++e){
5027    const auto* raw=reinterpret_cast<const uint8_t*>(xq+size_t(tokens[first+e])*80+kb*8+p);
5028    pvr::simd<uint32_t,8> offset(4,4);
5029    auto u=pvr::gather<int32_t,8>(reinterpret_cast<const int32_t*>(raw),offset);
5030    aw.template select<4,1>(e*16)=u.template select<4,1>(0);
5031    aw.template select<4,1>(e*16+12)=u.template select<4,1>(4);
5032    pvr::simd<uint32_t,1> zero_offset=0;
5033    auto dsbits=pvr::gather<uint16_t,1>(reinterpret_cast<const uint16_t*>(raw),zero_offset);
5034    pvr::simd<float,1> ds=dsbits.template bit_cast_view<sycl::half>().read();
5035    activation_scale[e]=ds[0];
5036   }
5037   pvr::simd<int8_t,E*64> A=aw.template bit_cast_view<int8_t>();
5038   pvr::simd<int32_t,E*32> zero=0;
5039   using P=pvr::xmx::dpas_argument_type;
5040   auto Cc=pvr::xmx::dpas<8,E*2,int32_t,int32_t,uint16_t,int8_t,P::s4,P::s8>(zero,Bc,A);
5041   auto Cr=pvr::xmx::dpas<8,E*2,int32_t,int32_t,uint16_t,int8_t,P::s4,P::s8>(zero,Br,A);
5042   auto pair_dots=Cc*8+Cr;
5043#pragma unroll
5044   for(int e=0;e<E;++e){
5045    pvr::simd<int32_t,16> s0=pair_dots.template select<16,1>(e*32);
5046    pvr::simd<int32_t,16> s1=pair_dots.template select<16,1>(e*32+16);
5047    pvr::simd<int32_t,16> si=(s0*a+s1*b+(s0+s1)/2)/4;
5048    pvr::simd<float,16> dot=si;
5049    const float scalar_ds=activation_scale[e];pvr::simd<float,16> factor=d*scalar_ds;
5050    pvr::simd<float,16> term=factor*dot;term.merge(0.f,!valid);
5051    sum[p][e]=sum[p][e]+term;
5052   }
5053  }
5054 }
5055#pragma unroll
5056 for(int e=0;e<E;++e){
5057  auto value=((sum[0][e]+sum[4][e])+(sum[2][e]+sum[6][e]))+
5058             ((sum[1][e]+sum[5][e])+(sum[3][e]+sum[7][e]));
5059  pvr::block_store<float,16>(dst+size_t(first+e)*640+row,value);
5060 }
5061}
5062
5063class GuGridS4Kernel;
5064template<bool Down,class Kernel>
5065void launch_grid_s4(unsigned groups,dpct::queue_ptr queue,
5066 const unsigned long long* pointers,const int32_t* starts,const int32_t* count,
5067 const int32_t* entries,const block_q8_1* x,const NativeExpertLayout& L,
5068 float* first_output,float* second_output){
5069 queue->parallel_for<Kernel>(
5070  sycl::nd_range<3>(sycl::range<3>(1,groups,(Down?40:20)*4),sycl::range<3>(1,1,4)),
5071  [=](sycl::nd_item<3> it) [[intel::sycl_explicit_simd]] {
5072   const int ng=*count;if(int(it.get_group(1))>=ng)return;
5073   const int v=int(it.get_group(2))*64+int(it.get_local_id(2))*16;
5074   const bool high=!Down&&v>=640;const int row=high?v-640:v;
5075   float* dst=high?second_output:first_output;
5076   for(int g=int(it.get_group(1));g<ng;g+=int(it.get_group_range(1))){
5077    const auto* w=reinterpret_cast<const uint8_t*>(pointers[g])+(Down?L.down_off:(high?L.up_off:0));
5078    int e=starts[g],end=starts[g+1];
5079#define PVR_CALL(E) if constexpr(Down)pvr_down_packet<E>(w,row,e,entries,x,dst);else grid_s4_packet<E>(w,row,e,entries,x,dst,int(L.n_ff))
5080    for(;end-e>=4;e+=4){PVR_CALL(4);}
5081    if(end-e>=2){PVR_CALL(2);e+=2;}
5082    for(;e<end;++e){PVR_CALL(1);}
5083#undef PVR_CALL
5084   }
5085  });
5086}
5087
5088// IQ1_M: one ESIMD item retains the original four rows x eight K lanes.
5089inline bool i1_enabled(const sycl::device& dev){
5090 static const bool on=[] {const char*p=std::getenv("STRATA_PRIVATE_GU_IQ1_PACKED");return p&&p[0]=='1';}();
5091 return on&&b60_main_actor()&&b60_weights_packed()&&strata::intel_gpu_gen(dev)==strata::IntelGpuGen::Battlemage;
5092}
5093template<int E>
5094SYCL_ESIMD_FUNCTION ESIMD_INLINE void i1_packet(
5095 const uint8_t* weights,int row,int first,const int32_t* tokens,
5096 const block_q8_1* xq,float* dst,int row_limit){
5097#pragma clang fp contract(off)
5098 pvr::simd<uint32_t,32> rows;
5099#pragma unroll
5100 for(int r=0;r<4;++r)rows.template select<8,1>(r*8)=uint32_t(row+r);
5101 auto valid=rows<uint32_t(row_limit);
5102 pvr::simd<float,32> sum[E];
5103#pragma unroll
5104 for(int e=0;e<E;++e)sum[e]=0.f;
5105 const auto* tile=weights+size_t(row/8)*4480;
5106 const int half=(row%8)/4;
5107#pragma unroll 1
5108 for(int kb=0;kb<10;++kb){
5109  const auto* block=tile+kb*448;
5110  auto qs=pvr::block_load<uint32_t,32>(reinterpret_cast<const uint32_t*>(block+half*128));
5111  auto qh=pvr::block_load<uint16_t,32>(reinterpret_cast<const uint16_t*>(block+256+half*64));
5112  auto sc=pvr::block_load<uint16_t,16>(reinterpret_cast<const uint16_t*>(block+384+half*32));
5113  pvr::simd<uint16_t,4> dbits=(sc.template select<4,4>(0)>>12)|((sc.template select<4,4>(1)>>8)&0x00f0u)|((sc.template select<4,4>(2)>>4)&0x0f00u)|(sc.template select<4,4>(3)&0xf000u);
5114  pvr::simd<float,4> d4=dbits.template bit_cast_view<sycl::half>().read();
5115  pvr::simd<float,32> d;
5116  pvr::simd<uint32_t,32> tmp;
5117#pragma unroll
5118  for(int r=0;r<4;++r){
5119   d.template select<8,1>(r*8)=float(d4[r]);
5120#pragma unroll
5121   for(int p=0;p<8;++p)tmp[r*8+p]=uint32_t(sc[r*4+p/2])>>(6*(p%2));
5122  }
5123  pvr::simd<int32_t,32> sc0=2*(tmp&7u)+1,sc1=2*((tmp>>3)&7u)+1;
5124  pvr::simd<int32_t,32> w[8];
5125#pragma unroll
5126  for(int j=0;j<4;++j){
5127   pvr::simd<uint32_t,32> high=qh>>(4*j);
5128   pvr::simd<uint32_t,32> index=((qs>>(8*j))&255u)|((high&7u)<<8);
5129   auto grid=pvr::gather<uint32_t,32>(iq1s_grid_gpu,index*4u);
5130   pvr::simd<uint32_t,32> offset=(7u+((high&8u)>>2))*0x01010101u;
5131   pvr::simd<uint32_t,32> lo=(grid&0x0f0f0f0fu)<<3,hi=((grid>>4)&0x0f0f0f0fu)<<3;
5132   w[2*j]=((lo|0x80808080u)-offset)^0x80808080u;
5133   w[2*j+1]=((hi|0x80808080u)-offset)^0x80808080u;
5134  }
5135#pragma unroll
5136  for(int e=0;e<E;++e){
5137   const auto* raw=reinterpret_cast<const uint8_t*>(xq+size_t(tokens[first+e])*80+kb*8);
5138   pvr::simd<uint32_t,8> offsets(0,36);
5139   auto u=pvr::gather<int32_t,64,8>(reinterpret_cast<const int32_t*>(raw),offsets+4u);
5140   auto dsbits=pvr::gather<uint16_t,8>(reinterpret_cast<const uint16_t*>(raw),offsets);
5141   pvr::simd<float,8> ds8=dsbits.template bit_cast_view<sycl::half>().read();
5142   pvr::simd<float,32> ds;
5143#pragma unroll
5144   for(int r=0;r<4;++r)ds.template select<8,1>(r*8)=ds8;
5145   pvr::simd<int32_t,32> s0=0,s1=0;
5146#pragma unroll
5147   for(int j=0;j<8;++j){
5148    pvr::simd<int32_t,32> word;
5149#pragma unroll
5150    for(int r=0;r<4;++r)word.template select<8,1>(r*8)=u.template select<8,1>(j*8);
5151    if(j<4)s0=pvr::dp4a<int32_t>(s0,w[j],word);else s1=pvr::dp4a<int32_t>(s1,w[j],word);
5152   }
5153   pvr::simd<int16_t,32> a16=s0,b16=s1;
5154   pvr::simd<int32_t,32> a32=a16,b32=b16;
5155   pvr::simd<int32_t,32> scaled=a32*sc0+b32*sc1;
5156   pvr::simd<float,32> integer_value=scaled;
5157   pvr::simd<float,32> dot=integer_value*0.125f,factor=d*ds;
5158   pvr::simd<float,32> term=factor*dot;term.merge(0.f,!valid);
5159   sum[e]=sum[e]+term;
5160  }
5161 }
5162#pragma unroll
5163 for(int e=0;e<E;++e){
5164  pvr::simd<float,4> s[8];
5165#pragma unroll
5166  for(int p=0;p<8;++p)s[p]=sum[e].template select<4,8>(p);
5167  auto value=((s[0]+s[4])+(s[2]+s[6]))+((s[1]+s[5])+(s[3]+s[7]));
5168  pvr::block_store<float,4>(dst+size_t(first+e)*640+row,value);
5169 }
5170}
5171class GuIQ1PackedKernel;
5172void launch_gu_iq1(unsigned groups,dpct::queue_ptr queue,
5173 const unsigned long long* pointers,const int32_t* starts,const int32_t* count,
5174 const int32_t* entries,const block_q8_1* x,const NativeExpertLayout& L,float* gate,float* up){
5175 queue->parallel_for<GuIQ1PackedKernel>(
5176  sycl::nd_range<3>(sycl::range<3>(1,groups,80*4),sycl::range<3>(1,1,4)),
5177  [=](sycl::nd_item<3> it) [[intel::sycl_explicit_simd]] {
5178   const int ng=*count;if(int(it.get_group(1))>=ng)return;
5179   const int v=int(it.get_group(2))*16+int(it.get_local_id(2))*4;
5180   const bool high=v>=640;const int row=high?v-640:v;float* dst=high?up:gate;
5181   for(int g=int(it.get_group(1));g<ng;g+=int(it.get_group_range(1))){
5182    const auto* w=reinterpret_cast<const uint8_t*>(pointers[g])+(high?L.up_off:0);
5183    int e=starts[g],end=starts[g+1];
5184    for(;end-e>=4;e+=4)i1_packet<4>(w,row,e,entries,x,dst,int(L.n_ff));
5185    if(end-e>=2){i1_packet<2>(w,row,e,entries,x,dst,int(L.n_ff));e+=2;}
5186    for(;e<end;++e)i1_packet<1>(w,row,e,entries,x,dst,int(L.n_ff));
5187   }
5188  });
5189}
5190
5191inline bool b60_next_iq_pool(){static const bool on=[] {const char*p=std::getenv("STRATA_PRIVATE_B60_NEXT_POOL");return p&&p[0]=='1';}();return on;}
5192inline bool grid_s4_slm_enabled(){static const bool on=[] {const char*p=std::getenv("STRATA_PRIVATE_GU_S4_SLM");return p&&p[0]=='1';}();return on;}
5193template<int E>
5194SYCL_ESIMD_FUNCTION ESIMD_INLINE void grid_s4_slm_packet(
5195 const uint8_t* weights,int row,int first,const int32_t* tokens,
5196 const block_q8_1* xq,float* dst,int row_limit){
5197#pragma clang fp contract(off)
5198 pvr::simd<uint32_t,16> rows(row,1);auto valid=rows<uint32_t(row_limit);
5199 pvr::simd<float,16> sum[8][E];
5200#pragma unroll
5201 for(int p=0;p<8;++p){
5202#pragma unroll
5203  for(int e=0;e<E;++e)sum[p][e]=0.f;
5204 }
5205 const auto* tile=weights+size_t(row/16)*13120;
5206 for(int kb=0;kb<10;++kb){
5207  const auto* block=tile+kb*1312;
5208  auto bits=pvr::block_load<uint16_t,16>(reinterpret_cast<const uint16_t*>(block+1280));
5209  pvr::simd<float,16> d=bits.template bit_cast_view<sycl::half>().read();
5210#pragma unroll
5211  for(int p=0;p<8;++p){
5212   const auto* plane=block+p*160;
5213   auto qs=pvr::block_load<uint32_t,16>(reinterpret_cast<const uint32_t*>(plane));
5214   auto signs=pvr::block_load<uint32_t,16>(reinterpret_cast<const uint32_t*>(plane+64));
5215   auto aux=pvr::block_load<uint16_t,16>(reinterpret_cast<const uint16_t*>(plane+128));
5216   pvr::simd<uint32_t,16> qh=aux&255u,scale=aux>>8;
5217   pvr::simd<uint32_t,64> indices,signs_all;
5218#pragma unroll
5219   for(int j=0;j<4;++j){
5220    indices.template select<16,1>(j*16)=((qs>>(8*j))&255u)|((qh<<(8-2*j))&0x300u);
5221    signs_all.template select<16,1>(j*16)=signs>>(8*j);
5222   }
5223   auto packed=pvr::slm_gather<uint32_t,64>(indices*4u);
5224   pvr::simd<uint32_t,64> residual=((packed>>1)&0x33333333u)+((packed>>2)&0x11111111u);
5225   pvr::simd<uint32_t,64> bits=signs_all&255u;
5226   bits=(bits|(bits<<12))&0x000f000fu;
5227   bits=(bits|(bits<<6))&0x03030303u;
5228   bits=(bits|(bits<<3))&0x11111111u;
5229   pvr::simd<uint32_t,64> mask=bits*15u;
5230   pvr::simd<uint32_t,64> coarse=(packed^mask)+bits;
5231   pvr::simd<uint32_t,64> negative=((0x88888888u-residual)^0x88888888u);
5232   residual=residual^((residual^negative)&mask);
5233   pvr::simd<uint16_t,128> Bc=coarse.template bit_cast_view<uint16_t>().read();
5234   pvr::simd<uint16_t,128> Br=residual.template bit_cast_view<uint16_t>().read();
5235   pvr::simd<int32_t,16> a=scale&15u,b=scale>>4;
5236   pvr::simd<int32_t,E*16> aw=0;
5237   pvr::simd<float,E> activation_scale;
5238#pragma unroll
5239   for(int e=0;e<E;++e){
5240    const auto* raw=reinterpret_cast<const uint8_t*>(xq+size_t(tokens[first+e])*80+kb*8+p);
5241    pvr::simd<uint32_t,8> offset(4,4);
5242    auto u=pvr::gather<int32_t,8>(reinterpret_cast<const int32_t*>(raw),offset);
5243    aw.template select<4,1>(e*16)=u.template select<4,1>(0);
5244    aw.template select<4,1>(e*16+12)=u.template select<4,1>(4);
5245    pvr::simd<uint32_t,1> zero_offset=0;
5246    auto dsbits=pvr::gather<uint16_t,1>(reinterpret_cast<const uint16_t*>(raw),zero_offset);
5247    pvr::simd<float,1> ds=dsbits.template bit_cast_view<sycl::half>().read();
5248    activation_scale[e]=ds[0];
5249   }
5250   pvr::simd<int8_t,E*64> A=aw.template bit_cast_view<int8_t>();
5251   pvr::simd<int32_t,E*32> zero=0;
5252   using P=pvr::xmx::dpas_argument_type;
5253   auto Cc=pvr::xmx::dpas<8,E*2,int32_t,int32_t,uint16_t,int8_t,P::s4,P::s8>(zero,Bc,A);
5254   auto Cr=pvr::xmx::dpas<8,E*2,int32_t,int32_t,uint16_t,int8_t,P::s4,P::s8>(zero,Br,A);
5255   auto pair_dots=Cc*8+Cr;
5256#pragma unroll
5257   for(int e=0;e<E;++e){
5258    pvr::simd<int32_t,16> s0=pair_dots.template select<16,1>(e*32);
5259    pvr::simd<int32_t,16> s1=pair_dots.template select<16,1>(e*32+16);
5260    pvr::simd<int32_t,16> si=(s0*a+s1*b+(s0+s1)/2)/4;
5261    pvr::simd<float,16> dot=si;
5262    const float scalar_ds=activation_scale[e];pvr::simd<float,16> factor=d*scalar_ds;
5263    pvr::simd<float,16> term=factor*dot;term.merge(0.f,!valid);
5264    sum[p][e]=sum[p][e]+term;
5265   }
5266  }
5267 }
5268#pragma unroll
5269 for(int e=0;e<E;++e){
5270  auto value=((sum[0][e]+sum[4][e])+(sum[2][e]+sum[6][e]))+
5271             ((sum[1][e]+sum[5][e])+(sum[3][e]+sum[7][e]));
5272  pvr::block_store<float,16>(dst+size_t(first+e)*640+row,value);
5273 }
5274}
5275
5276class GuGridS4SlmKernel;
5277template<bool Down,class Kernel>
5278void launch_grid_s4_slm(unsigned groups,dpct::queue_ptr queue,
5279 const unsigned long long* pointers,const int32_t* starts,const int32_t* count,
5280 const int32_t* entries,const block_q8_1* x,const NativeExpertLayout& L,
5281 float* first_output,float* second_output){
5282 queue->parallel_for<Kernel>(
5283  sycl::nd_range<3>(sycl::range<3>(1,groups,(Down?40:20)*4),sycl::range<3>(1,1,4)),
5284  [=](sycl::nd_item<3> it) [[intel::sycl_explicit_simd]] {
5285   const int ng=*count;if(int(it.get_group(1))>=ng)return;
5286   pvr::slm_init<4096>();
5287   const int lid=int(it.get_local_id(2));
5288   pvr::simd<uint32_t,128> grid_offsets(lid*1024,4);
5289   auto grid_lo=pvr::gather<uint32_t,128>(b60_s4_grid,grid_offsets);
5290   auto grid_hi=pvr::gather<uint32_t,128>(b60_s4_grid,grid_offsets+512u);
5291   pvr::slm_block_store<uint32_t,128>(lid*1024,grid_lo);
5292   pvr::slm_block_store<uint32_t,128>(lid*1024+512,grid_hi);
5293   pvr::barrier();
5294
5295   const int v=int(it.get_group(2))*64+int(it.get_local_id(2))*16;
5296   const bool high=!Down&&v>=640;const int row=high?v-640:v;
5297   float* dst=high?second_output:first_output;
5298   for(int g=int(it.get_group(1));g<ng;g+=int(it.get_group_range(1))){
5299    const auto* w=reinterpret_cast<const uint8_t*>(pointers[g])+(Down?L.down_off:(high?L.up_off:0));
5300    int e=starts[g],end=starts[g+1];
5301#define PVR_CALL(E) if constexpr(Down)pvr_down_packet<E>(w,row,e,entries,x,dst);else grid_s4_slm_packet<E>(w,row,e,entries,x,dst,int(L.n_ff))
5302    for(;end-e>=4;e+=4){PVR_CALL(4);}
5303    if(end-e>=2){PVR_CALL(2);e+=2;}
5304    for(;e<end;++e){PVR_CALL(1);}
5305#undef PVR_CALL
5306   }
5307  });
5308}
5309
5310inline bool grid_s4_basis9_enabled(){static const bool on=[] {const char*p=std::getenv("STRATA_PRIVATE_GU_S4_BASIS9");return p&&p[0]=='1';}();return on;}
5311template<int E>
5312SYCL_ESIMD_FUNCTION ESIMD_INLINE void grid_s4_basis9_packet(
5313 const uint8_t* weights,int row,int first,const int32_t* tokens,
5314 const block_q8_1* xq,float* dst,int row_limit){
5315#pragma clang fp contract(off)
5316 pvr::simd<uint32_t,16> rows(row,1);auto valid=rows<uint32_t(row_limit);
5317 pvr::simd<float,16> sum[8][E];
5318#pragma unroll
5319 for(int p=0;p<8;++p){
5320#pragma unroll
5321  for(int e=0;e<E;++e)sum[p][e]=0.f;
5322 }
5323 const auto* tile=weights+size_t(row/16)*13120;
5324 for(int kb=0;kb<10;++kb){
5325  const auto* block=tile+kb*1312;
5326  auto bits=pvr::block_load<uint16_t,16>(reinterpret_cast<const uint16_t*>(block+1280));
5327  pvr::simd<float,16> d=bits.template bit_cast_view<sycl::half>().read();
5328#pragma unroll
5329  for(int p=0;p<8;++p){
5330   const auto* plane=block+p*160;
5331   auto qs=pvr::block_load<uint32_t,16>(reinterpret_cast<const uint32_t*>(plane));
5332   auto signs=pvr::block_load<uint32_t,16>(reinterpret_cast<const uint32_t*>(plane+64));
5333   auto aux=pvr::block_load<uint16_t,16>(reinterpret_cast<const uint16_t*>(plane+128));
5334   pvr::simd<uint32_t,16> qh=aux&255u,scale=aux>>8;
5335   pvr::simd<uint32_t,64> indices,signs_all;
5336#pragma unroll
5337   for(int j=0;j<4;++j){
5338    indices.template select<16,1>(j*16)=((qs>>(8*j))&255u)|((qh<<(8-2*j))&0x300u);
5339    signs_all.template select<16,1>(j*16)=signs>>(8*j);
5340   }
5341   auto packed=pvr::slm_gather<uint32_t,64>(indices*4u);
5342   pvr::simd<uint32_t,64> residual=0x11111111u+(((packed>>1)|(packed>>2))&0x11111111u);
5343   pvr::simd<uint32_t,64> bits=signs_all&255u;
5344   bits=(bits|(bits<<12))&0x000f000fu;
5345   bits=(bits|(bits<<6))&0x03030303u;
5346   bits=(bits|(bits<<3))&0x11111111u;
5347   pvr::simd<uint32_t,64> mask=bits*15u;
5348   pvr::simd<uint32_t,64> coarse=(packed^mask)+bits;
5349   residual=(residual^mask)+bits;
5350   pvr::simd<uint16_t,128> Bc=coarse.template bit_cast_view<uint16_t>().read();
5351   pvr::simd<uint16_t,128> Br=residual.template bit_cast_view<uint16_t>().read();
5352   pvr::simd<int32_t,16> a=scale&15u,b=scale>>4;
5353   pvr::simd<int32_t,E*16> aw=0;
5354   pvr::simd<float,E> activation_scale;
5355#pragma unroll
5356   for(int e=0;e<E;++e){
5357    const auto* raw=reinterpret_cast<const uint8_t*>(xq+size_t(tokens[first+e])*80+kb*8+p);
5358    pvr::simd<uint32_t,8> offset(4,4);
5359    auto u=pvr::gather<int32_t,8>(reinterpret_cast<const int32_t*>(raw),offset);
5360    aw.template select<4,1>(e*16)=u.template select<4,1>(0);
5361    aw.template select<4,1>(e*16+12)=u.template select<4,1>(4);
5362    pvr::simd<uint32_t,1> zero_offset=0;
5363    auto dsbits=pvr::gather<uint16_t,1>(reinterpret_cast<const uint16_t*>(raw),zero_offset);
5364    pvr::simd<float,1> ds=dsbits.template bit_cast_view<sycl::half>().read();
5365    activation_scale[e]=ds[0];
5366   }
5367   pvr::simd<int8_t,E*64> A=aw.template bit_cast_view<int8_t>();
5368   pvr::simd<int32_t,E*32> zero=0;
5369   using P=pvr::xmx::dpas_argument_type;
5370   auto Cc=pvr::xmx::dpas<8,E*2,int32_t,int32_t,uint16_t,int8_t,P::s4,P::s8>(zero,Bc,A);
5371   auto Cr=pvr::xmx::dpas<8,E*2,int32_t,int32_t,uint16_t,int8_t,P::s4,P::s8>(zero,Br,A);
5372   auto pair_dots=Cc*9-Cr;
5373#pragma unroll
5374   for(int e=0;e<E;++e){
5375    pvr::simd<int32_t,16> s0=pair_dots.template select<16,1>(e*32);
5376    pvr::simd<int32_t,16> s1=pair_dots.template select<16,1>(e*32+16);
5377    pvr::simd<int32_t,16> si=(s0*a+s1*b+(s0+s1)/2)/4;
5378    pvr::simd<float,16> dot=si;
5379    const float scalar_ds=activation_scale[e];pvr::simd<float,16> factor=d*scalar_ds;
5380    pvr::simd<float,16> term=factor*dot;term.merge(0.f,!valid);
5381    sum[p][e]=sum[p][e]+term;
5382   }
5383  }
5384 }
5385#pragma unroll
5386 for(int e=0;e<E;++e){
5387  auto value=((sum[0][e]+sum[4][e])+(sum[2][e]+sum[6][e]))+
5388             ((sum[1][e]+sum[5][e])+(sum[3][e]+sum[7][e]));
5389  pvr::block_store<float,16>(dst+size_t(first+e)*640+row,value);
5390 }
5391}
5392
5393class GuGridS4Basis9Kernel;
5394template<bool Down,class Kernel>
5395void launch_grid_s4_basis9(unsigned groups,dpct::queue_ptr queue,
5396 const unsigned long long* pointers,const int32_t* starts,const int32_t* count,
5397 const int32_t* entries,const block_q8_1* x,const NativeExpertLayout& L,
5398 float* first_output,float* second_output){
5399 queue->parallel_for<Kernel>(
5400  sycl::nd_range<3>(sycl::range<3>(1,groups,(Down?40:20)*4),sycl::range<3>(1,1,4)),
5401  [=](sycl::nd_item<3> it) [[intel::sycl_explicit_simd]] {
5402   const int ng=*count;if(int(it.get_group(1))>=ng)return;
5403   pvr::slm_init<4096>();
5404   const int lid=int(it.get_local_id(2));
5405   pvr::simd<uint32_t,128> grid_offsets(lid*1024,4);
5406   auto grid_lo=pvr::gather<uint32_t,128>(b60_s4_grid,grid_offsets);
5407   auto grid_hi=pvr::gather<uint32_t,128>(b60_s4_grid,grid_offsets+512u);
5408   pvr::slm_block_store<uint32_t,128>(lid*1024,grid_lo);
5409   pvr::slm_block_store<uint32_t,128>(lid*1024+512,grid_hi);
5410   pvr::barrier();
5411
5412   const int v=int(it.get_group(2))*64+int(it.get_local_id(2))*16;
5413   const bool high=!Down&&v>=640;const int row=high?v-640:v;
5414   float* dst=high?second_output:first_output;
5415   for(int g=int(it.get_group(1));g<ng;g+=int(it.get_group_range(1))){
5416    const auto* w=reinterpret_cast<const uint8_t*>(pointers[g])+(Down?L.down_off:(high?L.up_off:0));
5417    int e=starts[g],end=starts[g+1];
5418#define PVR_CALL(E) if constexpr(Down)pvr_down_packet<E>(w,row,e,entries,x,dst);else grid_s4_basis9_packet<E>(w,row,e,entries,x,dst,int(L.n_ff))
5419    for(;end-e>=4;e+=4){PVR_CALL(4);}
5420    if(end-e>=2){PVR_CALL(2);e+=2;}
5421    for(;e<end;++e){PVR_CALL(1);}
5422#undef PVR_CALL
5423   }
5424  });
5425}
5426
5427inline bool grid_s4_wg16_enabled(){static const bool on=[] {const char*p=std::getenv("STRATA_PRIVATE_GU_S4_WG16");return p&&p[0]=='1';}();return on;}
5428class GuGridS4WG16Kernel;
5429template<bool Down,class Kernel>
5430void launch_grid_s4_wg16(unsigned groups,dpct::queue_ptr queue,
5431 const unsigned long long* pointers,const int32_t* starts,const int32_t* count,
5432 const int32_t* entries,const block_q8_1* x,const NativeExpertLayout& L,
5433 float* first_output,float* second_output){
5434 queue->parallel_for<Kernel>(
5435  sycl::nd_range<3>(sycl::range<3>(1,groups,(Down?10:5)*16),sycl::range<3>(1,1,16)),
5436  [=](sycl::nd_item<3> it) [[intel::sycl_explicit_simd]] {
5437   const int ng=*count;if(int(it.get_group(1))>=ng)return;
5438   pvr::slm_init<4096>();
5439   const int lid=int(it.get_local_id(2));
5440   pvr::simd<uint32_t,64> grid_offsets(lid*256,4);
5441   auto grid=pvr::gather<uint32_t,64>(b60_s4_grid,grid_offsets);
5442   pvr::slm_block_store<uint32_t,64>(lid*256,grid);
5443   pvr::barrier();
5444
5445   const int v=int(it.get_group(2))*256+int(it.get_local_id(2))*16;
5446   const bool high=!Down&&v>=640;const int row=high?v-640:v;
5447   float* dst=high?second_output:first_output;
5448   for(int g=int(it.get_group(1));g<ng;g+=int(it.get_group_range(1))){
5449    const auto* w=reinterpret_cast<const uint8_t*>(pointers[g])+(Down?L.down_off:(high?L.up_off:0));
5450    int e=starts[g],end=starts[g+1];
5451#define PVR_CALL(E) if constexpr(Down)pvr_down_packet<E>(w,row,e,entries,x,dst);else grid_s4_basis9_packet<E>(w,row,e,entries,x,dst,int(L.n_ff))
5452    for(;end-e>=4;e+=4){PVR_CALL(4);}
5453    if(end-e>=2){PVR_CALL(2);e+=2;}
5454    for(;e<end;++e){PVR_CALL(1);}
5455#undef PVR_CALL
5456   }
5457  });
5458}
5459
5460static const uint32_t b60_xxs_s4_grid[256]={
5461 0x11111111,0x11111115,0x11111133,0x11111151,0x11111155,0x11111313,0x11111331,0x11111511,0x11111515,0x11111551,0x11111555,0x11113113,0x11113131,0x11113311,0x11113351,0x11113513,
5462 0x11113531,0x11115111,0x11115115,0x11115155,0x11115515,0x11131113,0x11131131,0x11131311,0x11131333,0x11133111,0x11135131,0x11135351,0x11151111,0x11151115,0x11151515,0x11155115,
5463 0x11311113,0x11311131,0x11311311,0x11311513,0x11311531,0x11313111,0x11313115,0x11313151,0x11313511,0x11315113,0x11315131,0x11315311,0x11315531,0x11331111,0x11331115,0x11331151,
5464 0x11331511,0x11333135,0x11333553,0x11335111,0x11335313,0x11351153,0x11351311,0x11353111,0x11355131,0x11355531,0x11511111,0x11511133,0x11511151,0x11511331,0x11511551,0x11513113,
5465 0x11513131,0x11513311,0x11513315,0x11515151,0x11531131,0x11533111,0x11551115,0x11551331,0x13111113,0x13111131,0x13111311,0x13111513,0x13113111,0x13113511,0x13115131,0x13115311,
5466 0x13115333,0x13131111,0x13131151,0x13131511,0x13133311,0x13133355,0x13135111,0x13151531,0x13153133,0x13311111,0x13311151,0x13311511,0x13311533,0x13313153,0x13315111,0x13331351,
5467 0x13333515,0x13351111,0x13351335,0x13511113,0x13511131,0x13511311,0x13513111,0x13515113,0x13531111,0x13531133,0x13535511,0x13553313,0x15111111,0x15111115,0x15111155,0x15113131,
5468 0x15113513,0x15115111,0x15115115,0x15131553,0x15133151,0x15151111,0x15151115,0x15311113,0x15311131,0x15311311,0x15313111,0x15313335,0x15331111,0x15333113,0x15333531,0x15355311,
5469 0x15511151,0x15511511,0x15515331,0x15553131,0x31111113,0x31111131,0x31111311,0x31111351,0x31111513,0x31111531,0x31113111,0x31113151,0x31113335,0x31113511,0x31115113,0x31115131,
5470 0x31115311,0x31131111,0x31131511,0x31133513,0x31135111,0x31135133,0x31151113,0x31151311,0x31153151,0x31153335,0x31153551,0x31311111,0x31311151,0x31311511,0x31315111,0x31315353,
5471 0x31331315,0x31331531,0x31351111,0x31511113,0x31511131,0x31511311,0x31513111,0x31513133,0x31531111,0x31533351,0x31533513,0x31535115,0x31553133,0x31555311,0x33111111,0x33111151,
5472 0x33111313,0x33111353,0x33111511,0x33115111,0x33115151,0x33131131,0x33133115,0x33135531,0x33155313,0x33315311,0x33315315,0x33331155,0x33351113,0x33353331,0x33511111,0x33511313,
5473 0x33511353,0x33513531,0x33533111,0x33551151,0x35111131,0x35111311,0x35113111,0x35113551,0x35131111,0x35133333,0x35151351,0x35153511,0x35311111,0x35311133,0x35331311,0x35331315,
5474 0x35335131,0x35513115,0x51111111,0x51111115,0x51111155,0x51113113,0x51115115,0x51131131,0x51131351,0x51133111,0x51151313,0x51311113,0x51311131,0x51311311,0x51311333,0x51313111,
5475 0x51313511,0x51331111,0x51333135,0x51335331,0x51351153,0x51353111,0x51353511,0x51511115,0x51531131,0x51551313,0x53111131,0x53111311,0x53111531,0x53113111,0x53115513,0x53131335,
5476 0x53135111,0x53153133,0x53311111,0x53311515,0x53313131,0x53333313,0x53515113,0x53531511,0x55111115,0x55113311,0x55115133,0x55131153,0x55151111,0x55311351,0x55513311,0x55531131,
5477};
5478// Sixteen original rows; each retains its eight K leaves and original FP tree.
5479inline bool xxs_s4_enabled(){
5480 static const bool on=[] {const char*p=std::getenv("STRATA_PRIVATE_GU_XXS_S4");return p&&p[0]=='1';}();
5481 return on;
5482}
5483template<int E>
5484SYCL_ESIMD_FUNCTION ESIMD_INLINE void xxs_s4_packet(
5485 const uint8_t* weights,int row,int first,const int32_t* tokens,
5486 const block_q8_1* xq,float* dst,int row_limit){
5487#pragma clang fp contract(off)
5488 pvr::simd<uint32_t,16> rows(row,1);auto valid=rows<uint32_t(row_limit);
5489 pvr::simd<float,16> sum[8][E];
5490#pragma unroll
5491 for(int p=0;p<8;++p){
5492#pragma unroll
5493  for(int e=0;e<E;++e)sum[p][e]=0.f;
5494 }
5495 const auto* tile=weights+size_t(row/8)*5280;
5496#pragma unroll 1
5497 for(int kb=0;kb<10;++kb){
5498  const auto* block=tile+kb*528;
5499  pvr::simd<uint32_t,16> doff;
5500  doff.template select<8,1>(0)=pvr::simd<uint32_t,8>(0,2);
5501  doff.template select<8,1>(8)=pvr::simd<uint32_t,8>(5280,2);
5502  auto dbits=pvr::gather<uint16_t,16>(reinterpret_cast<const uint16_t*>(block+512),doff);
5503  pvr::simd<float,16> d=dbits.template bit_cast_view<sycl::half>().read();
5504#pragma unroll
5505  for(int p=0;p<8;++p){
5506   pvr::simd<uint32_t,16> offsets;
5507   offsets.template select<8,1>(0)=pvr::simd<uint32_t,8>(p*4,32);
5508   offsets.template select<8,1>(8)=pvr::simd<uint32_t,8>(5280+p*4,32);
5509   auto qs=pvr::gather<uint32_t,16>(reinterpret_cast<const uint32_t*>(block),offsets);
5510   auto aux=pvr::gather<uint32_t,16>(reinterpret_cast<const uint32_t*>(block+256),offsets);
5511   pvr::simd<uint32_t,64> indices,signs_all;
5512#pragma unroll
5513   for(int j=0;j<4;++j){
5514    indices.template select<16,1>(j*16)=(qs>>(8*j))&255u;
5515    pvr::simd<uint32_t,16> s7=(aux>>(7*j))&127u;
5516    signs_all.template select<16,1>(j*16)=s7|((pvr::cbit(s7)&1u)<<7);
5517   }
5518   auto packed=pvr::slm_gather<uint32_t,64>(indices*4u);
5519   pvr::simd<uint32_t,64> residual=0x11111111u+(((packed>>1)|(packed>>2))&0x11111111u);
5520   pvr::simd<uint32_t,64> bits=signs_all&255u;
5521   bits=(bits|(bits<<12))&0x000f000fu;
5522   bits=(bits|(bits<<6))&0x03030303u;
5523   bits=(bits|(bits<<3))&0x11111111u;
5524   pvr::simd<uint32_t,64> mask=bits*15u;
5525   pvr::simd<uint32_t,64> coarse=(packed^mask)+bits;
5526   residual=(residual^mask)+bits;
5527   // All sixteen DPAS columns hold real rows from two adjacent eight-row field tiles.
5528   pvr::simd<uint16_t,128> Bc=coarse.template bit_cast_view<uint16_t>().read();
5529   pvr::simd<uint16_t,128> Br=residual.template bit_cast_view<uint16_t>().read();
5530   pvr::simd<int32_t,E*8> aw;
5531   pvr::simd<float,E> activation_scale;
5532#pragma unroll
5533   for(int e=0;e<E;++e){
5534    const auto* raw=reinterpret_cast<const uint8_t*>(xq+size_t(tokens[first+e])*80+kb*8+p);
5535    pvr::simd<uint32_t,8> offset(4,4);
5536    aw.template select<8,1>(e*8)=pvr::gather<int32_t,8>(reinterpret_cast<const int32_t*>(raw),offset);
5537    pvr::simd<uint32_t,1> zero_offset=0;
5538    auto dsbits=pvr::gather<uint16_t,1>(reinterpret_cast<const uint16_t*>(raw),zero_offset);
5539    pvr::simd<float,1> ds=dsbits.template bit_cast_view<sycl::half>().read();
5540    activation_scale[e]=ds[0];
5541   }
5542   pvr::simd<int8_t,E*32> A=aw.template bit_cast_view<int8_t>();
5543   pvr::simd<int32_t,E*16> zero=0;
5544   using P=pvr::xmx::dpas_argument_type;
5545   auto Cc=pvr::xmx::dpas<8,E,int32_t,int32_t,uint16_t,int8_t,P::s4,P::s8>(zero,Bc,A);
5546   auto Cr=pvr::xmx::dpas<8,E,int32_t,int32_t,uint16_t,int8_t,P::s4,P::s8>(zero,Br,A);
5547   auto dots=Cc*9-Cr;
5548   pvr::simd<int32_t,16> odd=(aux>>27)|1u;
5549#pragma unroll
5550   for(int e=0;e<E;++e){
5551    pvr::simd<int32_t,16> dot32=dots.template select<16,1>(e*16);
5552    pvr::simd<int32_t,16> si=dot32*odd/8;
5553    pvr::simd<float,16> dot=si;
5554    const float scalar_ds=activation_scale[e];pvr::simd<float,16> factor=d*scalar_ds;
5555    pvr::simd<float,16> term=factor*dot;term.merge(0.f,!valid);
5556    sum[p][e]=sum[p][e]+term;
5557   }
5558  }
5559 }
5560#pragma unroll
5561 for(int e=0;e<E;++e){
5562  auto value=((sum[0][e]+sum[4][e])+(sum[2][e]+sum[6][e]))+
5563             ((sum[1][e]+sum[5][e])+(sum[3][e]+sum[7][e]));
5564  pvr::block_store<float,16>(dst+size_t(first+e)*640+row,value);
5565 }
5566}
5567class GuXXSS4Rows16Kernel;
5568void launch_gu_xxs_s4(unsigned groups,dpct::queue_ptr queue,
5569 const unsigned long long* pointers,const int32_t* starts,const int32_t* count,
5570 const int32_t* entries,const block_q8_1* x,const NativeExpertLayout& L,float* gate,float* up){
5571 queue->parallel_for<GuXXSS4Rows16Kernel>(
5572  sycl::nd_range<3>(sycl::range<3>(1,groups,20*4),sycl::range<3>(1,1,4)),
5573  [=](sycl::nd_item<3> it) [[intel::sycl_explicit_simd]] {
5574   const int ng=*count;if(int(it.get_group(1))>=ng)return;
5575   pvr::slm_init<1024>();
5576   const int lid=int(it.get_local_id(2));
5577   pvr::simd<uint32_t,64> offsets(lid*256,4);
5578   auto grid=pvr::gather<uint32_t,64>(b60_xxs_s4_grid,offsets);
5579   pvr::slm_block_store<uint32_t,64>(lid*256,grid);
5580   pvr::barrier();
5581   const int v=int(it.get_group(2))*64+lid*16;
5582   const bool high=v>=640;const int row=high?v-640:v;float* dst=high?up:gate;
5583   for(int g=int(it.get_group(1));g<ng;g+=int(it.get_group_range(1))){
5584    const auto* w=reinterpret_cast<const uint8_t*>(pointers[g])+(high?L.up_off:0);
5585    int e=starts[g],end=starts[g+1];
5586    for(;end-e>=4;e+=4)xxs_s4_packet<4>(w,row,e,entries,x,dst,int(L.n_ff));
5587    if(end-e>=2){xxs_s4_packet<2>(w,row,e,entries,x,dst,int(L.n_ff));e+=2;}
5588    for(;e<end;++e)xxs_s4_packet<1>(w,row,e,entries,x,dst,int(L.n_ff));
5589   }
5590  });
5591}
5592
5593void launch_ps_gu(unsigned groups,dpct::queue_ptr s,const unsigned long long* p,
5594 const int32_t* st,const int32_t* n,const int32_t* tok,const block_q8_1* x,
5595 const NativeExpertLayout& L,float* gate,float* up){
5596 launch_pvr<false,GuPackedRegisterKernel>(groups,s,p,st,n,tok,x,L,gate,up);
5597}
5598void launch_ps_down(unsigned groups,dpct::queue_ptr s,const unsigned long long* p,
5599 const int32_t* st,const int32_t* n,const int32_t* dst,const block_q8_1* x,
5600 const NativeExpertLayout& L,float* out){
5601 if(p4_enabled())launch_pvr_s4<true,DownPackedS4Kernel>(groups,s,p,st,n,dst,x,L,out,nullptr);
5602 else launch_pvr<true,DownPackedRegisterKernel>(groups,s,p,st,n,dst,x,L,out,nullptr);
5603}
5604
5605template <int TG, int LN, bool KM = true>
5606void launch_gu_port(unsigned groups, dpct::queue_ptr s, const unsigned long long *grp_ptr, const int32_t *grp_start,
5607                    const int32_t *n_groups, const int32_t *ent_tok, const block_q8_1 *X,
5608                    const NativeExpertLayout &L, float *gate, float *up, bool bounded = false) {
5609    // #3153's explicit opt-ins first (STRATA_PRIVATE_* / STRATA_SYCL_*, all off unless set), then the head's #4185 defaults
5610    if constexpr(TG==16 && LN==8 && KM) {
5611        if(L.n_embd==2560 && L.n_ff==640 && !g_old_kernels && !g_split_multi && p16_enabled(s->get_device())) {
5612            launch_gu_xxs(groups,s,grp_ptr,grp_start,n_groups,ent_tok,X,L,gate,up);return;
5613        }
5614    }
5615    if constexpr(TG==29 && LN==8 && KM) {
5616        if(L.n_embd==2560 && L.n_ff==640 && !g_old_kernels && !g_split_multi && i1_enabled(s->get_device())) {
5617            launch_gu_iq1(groups,s,grp_ptr,grp_start,n_groups,ent_tok,X,L,gate,up);return;
5618        }
5619    }
5620    if constexpr((TG==16 || TG==29) && LN==8 && KM) {
5621        if(L.n_embd==2560 && L.n_ff==640 && !g_old_kernels && !g_split_multi && gu_prepared_enabled(s->get_device())) {
5622            launch_gu_prepared<TG>(groups,s,grp_ptr,grp_start,n_groups,ent_tok,X,L,gate,up);return;
5623        }
5624    }
5625    if constexpr(TG==22 && LN==8 && KM) {
5626        if(L.n_embd==2560 && L.n_ff==640 && !g_old_kernels && !g_split_multi && ps_enabled(s->get_device())) {
5627            launch_ps_gu(groups,s,grp_ptr,grp_start,n_groups,ent_tok,X,L,gate,up);return;
5628        }
5629    }
5630    // BEGIN PRIVATE GU22 ROW REUSE HOOK (#3153; launch_gu_row_reuse is the head's two-row reuse launcher, the same kernel)
5631    if constexpr (TG == 22 && LN == 8) {
5632#if !STRATA_GRID_SLM
5633        if (!g_old_kernels && !g_split_multi && gu22_row_reuse_enabled(s->get_device())) {
5634            launch_gu_row_reuse<TG>(groups, s, grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up);
5635            return;
5636        }
5637#endif
5638    }
5639    // END PRIVATE GU22 ROW REUSE HOOK
5640    if constexpr (TG == 16 && LN == 8) {
5641        if (env_on("STRATA_SYCL_PACKED_SIGNS") && !g_old_kernels && !g_split_multi && !g_iq2xxs_reuse && bounded &&
5642            L.n_embd == 2560 && L.n_ff == 640 && L.gu_row == 660 && L.up_off == 640 * 660) {
5643            launch_gu_packed_fixed<10016>(groups, s, grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up);
5644            return;
5645        }
5646    }
5647    if constexpr (TG == 22 && LN == 8) {
5648        if (env_on("STRATA_SYCL_PACKED_SIGNS") && !g_old_kernels && !g_split_multi && bounded &&
5649            L.n_embd == 2560 && L.n_ff == 640 && L.gu_row == 820 && L.up_off == 640 * 820) {
5650            launch_gu_packed_fixed<10022>(groups, s, grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up);
5651            return;
5652        }
5653    }
5654    if constexpr (TG == 16 && LN == 8) {
5655        if (g_iq2xxs_reuse) { launch_gu_iq2xxs_reuse(groups, s, grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); return; }
5656    }
5657#if !STRATA_GRID_SLM
5658    if constexpr ((TG == 22 || TG == 18) && LN == 8) {
5659        static const bool reuse = strata::bm_default_on(TG == 22 ? "STRATA_IQ2S_GU_ROW_REUSE" : "STRATA_IQ3XXS_GU_ROW_REUSE", s->get_device());
5660        if (reuse && !g_old_kernels && !g_split_multi &&
5661            strata::intel_gpu_gen(s->get_device()) == strata::IntelGpuGen::Battlemage) {
5662            static const bool note = [] {
5663                std::fprintf(stderr, "strata: %s raw two-row GU reuse enabled (8 lanes, SIMD16)\n",
5664                             TG == 22 ? "IQ2_S" : "IQ3_XXS");
5665                return true;
5666            }();
5667            (void) note;
5668            launch_gu_row_reuse<TG>(groups, s, grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up);
5669            return;
5670        }
5671    }
5672#endif
5673    constexpr int ROWS = 256 / LN;
5674    const unsigned gx = (unsigned) ((2 * L.n_ff + ROWS - 1) / ROWS);
5675    auto exp_props = sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};
5676    strata::kprof::kp(s, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class native_gu_port, dpct_kernel_scalar<TG>, dpct_kernel_scalar<LN>, dpct_kernel_scalar<KM>>>(
5677        sycl::nd_range<3>(sycl::range<3>(1, groups, (size_t) gx * 256), sycl::range<3>(1, 1, 256)), exp_props,
5678        [=](sycl::nd_item<3>) [[sycl::reqd_sub_group_size(32)]] {
5679            native_gu_kernel<TG, LN, false, false, KM>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up);
5680        });
5681}
5682// STRATA_KQ_SPLIT=0 (or native_expert_set_kq_split(false)): the K-quant / Q5_1 / Q8_0 lane kernels without the
5683// multi-entry split (one weight read per entry, as before); the outputs are the same bits either way
5684bool g_kq_split = [] { const char* v = std::getenv("STRATA_KQ_SPLIT"); return !(v && v[0] == '0'); }();
5685template <int TG, int LN>
5686void gu_port_km(unsigned groups, dpct::queue_ptr s, const unsigned long long *grp_ptr, const int32_t *grp_start,
5687                const int32_t *n_groups, const int32_t *ent_tok, const block_q8_1 *X, const NativeExpertLayout &L,
5688                float *gate, float *up, bool bounded = false) {
5689    if constexpr (KqSplit<TG>::has) {
5690        if (!g_kq_split) { launch_gu_port<TG, LN, false>(groups, s, grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up, bounded); return; }
5691        if constexpr (TG == 23) {
5692            static const bool logged = [] {
5693                std::fprintf(stderr, "strata: IQ4_XS exact multi-entry decode reuse enabled\n");
5694                return true;
5695            }();
5696            (void) logged;
5697        }
5698    }
5699    launch_gu_port<TG, LN, true>(groups, s, grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up, bounded);
5700}
5701template <int TG>
5702void launch_gu_lanes(dpct::dim3 grid, dpct::queue_ptr s, const unsigned long long *grp_ptr, const int32_t *grp_start,
5703                     const int32_t *n_groups, const int32_t *ent_tok, const block_q8_1 *X,
5704                     const NativeExpertLayout &L, float *gate, float *up, bool bounded = false) {
5705    // IQ4_XS retains its original lane selection and reduction tree.
5706    switch ((KqSplit<TG>::has && TG != 23) ? kq_gu_lanes() : gu_lanes()) {
5707        case 4: gu_port_km<TG, 4>(grid.y, s, grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up, bounded); break;
5708        case 16: gu_port_km<TG, 16>(grid.y, s, grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up, bounded); break;
5709        case 32: gu_port_km<TG, 32>(grid.y, s, grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up, bounded); break;
5710        default: gu_port_km<TG, 8>(grid.y, s, grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up, bounded); break;
5711    }
5712}
5713template <int TD, int LN, bool KM = true>
5714void launch_down_port(unsigned groups, dpct::queue_ptr s, const unsigned long long *grp_ptr, const int32_t *grp_start,
5715                      const int32_t *n_groups, const int32_t *ent_dst, const block_q8_1 *hq,
5716                      const NativeExpertLayout &L, float *out) {
5717    constexpr int ROWS = 256 / LN;
5718    const unsigned gx = (unsigned) ((L.n_embd + ROWS - 1) / ROWS);
5719    auto exp_props = sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};
5720    strata::kprof::kp(s, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class native_down_port, dpct_kernel_scalar<TD>, dpct_kernel_scalar<LN>, dpct_kernel_scalar<KM>>>(
5721        sycl::nd_range<3>(sycl::range<3>(1, groups, (size_t) gx * 256), sycl::range<3>(1, 1, 256)), exp_props,
5722        [=](sycl::nd_item<3>) [[sycl::reqd_sub_group_size(32)]] {
5723            native_down_kernel<TD, LN, KM>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out);
5724        });
5725}
5726
5727void launch_down_q2_word_expand(unsigned groups, dpct::queue_ptr s, const unsigned long long *grp_ptr,
5728                                const int32_t *grp_start, const int32_t *n_groups, const int32_t *ent_dst,
5729                                const block_q8_1 *hq, const NativeExpertLayout &L, float *out) {
5730    if(L.n_embd==2560 && L.n_ff==640 && ps_enabled(s->get_device())) {
5731        launch_ps_down(groups,s,grp_ptr,grp_start,n_groups,ent_dst,hq,L,out);return;
5732    }
5733    constexpr int LN = 8, ROWS = 256 / LN;
5734    const unsigned gx = (unsigned) ((L.n_embd + ROWS - 1) / ROWS);
5735    auto exp_props = sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};
5736    s->parallel_for<class native_down_q2_word_expand>(
5737        sycl::nd_range<3>(sycl::range<3>(1, groups, (size_t) gx * 256), sycl::range<3>(1, 1, 256)), exp_props,
5738        [=](sycl::nd_item<3>) [[sycl::reqd_sub_group_size(32)]] {
5739            native_down_kernel<42, LN, true, true>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out);
5740        });
5741}
5742
5743template <int TD, int LN>
5744void down_port_km(unsigned groups, dpct::queue_ptr s, const unsigned long long *grp_ptr, const int32_t *grp_start,
5745                  const int32_t *n_groups, const int32_t *ent_dst, const block_q8_1 *hq, const NativeExpertLayout &L,
5746                  float *out) {
5747    if constexpr (KqSplit<TD>::has) {
5748        if (!g_kq_split) { launch_down_port<TD, LN, false>(groups, s, grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); return; }
5749    }
5750    launch_down_port<TD, LN, true>(groups, s, grp_ptr, grp_start, n_groups, ent_dst, hq, L, out);
5751}
5752template <int TD>
5753void launch_down_lanes(dpct::dim3 grid, dpct::queue_ptr s, const unsigned long long *grp_ptr, const int32_t *grp_start,
5754                       const int32_t *n_groups, const int32_t *ent_dst, const block_q8_1 *hq,
5755                       const NativeExpertLayout &L, float *out) {
5756    switch (down_lanes()) {
5757        case 4: down_port_km<TD, 4>(grid.y, s, grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); break;
5758        case 16: down_port_km<TD, 16>(grid.y, s, grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); break;
5759        case 32: down_port_km<TD, 32>(grid.y, s, grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); break;
5760        default: down_port_km<TD, 8>(grid.y, s, grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); break;
5761    }
5762}
5763
5764// STRATA_EXPERT_SPLIT=1 (opt-in): upstream's multi-entry kernels, one warp per row, GU_ROWS rows a group, launched with
5765// their own grid.  The sub-warp variants (SUB16 / SUB_DOWN) are not launched here: they are bitwise equal to the
5766// generic path and need their own row counts; the port's lane kernels are the default for every format.
5767template <int TG, bool STAGE_GRID>
5768void launch_gu_multi(dpct::dim3 grid, dpct::queue_ptr s, const unsigned long long *grp_ptr, const int32_t *grp_start,
5769                     const int32_t *n_groups, const int32_t *ent_tok, const block_q8_1 *X,
5770                     const NativeExpertLayout &L, float *gate, float *up) {
5771    auto exp_props = sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};
5772    const sycl::range<3> g(1, grid.y, (size_t) ((2 * L.n_ff + GU_ROWS - 1) / GU_ROWS));
5773    strata::kprof::kp(s, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class native_gu_multi_split, dpct_kernel_scalar<TG>,
5774                                     dpct_kernel_scalar<STAGE_GRID>>>(
5775        sycl::nd_range<3>(sycl::range<3>(1, g[1], g[2] * 256), sycl::range<3>(1, 1, 256)), exp_props,
5776        [=](sycl::nd_item<3>) [[sycl::reqd_sub_group_size(32)]] {
5777            native_gu_multi_kernel<TG, STAGE_GRID, false>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up);
5778        });
5779}
5780
5781template <int TG>
5782void launch_gu(dpct::dim3 grid, dpct::queue_ptr s,
5783               const unsigned long long *grp_ptr, const int32_t *grp_start,
5784               const int32_t *n_groups, const int32_t *ent_tok,
5785               const block_q8_1 *X, const NativeExpertLayout &L, float *gate,
5786               float *up, bool bounded = false) {
5787    if constexpr (TG == 21) {
5788#if !STRATA_GRID_SLM
5789        static const bool reuse = strata::bm_default_on("STRATA_IQ3S_GU_ROW_REUSE", s->get_device());
5790        if (reuse && !g_old_kernels && !g_split_multi && gu_lanes() == 8 &&
5791            L.n_embd == 2560 && L.n_ff == 640 &&
5792            strata::intel_gpu_gen(s->get_device()) == strata::IntelGpuGen::Battlemage) {
5793            static const bool logged = [] {
5794                std::fprintf(stderr, "strata: IQ3_S two-row GU reuse enabled (8 lanes, SIMD16, direct activation reads)\n");
5795                return true;
5796            }();
5797            (void) logged;
5798            launch_gu_row_reuse<21>(grid.y, s, grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up);
5799            return;
5800        }
5801#endif
5802        static const bool iq3s_gu_slm = strata::bm_default_on("STRATA_IQ3S_GU_SLM", s->get_device(), false);
5803        if (!g_old_kernels && iq3s_gu_slm && L.n_embd == 2560 && L.n_ff == 640) {
5804            auto exp_props =
5805                sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};
5806            const size_t gx = (size_t) ((2 * L.n_ff + 31) / 32);
5807            s->parallel_for<dpct_kernel_name<class native_gu_iq3s_slm>>(
5808                sycl::nd_range<3>(sycl::range<3>(1, grid.y, gx * 256), sycl::range<3>(1, 1, 256)), exp_props,
5809                [=](sycl::nd_item<3>) [[sycl::reqd_sub_group_size(32)]] {
5810                    native_gu_iq3s_slm_kernel(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up);
5811                });
5812            return;
5813        }
5814    }
5815    if constexpr (!kSplit<TG>) {
5816
5817        launch_gu_lanes<TG>(grid, s, grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up, bounded);
5818    } else if (g_old_kernels || !g_split_multi) {
5819
5820        launch_gu_lanes<TG>(grid, s, grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up, bounded);
5821    } else {
5822        if constexpr (kStageIqGrid<TG>) {
5823            if (g_stage_grid) {
5824                launch_gu_multi<TG, true>(grid, s, grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up);
5825                return;
5826            }
5827        }
5828        launch_gu_multi<TG, false>(grid, s, grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up);
5829    }
5830}
5831
5832template <int TD>
5833void launch_down_multi(dpct::dim3 grid, dpct::queue_ptr s, const unsigned long long *grp_ptr,
5834                       const int32_t *grp_start, const int32_t *n_groups, const int32_t *ent_dst,
5835                       const block_q8_1 *hq, const NativeExpertLayout &L, float *out) {
5836    auto exp_props = sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};
5837    const size_t gx = (size_t) ((L.n_embd + GU_ROWS - 1) / GU_ROWS);
5838    strata::kprof::kp(s, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class native_down_multi_split, dpct_kernel_scalar<TD>>>(
5839        sycl::nd_range<3>(sycl::range<3>(1, grid.y, gx * 256), sycl::range<3>(1, 1, 256)), exp_props,
5840        [=](sycl::nd_item<3>) [[sycl::reqd_sub_group_size(32)]] {
5841            native_down_multi_kernel<TD, false>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out);
5842        });
5843}
5844
5845void launch_down_iq4nl_slm(dpct::dim3 grid, dpct::queue_ptr s, const unsigned long long *grp_ptr,
5846                            const int32_t *grp_start, const int32_t *n_groups, const int32_t *ent_dst,
5847                            const block_q8_1 *hq, const NativeExpertLayout &L, float *out) {
5848    auto exp_props = sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};
5849    const size_t gx = (size_t) ((L.n_embd + 31) / 32);
5850    s->parallel_for<dpct_kernel_name<class native_down_iq4nl_slm>>(
5851        sycl::nd_range<3>(sycl::range<3>(1, grid.y, gx * 256), sycl::range<3>(1, 1, 256)), exp_props,
5852        [=](sycl::nd_item<3>) [[sycl::reqd_sub_group_size(32)]] {
5853            native_down_iq4nl_slm_kernel(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out);
5854        });
5855}
5856
5857template <int TD>
5858void launch_down(dpct::dim3 grid, dpct::queue_ptr s,
5859                 const unsigned long long *grp_ptr, const int32_t *grp_start,
5860                 const int32_t *n_groups, const int32_t *ent_dst,
5861                 const block_q8_1 *hq, const NativeExpertLayout &L,
5862                 float *out) {
5863    if constexpr (TD == 42) {
5864        if (!g_old_kernels && !g_split_multi && down_lanes() == 8 &&
5865            q2_word_expand_enabled(s->get_device())) {
5866            launch_down_q2_word_expand(grid.y, s, grp_ptr, grp_start, n_groups, ent_dst, hq, L, out);
5867            return;
5868        }
5869    }
5870    if constexpr (TD == 20) {
5871        static const bool iq4nl_down_slm = strata::bm_default_on("STRATA_IQ4NL_DOWN_SLM", s->get_device(), false);
5872        if (!g_old_kernels && iq4nl_down_slm && L.n_embd == 2560 && L.n_ff == 640) {
5873            launch_down_iq4nl_slm(grid, s, grp_ptr, grp_start, n_groups, ent_dst, hq, L, out);
5874            return;
5875        }
5876    }
5877    if constexpr (!kSplit<TD>) {
5878        launch_down_lanes<TD>(grid, s, grp_ptr, grp_start, n_groups, ent_dst, hq, L, out);
5879    } else if (g_old_kernels || !g_split_multi) {
5880        launch_down_lanes<TD>(grid, s, grp_ptr, grp_start, n_groups, ent_dst, hq, L, out);
5881    } else {
5882        launch_down_multi<TD>(grid, s, grp_ptr, grp_start, n_groups, ent_dst, hq, L, out);
5883    }
5884}
5885
5886}  // namespace
5887
5888void iq_set_old_kernels(bool old) { g_old_kernels = old; }
5889void native_expert_set_kq_split(bool on) { g_kq_split = on; }
5890bool iq_old_kernels() { return g_old_kernels; }
5891
5892// APR (prism.hadamard): see iq_kernels.hpp.  A block that is not a power of two in [2, 1024] dividing the row width exits with a
5893// message, like check() does for a failed launch.
5894namespace {
5895void hadamard_bad_block(const char* what, int block, int64_t width) {
5896    std::fprintf(stderr, "%s: Hadamard block %d is not a power of two in [2, 1024] dividing the row width %lld "
5897                         "(hadamard.txt's block and the expert widths disagree)\n", what, block, (long long) width);
5898    std::exit(1);
5899}
5900constexpr int64_t kHadamardMaxRows = 65535;   // the CUDA grid limit; a prompt chunk's rows go up in the same slices
5901bool hadamard_block_ok(int block, int64_t width) {
5902    return block >= 2 && block <= 1024 && (block & (block - 1)) == 0 && width % block == 0;
5903}
5904}  // namespace
5905
5906void hadamard_rows(const float* x, float* y, int64_t rows, int64_t width, int block, const float* signs, void* stream) {
5907    if (rows <= 0) return;
5908    if (!hadamard_block_ok(block, width)) hadamard_bad_block("hadamard_rows", block, width);
5909    dpct::queue_ptr s = strata::q_of(stream);
5910    for (int64_t r0 = 0; r0 < rows; r0 += kHadamardMaxRows) {
5911        const int64_t n = std::min<int64_t>(kHadamardMaxRows, rows - r0);
5912        launch_hadamard_rows<float>(x + r0 * width, y + r0 * width, n, width, block, signs, s);
5913    }
5914    check("hadamard_rows");
5915}
5916
5917void hadamard_rows_f16(uint16_t* x, int64_t rows, int64_t width, int block, const float* signs, void* stream) {
5918    if (rows <= 0) return;
5919    if (!hadamard_block_ok(block, width)) hadamard_bad_block("hadamard_rows_f16", block, width);
5920    dpct::queue_ptr s = strata::q_of(stream);
5921    for (int64_t r0 = 0; r0 < rows; r0 += kHadamardMaxRows) {
5922        const int64_t n = std::min<int64_t>(kHadamardMaxRows, rows - r0);
5923        launch_hadamard_rows<sycl::half>((const sycl::half*) x + r0 * width, (sycl::half*) x + r0 * width, n, width, block,
5924                                         signs, s);
5925    }
5926    check("hadamard_rows_f16");
5927}
5928
5929const float* hadamard_device_signs(const float* host, int width) {
5930    if (host == nullptr || width <= 0) return nullptr;
5931    static std::mutex mu;
5932    static std::map<std::tuple<int, const float*, int>, float*> table;   // (device, host vector, width)
5933    const int dev = dpct::get_current_device_id();
5934    std::lock_guard<std::mutex> lock(mu);
5935    float*& d = table[std::make_tuple(dev, host, width)];
5936    if (d == nullptr) {
5937        sycl::queue& q = dpct::get_in_order_queue();
5938        d = (float*) strata::malloc_device_guarded((size_t) width * sizeof(float), q, "Hadamard signs");
5939        q.memcpy(d, host, (size_t) width * sizeof(float)).wait();
5940    }
5941    return d;
5942}
5943
5944bool iq_supported(int t) noexcept { return is_iq(t); }
5945bool embed_type_supported(int t) noexcept { return is_iq(t) || t == 30; }
5946
5947size_t iq_row_bytes(int t, int64_t n) noexcept {
5948    switch (t) {
5949        case 16: return (size_t) (n / 256) * sizeof(block_iq2_xxs);
5950        case 17: return (size_t) (n / 256) * sizeof(block_iq2_xs);
5951        case 18: return (size_t) (n / 256) * sizeof(block_iq3_xxs);
5952        case 20: return (size_t) (n / 32) * sizeof(block_iq4_nl);
5953        case 21: return (size_t) (n / 256) * sizeof(block_iq3_s);
5954        case 22: return (size_t) (n / 256) * sizeof(block_iq2_s);
5955        case 29: return (size_t) (n / 256) * sizeof(block_iq1_m);
5956        case 23: return (size_t) (n / 256) * sizeof(block_iq4_xs);
5957        case 11: return (size_t) (n / 256) * sizeof(block_q3_K);
5958        case 42: return (size_t) (n / 64) * sizeof(block_q2_0);
5959        case 12: return (size_t) (n / 256) * sizeof(block_q4_K);
5960        case 13: return (size_t) (n / 256) * sizeof(block_q5_K);
5961        case 14: return (size_t) (n / 256) * sizeof(block_q6_K);
5962        case 7: return (size_t) (n / 32) * sizeof(block_q5_1);
5963        case 6: return (size_t) (n / 32) * sizeof(block_q5_0);
5964        case 2: return (size_t) (n / 32) * sizeof(block_q4_0);
5965        case 3: return (size_t) (n / 32) * sizeof(block_q4_1);
5966        case 8: return (size_t) (n / 32) * sizeof(block_q8_0);
5967        case 144: return (size_t) (n / 128) * sizeof(block_tq2_t);   // APR trellis types
5968        case 145: return (size_t) (n / 128) * sizeof(block_tqk6);
5969        case 146: return (size_t) (n / 128) * sizeof(block_tqk7);
5970        case 30: return (size_t) n * 2;   // BF16: the token embedding only (iq_embed_rows, iq_dequant_f32)
5971        default: return 0;
5972    }
5973}
5974
5975void quantize_q8_1_rows(const float* x, int64_t n_rows, int64_t n_cols, void* y, void* stream) {
5976    const long long n = (long long) n_rows * n_cols;
5977    if (n <= 0) return;
5978    {
5979        auto exp_props = sycl::ext::oneapi::experimental::properties{
5980            sycl::ext::oneapi::experimental::use_root_sync};
5981
5982        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
5983            ->template parallel_for<dpct_kernel_name<class quantize_q8_1_kernel_422964>>(
5984                sycl::nd_range<3>(
5985                    sycl::range(1, 1, (unsigned)((n + 255) / 256)) *
5986                        sycl::range(1, 1, 256),
5987                    sycl::range(1, 1, 256)),
5988                exp_props,
5989                [=](sycl::nd_item<3> item_ct1)
5990                    [[sycl::reqd_sub_group_size(32)]] {
5991                        quantize_q8_1_kernel(x, (block_q8_1 *)y, n);
5992                    });
5993    }
5994    check("quantize_q8_1_rows");
5995}
5996
5997// IQ3_S: identical32 FP chains/tree, field-packed bytes, exact2*S4+sign integers.
5998namespace {
5999namespace p3=sycl::ext::intel::esimd;
6000template<int NT,int KB>class IQ3PackedS4;
6001template<int NT,int KB>
6002void iq3_packed_s4_launch(const uint8_t* weights,const block_q8_1* acts,float* y,int N,sycl::queue* q){
6003 constexpr int NR=16,NS=32,XB=KB*8,Partial=2048;
6004 q->parallel_for<IQ3PackedS4<NT,KB>>(
6005  sycl::nd_range<1>(size_t(N/16)*NS,NS),
6006  [=](sycl::nd_item<1> it) [[intel::sycl_explicit_simd]] {
6007#pragma clang fp contract(off)
6008   p3::slm_init<2048+NS*NT*NR*4>();
6009   const int sid=int(it.get_local_id(0)),base=int(it.get_group(0))*16;
6010   p3::simd<uint32_t,16> rows(base,1);auto valid=rows<uint32_t(N);
6011   p3::simd<uint32_t,16> table_offsets(sid*64,4);
6012   auto table=p3::gather<uint32_t,16>(iq3s_grid,table_offsets);
6013   p3::slm_block_store<uint32_t,16>(sid*64,table);
6014   p3::barrier();
6015   p3::simd<float,16> acc[NT];
6016#pragma unroll
6017   for(int e=0;e<NT;++e)acc[e]=0.f;
6018   const auto* tile=weights+size_t(base)*KB*110;
6019   for(int seg=sid;seg<XB;seg+=NS){
6020    const int part=seg%8;const auto* block=tile+(seg/8)*1760;
6021    const auto* plane=block+part*208;
6022    auto q0=p3::block_load<uint32_t,16>(reinterpret_cast<const uint32_t*>(plane));
6023    auto q1=p3::block_load<uint32_t,16>(reinterpret_cast<const uint32_t*>(plane+64));
6024    auto signs=p3::block_load<uint32_t,16>(reinterpret_cast<const uint32_t*>(plane+128));
6025    auto qh8=p3::block_load<uint8_t,16>(plane+192);
6026    p3::simd<uint32_t,16> qh=qh8;
6027    auto scales=p3::block_load<uint32_t,16>(reinterpret_cast<const uint32_t*>(block+1664));
6028    p3::simd<int32_t,16> ls=1+2*((scales>>(4*part))&15u);
6029    auto dbits=p3::block_load<uint16_t,16>(reinterpret_cast<const uint16_t*>(block+1728));
6030    p3::simd<float,16> d=dbits.template bit_cast_view<sycl::half>().read();
6031    p3::simd<uint32_t,64> coarse_words,sign_words;
6032#pragma unroll
6033    for(int group=0;group<2;++group){
6034     p3::simd<uint32_t,64> index,sign;
6035#pragma unroll
6036     for(int j=0;j<4;++j){
6037      p3::simd<uint32_t,16> qs=group==0?q0:q1;
6038      index.template select<16,1>(j*16)=((qs>>(8*j))&255u)|(((qh>>(group*4+j))&1u)<<8);
6039      sign.template select<16,1>(j*16)=(signs>>(4*(group*4+j)))&15u;
6040     }
6041     auto grid=p3::slm_gather<uint32_t,64>(index*4u);
6042     // Each positive codebook coefficient is odd in1..15.
6043     p3::simd<uint32_t,64> packed=(grid&15u)|((grid>>4)&240u)|((grid>>8)&3840u)|((grid>>12)&61440u);
6044     p3::simd<uint32_t,64> positive=(packed>>1)&0x7777u;
6045     // Guarded nibble subtraction also handles signed zero without carries.
6046     p3::simd<uint32_t,64> negative=((0x8888u-positive)^0x8888u)&65535u;
6047     p3::simd<uint32_t,64> bit=(sign&1u)|((sign&2u)<<3)|((sign&4u)<<6)|((sign&8u)<<9);
6048     p3::simd<uint32_t,64> mask=bit*15u;
6049     p3::simd<uint32_t,64> c=positive^((positive^negative)&mask),sgn=0x1111u+bit*14u;
6050#pragma unroll
6051     for(int pair=0;pair<2;++pair){
6052      coarse_words.template select<16,1>((group*2+pair)*16)=c.template select<16,1>(pair*32)|(c.template select<16,1>(pair*32+16)<<16);
6053      sign_words.template select<16,1>((group*2+pair)*16)=sgn.template select<16,1>(pair*32)|(sgn.template select<16,1>(pair*32+16)<<16);
6054     }
6055    }
6056    p3::simd<uint16_t,128> Bc=coarse_words.template bit_cast_view<uint16_t>().read();
6057    p3::simd<uint16_t,128> Bs=sign_words.template bit_cast_view<uint16_t>().read();
6058    auto aw=p3::load_2d<uint32_t,8,NT,1,false,false>(reinterpret_cast<const uint32_t*>(acts),XB*36-1,NT-1,XB*36-1,seg*9+1,0);
6059    p3::simd<int8_t,NT*32> A=aw.template bit_cast_view<int8_t>();
6060    p3::simd<int32_t,NT*16> zero=0;
6061    using P=p3::xmx::dpas_argument_type;
6062    // Natural K0..31, as in the qualified Q2 S4 basis probe; no IQ4 interleave.
6063    auto Cc=p3::xmx::dpas<8,NT,int32_t,int32_t,uint16_t,int8_t,P::s4,P::s8>(zero,Bc,A);
6064    auto Cs=p3::xmx::dpas<8,NT,int32_t,int32_t,uint16_t,int8_t,P::s4,P::s8>(zero,Bs,A);
6065#pragma unroll
6066    for(int e=0;e<NT;++e){
6067     p3::simd<int32_t,16> c=Cc.template select<16,1>(e*16),sgn=Cs.template select<16,1>(e*16);
6068     p3::simd<int32_t,16> scaled=(c*2+sgn)*ls;
6069     p3::simd<float,16> dot=scaled;
6070     p3::simd<uint32_t,1> off=uint32_t((e*XB+seg)*36);
6071     auto bits=p3::gather<uint16_t,1>(reinterpret_cast<const uint16_t*>(acts),off);
6072     p3::simd<float,1> ds=bits.template bit_cast_view<sycl::half>().read();
6073     p3::simd<float,16> factor=d*float(ds[0]);
6074     p3::simd<float,16> term=factor*dot;
6075     term.merge(0.f,!valid);acc[e]=acc[e]+term;
6076    }
6077   }
6078#pragma unroll
6079   for(int e=0;e<NT;++e)p3::slm_block_store<float,16>(Partial+sid*NT*64+e*64,acc[e]);
6080   p3::barrier();
6081   if(sid<NT){
6082    p3::simd<float,16> v[16];
6083#pragma unroll
6084    for(int r=0;r<16;++r)v[r]=p3::slm_block_load<float,16>(Partial+r*NT*64+sid*64)+p3::slm_block_load<float,16>(Partial+(r+16)*NT*64+sid*64);
6085#pragma unroll
6086    for(int off=8;off;off/=2){
6087#pragma unroll
6088     for(int r=0;r<off;++r)v[r]=v[r]+v[r+off];
6089    }
6090    p3::block_store<float,16>(y+size_t(sid)*N+base,v[0]);
6091   }
6092  });
6093}
6094}
6095namespace {
6096template<int NT,int KB>class IQ3PairedS4;
6097template<int NT,int KB>
6098void iq3_paired_s4_launch(const uint8_t* weights,const block_q8_1* acts,float* y,int N,sycl::queue* q){
6099 constexpr int NR=16,NS=32,WG=16,XB=KB*8,Partial=2048;
6100 q->parallel_for<IQ3PairedS4<NT,KB>>(
6101  sycl::nd_range<1>(size_t(N/16)*WG,WG),
6102  [=](sycl::nd_item<1> it) [[intel::sycl_explicit_simd]] {
6103#pragma clang fp contract(off)
6104   p3::slm_init<2048+WG*NT*NR*4>();
6105   const int sid=int(it.get_local_id(0)),base=int(it.get_group(0))*16;
6106   p3::simd<uint32_t,16> rows(base,1);auto valid=rows<uint32_t(N);
6107   p3::simd<uint32_t,32> table_offsets(sid*128,4);
6108   auto table=p3::gather<uint32_t,32>(iq3s_grid,table_offsets);
6109   p3::slm_block_store<uint32_t,32>(sid*128,table);
6110   p3::barrier();
6111   p3::simd<float,16> acc[2][NT];
6112#pragma unroll
6113   for(int branch=0;branch<2;++branch){
6114#pragma unroll
6115    for(int e=0;e<NT;++e)acc[branch][e]=0.f;
6116   }
6117   const auto* tile=weights+size_t(base)*KB*110;
6118#pragma unroll
6119   for(int branch=0;branch<2;++branch){
6120   for(int seg=sid+branch*16;seg<XB;seg+=NS){
6121    const int part=seg%8;const auto* block=tile+(seg/8)*1760;
6122    const auto* plane=block+part*208;
6123    auto q0=p3::block_load<uint32_t,16>(reinterpret_cast<const uint32_t*>(plane));
6124    auto q1=p3::block_load<uint32_t,16>(reinterpret_cast<const uint32_t*>(plane+64));
6125    auto signs=p3::block_load<uint32_t,16>(reinterpret_cast<const uint32_t*>(plane+128));
6126    auto qh8=p3::block_load<uint8_t,16>(plane+192);
6127    p3::simd<uint32_t,16> qh=qh8;
6128    auto scales=p3::block_load<uint32_t,16>(reinterpret_cast<const uint32_t*>(block+1664));
6129    p3::simd<int32_t,16> ls=1+2*((scales>>(4*part))&15u);
6130    auto dbits=p3::block_load<uint16_t,16>(reinterpret_cast<const uint16_t*>(block+1728));
6131    p3::simd<float,16> d=dbits.template bit_cast_view<sycl::half>().read();
6132    p3::simd<uint32_t,64> coarse_words,sign_words;
6133#pragma unroll
6134    for(int group=0;group<2;++group){
6135     p3::simd<uint32_t,64> index,sign;
6136#pragma unroll
6137     for(int j=0;j<4;++j){
6138      p3::simd<uint32_t,16> qs=group==0?q0:q1;
6139      index.template select<16,1>(j*16)=((qs>>(8*j))&255u)|(((qh>>(group*4+j))&1u)<<8);
6140      sign.template select<16,1>(j*16)=(signs>>(4*(group*4+j)))&15u;
6141     }
6142     auto grid=p3::slm_gather<uint32_t,64>(index*4u);
6143     // Each positive codebook coefficient is odd in1..15.
6144     p3::simd<uint32_t,64> packed=(grid&15u)|((grid>>4)&240u)|((grid>>8)&3840u)|((grid>>12)&61440u);
6145     p3::simd<uint32_t,64> positive=(packed>>1)&0x7777u;
6146     // Guarded nibble subtraction also handles signed zero without carries.
6147     p3::simd<uint32_t,64> negative=((0x8888u-positive)^0x8888u)&65535u;
6148     p3::simd<uint32_t,64> bit=(sign&1u)|((sign&2u)<<3)|((sign&4u)<<6)|((sign&8u)<<9);
6149     p3::simd<uint32_t,64> mask=bit*15u;
6150     p3::simd<uint32_t,64> c=positive^((positive^negative)&mask),sgn=0x1111u+bit*14u;
6151#pragma unroll
6152     for(int pair=0;pair<2;++pair){
6153      coarse_words.template select<16,1>((group*2+pair)*16)=c.template select<16,1>(pair*32)|(c.template select<16,1>(pair*32+16)<<16);
6154      sign_words.template select<16,1>((group*2+pair)*16)=sgn.template select<16,1>(pair*32)|(sgn.template select<16,1>(pair*32+16)<<16);
6155     }
6156    }
6157    p3::simd<uint16_t,128> Bc=coarse_words.template bit_cast_view<uint16_t>().read();
6158    p3::simd<uint16_t,128> Bs=sign_words.template bit_cast_view<uint16_t>().read();
6159    auto aw=p3::load_2d<uint32_t,8,NT,1,false,false>(reinterpret_cast<const uint32_t*>(acts),XB*36-1,NT-1,XB*36-1,seg*9+1,0);
6160    p3::simd<int8_t,NT*32> A=aw.template bit_cast_view<int8_t>();
6161    p3::simd<int32_t,NT*16> zero=0;
6162    using P=p3::xmx::dpas_argument_type;
6163    // Natural K0..31, as in the qualified Q2 S4 basis probe; no IQ4 interleave.
6164    auto Cc=p3::xmx::dpas<8,NT,int32_t,int32_t,uint16_t,int8_t,P::s4,P::s8>(zero,Bc,A);
6165    auto Cs=p3::xmx::dpas<8,NT,int32_t,int32_t,uint16_t,int8_t,P::s4,P::s8>(zero,Bs,A);
6166#pragma unroll
6167    for(int e=0;e<NT;++e){
6168     p3::simd<int32_t,16> c=Cc.template select<16,1>(e*16),sgn=Cs.template select<16,1>(e*16);
6169     p3::simd<int32_t,16> scaled=(c*2+sgn)*ls;
6170     p3::simd<float,16> dot=scaled;
6171     p3::simd<uint32_t,1> off=uint32_t((e*XB+seg)*36);
6172     auto bits=p3::gather<uint16_t,1>(reinterpret_cast<const uint16_t*>(acts),off);
6173     p3::simd<float,1> ds=bits.template bit_cast_view<sycl::half>().read();
6174     p3::simd<float,16> factor=d*float(ds[0]);
6175     p3::simd<float,16> term=factor*dot;
6176     term.merge(0.f,!valid);acc[branch][e]=acc[branch][e]+term;
6177    }
6178   }
6179   }
6180#pragma unroll
6181   for(int e=0;e<NT;++e)p3::slm_block_store<float,16>(Partial+sid*NT*64+e*64,acc[0][e]+acc[1][e]);
6182   p3::barrier();
6183   if(sid<NT){
6184    p3::simd<float,16> v[16];
6185#pragma unroll
6186    for(int r=0;r<16;++r)v[r]=p3::slm_block_load<float,16>(Partial+r*NT*64+sid*64);
6187#pragma unroll
6188    for(int off=8;off;off/=2){
6189#pragma unroll
6190     for(int r=0;r<off;++r)v[r]=v[r]+v[r+off];
6191    }
6192    p3::block_store<float,16>(y+size_t(sid)*N+base,v[0]);
6193   }
6194  });
6195}
6196}
6197void b60_iq3_s4_probe(bool candidate,const void* w,const void* x,float* y,int K,int N,int T,void* stream){
6198 if(!w||!x||!y||!stream||N<=0||N%16||!((K==2560&&N==6144)||(K==6144&&N==2560)))throw std::invalid_argument("IQ3 S4 component shape");
6199 auto*q=strata::q_of(stream);const auto*weights=static_cast<const uint8_t*>(w);const auto*acts=static_cast<const block_q8_1*>(x);
6200 if(!candidate){if(K==2560)iq3_public_xmx_T<10>(T,weights,acts,y,N,q);else iq3_public_xmx_T<24>(T,weights,acts,y,N,q);return;}
6201#define I3_CALL(E) case E: if(K==2560)iq3_paired_s4_launch<E,10>(weights,acts,y,N,q);else iq3_paired_s4_launch<E,24>(weights,acts,y,N,q);break;
6202 switch(T){I3_CALL(1) I3_CALL(2) I3_CALL(4) default:throw std::invalid_argument("IQ3 S4 component T");}
6203#undef I3_CALL
6204}
6205
6206// SYCL port: a wide kernel for the dense IQ3_S matrices (attn_q, attn_gate, ssm_out, attn_k, the shared experts'
6207// gate/up), shaped like the Q4_K..IQ4_XS wide kernels: 8 lanes share a 256-block, lane g takes sub-block g, so a
6208// 32-lane sub-group has four blocks in flight. Each sub-block's value is vec_dot_iq3_s_q8_1's; only the order the
6209// sub-blocks are summed in differs from mmvq_multi_kernel, so the output differs in the last bits.
6210template <int NCOLS>
6211__dpct_inline__ void iq3s_wide_kernel(const uint8_t* __restrict__ w, size_t rb, const block_q8_1* __restrict__ x,
6212                                      float* __restrict__ y, int n_in, int n_out) {
6213    auto item = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
6214    const int lane = (int) item.get_local_id(2), warp = (int) item.get_local_id(1);
6215    const int row = (int) item.get_group(2) * (int) item.get_local_range(1) + warp;
6216    if (row >= n_out) return;
6217    const int nb = n_in / QK_K, xs = n_in / QK8_1;
6218    const int g = lane & 7, sub = lane >> 3;
6219    const block_iq3_s* wr = (const block_iq3_s*) (w + (size_t) row * rb);
6220    float acc[NCOLS];
6221#pragma unroll
6222    for (int c = 0; c < NCOLS; ++c) acc[c] = 0.0f;
6223    for (int kbx = sub; kbx < nb; kbx += 4) {
6224        const block_iq3_s* b = wr + kbx;
6225        const sycl::int2 qs_packed = load8_a2(b->qs + 8 * g);
6226        const uint8_t* qs = (const uint8_t*) &qs_packed;
6227        const int qh = b->qh[g];
6228        const int signs_packed_32 = load4_a2(b->signs + 4 * g);
6229        const uint8_t* signs_packed_8 = (const uint8_t*) &signs_packed_32;
6230        const int scale = 1 + 2 * ((b->scales[g / 2] >> (4 * (g & 1))) & 0x0F);
6231        const float d3 = sycl::vec<sycl::half, 1>(b->d).convert<float, sycl::rounding_mode::automatic>()[0];
6232        int wv[8];
6233#pragma unroll
6234        for (int l0 = 0; l0 < 8; l0 += 2) {
6235            const sycl::int2 grid_pos = sycl::int2(iq3s_grid[qs[l0 + 0] | ((qh << (8 - l0)) & 0x100)],
6236                                                   iq3s_grid[qs[l0 + 1] | ((qh << (7 - l0)) & 0x100)]);
6237            const int signs0 = swar_ne4(((signs_packed_8[l0 / 2] & 0x03) << 7) | ((signs_packed_8[l0 / 2] & 0x0C) << 21));
6238            const int signs1 = swar_ne4(((signs_packed_8[l0 / 2] & 0x30) << 3) | ((signs_packed_8[l0 / 2] & 0xC0) << 17));
6239            wv[l0 + 0] = swar_sub4(grid_pos.x() ^ signs0, signs0);
6240            wv[l0 + 1] = swar_sub4(grid_pos.y() ^ signs1, signs1);
6241        }
6242#pragma unroll
6243        for (int c = 0; c < NCOLS; ++c) {
6244            const block_q8_1* xb = x + (size_t) c * xs + (size_t) kbx * (QK_K / QK8_1) + g;
6245            const int* u = reinterpret_cast<const int*>(xb->qs);
6246            int sumi = 0;
6247#pragma unroll
6248            for (int l = 0; l < 8; ++l) sumi = ggml_cuda_dp4a(wv[l], u[l], sumi);
6249            sumi *= scale;
6250            const float d = d3 * xb->ds[0];
6251            acc[c] += d * sumi;
6252        }
6253    }
6254    auto sg = item.get_sub_group();
6255#pragma unroll
6256    for (int c = 0; c < NCOLS; ++c) {
6257        float v = acc[c];
6258#pragma unroll
6259        for (int o = 16; o > 0; o >>= 1) v += sycl::permute_group_by_xor(sg, v, o);
6260        if (lane == 0) y[(size_t) c * n_out + row] = v;
6261    }
6262}
6263// STRATA_IQ3S_WIDE=1: the wide kernel; unset or 0: the multi kernel (default).
6264bool iq3s_wide_on() {
6265    static const bool v = [] { const char* e = std::getenv("STRATA_IQ3S_WIDE"); return e && std::atoi(e) != 0; }();
6266    return v;
6267}
6268template <int NCOLS>
6269void launch_iq3s_wide_t(const uint8_t* W, size_t rb, const block_q8_1* X, float* y, int n_in, int n_out, dpct::queue_ptr s) {
6270    constexpr int WPG = 4;   // sub-groups per work-group
6271    const unsigned groups = unsigned((n_out + WPG - 1) / WPG);
6272    strata::kprof::kp(s, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class iq3s_wide_k, dpct_kernel_scalar<NCOLS>>>(
6273        sycl::nd_range<3>(sycl::range(1, WPG, groups * 32), sycl::range(1, WPG, 32)),
6274        [=](sycl::nd_item<3>) [[sycl::reqd_sub_group_size(32)]] { iq3s_wide_kernel<NCOLS>(W, rb, X, y, n_in, n_out); });
6275}
6276bool launch_iq3s_wide(const uint8_t* W, size_t rb, const block_q8_1* X, float* y, int n_in, int n_out, int ncols, dpct::queue_ptr s) {
6277    if (!iq3s_wide_on() || n_in % QK_K != 0) return false;
6278    switch (ncols) {
6279        case 1: launch_iq3s_wide_t<1>(W, rb, X, y, n_in, n_out, s); return true;
6280        case 2: launch_iq3s_wide_t<2>(W, rb, X, y, n_in, n_out, s); return true;
6281        case 3: launch_iq3s_wide_t<3>(W, rb, X, y, n_in, n_out, s); return true;
6282        case 4: launch_iq3s_wide_t<4>(W, rb, X, y, n_in, n_out, s); return true;
6283        case 5: launch_iq3s_wide_t<5>(W, rb, X, y, n_in, n_out, s); return true;
6284        case 6: launch_iq3s_wide_t<6>(W, rb, X, y, n_in, n_out, s); return true;
6285        case 7: launch_iq3s_wide_t<7>(W, rb, X, y, n_in, n_out, s); return true;
6286        case 8: launch_iq3s_wide_t<8>(W, rb, X, y, n_in, n_out, s); return true;
6287        default: return false;
6288    }
6289}
6290
6291void iq_mmvq(int t, const void* w, const void* x_q8_1, float* y, int n_in, int n_out, int ncols, void* stream) {
6292    const size_t rb = iq_row_bytes(t, n_in);
6293    dpct::queue_ptr s = strata::q_of(stream);
6294    const auto* W = (const uint8_t*) w;
6295    const auto* X = (const block_q8_1*) x_q8_1;
6296    if (t == 21 && launch_iq3s_wide(W, rb, X, y, n_in, n_out, ncols, s)) { check("iq_mmvq"); return; }
6297    if(t==21 && !g_old_kernels && b60_cache_requested(21) && b60_main_actor() && b60_weights_packed() &&
6298       ((n_in==2560&&n_out==6144)||(n_in==6144&&n_out==2560)) && (ncols==1||ncols==2||ncols==4) &&
6299       strata::intel_gpu_gen(s->get_device())==strata::IntelGpuGen::Battlemage){
6300        const auto* cached=static_cast<const uint8_t*>(b60_cached_weight(w,21));
6301        if(!cached)throw std::logic_error("B60 missing IQ3 decode cache");
6302        b60_iq3_s4_probe(true,cached,x_q8_1,y,n_in,n_out,ncols,stream);return;
6303    }
6304    // The previously byte-checked public XMX implementation, real format21 only.
6305    if (t == 21 && !g_old_kernels && ncols >= 1 && ncols <= 8 && n_out >= 1 &&
6306        ((n_in == 2560 && n_out <= 12288) || (n_in == 6144 && n_out <= 2560)) &&
6307        strata::intel_gpu_gen(s->get_device()) == strata::IntelGpuGen::Battlemage) {
6308        if (n_in == 2560) iq3_public_xmx_T<10>(ncols, W, X, y, n_out, s);
6309        else iq3_public_xmx_T<24>(ncols, W, X, y, n_out, s);
6310        check("iq_mmvq");
6311        return;
6312    }
6313    switch (t) {
6314#define STRATA_MMVQ(T) case T: launch_mmvq<T>(W, rb, X, y, n_in, n_out, ncols, s); break;
6315        STRATA_MMVQ_FMTS(STRATA_MMVQ)
6316#undef STRATA_MMVQ
6317        default: std::fprintf(stderr, "iq_mmvq: type %d is not supported\n", t); std::exit(1);
6318    }
6319    check("iq_mmvq");
6320}
6321
6322// BEGIN PRIVATE IQ3 XMX REUSE ENTRY
6323void iq3_xmx_reuse_probe(int mode,const void* weights,const void* activations,float* out,int K,int N,int T,void* stream){
6324    if(!weights||!activations||!out||!stream||T<1||T>8||mode<0||mode>1||N<1||
6325       !((K==2560&&N<=12288)||(K==6144&&N<=2560)))
6326        throw std::invalid_argument("IQ3 XMX reuse diagnostic arguments");
6327    const auto* w=static_cast<const uint8_t*>(weights);
6328    const auto* x=static_cast<const block_q8_1*>(activations);
6329    auto* q=strata::q_of(stream);
6330    if(mode==0){launch_mmvq<21>(w,iq_row_bytes(21,K),x,out,K,N,T,q);return;}
6331    if(K==2560)iq3_public_xmx_T<10>(T,w,x,out,N,q);
6332    else iq3_public_xmx_T<24>(T,w,x,out,N,q);
6333}
6334void iq3_codebook_audit(uint32_t* out,void* stream){
6335    if(!out||!stream)throw std::invalid_argument("IQ3 codebook diagnostic arguments");
6336    strata::q_of(stream)->parallel_for(sycl::range<1>(512),[=](sycl::id<1> i){out[i]=iq3s_grid[i];});
6337}
6338// END PRIVATE IQ3 XMX REUSE ENTRY
6339void iq_dequant_f16(int t, const void* src, int64_t n, uint16_t* dst, void* stream, const float* scale) {
6340    // scale: NVFP4's s_down (CUDA only; the SYCL port has no NVFP4 experts, so it is never given here)
6341    if (n % 256 != 0 || !is_iq(t) || scale != nullptr) { std::fprintf(stderr, "iq_dequant_f16: bad arguments\n"); std::exit(1); }
6342    {
6343
6344        auto exp_props = sycl::ext::oneapi::experimental::properties{
6345            sycl::ext::oneapi::experimental::use_root_sync};
6346        dpct::has_capability_or_fail(
6347            strata::q_of(stream)->get_device(),
6348            {sycl::aspect::fp16});
6349
6350        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
6351            ->submit([&](sycl::handler &cgh) {
6352
6353                cgh.parallel_for<dpct_kernel_name<
6354                    class dequant_flat_kernel_c7cec2, sycl::half>>(
6355                    sycl::nd_range<3>(sycl::range(1, 1, (unsigned)(n / 256)) *
6356                                          sycl::range(1, 1, 32),
6357                                      sycl::range(1, 1, 32)),
6358                    exp_props, [=](sycl::nd_item<3> item_ct1) {
6359                        dequant_flat_kernel<sycl::half>(
6360                            t, src, (sycl::half *)dst);
6361                    });
6362            });
6363    }
6364    check("iq_dequant_f16");
6365}
6366
6367void iq_dequant_f16_plain_launch(int t, const void* src, int64_t n, uint16_t* dst, void* stream) {
6368    if (n % 256 != 0 || !is_iq(t)) { std::fprintf(stderr, "iq_dequant_f16: bad arguments\n"); std::exit(1); }
6369    {
6370
6371        auto exp_props = sycl::ext::oneapi::experimental::properties{
6372            };
6373        dpct::has_capability_or_fail(
6374            strata::q_of(stream)->get_device(),
6375            {sycl::aspect::fp16});
6376
6377        strata::q_of(stream)
6378            ->submit([&](sycl::handler &cgh) {
6379
6380                cgh.parallel_for<dpct_kernel_name<
6381                    class b70_no_root_dequant_flat_kernel, sycl::half>>(
6382                    sycl::nd_range<3>(sycl::range(1, 1, (unsigned)(n / 256)) *
6383                                          sycl::range(1, 1, 32),
6384                                      sycl::range(1, 1, 32)),
6385                    exp_props, [=](sycl::nd_item<3> item_ct1) {
6386                        dequant_flat_kernel<sycl::half>(
6387                            t, src, (sycl::half *)dst);
6388                    });
6389            });
6390    }
6391    check("iq_dequant_f16");
6392}
6393
6394namespace {
6395__dpct_inline__ void embed_rows_kernel(
6396    int ty, const uint8_t *__restrict__ table, size_t row_bytes,
6397    const int32_t *__restrict__ tokens, int64_t n_embd, float *__restrict__ y) {
6398    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
6399    const int t = item_ct1.get_group(1);
6400    const int64_t b = item_ct1.get_group(2);
6401    const uint8_t* row = table + (size_t) tokens[t] * row_bytes;
6402    dq_dispatch<float>(ty, row, b, y + (size_t)t * n_embd + b * QK_K,
6403                       item_ct1.get_local_id(2));
6404}
6405}  // namespace
6406
6407void iq_embed_rows(int t, const void* table, size_t row_bytes, const int32_t* tokens, int64_t n_tok, int64_t n_embd,
6408                   float* out, void* stream) {
6409    if (n_tok <= 0) return;
6410    if (n_embd % 256 != 0 || !embed_type_supported(t)) { std::fprintf(stderr, "iq_embed_rows: bad arguments\n"); std::exit(1); }
6411    {
6412
6413        auto exp_props = sycl::ext::oneapi::experimental::properties{
6414            sycl::ext::oneapi::experimental::use_root_sync};
6415        dpct::has_capability_or_fail(
6416            strata::q_of(stream)->get_device(),
6417            {sycl::aspect::fp16});
6418
6419        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
6420            ->submit([&](sycl::handler &cgh) {
6421
6422                cgh.parallel_for<
6423                    dpct_kernel_name<class embed_rows_kernel_284a43>>(
6424                    sycl::nd_range<3>(sycl::range(1, (unsigned)n_tok,
6425                                                  (unsigned)(n_embd / 256)) *
6426                                          sycl::range(1, 1, 32),
6427                                      sycl::range(1, 1, 32)),
6428                    exp_props, [=](sycl::nd_item<3> item_ct1) {
6429                        embed_rows_kernel(
6430                            t, (const uint8_t *)table, row_bytes, tokens,
6431                            n_embd, out);
6432                    });
6433            });
6434    }
6435    check("iq_embed_rows");
6436}
6437
6438void iq_dequant_f32(int t, const void* src, int64_t n, float* dst, void* stream) {
6439    if (n % 256 != 0 || !embed_type_supported(t)) { std::fprintf(stderr, "iq_dequant_f32: bad arguments\n"); std::exit(1); }
6440    {
6441
6442        auto exp_props = sycl::ext::oneapi::experimental::properties{
6443            sycl::ext::oneapi::experimental::use_root_sync};
6444        dpct::has_capability_or_fail(
6445            strata::q_of(stream)->get_device(),
6446            {sycl::aspect::fp16});
6447
6448        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
6449            ->submit([&](sycl::handler &cgh) {
6450
6451                cgh.parallel_for<
6452                    dpct_kernel_name<class dequant_flat_kernel_9052bc, float>>(
6453                    sycl::nd_range<3>(sycl::range(1, 1, (unsigned)(n / 256)) *
6454                                          sycl::range(1, 1, 32),
6455                                      sycl::range(1, 1, 32)),
6456                    exp_props, [=](sycl::nd_item<3> item_ct1) {
6457                        dequant_flat_kernel<float>(
6458                            t, src, dst);
6459                    });
6460            });
6461    }
6462    check("iq_dequant_f32");
6463}
6464
6465namespace {
6466template <int Type, uint32_t PerRow = 0>
6467void launch_dequant_gu_bounded(const void* gate, const void* up, uint32_t n_ff,
6468                               uint32_t n_embd, uint16_t* dst, void* stream) {
6469    using Block = std::conditional_t<Type == 16, block_iq2_xxs,
6470                  std::conditional_t<Type == 22, block_iq2_s, block_iq1_m>>;
6471    constexpr uint32_t subgroups = 8;
6472    const uint32_t per_row = PerRow ? PerRow : n_embd / QK_K;
6473    const uint32_t blocks = n_ff * per_row;
6474    const size_t groups = (blocks + subgroups - 1) / subgroups;
6475    const auto properties = sycl::ext::oneapi::experimental::properties{
6476        sycl::ext::oneapi::experimental::use_root_sync};
6477    strata::q_of(stream)->parallel_for<dpct_kernel_name<class dequant_gu_bounded,
6478                                                       dpct_kernel_scalar<Type>,
6479                                                       dpct_kernel_scalar<PerRow>>>(
6480        sycl::nd_range<3>(sycl::range<3>(1, 2, groups * subgroups * 32),
6481                          sycl::range<3>(1, 1, subgroups * 32)), properties,
6482        [=](sycl::nd_item<3> item) [[sycl::reqd_sub_group_size(32)]] {
6483            const auto sg = item.get_sub_group();
6484            const uint32_t block = uint32_t(item.get_group(2)) * subgroups + sg.get_group_linear_id();
6485            if (block >= blocks) return;
6486            const uint32_t parity = item.get_group(1);
6487            const uint32_t row = block / per_row, col = block % per_row;
6488            const uint32_t bytes = ((2u * row + parity) * per_row + col) * QK_K * 2u;
6489            const Block* selected = iq_signed_grid::block_at<Block>(parity ? up : gate, block);
6490            // The IQ2_S decoder already maps adjacent lanes to adjacent runs.
6491            // Keep the earlier caller permutation for the other formats.
6492            const uint32_t lane = sg.get_local_linear_id();
6493            const uint32_t dequant_thread = Type == 22 ? lane : (lane & 3u) * 8u + (lane >> 2);
6494            dq_dispatch<sycl::half>(Type, selected, 0,
6495                reinterpret_cast<sycl::half*>(reinterpret_cast<uint8_t*>(dst) + bytes),
6496                dequant_thread);
6497        });
6498}
6499}
6500
6501namespace {
6502template <int Type, uint32_t PerRow = 0>
6503sycl::event launch_dequant_gu_metadata(const void* gate, const void* up, uint32_t n_ff,
6504                               uint32_t n_embd, uint16_t* dst, void* stream) {
6505    using Block = std::conditional_t<Type == 16, block_iq2_xxs,
6506                  std::conditional_t<Type == 22, block_iq2_s, block_iq1_m>>;
6507    constexpr uint32_t subgroups = 8;
6508    const uint32_t per_row = PerRow ? PerRow : n_embd / QK_K;
6509    const uint32_t blocks = n_ff * per_row;
6510    const size_t groups = (blocks + subgroups - 1) / subgroups;
6511    const auto properties = sycl::ext::oneapi::experimental::properties{
6512        sycl::ext::oneapi::experimental::use_root_sync};
6513    return strata::q_of(stream)->parallel_for<dpct_kernel_name<class dequant_gu_metadata,
6514                                                       dpct_kernel_scalar<Type>,
6515                                                       dpct_kernel_scalar<PerRow>>>(
6516        sycl::nd_range<3>(sycl::range<3>(1, 2, groups * subgroups * 32),
6517                          sycl::range<3>(1, 1, subgroups * 32)), properties,
6518        [=](sycl::nd_item<3> item) [[sycl::reqd_sub_group_size(32)]] {
6519            const auto sg = item.get_sub_group();
6520            const uint32_t block = uint32_t(item.get_group(2)) * subgroups + sg.get_group_linear_id();
6521            if (block >= blocks) return;
6522            const uint32_t parity = item.get_group(1);
6523            const uint32_t row = block / per_row, col = block % per_row;
6524            const uint32_t bytes = ((2u * row + parity) * per_row + col) * QK_K * 2u;
6525            const Block* selected = iq_signed_grid::block_at<Block>(parity ? up : gate, block);
6526            // These formats independently emit eight consecutive values per
6527            // logical dequant thread. Transpose the original 8-by-4 lane map
6528            // so adjacent hardware lanes store adjacent 16-byte runs.
6529            const uint32_t lane = sg.get_local_linear_id();
6530            const uint32_t dequant_thread = (lane & 3u) * 8u + (lane >> 2);
6531            dq_iq2_xxs_metadata<sycl::half>(selected, 0,
6532                reinterpret_cast<sycl::half*>(reinterpret_cast<uint8_t*>(dst) + bytes),
6533                dequant_thread, sg);
6534        });
6535}
6536}
6537bool iq_dequant_gu_f16_bounded(int type, const void* gate, const void* up,
6538                              int64_t n_ff, int64_t n_embd, uint16_t* dst, void* stream) {
6539    if (n_ff <= 0 || n_embd <= 0 || n_embd % QK_K != 0 ||
6540        uint64_t(n_embd) > UINT32_MAX / 4u ||
6541        uint64_t(n_ff) > UINT32_MAX / (uint64_t(n_embd) * 4u)) return false;
6542#define STRATA_DEQUANT_BOUNDED(TYPE) \
6543    case TYPE: \
6544        if (n_embd == 2560) launch_dequant_gu_bounded<TYPE, 10>(gate, up, n_ff, n_embd, dst, stream); \
6545        else launch_dequant_gu_bounded<TYPE>(gate, up, n_ff, n_embd, dst, stream); \
6546        return true;
6547    static const bool metadata=[](){const char* e=std::getenv("STRATA_SYCL_GU16_METADATA_QUARTET");return e&&e[0]=='1';}();
6548    if(metadata&&type==16&&n_ff==640&&n_embd==2560){
6549        launch_dequant_gu_metadata<16,10>(gate,up,640,2560,dst,stream);
6550        return true;
6551    }
6552    switch (type) {
6553        STRATA_DEQUANT_BOUNDED(16)
6554        STRATA_DEQUANT_BOUNDED(22)
6555        STRATA_DEQUANT_BOUNDED(29)
6556        default: return false;
6557    }
6558#undef STRATA_DEQUANT_BOUNDED
6559}
6560
6561namespace {
6562template <int Subgroups, int Type = 0, int PerRow = 0>
6563void launch_dequant_gu_tiled(int type, const void* gate, const void* up,
6564                             int64_t n_ff, int64_t n_embd, uint16_t* dst,
6565                             void* stream) {
6566    const int64_t per_row = PerRow ? PerRow : n_embd / 256;
6567    const int64_t blocks = n_ff * per_row;
6568    const size_t groups = (size_t) ((blocks + Subgroups - 1) / Subgroups);
6569    auto* queue = strata::q_of(stream);
6570    const auto properties = sycl::ext::oneapi::experimental::properties{
6571        sycl::ext::oneapi::experimental::use_root_sync};
6572    queue->parallel_for<dpct_kernel_name<class dequant_gu_tiled_kernel,
6573                                        dpct_kernel_scalar<Subgroups>,
6574                                        dpct_kernel_scalar<Type>,
6575                                        dpct_kernel_scalar<PerRow>>>(
6576        sycl::nd_range<3>(sycl::range<3>(1, 2, groups * Subgroups * 32),
6577                          sycl::range<3>(1, 1, Subgroups * 32)),
6578        properties,
6579        [=](sycl::nd_item<3> item) [[sycl::reqd_sub_group_size(32)]] {
6580            const auto sg = item.get_sub_group();
6581            const int64_t block = item.get_group(2) * Subgroups + sg.get_group_linear_id();
6582            if (block >= blocks) return;
6583            const int parity = item.get_group(1);
6584            const int64_t row = block / per_row, col = block % per_row;
6585            dq_dispatch<sycl::half>(Type ? Type : type, parity ? up : gate, block,
6586                reinterpret_cast<sycl::half*>(dst) +
6587                    ((2 * row + parity) * per_row + col) * QK_K,
6588                sg.get_local_linear_id());
6589        });
6590}
6591template <int Subgroups>
6592void dispatch_dequant_gu_tiled(int type, const void* gate, const void* up,
6593                              int64_t n_ff, int64_t n_embd, uint16_t* dst,
6594                              void* stream, bool static_type, bool static_row) {
6595    if (static_row && n_embd == 2560) {
6596        switch (type) {
6597            case 16: launch_dequant_gu_tiled<Subgroups, 16, 10>(type, gate, up, n_ff, n_embd, dst, stream); return;
6598            case 22: launch_dequant_gu_tiled<Subgroups, 22, 10>(type, gate, up, n_ff, n_embd, dst, stream); return;
6599            case 29: launch_dequant_gu_tiled<Subgroups, 29, 10>(type, gate, up, n_ff, n_embd, dst, stream); return;
6600        }
6601    }
6602    if (static_type) {
6603        switch (type) {
6604            case 16: launch_dequant_gu_tiled<Subgroups, 16>(type, gate, up, n_ff, n_embd, dst, stream); return;
6605            case 22: launch_dequant_gu_tiled<Subgroups, 22>(type, gate, up, n_ff, n_embd, dst, stream); return;
6606            case 29: launch_dequant_gu_tiled<Subgroups, 29>(type, gate, up, n_ff, n_embd, dst, stream); return;
6607        }
6608    }
6609    launch_dequant_gu_tiled<Subgroups>(type, gate, up, n_ff, n_embd, dst, stream);
6610}
6611int dequant_gu_subgroups() {
6612    static const int value = [] {
6613        const char* text = std::getenv("STRATA_SYCL_DEQUANT_GU_SG");
6614        const int requested = text ? std::atoi(text) : 1;
6615        return requested == 2 || requested == 4 || requested == 8 ? requested : 1;
6616    }();
6617    return value;
6618}
6619}
6620
6621void iq_dequant_gu_f16_tiled(int type, const void* gate, const void* up,
6622                           int64_t n_ff, int64_t n_embd, uint16_t* dst,
6623                           void* stream, int subgroups, bool static_type, bool static_row) {
6624    if (n_ff <= 0 || n_embd <= 0 || n_embd % 256 != 0 || !is_iq(type)) {
6625        std::fprintf(stderr, "iq_dequant_gu_f16_tiled: invalid type or shape\n");
6626        std::exit(1);
6627    }
6628    dpct::has_capability_or_fail(strata::q_of(stream)->get_device(), {sycl::aspect::fp16});
6629    switch (subgroups) {
6630        case 2: dispatch_dequant_gu_tiled<2>(type, gate, up, n_ff, n_embd, dst, stream, static_type, static_row); break;
6631        case 4: dispatch_dequant_gu_tiled<4>(type, gate, up, n_ff, n_embd, dst, stream, static_type, static_row); break;
6632        case 8: dispatch_dequant_gu_tiled<8>(type, gate, up, n_ff, n_embd, dst, stream, static_type, static_row); break;
6633        default: std::fprintf(stderr, "iq_dequant_gu_f16_tiled: subgroups must be 2, 4 or 8\n"); std::exit(1);
6634    }
6635    check("iq_dequant_gu_f16_tiled");
6636}
6637
6638void iq_dequant_gu_f16(int t, const void* gate, const void* up, int64_t n_ff, int64_t n_embd, uint16_t* dst, void* stream,
6639                       const float* tail) {
6640    // checked like the other entry points: an unknown type used to leave `dst` unwritten, a wrong prompt and no error
6641    // (tail: NVFP4's per-expert scales, CUDA only - never given on SYCL)
6642    if (n_embd % 256 != 0 || !is_iq(t) || tail != nullptr) { std::fprintf(stderr, "iq_dequant_gu_f16: type %d / %lld\n", t, (long long) n_embd); std::exit(1); }
6643    static const bool bounded = env_on("STRATA_SYCL_DEQUANT_GU_BOUNDED");
6644    if (bounded && iq_dequant_gu_f16_bounded(t, gate, up, n_ff, n_embd, dst, stream)) return;
6645    if (dequant_gu_subgroups() != 1) {
6646        static const bool static_type = env_on("STRATA_SYCL_DEQUANT_GU_STATIC_TYPE");
6647        static const bool static_row = env_on("STRATA_SYCL_DEQUANT_GU_STATIC_ROW");
6648        iq_dequant_gu_f16_tiled(t, gate, up, n_ff, n_embd, dst, stream, dequant_gu_subgroups(), static_type, static_row);
6649        return;
6650    }
6651    const int64_t per_row = n_embd / 256;
6652    {
6653
6654        auto exp_props = sycl::ext::oneapi::experimental::properties{
6655            sycl::ext::oneapi::experimental::use_root_sync};
6656        dpct::has_capability_or_fail(
6657            strata::q_of(stream)->get_device(),
6658            {sycl::aspect::fp16});
6659
6660        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
6661            ->submit([&](sycl::handler &cgh) {
6662
6663                cgh.parallel_for<
6664                    dpct_kernel_name<class dequant_gu_kernel_2397ca>>(
6665                    sycl::nd_range<3>(
6666                        sycl::range(1, 2, (unsigned)(n_ff * per_row)) *
6667                            sycl::range(1, 1, 32),
6668                        sycl::range(1, 1, 32)),
6669                    exp_props, [=](sycl::nd_item<3> item_ct1) {
6670                        dequant_gu_kernel(
6671                            t, gate, up, per_row, (sycl::half *)dst);
6672                    });
6673            });
6674    }
6675    check("iq_dequant_gu_f16");
6676}
6677
6678// 0.1.43: gate/up and down of one expert in one launch.  Work-group g of the first 2 * n_ff * per_row is the gu kernel's
6679// (row-superblock g / 2, parity g % 2); the rest are the flat kernel's superblocks of the down matrix.
6680namespace {
6681__dpct_inline__ void dequant_expert_kernel(int gt, int dt, const void *__restrict__ gate, const void *__restrict__ up,
6682                                           const void *__restrict__ down, int64_t per_row, int64_t gu_wgs,
6683                                           sycl::half *__restrict__ ygu, sycl::half *__restrict__ yd) {
6684    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
6685    const int64_t g = item_ct1.get_group(2);
6686    if (g < gu_wgs) {
6687        const int64_t i = g >> 1;
6688        const int parity = (int) (g & 1);
6689        const int64_t r = i / per_row, c = i % per_row;
6690        dq_dispatch<sycl::half>(gt, parity ? up : gate, i, ygu + ((2 * r + parity) * per_row + c) * QK_K,
6691                                item_ct1.get_local_id(2));
6692    } else {
6693        const int64_t j = g - gu_wgs;
6694        dq_dispatch<sycl::half>(dt, down, j, yd + j * QK_K, item_ct1.get_local_id(2));
6695    }
6696}
6697}  // namespace
6698
6699void iq_dequant_expert_f16(int gt, int dt, const void* gate, const void* up, const void* down, int64_t n_ff,
6700                           int64_t n_embd, uint16_t* dst_gu, uint16_t* dst_d, void* stream) {
6701    if (n_embd % 256 != 0 || (n_ff * n_embd) % 256 != 0 || !is_iq(gt) || !is_iq(dt)) {
6702        std::fprintf(stderr, "iq_dequant_expert_f16: types %d/%d, %lld x %lld\n", gt, dt, (long long) n_ff, (long long) n_embd);
6703        std::exit(1);
6704    }
6705    const int64_t per_row = n_embd / 256, gu_wgs = 2 * n_ff * per_row, d_wgs = n_ff * n_embd / 256;
6706    {
6707        auto exp_props = sycl::ext::oneapi::experimental::properties{
6708            sycl::ext::oneapi::experimental::use_root_sync};
6709        dpct::has_capability_or_fail(strata::q_of(stream)->get_device(), {sycl::aspect::fp16});
6710        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)->submit([&](sycl::handler &cgh) {
6711            cgh.parallel_for<dpct_kernel_name<class dequant_expert_kernel_7d2c41>>(
6712                sycl::nd_range<3>(sycl::range(1, 1, (unsigned) (gu_wgs + d_wgs)) * sycl::range(1, 1, 32),
6713                                  sycl::range(1, 1, 32)),
6714                exp_props, [=](sycl::nd_item<3> item_ct1) {
6715                    dequant_expert_kernel(gt, dt, gate, up, down, per_row, gu_wgs, (sycl::half *) dst_gu,
6716                                          (sycl::half *) dst_d);
6717                });
6718        });
6719    }
6720    check("iq_dequant_expert_f16");
6721}
6722
6723bool native_expert_supported(int gu_type, int d_type, int64_t n_embd, int64_t n_ff) noexcept {
6724    const int qg = gu_qk(gu_type), qd = d_qk(d_type);
6725    return qg > 0 && qd > 0 && is_iq(gu_type) && is_iq(d_type) && n_embd % qg == 0 && n_ff % qd == 0 &&
6726           n_embd % 256 == 0 && (n_ff * n_embd) % 256 == 0;
6727}
6728
6729NativeExpertLayout native_expert_layout(int gu_type, int d_type, int64_t n_embd, int64_t n_ff) {
6730    NativeExpertLayout L;
6731    L.gu_type = gu_type;
6732    L.d_type = d_type;
6733    L.n_embd = n_embd;
6734    L.n_ff = n_ff;
6735    L.gu_row = iq_row_bytes(gu_type, n_embd);
6736    L.d_row = iq_row_bytes(d_type, n_ff);
6737    L.up_off = (size_t) n_ff * L.gu_row;
6738    L.down_off = 2 * L.up_off;
6739    L.bytes = L.down_off + (size_t) n_embd * L.d_row;
6740    return L;
6741}
6742
6743size_t native_expert_scratch_bytes(int64_t cap, int64_t n_ff) {
6744    const size_t f = (size_t) cap * (size_t) n_ff * sizeof(float);
6745    return 3 * ((f + 255) & ~(size_t) 255) + (((size_t) cap * (size_t) (n_ff / 32) * sizeof(block_q8_1) + 255) & ~(size_t) 255);
6746}
6747
6748
6749#if defined(STRATA_HIP_GFX906)
6750// ---- AMD layouts for the grouped native experts (STRATA_EXP_MODE; 0 = the CUDA one above).
6751// 1 (W64): a row per 64-lane wavefront - 4x the wavefronts, ~1-2 calls per lane, a 64-lane butterfly.
6752// 2 (R2):  a 32-lane logical warp computes TWO rows in one loop - two independent load chains in flight.
6753// Either way a (row, entry) sum does not depend on the window size.
6754template<int TY>
6755__device__ __forceinline__ float row_dot64(const uint8_t* row, const block_q8_1* x, int nb, int lane) {
6756    using F = Fmt<TY>;
6757    float s = 0.0f;
6758    for (int k = lane; k < nb * F::ipb; k += 64) {
6759        const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb);
6760        s += F::dot(row, x + kbx * (F::qk / 32), kbx, iqs);
6761    }
6762#pragma unroll
6763    for (int o = 32; o > 0; o >>= 1) s += __shfl_xor(s, o, 64);
6764    return s;
6765}
6766template<int TY>
6767__device__ __forceinline__ void row_dot2(const uint8_t* r0, const uint8_t* r1, const block_q8_1* x, int nb, int lane,
6768                                         float& o0, float& o1) {
6769    using F = Fmt<TY>;
6770    float s0 = 0.0f, s1 = 0.0f;
6771    for (int k = lane; k < nb * F::ipb; k += 32) {
6772        const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb);
6773        const block_q8_1* xk = x + kbx * (F::qk / 32);
6774        const float a = F::dot(r0, xk, kbx, iqs);
6775        const float b = F::dot(r1, xk, kbx, iqs);
6776        s0 += a;
6777        s1 += b;
6778    }
6779    o0 = warp_sum(s0);
6780    o1 = warp_sum(s1);
6781}
6782template<int TY, int NR>
6783__device__ __forceinline__ void row_dotn(const uint8_t* const* r, const block_q8_1* x, int nb, int lane, float* o) {
6784    using F = Fmt<TY>;
6785    float acc[NR];
6786#pragma unroll
6787    for (int i = 0; i < NR; ++i) acc[i] = 0.0f;
6788    for (int k = lane; k < nb * F::ipb; k += 32) {
6789        const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb);
6790        const block_q8_1* xk = x + kbx * (F::qk / 32);
6791        float d[NR];
6792#pragma unroll
6793        for (int i = 0; i < NR; ++i) d[i] = F::dot(r[i], xk, kbx, iqs);
6794#pragma unroll
6795        for (int i = 0; i < NR; ++i) acc[i] += d[i];
6796    }
6797#pragma unroll
6798    for (int i = 0; i < NR; ++i) o[i] = warp_sum(acc[i]);
6799}
6800template<int TG, int MODE>
6801__global__ void __launch_bounds__(256) native_gu_amd_kernel(const unsigned long long* __restrict__ grp_ptr,
6802                                                            const int32_t* __restrict__ grp_start,
6803                                                            const int32_t* __restrict__ n_groups,
6804                                                            const int32_t* __restrict__ ent_tok,
6805                                                            const block_q8_1* __restrict__ xq, NativeExpertLayout L,
6806                                                            float* __restrict__ gate, float* __restrict__ up) {
6807    const int g = blockIdx.y;
6808    if (g >= *n_groups) return;
6809    const uint8_t* blob = (const uint8_t*) grp_ptr[g];
6810    const int nb = (int) (L.n_embd / Fmt<TG>::qk), xb = (int) (L.n_embd / 32);
6811    const int e0 = grp_start[g], e1 = grp_start[g + 1];
6812    const int nrow = 2 * (int) L.n_ff;
6813    auto wrow = [&](int row) -> const uint8_t* {
6814        const bool is_up = row >= L.n_ff;
6815        return blob + (is_up ? L.up_off : 0) + (size_t) (is_up ? row - (int) L.n_ff : row) * L.gu_row;
6816    };
6817    auto put = [&](int row, int e, float v) {
6818        const bool is_up = row >= L.n_ff;
6819        (is_up ? up : gate)[(size_t) e * L.n_ff + (is_up ? row - (int) L.n_ff : row)] = v;
6820    };
6821    if constexpr (MODE == 1) {
6822        const int lane = threadIdx.x & 63, row = blockIdx.x * 4 + (threadIdx.x >> 6);
6823        if (row >= nrow) return;
6824        const uint8_t* wr = wrow(row);
6825        for (int e = e0; e < e1; ++e) {
6826            const float v = row_dot64<TG>(wr, xq + (size_t) ent_tok[e] * xb, nb, lane);
6827            if (lane == 0) put(row, e, v);
6828        }
6829    } else if constexpr (MODE == 4) {
6830        const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5;
6831        const int row0 = blockIdx.x * 32 + warp;
6832        if (row0 >= nrow) return;
6833        const uint8_t* w[4];
6834#pragma unroll
6835        for (int i = 0; i < 4; ++i) w[i] = wrow(row0 + 8 * i < nrow ? row0 + 8 * i : row0);
6836        for (int e = e0; e < e1; ++e) {
6837            float o[4];
6838            row_dotn<TG, 4>(w, xq + (size_t) ent_tok[e] * xb, nb, lane, o);
6839            if (lane == 0)
6840#pragma unroll
6841                for (int i = 0; i < 4; ++i) if (row0 + 8 * i < nrow) put(row0 + 8 * i, e, o[i]);
6842        }
6843    } else {
6844        const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5;
6845        const int row0 = blockIdx.x * 16 + warp, row1 = row0 + 8;
6846        if (row0 >= nrow) return;
6847        const bool two = row1 < nrow;
6848        const uint8_t* w0 = wrow(row0);
6849        const uint8_t* w1 = wrow(two ? row1 : row0);
6850        for (int e = e0; e < e1; ++e) {
6851            float a, b;
6852            row_dot2<TG>(w0, w1, xq + (size_t) ent_tok[e] * xb, nb, lane, a, b);
6853            if (lane == 0) { put(row0, e, a); if (two) put(row1, e, b); }
6854        }
6855    }
6856}
6857template<int TD, int MODE>
6858__global__ void __launch_bounds__(256) native_down_amd_kernel(const unsigned long long* __restrict__ grp_ptr,
6859                                                              const int32_t* __restrict__ grp_start,
6860                                                              const int32_t* __restrict__ n_groups,
6861                                                              const int32_t* __restrict__ ent_dst,
6862                                                              const block_q8_1* __restrict__ hq, NativeExpertLayout L,
6863                                                              float* __restrict__ out) {
6864    const int g = blockIdx.y;
6865    if (g >= *n_groups) return;
6866    const uint8_t* blob = (const uint8_t*) grp_ptr[g];
6867    const int nb = (int) (L.n_ff / Fmt<TD>::qk), hb = (int) (L.n_ff / 32);
6868    const int e0 = grp_start[g], e1 = grp_start[g + 1];
6869    const int nrow = (int) L.n_embd;
6870    if constexpr (MODE == 1) {
6871        const int lane = threadIdx.x & 63, r = blockIdx.x * 4 + (threadIdx.x >> 6);
6872        if (r >= nrow) return;
6873        const uint8_t* wr = blob + L.down_off + (size_t) r * L.d_row;
6874        for (int e = e0; e < e1; ++e) {
6875            const float v = row_dot64<TD>(wr, hq + (size_t) e * hb, nb, lane);
6876            if (lane == 0) out[(size_t) ent_dst[e] * L.n_embd + r] = v;
6877        }
6878    } else if constexpr (MODE == 4) {
6879        const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5;
6880        const int r0 = blockIdx.x * 32 + warp;
6881        if (r0 >= nrow) return;
6882        const uint8_t* w[4];
6883#pragma unroll
6884        for (int i = 0; i < 4; ++i) w[i] = blob + L.down_off + (size_t) (r0 + 8 * i < nrow ? r0 + 8 * i : r0) * L.d_row;
6885        for (int e = e0; e < e1; ++e) {
6886            float o[4];
6887            row_dotn<TD, 4>(w, hq + (size_t) e * hb, nb, lane, o);
6888            if (lane == 0)
6889#pragma unroll
6890                for (int i = 0; i < 4; ++i) if (r0 + 8 * i < nrow) out[(size_t) ent_dst[e] * L.n_embd + r0 + 8 * i] = o[i];
6891        }
6892    } else {
6893        const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5;
6894        const int r0 = blockIdx.x * 16 + warp, r1 = r0 + 8;
6895        if (r0 >= nrow) return;
6896        const bool two = r1 < nrow;
6897        const uint8_t* w0 = blob + L.down_off + (size_t) r0 * L.d_row;
6898        const uint8_t* w1 = blob + L.down_off + (size_t) (two ? r1 : r0) * L.d_row;
6899        for (int e = e0; e < e1; ++e) {
6900            float a, b;
6901            row_dot2<TD>(w0, w1, hq + (size_t) e * hb, nb, lane, a, b);
6902            if (lane == 0) {
6903                out[(size_t) ent_dst[e] * L.n_embd + r0] = a;
6904                if (two) out[(size_t) ent_dst[e] * L.n_embd + r1] = b;
6905            }
6906        }
6907    }
6908}
6909// ---- 5 (LDS): gate/up of the grid formats (IQ2_S, IQ3_XXS, IQ3_S) with the codebook grid and the group's q8_1
6910// activations in LDS.  The bench showed gate/up compute-bound, not bandwidth-bound (T = 2 costs ~1.8x T = 1 on the
6911// same weights, 110-130 GB/s): each call issues its grid lookups and eight activation loads through the vector
6912// memory path after the weight load.  Same calls, same lane-strided k, same R2 row pairs, same warp_sum: the
6913// output is bitwise the mode-2 one.
6914template<int TY> struct GridOf;
6915template<> struct GridOf<22> { using T = uint64_t; static constexpr int N = 1024; __device__ static const T* src() { return iq2s_grid; } };
6916template<> struct GridOf<18> { using T = uint32_t; static constexpr int N = 256; __device__ static const T* src() { return iq3xxs_grid; } };
6917template<> struct GridOf<21> { using T = uint32_t; static constexpr int N = 512; __device__ static const T* src() { return iq3s_grid; } };
6918template<> struct GridOf<23> { using T = uint32_t; static constexpr int N = 1; __device__ static const T* src() { return iq3s_grid; } };   // IQ4_XS: no grid
6919
6920// SG = 1 (mode 6): the signs without byte-SIMD ops, which gfx906 lacks (strata_vcmpne4 / strata_vsub4 unpack to
6921// ~12 word ops each).  m = the sign nibble as 0x00/0xff bytes; (g ^ m) is g or -g-1 per byte, so
6922// dp4a(g ^ m, u) - dp4a(m, u) = sum(s g u) exactly - the same integers, the same floats.
6923__device__ __forceinline__ int nib_mask(uint32_t n) {
6924    const uint32_t b = __umul24(n & 0xFu, 0x204081u) & 0x01010101u;
6925    return (int) ((b << 8) - b);
6926}
6927template<int TY, int SG> struct DotG;
6928template<int SG> struct DotG<22, SG> { __device__ static __forceinline__ float f(const void* vbq, const block_q8_1* bq8_1, int kbx, int iqs,
6929                                                      const uint64_t* grid) {
6930    const block_iq2_s* bq2 = (const block_iq2_s*) vbq + kbx;
6931    const int qs_packed = get_int_b2(bq2->qs, iqs / 2);
6932    const uint8_t* qs = (const uint8_t*) &qs_packed;
6933    const int qh = bq2->qh[iqs / 2];
6934    const int signs_packed_32 = get_int_b2(bq2->qs, QK_K / 32 + iqs / 2);
6935    const uint8_t* signs_packed_8 = (const uint8_t*) &signs_packed_32;
6936    const int ls0 = bq2->scales[iqs / 2] & 0x0F;
6937    const int ls1 = bq2->scales[iqs / 2] >> 4;
6938    int sumi0 = 0, sumi1 = 0;
6939#pragma unroll
6940    for (int l0 = 0; l0 < 8; l0 += 2) {
6941        const int* grid_pos = (const int*) (grid + (qs[l0 / 2] | ((qh << (8 - l0)) & 0x300)));
6942        const int u0 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 0);
6943        const int u1 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 1);
6944        int& acc = l0 < 4 ? sumi0 : sumi1;
6945        if constexpr (SG == 1) {
6946            const int m0 = nib_mask(signs_packed_8[l0 / 2]), m1 = nib_mask(signs_packed_8[l0 / 2] >> 4);
6947            acc = ggml_cuda_dp4a(grid_pos[0] ^ m0, u0, acc);
6948            acc = ggml_cuda_dp4a(grid_pos[1] ^ m1, u1, acc);
6949            acc -= ggml_cuda_dp4a(m1, u1, ggml_cuda_dp4a(m0, u0, 0));
6950        } else {
6951            const int signs0 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x03) << 7) | ((signs_packed_8[l0 / 2] & 0x0C) << 21), 0x00000000);
6952            const int signs1 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x30) << 3) | ((signs_packed_8[l0 / 2] & 0xC0) << 17), 0x00000000);
6953            const int grid_l = __vsub4(grid_pos[0] ^ signs0, signs0);
6954            const int grid_h = __vsub4(grid_pos[1] ^ signs1, signs1);
6955            acc = ggml_cuda_dp4a(grid_l, u0, acc);
6956            acc = ggml_cuda_dp4a(grid_h, u1, acc);
6957        }
6958    }
6959    const int sumi = (sumi0 * ls0 + sumi1 * ls1 + (sumi0 + sumi1) / 2) / 4;
6960    const float d = __half2float(bq2->d) * __low2float(bq8_1[iqs / 2].ds);
6961    return d * sumi;
6962} };
6963template<int SG> struct DotG<18, SG> { __device__ static __forceinline__ float f(const void* vbq, const block_q8_1* bq8_1, int kbx, int iqs,
6964                                                      const uint32_t* grid) {
6965    const block_iq3_xxs* bq3 = (const block_iq3_xxs*) vbq + kbx;
6966    const int2 q3_packed = make_int2(get_int_b2(bq3->qs, iqs), get_int_b2(bq3->qs, iqs + 1));
6967    const uint8_t* q3 = (const uint8_t*) &q3_packed;
6968    const uint32_t aux32 = get_int_b2(bq3->qs, QK_K / 16 + iqs / 2);
6969    int sumi = 0;
6970#pragma unroll
6971    for (int l0 = 0; l0 < 8; l0 += 2) {
6972        const int2 grid_pos = make_int2(grid[q3[l0 + 0]], grid[q3[l0 + 1]]);
6973        const uint32_t signs = unpack_ksigns(aux32 >> (7 * l0 / 2));
6974        const int u0 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 0);
6975        const int u1 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 1);
6976        if constexpr (SG == 1) {
6977            const int m0 = nib_mask(signs), m1 = nib_mask(signs >> 4);
6978            sumi = ggml_cuda_dp4a(grid_pos.x ^ m0, u0, sumi);
6979            sumi = ggml_cuda_dp4a(grid_pos.y ^ m1, u1, sumi);
6980            sumi -= ggml_cuda_dp4a(m1, u1, ggml_cuda_dp4a(m0, u0, 0));
6981        } else {
6982            const int signs0 = __vcmpne4(signs & 0x08040201, 0);
6983            const int grid_l = __vsub4(grid_pos.x ^ signs0, signs0);
6984            const int signs1 = __vcmpne4(signs & 0x80402010, 0);
6985            const int grid_h = __vsub4(grid_pos.y ^ signs1, signs1);
6986            sumi = ggml_cuda_dp4a(grid_l, u0, sumi);
6987            sumi = ggml_cuda_dp4a(grid_h, u1, sumi);
6988        }
6989    }
6990    const int ls = aux32 >> 28;
6991    sumi = (ls * sumi + sumi / 2) / 2;
6992    const float d = __half2float(bq3->d) * __low2float(bq8_1[iqs / 2].ds);
6993    return d * sumi;
6994} };
6995template<int SG> struct DotG<21, SG> { __device__ static __forceinline__ float f(const void* vbq, const block_q8_1* bq8_1, int kbx, int iqs,
6996                                                      const uint32_t* grid) {
6997    const block_iq3_s* bq3 = (const block_iq3_s*) vbq + kbx;
6998    const int2 qs_packed = make_int2(get_int_b2(bq3->qs, iqs + 0), get_int_b2(bq3->qs, iqs + 1));
6999    const uint8_t* qs = (const uint8_t*) &qs_packed;
7000    const int qh = bq3->qh[iqs / 2];
7001    const int signs_packed_32 = get_int_b2(bq3->signs, iqs / 2);
7002    const uint8_t* signs_packed_8 = (const uint8_t*) &signs_packed_32;
7003    int sumi = 0;
7004#pragma unroll
7005    for (int l0 = 0; l0 < 8; l0 += 2) {
7006        const int2 grid_pos = make_int2(grid[qs[l0 + 0] | ((qh << (8 - l0)) & 0x100)],
7007                                        grid[qs[l0 + 1] | ((qh << (7 - l0)) & 0x100)]);
7008        const int u0 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 0);
7009        const int u1 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 1);
7010        if constexpr (SG == 1) {
7011            const int m0 = nib_mask(signs_packed_8[l0 / 2]), m1 = nib_mask(signs_packed_8[l0 / 2] >> 4);
7012            sumi = ggml_cuda_dp4a(grid_pos.x ^ m0, u0, sumi);
7013            sumi = ggml_cuda_dp4a(grid_pos.y ^ m1, u1, sumi);
7014            sumi -= ggml_cuda_dp4a(m1, u1, ggml_cuda_dp4a(m0, u0, 0));
7015        } else {
7016            const int signs0 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x03) << 7) | ((signs_packed_8[l0 / 2] & 0x0C) << 21), 0x00000000);
7017            const int signs1 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x30) << 3) | ((signs_packed_8[l0 / 2] & 0xC0) << 17), 0x00000000);
7018            const int grid_l = __vsub4(grid_pos.x ^ signs0, signs0);
7019            const int grid_h = __vsub4(grid_pos.y ^ signs1, signs1);
7020            sumi = ggml_cuda_dp4a(grid_l, u0, sumi);
7021            sumi = ggml_cuda_dp4a(grid_h, u1, sumi);
7022        }
7023    }
7024    sumi *= 1 + 2 * ((bq3->scales[iqs / 4] >> ((iqs << 1) & 0x04)) & 0x0F);
7025    const float d = __half2float(bq3->d) * __low2float(bq8_1[iqs / 2].ds);
7026    return d * sumi;
7027} };
7028
7029template<int SG> struct DotG<23, SG> { __device__ static __forceinline__ float f(const void* vbq, const block_q8_1* bq8_1, int kbx, int iqs,
7030                                                      const uint32_t*) { return vec_dot_iq4_xs_q8_1(vbq, bq8_1, kbx, iqs); } };
7031
7032constexpr int LDS_RB = 64;    // gate/up rows per block (4 R2 passes of 16)
7033constexpr int LDS_NT = 4;     // entries whose activations sit in LDS at once
7034
7035template<int TG, int SG, bool TI = false>
7036__global__ void __launch_bounds__(256) native_gu_lds_kernel(const unsigned long long* __restrict__ grp_ptr,
7037                                                            const int32_t* __restrict__ grp_start,
7038                                                            const int32_t* __restrict__ n_groups,
7039                                                            const int32_t* __restrict__ ent_tok,
7040                                                            const block_q8_1* __restrict__ xq, NativeExpertLayout L,
7041                                                            float* __restrict__ gate, float* __restrict__ up) {
7042    using GT = typename GridOf<TG>::T;
7043    using F = Fmt<TG>;
7044    __shared__ GT sgrid[GridOf<TG>::N];
7045    extern __shared__ int sx_raw[];   // LDS_NT tokens x xb blocks of q8_1 (36 bytes = 9 ints each)
7046    const int g = blockIdx.y;
7047    if (g >= *n_groups) return;       // uniform over the block
7048    const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5;
7049    const GT* gsrc = GridOf<TG>::src();
7050    for (int i = tid; i < GridOf<TG>::N; i += 256) sgrid[i] = gsrc[i];
7051    const uint8_t* blob = (const uint8_t*) grp_ptr[g];
7052    const int nb = (int) (L.n_embd / F::qk), xb = (int) (L.n_embd / 32);
7053    const int e0 = grp_start[g], e1 = grp_start[g + 1];
7054    const int nrow = 2 * (int) L.n_ff;
7055    const block_q8_1* sx = (const block_q8_1*) sx_raw;
7056    auto wrow = [&](int row) -> const uint8_t* {
7057        const bool is_up = row >= L.n_ff;
7058        return blob + (is_up ? L.up_off : 0) + (size_t) (is_up ? row - (int) L.n_ff : row) * L.gu_row;
7059    };
7060    auto put = [&](int row, int e, float v) {
7061        const bool is_up = row >= L.n_ff;
7062        (is_up ? up : gate)[(size_t) e * L.n_ff + (is_up ? row - (int) L.n_ff : row)] = v;
7063    };
7064    for (int c0 = e0; c0 < e1; c0 += LDS_NT) {
7065        const int cn = min(LDS_NT, e1 - c0);
7066        __syncthreads();
7067        for (int j = 0; j < cn; ++j) {
7068            const int* src = (const int*) (xq + (size_t) ent_tok[c0 + j] * xb);
7069            for (int i = tid; i < xb * 9; i += 256) sx_raw[j * xb * 9 + i] = src[i];
7070        }
7071        __syncthreads();
7072        for (int p = 0; p < LDS_RB / 16; ++p) {
7073            const int row0 = blockIdx.x * LDS_RB + p * 16 + warp, row1 = row0 + 8;
7074            if (row0 >= nrow) break;
7075            const bool two = row1 < nrow;
7076            const uint8_t* w0 = wrow(row0);
7077            const uint8_t* w1 = wrow(two ? row1 : row0);
7078            if constexpr (TI) {   // mode 7: the tokens inside the k loop - one weight load per k for all of them
7079                auto pass = [&](auto ntc) {
7080                    constexpr int NTC = decltype(ntc)::value;
7081                    float s0[NTC], s1[NTC];
7082#pragma unroll
7083                    for (int j = 0; j < NTC; ++j) { s0[j] = 0.0f; s1[j] = 0.0f; }
7084                    for (int k = lane; k < nb * F::ipb; k += 32) {
7085                        const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb);
7086#pragma unroll
7087                        for (int j = 0; j < NTC; ++j) {
7088                            const block_q8_1* xk = sx + (size_t) j * xb + kbx * (F::qk / 32);
7089                            const float a = DotG<TG, SG>::f(w0, xk, kbx, iqs, sgrid);
7090                            const float b = DotG<TG, SG>::f(w1, xk, kbx, iqs, sgrid);
7091                            s0[j] += a;
7092                            s1[j] += b;
7093                        }
7094                    }
7095#pragma unroll
7096                    for (int j = 0; j < NTC; ++j) {
7097                        const float a = warp_sum(s0[j]), b = warp_sum(s1[j]);
7098                        if (lane == 0) { put(row0, c0 + j, a); if (two) put(row1, c0 + j, b); }
7099                    }
7100                };
7101                switch (cn) {
7102                    case 1: pass(std::integral_constant<int, 1>{}); break;
7103                    case 2: pass(std::integral_constant<int, 2>{}); break;
7104                    case 3: pass(std::integral_constant<int, 3>{}); break;
7105                    default: pass(std::integral_constant<int, 4>{}); break;
7106                }
7107                continue;
7108            }
7109            for (int j = 0; j < cn; ++j) {
7110                const block_q8_1* x = sx + (size_t) j * xb;
7111                float s0 = 0.0f, s1 = 0.0f;
7112                for (int k = lane; k < nb * F::ipb; k += 32) {
7113                    const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb);
7114                    const block_q8_1* xk = x + kbx * (F::qk / 32);
7115                    const float a = DotG<TG, SG>::f(w0, xk, kbx, iqs, sgrid);
7116                    const float b = DotG<TG, SG>::f(w1, xk, kbx, iqs, sgrid);
7117                    s0 += a;
7118                    s1 += b;
7119                }
7120                s0 = warp_sum(s0);
7121                s1 = warp_sum(s1);
7122                if (lane == 0) { put(row0, c0 + j, s0); if (two) put(row1, c0 + j, s1); }
7123            }
7124        }
7125    }
7126}
7127
7128// ---- 7 (down): the group's q8_1 h rows in LDS, the tokens inside the k loop, the R2 row pairs of mode 2 -
7129// the same per-(row, entry) sums in the same order: bitwise the mode-2 output.
7130template<int TD>
7131__global__ void __launch_bounds__(256) native_down_lds_kernel(const unsigned long long* __restrict__ grp_ptr,
7132                                                              const int32_t* __restrict__ grp_start,
7133                                                              const int32_t* __restrict__ n_groups,
7134                                                              const int32_t* __restrict__ ent_dst,
7135                                                              const block_q8_1* __restrict__ hq, NativeExpertLayout L,
7136                                                              float* __restrict__ out) {
7137    using F = Fmt<TD>;
7138    extern __shared__ int sh_raw[];   // LDS_NT entries x hb blocks of q8_1
7139    const int g = blockIdx.y;
7140    if (g >= *n_groups) return;
7141    const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5;
7142    const uint8_t* blob = (const uint8_t*) grp_ptr[g];
7143    const int nb = (int) (L.n_ff / F::qk), hb = (int) (L.n_ff / 32);
7144    const int e0 = grp_start[g], e1 = grp_start[g + 1];
7145    const int nrow = (int) L.n_embd;
7146    const block_q8_1* sh = (const block_q8_1*) sh_raw;
7147    for (int c0 = e0; c0 < e1; c0 += LDS_NT) {
7148        const int cn = min(LDS_NT, e1 - c0);
7149        __syncthreads();
7150        {
7151            const int* src = (const int*) (hq + (size_t) c0 * hb);   // the chunk's entries are contiguous
7152            for (int i = tid; i < cn * hb * 9; i += 256) sh_raw[i] = src[i];
7153        }
7154        __syncthreads();
7155        for (int p = 0; p < LDS_RB / 16; ++p) {
7156            const int r0 = blockIdx.x * LDS_RB + p * 16 + warp, r1 = r0 + 8;
7157            if (r0 >= nrow) break;
7158            const bool two = r1 < nrow;
7159            const uint8_t* w0 = blob + L.down_off + (size_t) r0 * L.d_row;
7160            const uint8_t* w1 = blob + L.down_off + (size_t) (two ? r1 : r0) * L.d_row;
7161            auto pass = [&](auto ntc) {
7162                constexpr int NTC = decltype(ntc)::value;
7163                float s0[NTC], s1[NTC];
7164#pragma unroll
7165                for (int j = 0; j < NTC; ++j) { s0[j] = 0.0f; s1[j] = 0.0f; }
7166                for (int k = lane; k < nb * F::ipb; k += 32) {
7167                    const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb);
7168#pragma unroll
7169                    for (int j = 0; j < NTC; ++j) {
7170                        const block_q8_1* xk = sh + (size_t) j * hb + kbx * (F::qk / 32);
7171                        const float a = F::dot(w0, xk, kbx, iqs);
7172                        const float b = F::dot(w1, xk, kbx, iqs);
7173                        s0[j] += a;
7174                        s1[j] += b;
7175                    }
7176                }
7177#pragma unroll
7178                for (int j = 0; j < NTC; ++j) {
7179                    const float a = warp_sum(s0[j]), b = warp_sum(s1[j]);
7180                    if (lane == 0) {
7181                        out[(size_t) ent_dst[c0 + j] * L.n_embd + r0] = a;
7182                        if (two) out[(size_t) ent_dst[c0 + j] * L.n_embd + r1] = b;
7183                    }
7184                }
7185            };
7186            switch (cn) {
7187                case 1: pass(std::integral_constant<int, 1>{}); break;
7188                case 2: pass(std::integral_constant<int, 2>{}); break;
7189                case 3: pass(std::integral_constant<int, 3>{}); break;
7190                default: pass(std::integral_constant<int, 4>{}); break;
7191            }
7192        }
7193    }
7194}
7195
7196// ---- 8: mode 7's gate/up with SwiGLU and the q8_1 quantization in the epilogue.  A block takes h rows
7197// [r0, r0 + 32): gate rows r0.. and up rows r0.. (64 weight rows, the same per-(row, entry) sums as mode 7), so
7198// one 32-lane warp per entry holds exactly one q8_1 block of h and runs quantize_q8_1_kernel's own code on it -
7199// bitwise the separate kernels' hq, two launches fewer per call.
7200template<int TG>
7201__global__ void __launch_bounds__(256) native_gu_fused_kernel(const unsigned long long* __restrict__ grp_ptr,
7202                                                              const int32_t* __restrict__ grp_start,
7203                                                              const int32_t* __restrict__ n_groups,
7204                                                              const int32_t* __restrict__ ent_tok,
7205                                                              const block_q8_1* __restrict__ xq, NativeExpertLayout L,
7206                                                              block_q8_1* __restrict__ hq) {
7207    using GT = typename GridOf<TG>::T;
7208    using F = Fmt<TG>;
7209    __shared__ GT sgrid[GridOf<TG>::N];
7210    __shared__ float res[LDS_NT][64];
7211    extern __shared__ int sx_raw[];
7212    const int g = blockIdx.y;
7213    if (g >= *n_groups) return;
7214    const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5;
7215    const GT* gsrc = GridOf<TG>::src();
7216    for (int i = tid; i < GridOf<TG>::N; i += 256) sgrid[i] = gsrc[i];
7217    const uint8_t* blob = (const uint8_t*) grp_ptr[g];
7218    const int nb = (int) (L.n_embd / F::qk), xb = (int) (L.n_embd / 32), hb = (int) (L.n_ff / 32);
7219    const int e0 = grp_start[g], e1 = grp_start[g + 1];
7220    const int r0 = blockIdx.x * 32;
7221    const block_q8_1* sx = (const block_q8_1*) sx_raw;
7222    auto wrow = [&](int i) -> const uint8_t* {   // i < 32: gate row r0 + i, else up row r0 + i - 32
7223        return blob + (i < 32 ? (size_t) 0 : L.up_off) + (size_t) (r0 + (i & 31)) * L.gu_row;
7224    };
7225    for (int c0 = e0; c0 < e1; c0 += LDS_NT) {
7226        const int cn = min(LDS_NT, e1 - c0);
7227        __syncthreads();
7228        for (int j = 0; j < cn; ++j) {
7229            const int* src = (const int*) (xq + (size_t) ent_tok[c0 + j] * xb);
7230            for (int i = tid; i < xb * 9; i += 256) sx_raw[j * xb * 9 + i] = src[i];
7231        }
7232        __syncthreads();
7233        for (int p = 0; p < 4; ++p) {
7234            const int i0 = p * 16 + warp, i1 = i0 + 8;
7235            const uint8_t* w0 = wrow(i0);
7236            const uint8_t* w1 = wrow(i1);
7237            auto pass = [&](auto ntc) {
7238                constexpr int NTC = decltype(ntc)::value;
7239                float s0[NTC], s1[NTC];
7240#pragma unroll
7241                for (int j = 0; j < NTC; ++j) { s0[j] = 0.0f; s1[j] = 0.0f; }
7242                for (int k = lane; k < nb * F::ipb; k += 32) {
7243                    const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb);
7244#pragma unroll
7245                    for (int j = 0; j < NTC; ++j) {
7246                        const block_q8_1* xk = sx + (size_t) j * xb + kbx * (F::qk / 32);
7247                        const float a = DotG<TG, 1>::f(w0, xk, kbx, iqs, sgrid);
7248                        const float b = DotG<TG, 1>::f(w1, xk, kbx, iqs, sgrid);
7249                        s0[j] += a;
7250                        s1[j] += b;
7251                    }
7252                }
7253#pragma unroll
7254                for (int j = 0; j < NTC; ++j) {
7255                    const float a = warp_sum(s0[j]), b = warp_sum(s1[j]);
7256                    if (lane == 0) { res[j][i0] = a; res[j][i1] = b; }
7257                }
7258            };
7259            switch (cn) {
7260                case 1: pass(std::integral_constant<int, 1>{}); break;
7261                case 2: pass(std::integral_constant<int, 2>{}); break;
7262                case 3: pass(std::integral_constant<int, 3>{}); break;
7263                default: pass(std::integral_constant<int, 4>{}); break;
7264            }
7265        }
7266        __syncthreads();
7267        if (warp < cn) {   // swiglu_entries_kernel + quantize_q8_1_kernel, one block of 32 h values per entry
7268            const float gg = res[warp][lane], uu = res[warp][32 + lane];
7269            const float xi = (gg / (1.0f + __expf(-gg))) * uu;
7270            float amax = fabsf(xi), sum = xi;
7271#pragma unroll
7272            for (int o = 16; o > 0; o >>= 1) {
7273                amax = fmaxf(amax, __shfl_xor_sync(0xffffffffu, amax, o));
7274                sum += __shfl_xor_sync(0xffffffffu, sum, o);
7275            }
7276            const float d = q8_1_finite(amax / 127.0f);   // #606, as q8_1_store: finite blocks bit for bit
7277            const int8_t q = q8_1_quant(xi, d, amax);
7278            block_q8_1* y = hq + (size_t) (c0 + warp) * hb + blockIdx.x;
7279            y->qs[lane] = q;
7280            if (lane == 0) y->ds = q8_1_ds(d, sum);
7281        }
7282    }
7283}
7284
7285int g_exp_mode = -1;   // native_expert_set_mode (the bench); -1 = STRATA_EXP_MODE, default 7
7286int exp_mode() {
7287    static const int m = [] { const char* v = std::getenv("STRATA_EXP_MODE"); return v ? std::atoi(v) : 7; }();
7288    return g_exp_mode >= 0 ? g_exp_mode : m;
7289}
7290#endif
7291int g_exp_phase = 0;   // the bench: 0 all, 1 gate/up + swiglu + quantize only, 2 down only
7292
7293void native_expert_set_mode(int mode, int phase) {
7294#if defined(STRATA_HIP_GFX906)
7295    g_exp_mode = mode;
7296#else
7297    (void) mode;
7298#endif
7299    g_exp_phase = phase;
7300}
7301
7302namespace {
7303bool g_grouped_v1 = env_on("STRATA_GROUPED_V1");
7304}  // namespace
7305
7306void native_grouped_set_v1(bool v1) { g_grouped_v1 = v1; }
7307
7308void native_expert_grouped(const NativeExpertLayout& L, const unsigned long long* grp_ptr, const int32_t* grp_start,
7309                           const int32_t* n_groups, const int32_t* ent_dst, const int32_t* ent_tok, int64_t cap_groups,
7310                           int64_t cap_entries, const void* x_q8_1, void* scratch, float* out, void* stream,
7311                           int64_t grid_groups) {
7312    strata::workload_trace::Scope trace("decode.expert_grouped", stream, cap_entries, L.n_ff, L.n_embd,
7313                                        L.gu_row, L.d_row, L.gu_type);
7314    if (cap_groups <= 0 || cap_entries <= 0) return;
7315    if (L.n_ff % 32 != 0) { std::fprintf(stderr, "native_expert_grouped: n_ff %lld\n", (long long) L.n_ff); std::exit(1); }
7316    dpct::queue_ptr s = strata::q_of(stream);
7317    const size_t f = (size_t) cap_entries * (size_t) L.n_ff * sizeof(float), fa = (f + 255) & ~(size_t) 255;
7318    float* gate = (float*) scratch;
7319    float* up = (float*) ((uint8_t*) scratch + fa);
7320    float* h = (float*) ((uint8_t*) scratch + 2 * fa);
7321    block_q8_1* hq = (block_q8_1*) ((uint8_t*) scratch + 3 * fa);
7322    const auto* X = (const block_q8_1*) x_q8_1;
7323    // SYCL port: STRATA_EXPERT_V2 / STRATA_EXPERT_V2K (upstream's AMD-tuned S26 / S27 kernels) are not built here
7324    static const bool v2_note = [] {
7325        const char* a = std::getenv("STRATA_EXPERT_V2");
7326        const char* b = std::getenv("STRATA_EXPERT_V2K");
7327        if ((a && a[0] == '1') || (b && b[0] == '1'))
7328            std::fprintf(stderr, "note: STRATA_EXPERT_V2 / STRATA_EXPERT_V2K are AMD-only experiments, ignored on SYCL\n");
7329        return true;
7330    }();
7331    (void) v2_note;
7332    const bool v1 = g_grouped_v1;
7333    // #363: a verify window's PCIe call usually has no group: `grid_groups` block rows stride over the groups instead
7334    // of one row per possible group (the results do not depend on it)
7335    const int64_t gy = (v1 || grid_groups <= 0 || grid_groups > cap_groups) ? cap_groups : grid_groups;
7336    const dpct::dim3 ggu((unsigned)((2 * L.n_ff + kExpertRows - 1) / kExpertRows),
7337                         (unsigned)gy);
7338#if defined(STRATA_HIP_GFX906)
7339    const int em0 = exp_mode();
7340#endif
7341#if defined(STRATA_HIP_GFX906)
7342    const bool fused_gu = em0 == 8 && (L.gu_type == 18 || L.gu_type == 21 || L.gu_type == 22 || L.gu_type == 23) &&
7343                          L.n_ff % 32 == 0;
7344    if (fused_gu && g_exp_phase != 2) {
7345        const dim3 gl((unsigned) (L.n_ff / 32), (unsigned) cap_groups);
7346        const size_t sh = (size_t) LDS_NT * (size_t) (L.n_embd / 32) * sizeof(block_q8_1);
7347        switch (L.gu_type) {
7348            case 18: native_gu_fused_kernel<18><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, hq); break;
7349            case 21: native_gu_fused_kernel<21><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, hq); break;
7350            case 23: native_gu_fused_kernel<23><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, hq); break;
7351            default: native_gu_fused_kernel<22><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, hq); break;
7352        }
7353        check("native_expert_grouped/gu fused");
7354    }
7355    if (g_exp_phase != 2 && !fused_gu) {
7356#else
7357    if (g_exp_phase != 2) {
7358#endif
7359#if defined(STRATA_HIP_GFX906)
7360    const bool lds_gu = (em0 == 5 || em0 == 6 || em0 == 7 || em0 == 8) && (L.gu_type == 18 || L.gu_type == 21 || L.gu_type == 22 || L.gu_type == 23);
7361    if (lds_gu) {
7362        const dim3 gl((unsigned) ((2 * L.n_ff + LDS_RB - 1) / LDS_RB), (unsigned) cap_groups);
7363        const size_t sh = (size_t) LDS_NT * (size_t) (L.n_embd / 32) * sizeof(block_q8_1);
7364        switch (L.gu_type) {
7365            case 18: if (em0 >= 7) native_gu_lds_kernel<18, 1, true><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else if (em0 == 6) native_gu_lds_kernel<18, 1><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else native_gu_lds_kernel<18, 0><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break;
7366            case 21: if (em0 >= 7) native_gu_lds_kernel<21, 1, true><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else if (em0 == 6) native_gu_lds_kernel<21, 1><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else native_gu_lds_kernel<21, 0><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break;
7367            case 23: if (em0 >= 7) native_gu_lds_kernel<23, 1, true><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else native_gu_lds_kernel<23, 1><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break;
7368            default: if (em0 >= 7) native_gu_lds_kernel<22, 1, true><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else if (em0 == 6) native_gu_lds_kernel<22, 1><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else native_gu_lds_kernel<22, 0><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break;
7369        }
7370    } else {
7371    const int em = exp_mode() >= 5 ? 2 : exp_mode();
7372    const dim3 ggu_amd((unsigned) ((2 * L.n_ff + (em == 1 ? 3 : em == 4 ? 31 : 15)) / (em == 1 ? 4 : em == 4 ? 32 : 16)), (unsigned) cap_groups);
7373#define STRATA_GU_AMD(T) \
7374    case T: if (em == 1) native_gu_amd_kernel<T, 1><<<ggu_amd, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); \
7375            else if (em == 4) native_gu_amd_kernel<T, 4><<<ggu_amd, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); \
7376            else native_gu_amd_kernel<T, 2><<<ggu_amd, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break;
7377    // the AMD layouts cover the IQ packs' gate/up types; Unsloth's Q4_K / Q5_K take the CUDA layout below
7378    const bool amd_gu = L.gu_type == 16 || L.gu_type == 17 || L.gu_type == 18 || L.gu_type == 21 || L.gu_type == 22 ||
7379                        L.gu_type == 23 || L.gu_type == 29 || L.gu_type == 42;
7380    if ((em == 1 || em == 2 || em == 4) && amd_gu) {
7381        switch (L.gu_type) {
7382            STRATA_GU_AMD(16) STRATA_GU_AMD(17) STRATA_GU_AMD(18) STRATA_GU_AMD(21) STRATA_GU_AMD(22) STRATA_GU_AMD(23)
7383            STRATA_GU_AMD(29) STRATA_GU_AMD(42)
7384        }
7385    } else
7386#undef STRATA_GU_AMD
7387#endif
7388    if(L.gu_type==16 && L.n_embd==2560 && L.n_ff==640 && !v1 && !g_old_kernels && !g_split_multi &&
7389       gu_lanes()==8 && grid_groups==0 && cap_groups==cap_entries && p16_enabled(s->get_device()) &&
7390       b60_next_iq_pool() && (((cap_entries==40) && (!b60_single_actor_requested()&&s->get_device()==static_cast<const sycl::device&>(dpct::get_device(0)))) || ((cap_entries==20) && (b60_single_actor_requested()||s->get_device()==static_cast<const sycl::device&>(dpct::get_device(1)))))) {
7391        launch_gu_xxs_s4(unsigned(gy),s,grp_ptr,grp_start,n_groups,ent_tok,X,L,gate,up);
7392    } else
7393    if(L.gu_type==22 && L.n_embd==2560 && L.n_ff==640 && !v1 && !g_old_kernels && !g_split_multi &&
7394       gu_lanes()==8 && grid_groups==0 && cap_groups==cap_entries && ps_enabled(s->get_device()) &&
7395       b60_next_iq_pool() && (((cap_entries==20) && (b60_single_actor_requested()||s->get_device()==static_cast<const sycl::device&>(dpct::get_device(1)))))) {
7396        launch_grid_s4_basis9<false,GuGridS4Basis9Kernel>(unsigned(gy),s,grp_ptr,grp_start,n_groups,ent_tok,X,L,gate,up);
7397    } else
7398    if(L.gu_type==22 && L.n_embd==2560 && L.n_ff==640 && !v1 && !g_old_kernels && !g_split_multi &&
7399       gu_lanes()==8 && grid_groups==0 && cap_groups==cap_entries && ps_enabled(s->get_device()) &&
7400       b60_next_iq_pool() && (((cap_entries==10 || cap_entries==20 || cap_entries==40) && (!b60_single_actor_requested()&&s->get_device()==static_cast<const sycl::device&>(dpct::get_device(0)))) || ((cap_entries==10 || cap_entries==40) && (b60_single_actor_requested()||s->get_device()==static_cast<const sycl::device&>(dpct::get_device(1)))))) {
7401        launch_grid_s4_wg16<false,GuGridS4WG16Kernel>(unsigned(gy),s,grp_ptr,grp_start,n_groups,ent_tok,X,L,gate,up);
7402    } else
7403    if(L.gu_type==22 && L.n_embd==2560 && L.n_ff==640 && !v1 && !g_old_kernels && !g_split_multi &&
7404       gu_lanes()==8 && grid_groups==0 && cap_groups==cap_entries && (cap_entries==10 || ((cap_entries==20 || cap_entries==40) && (!b60_single_actor_requested()&&s->get_device()==static_cast<const sycl::device&>(dpct::get_device(0))))) &&
7405       ps_enabled(s->get_device()) && grid_s4_enabled()) {
7406        launch_grid_s4<false,GuGridS4Kernel>(unsigned(gy),s,grp_ptr,grp_start,n_groups,ent_tok,X,L,gate,up);
7407    } else
7408    if(L.gu_type==22 && L.n_embd==2560 && L.n_ff==640 && !v1 && !g_old_kernels && !g_split_multi &&
7409       gu_lanes()==8 && grid_groups==0 && cap_groups==cap_entries && (cap_entries==20 || cap_entries==40) &&
7410       ps_enabled(s->get_device()) && grid64_enabled()) {
7411        launch_grid64<false,GuGrid64Kernel>(unsigned(gy),s,grp_ptr,grp_start,n_groups,ent_tok,X,L,gate,up);
7412    } else
7413    switch (L.gu_type) {
7414#define STRATA_GU(T) case T: launch_gu<T>(ggu, s, grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up, cap_entries <= 80); break;
7415        STRATA_GU_FMTS(STRATA_GU)
7416#undef STRATA_GU
7417        default: std::fprintf(stderr, "native_expert_grouped: gate/up type %d\n", L.gu_type); std::exit(1);
7418    }
7419#if defined(STRATA_HIP_GFX906)
7420    }
7421#endif
7422    check("native_expert_grouped/gu");
7423    const long long nh = (long long) cap_entries * L.n_ff;
7424#if defined(STRATA_HIP_GFX906)
7425    // gfx906: the separate SwiGLU and q8_1 passes stay the default (the A/B baseline); the RDNA one-pass
7426    // kernel (bitwise the same) with STRATA_HIP_SWIGLU_FUSED=1
7427    static const bool sw_fused = env_on("STRATA_HIP_SWIGLU_FUSED");
7428    const bool sw_v1 = v1 || !sw_fused;
7429#else
7430    const bool sw_v1 = v1;
7431#endif
7432    // APR: Hadamard-folded down weights take the rotated h, so h exists as floats first (the separate passes)
7433    if (sw_v1 || L.had_block > 0) {
7434            {
7435                auto exp_props = sycl::ext::oneapi::experimental::properties{
7436                    sycl::ext::oneapi::experimental::use_root_sync};
7437
7438                strata::kprof::kp(s, __FILE__, __func__, __LINE__)->template parallel_for<
7439                    dpct_kernel_name<class swiglu_entries_kernel_a4959c>>(
7440                    sycl::nd_range<3>(
7441                        sycl::range(1, 1, (unsigned)((nh + 255) / 256)) *
7442                            sycl::range(1, 1, 256),
7443                        sycl::range(1, 1, 256)),
7444                    exp_props, [=](sycl::nd_item<3> item_ct1) {
7445                        swiglu_entries_kernel(gate, up, h, nh);
7446                    });
7447            }
7448            if (L.had_block > 0)   // APR: the down weights are Hadamard-folded, so is their input (in place, every entry row)
7449                hadamard_rows(h, h, cap_entries, L.n_ff, L.had_block, L.d_signs, stream);
7450            {
7451                auto exp_props = sycl::ext::oneapi::experimental::properties{
7452                    sycl::ext::oneapi::experimental::use_root_sync};
7453                dpct::has_capability_or_fail(s->get_device(),
7454                                             {sycl::aspect::fp16});
7455
7456                strata::kprof::kp(s, __FILE__, __func__, __LINE__)->template parallel_for<
7457                    dpct_kernel_name<class quantize_q8_1_kernel_f68c59>>(
7458                    sycl::nd_range<3>(
7459                        sycl::range(1, 1, (unsigned)((nh + 255) / 256)) *
7460                            sycl::range(1, 1, 256),
7461                        sycl::range(1, 1, 256)),
7462                    exp_props,
7463                    [=](sycl::nd_item<3> item_ct1)
7464                        [[sycl::reqd_sub_group_size(32)]] {
7465                            quantize_q8_1_kernel(h, hq, nh);
7466                        });
7467            }
7468    } else {
7469            auto exp_props = sycl::ext::oneapi::experimental::properties{
7470                sycl::ext::oneapi::experimental::use_root_sync};
7471
7472            strata::kprof::kp(s, __FILE__, __func__, __LINE__)->template parallel_for<
7473                dpct_kernel_name<class swiglu_q8_1_entries_kernel_115291>>(
7474                sycl::nd_range<3>(
7475                    sycl::range(1, 1, (unsigned)((nh + 255) / 256)) *
7476                        sycl::range(1, 1, 256),
7477                    sycl::range(1, 1, 256)),
7478                exp_props,
7479                [=](sycl::nd_item<3> item_ct1)
7480                    [[sycl::reqd_sub_group_size(32)]] {
7481                        swiglu_q8_1_entries_kernel(gate, up, grp_start,
7482                                                   n_groups, (int)L.n_ff, hq);
7483                    });
7484    }
7485    check("native_expert_grouped/swiglu");
7486    }
7487    if (g_exp_phase == 1) return;
7488    const int d_rows = (!g_old_kernels && !g_no_sub16_gu && L.n_ff == 640) ? (L.d_type == 20 ? 32 : (L.d_type == 42 ? 16 : 8)) : 8;
7489    const dpct::dim3 gd((unsigned)((L.n_embd + d_rows - 1) / d_rows),
7490                        (unsigned)gy);
7491#if defined(STRATA_HIP_GFX906)
7492    if ((em0 == 7 || em0 == 8) && (L.d_type == 20 || L.d_type == 42)) {
7493        const dim3 gl((unsigned) ((L.n_embd + LDS_RB - 1) / LDS_RB), (unsigned) cap_groups);
7494        const size_t sh = (size_t) LDS_NT * (size_t) (L.n_ff / 32) * sizeof(block_q8_1);
7495        if (L.d_type == 20) native_down_lds_kernel<20><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out);
7496        else native_down_lds_kernel<42><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out);
7497        check("native_expert_grouped/down");
7498        return;
7499    }
7500    const int em = exp_mode() >= 5 ? 2 : exp_mode();
7501    const dim3 gd_amd((unsigned) ((L.n_embd + (em == 1 ? 3 : em == 4 ? 31 : 15)) / (em == 1 ? 4 : em == 4 ? 32 : 16)), (unsigned) cap_groups);
7502#define STRATA_D_AMD(T) \
7503    case T: if (em == 1) native_down_amd_kernel<T, 1><<<gd_amd, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); \
7504            else if (em == 4) native_down_amd_kernel<T, 4><<<gd_amd, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); \
7505            else native_down_amd_kernel<T, 2><<<gd_amd, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); break;
7506    // the AMD layouts cover the IQ packs' down types; the others (Unsloth's Q4_K / Q5_K / Q5_1 / Q8_0) take the
7507    // CUDA layout below
7508    if ((em == 1 || em == 2 || em == 4) && (L.d_type == 20 || L.d_type == 23 || L.d_type == 42)) {
7509        switch (L.d_type) {
7510            STRATA_D_AMD(20) STRATA_D_AMD(23) STRATA_D_AMD(42)
7511        }
7512    } else
7513#undef STRATA_D_AMD
7514#endif
7515    switch (L.d_type) {
7516#define STRATA_DOWN(T) case T: launch_down<T>(gd, s, grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); break;
7517        STRATA_D_FMTS(STRATA_DOWN)
7518#undef STRATA_DOWN
7519        default: std::fprintf(stderr, "native_expert_grouped: down type %d\n", L.d_type); std::exit(1);
7520    }
7521    check("native_expert_grouped/down");
7522}
7523
7524
7525// A770 port (STRATA_PF_XMX=2): a group of experts' products in ONE launch, the weight tiles decoded straight from
7526// the quantized blobs into local memory (no FP16 copy of the expert in global memory).  Sub-group 8, joint_matrix
7527// 8x8x16 (DG2), 256 GRF.  Per expert i of the group: Y_i = X_i . W_i^T, rows back to back (cnt[i] each).
7528// gate/up: up_i != nullptr, virtual row 2r = gate row r, 2r+1 = up row r (iq_dequant_gu_f16's interleave).
7529namespace xmxg {
7530// Sub-group width = the XMX tile N: 8 (DG2, 8x8x16) or 16 (Xe2, 8x16x16; CMake STRATA_XMX_SG16 for an AOT bmg / lnl build)
7531#ifdef STRATA_XMX_SG16
7532constexpr int kSgW = 16;
7533#else
7534constexpr int kSgW = 8;
7535#endif
7536namespace jm = sycl::ext::oneapi::experimental::matrix;
7537struct Grp {
7538    const uint8_t* a[kXmxGroupMax];
7539    const uint8_t* b[kXmxGroupMax];
7540    int off[kXmxGroupMax + 1];
7541    int tstart[kXmxGroupMax + 1];
7542    int n;
7543};
7544template <int SGM_, int SGN_, int MT_, int NT_>
7545struct Cfg {
7546    static constexpr int SGM = SGM_, SGN = SGN_, MT = MT_, NT = NT_, KS = 32, SG = kSgW;
7547    static constexpr int BM = SGM * MT * 8, BN = SGN * NT * kSgW, WG = SGM * SGN * kSgW;
7548};
7549template <class C, class Name>
7550void launch(sycl::queue& q, int ty, bool gu, const sycl::half* X, float* Y, const Grp& gp, int ntiles, int N, int K) {
7551    constexpr int BM = C::BM, BN = C::BN, KS = C::KS, WG = C::WG, SG = C::SG;
7552    constexpr int LDA = KS + 8, LDB = KS + 8;
7553    const int nb = N / BN;
7554#ifndef STRATA_NO_DG2_XMX
7555    constexpr int TN = kSgW;
7556    strata::kprof::kp(&q, __FILE__, __func__, __LINE__)->submit([&](sycl::handler& h) {
7557        sycl::local_accessor<sycl::half, 1> sa(BM * LDA, h), sb(BN * LDB, h);
7558        auto props = sycl::ext::oneapi::experimental::properties{sycl::ext::intel::experimental::grf_size<256>};
7559        h.parallel_for<Name>(sycl::nd_range<2>({(size_t) ntiles, (size_t) nb * WG}, {1, (size_t) WG}), props,
7560                             [=](sycl::nd_item<2> it) [[sycl::reqd_sub_group_size(kSgW)]] {
7561            auto sg = it.get_sub_group();
7562            const int t = (int) it.get_group(0);
7563            int e = 0;
7564            while (e + 1 < gp.n && t >= gp.tstart[e + 1]) ++e;
7565            const int m0 = (t - gp.tstart[e]) * BM;
7566            const int rows = sycl::min(BM, gp.off[e + 1] - gp.off[e] - m0);
7567            const sycl::half* Xe = X + ((size_t) gp.off[e] + m0) * K;
7568            float* Ye = Y + ((size_t) gp.off[e] + m0) * N;
7569            const uint8_t* wa = gp.a[e];
7570            const uint8_t* wb = gp.b[e];
7571            const int n0 = (int) it.get_group(1) * BN;
7572            const int lid = (int) it.get_local_id(1), sgid = lid / SG;
7573            const int sgm = sgid / C::SGN, sgn = sgid % C::SGN;
7574            jm::joint_matrix<sycl::sub_group, float, jm::use::accumulator, 8, TN> acc[C::MT][C::NT];
7575            for (int i = 0; i < C::MT; ++i)
7576                for (int j = 0; j < C::NT; ++j) jm::joint_matrix_fill(sg, acc[i][j], 0.0f);
7577            sycl::half* pa = sa.template get_multi_ptr<sycl::access::decorated::no>().get();
7578            sycl::half* pb = sb.template get_multi_ptr<sycl::access::decorated::no>().get();
7579            for (int k0 = 0; k0 < K; k0 += KS) {
7580                constexpr int VA = BM * KS / 8;
7581                for (int v = lid; v < VA; v += WG) {
7582                    const int r = v / (KS / 8), c = (v % (KS / 8)) * 8;
7583                    sycl::vec<sycl::half, 8> x(0);
7584                    if (r < rows) x = *reinterpret_cast<const sycl::vec<sycl::half, 8>*>(Xe + (size_t) r * K + k0 + c);
7585                    *reinterpret_cast<sycl::vec<sycl::half, 8>*>(pa + r * LDA + c) = x;
7586                }
7587                // B: row r of the tile, 32 values from k0 = 4 runs of 8, each one thread of the format's decoder
7588                for (int v = lid; v < BN * 4; v += WG) {
7589                    const int r = v >> 2, sub = v & 3, nr = n0 + r;
7590                    const uint8_t* base = gu ? ((nr & 1) ? wb : wa) : wa;
7591                    const int64_t row = gu ? (nr >> 1) : nr;
7592                    const int64_t flat = row * K + k0;            // a multiple of 32
7593                    const int64_t ibs = flat >> 8;
7594                    const int o32 = (int) (flat & 255), o = o32 + 8 * sub;
7595                    // the decoder thread that writes values [o, o + 8) of the superblock: the IQ2/IQ3/IQ4_NL/IQ1_M and
7596                    // Q2_0 decoders write [8 tid, 8 tid + 8) (coalesced runs); IQ4_XS and the rest keep the
7597                    // (sub-run, 32-block) split
7598                    // (the trellis decoder thread tid writes values [8 tid, 8 tid + 8) of the 256-value call as well)
7599                    const bool run8 = ty == 16 || ty == 17 || ty == 18 || ty == 20 || ty == 21 || ty == 22 ||
7600                                      ty == 29 || ty == 42 || ty == 144 || ty == 145 || ty == 146;
7601                    const int tid = run8 ? (o >> 3) : (sub * 8 + (o32 >> 5));
7602                    dq_dispatch<sycl::half>(ty, base, ibs, pb + r * LDB - o32, tid);
7603                }
7604                it.barrier(sycl::access::fence_space::local_space);
7605                for (int kk = 0; kk < KS; kk += 16) {
7606                    jm::joint_matrix<sycl::sub_group, sycl::half, jm::use::a, 8, 16, jm::layout::row_major> am[C::MT];
7607                    jm::joint_matrix<sycl::sub_group, sycl::half, jm::use::b, 16, TN, jm::layout::col_major> bm[C::NT];
7608                    for (int i = 0; i < C::MT; ++i)
7609                        jm::joint_matrix_load(sg, am[i], sa.template get_multi_ptr<sycl::access::decorated::no>() +
7610                                                             (sgm * C::MT * 8 + i * 8) * LDA + kk, LDA);
7611                    for (int j = 0; j < C::NT; ++j)
7612                        jm::joint_matrix_load(sg, bm[j], sb.template get_multi_ptr<sycl::access::decorated::no>() +
7613                                                             (sgn * C::NT * TN + j * TN) * LDB + kk, LDB);
7614                    for (int i = 0; i < C::MT; ++i)
7615                        for (int j = 0; j < C::NT; ++j) jm::joint_matrix_mad(sg, acc[i][j], am[i], bm[j], acc[i][j]);
7616                }
7617                it.barrier(sycl::access::fence_space::local_space);
7618            }
7619            for (int i = 0; i < C::MT; ++i) {
7620                const int r = sgm * C::MT * 8 + i * 8;
7621                if (r >= rows) continue;
7622                for (int j = 0; j < C::NT; ++j) {
7623                    const int c = n0 + sgn * C::NT * TN + j * TN;
7624                    if (r + 8 <= rows) {
7625                        jm::joint_matrix_store(sg, acc[i][j],
7626                            sycl::address_space_cast<sycl::access::address_space::global_space, sycl::access::decorated::no>(
7627                                Ye + (size_t) r * N + c), N, jm::layout::row_major);
7628                    } else {
7629                        float* st = reinterpret_cast<float*>(pa) + sgid * 8 * TN;
7630                        jm::joint_matrix_store(sg, acc[i][j],
7631                            sycl::address_space_cast<sycl::access::address_space::local_space, sycl::access::decorated::no>(st),
7632                            TN, jm::layout::row_major);
7633                        sycl::group_barrier(sg);
7634                        const int lim = rows - r, ln = (int) sg.get_local_linear_id();
7635                        for (int rr = 0; rr < lim; ++rr) Ye[(size_t) (r + rr) * N + c + ln] = st[rr * TN + ln];
7636                        sycl::group_barrier(sg);
7637                    }
7638                }
7639            }
7640        });
7641    });
7642#else
7643    (void) q; (void) X; (void) Y; (void) gp; (void) ntiles; (void) N; (void) K;
7644    std::fprintf(stderr, "grouped XMX: the 8x8x16 / sub-group 8 kernel is not built for this device (STRATA_NO_DG2_XMX)\n");
7645    std::exit(1);
7646#endif
7647}
7648class k_xg_small; class k_xg_big;
7649#ifdef STRATA_XMX_SG16
7650using Small = Cfg<2, 4, 4, 2>;   // 64 x 128 (8 sub-groups of 16)
7651using Big = Cfg<4, 2, 4, 4>;     // 128 x 128
7652#else
7653using Small = Cfg<2, 8, 4, 2>;   // 64 x 128
7654using Big = Cfg<4, 4, 4, 4>;     // 128 x 128
7655#endif
7656template <class C>
7657int fill(Grp& gp, const int32_t* cnt, int n) {
7658    int t = 0, o = 0;
7659    for (int i = 0; i < n; ++i) { gp.off[i] = o; gp.tstart[i] = t; o += cnt[i]; t += (cnt[i] + C::BM - 1) / C::BM; }
7660    gp.off[n] = o; gp.tstart[n] = t; gp.n = n;
7661    return t;
7662}
7663}  // namespace xmxg
7664
7665void iq_xmx_grouped(int ty, const uint8_t* const* a, const uint8_t* const* b, const int32_t* cnt, int n,
7666                    const uint16_t* X, float* Y, int N, int K, void* stream) {
7667    if (n <= 0) return;
7668    if (n > kXmxGroupMax || N % 128 != 0 || K % 32 != 0 || !is_iq(ty)) {
7669        std::fprintf(stderr, "iq_xmx_grouped: bad arguments (type %d, n %d, N %d, K %d)\n", ty, n, N, K);
7670        std::exit(1);
7671    }
7672    xmxg::Grp gp{};
7673    int64_t tot = 0;
7674    for (int i = 0; i < n; ++i) { gp.a[i] = a[i]; gp.b[i] = b ? b[i] : nullptr; tot += cnt[i]; }
7675    if (tot <= 0) return;
7676    sycl::queue& q = *strata::q_of(stream);
7677    const auto* Xh = reinterpret_cast<const sycl::half*>(X);
7678    const bool gu = b != nullptr;
7679    if (tot / n < 96) {
7680        const int nt = xmxg::fill<xmxg::Small>(gp, cnt, n);
7681        xmxg::launch<xmxg::Small, xmxg::k_xg_small>(q, ty, gu, Xh, Y, gp, nt, N, K);
7682    } else {
7683        const int nt = xmxg::fill<xmxg::Big>(gp, cnt, n);
7684        xmxg::launch<xmxg::Big, xmxg::k_xg_big>(q, ty, gu, Xh, Y, gp, nt, N, K);
7685    }
7686    check("iq_xmx_grouped");
7687}
7688
7689
7690// ================================================================ SYCL port: XMX GEMM straight from the quantized rows
7691//
7692// The prompt path dequantizes every routed expert to FP16 (8 MB written, then read back by oneMKL) before its GEMMs:
7693// 39-41% of the prompt time on the B70 (2026-09-30), the GEMMs themselves another 16%. This kernel dequantizes a
7694// 16-feature strip of the weight matrix into local memory, packs it for the XMX B operand and multiplies it against
7695// every activation row with joint_matrix (16x16x16, FP16 in, FP32 out; sub-group 16 as XMX wants). The FP16 weights
7696// never touch global memory.
7697//
7698//   Y[M][n_out] = X[M][K] . W[n_out][K]^T      X FP16 row-major (lda K), Y FP32 (ldy), W quantized rows (a ggml IQ type)
7699//
7700// Gate/up: `up != nullptr`, virtual row 2r = gate row r, 2r+1 = up row r (the order iq_dequant_gu_f16 produces, which
7701// swiglu_interleaved expects). K must be a multiple of 256 (a QK_K block per slab) or the whole row must fit a slab
7702// (K = 640: 16 rows are 40 blocks, block-aligned since 16 * 640 / 256 = 40).
7703namespace xmx {
7704namespace jm = sycl::ext::oneapi::experimental::matrix;
7705constexpr int SG = 16;                 // XMX sub-group size
7706constexpr int NSG = 8;                 // sub-groups per work-group
7707constexpr int WG = SG * NSG;
7708constexpr int NT = 16;                 // features per work-group: one B tile
7709constexpr int MAXT = 4;                // C tiles per sub-group -> 512 rows per chunk
7710constexpr int APAD = 8;                // halves of padding on the staged A tile rows
7711struct Src { const uint8_t* gate; const uint8_t* up; int ty; int64_t per_row; };
7712struct Smem { sycl::half* stage; sycl::half* packed; sycl::half* atile; float* ctile; };
7713
7714// the block index (x[ibs] in dq_dispatch) of virtual row v's k-range [k0, k0 + 256) - rows are per_row blocks long
7715__dpct_inline__ const void* block_of(const Src& s, int v, int cblk, int64_t& ibs) {
7716    if (s.up != nullptr) { ibs = (int64_t) (v >> 1) * s.per_row + cblk; return (v & 1) ? s.up : s.gate; }
7717    ibs = (int64_t) v * s.per_row + cblk;
7718    return s.gate;
7719}
7720
7721// one work-group: features [f0, f0 + 16) of the weight matrix against all M rows; slab_k halves of K per pass
7722void gemm_kernel(Src src, const sycl::half* X, int K, int slab_k, float* Y, int64_t ldy, int M, int n_out, Smem sm) {
7723    auto it = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
7724    auto sg = it.get_sub_group();
7725    const int sgid = (int) sg.get_group_id()[0], lane = (int) sg.get_local_id()[0], t = (int) it.get_local_id(2);
7726    const int f0 = (int) it.get_group(2) * NT;
7727    const int per_slab = slab_k / 256;                    // blocks of one row per slab (K % 256 == 0), or
7728    const int whole = (slab_k == K) ? 1 : 0;              // the whole 16-row strip as NT * K / 256 flat blocks
7729    const int nblk = whole ? NT * K / 256 : NT * per_slab;
7730    auto gptr = [](auto* p) { return sycl::address_space_cast<sycl::access::address_space::global_space, sycl::access::decorated::no>(p); };
7731    auto lptr = [](auto* p) { return sycl::address_space_cast<sycl::access::address_space::local_space, sycl::access::decorated::no>(p); };
7732    sycl::half* atile = sm.atile + (size_t) sgid * 16 * (16 + APAD);
7733    float* ctile = sm.ctile + (size_t) sgid * 256;
7734    for (int m_base = 0; m_base < M; m_base += MAXT * NSG * 16) {
7735        jm::joint_matrix<sycl::sub_group, float, jm::use::accumulator, 16, 16> C[MAXT];
7736#pragma unroll
7737        for (int k = 0; k < MAXT; ++k) jm::joint_matrix_fill(sg, C[k], 0.0f);
7738        const int tiles = std::min((M - m_base + 15) / 16, MAXT * NSG);
7739        for (int k0 = 0; k0 < K; k0 += slab_k) {
7740            it.barrier(sycl::access::fence_space::local_space);
7741            // dequantize the strip's blocks of this slab into stage[NT][slab_k] (flat, row-major): 32 "threads" per
7742            // block in dq_dispatch's terms, two calls per lane
7743            for (int b = sgid; b < nblk; b += NSG) {
7744                int v, kk;
7745                if (whole) { v = (b * 256) / K; kk = (b * 256) % K; }
7746                else { v = b / per_slab; kk = (b % per_slab) * 256; }
7747                sycl::half* dst = sm.stage + (size_t) v * slab_k + kk;
7748                const int row = f0 + v;
7749                if (row < n_out) {
7750                    int64_t ibs;
7751                    const void* blk = src.gate;
7752                    if (whole) ibs = ((int64_t) f0 * K) / 256 + b;   // flat blocks of the [n_out][K] matrix
7753                    else blk = block_of(src, row, k0 / 256 + b % per_slab, ibs);
7754                    dq_dispatch<sycl::half>(src.ty, blk, ibs, dst, lane);
7755                    dq_dispatch<sycl::half>(src.ty, blk, ibs, dst, lane + 16);
7756                } else {
7757                    for (int i = lane; i < 256; i += SG) dst[i] = sycl::half(0.0f);
7758                }
7759            }
7760            it.barrier(sycl::access::fence_space::local_space);
7761            // pack for the XMX B operand: element (k, n) at packed[(k / 2) * (NT * 2) + n * 2 + (k & 1)]
7762            for (int i = t; i < NT * slab_k; i += WG) {
7763                const int n = i / slab_k, k = i - n * slab_k;
7764                sm.packed[(k >> 1) * (NT * 2) + n * 2 + (k & 1)] = sm.stage[i];
7765            }
7766            it.barrier(sycl::access::fence_space::local_space);
7767            for (int ks = 0; ks < slab_k; ks += 16) {
7768                jm::joint_matrix<sycl::sub_group, sycl::half, jm::use::b, 16, 16, jm::layout::ext_intel_packed> B;
7769                jm::joint_matrix_load(sg, B, lptr(sm.packed + (ks >> 1) * (NT * 2)), NT * 2);
7770#pragma unroll
7771                for (int tt = 0; tt < MAXT; ++tt) {
7772                    const int tile = sgid + tt * NSG;
7773                    if (tile >= tiles) break;
7774                    const int m0 = m_base + tile * 16;
7775                    jm::joint_matrix<sycl::sub_group, sycl::half, jm::use::a, 16, 16, jm::layout::row_major> A;
7776                    if (m0 + 16 <= M) {
7777                        jm::joint_matrix_load(sg, A, gptr(X + (size_t) m0 * K + k0 + ks), (size_t) K);
7778                    } else {   // the tail tile: valid rows staged, the rest zero
7779                        for (int i = lane; i < 16 * 16; i += SG) {
7780                            const int r = i >> 4, c = i & 15;
7781                            atile[r * (16 + APAD) + c] = (m0 + r < M) ? X[(size_t) (m0 + r) * K + k0 + ks + c] : sycl::half(0.0f);
7782                        }
7783                        sycl::group_barrier(sg);
7784                        jm::joint_matrix_load(sg, A, lptr(atile), (size_t) (16 + APAD));
7785                        sycl::group_barrier(sg);
7786                    }
7787                    jm::joint_matrix_mad(sg, C[tt], A, B, C[tt]);
7788                }
7789            }
7790        }
7791        // the chunk's results
7792#pragma unroll
7793        for (int tt = 0; tt < MAXT; ++tt) {
7794            const int tile = sgid + tt * NSG;
7795            if (tile >= tiles) break;
7796            const int m0 = m_base + tile * 16;
7797            if (m0 + 16 <= M && f0 + NT <= n_out) {
7798                jm::joint_matrix_store(sg, C[tt], gptr(Y + (size_t) m0 * ldy + f0), (size_t) ldy, jm::layout::row_major);
7799            } else {
7800                jm::joint_matrix_store(sg, C[tt], lptr(ctile), (size_t) 16, jm::layout::row_major);
7801                sycl::group_barrier(sg);
7802                for (int i = lane; i < 256; i += SG) {
7803                    const int r = i >> 4, c = i & 15;
7804                    if (m0 + r < M && f0 + c < n_out) Y[(size_t) (m0 + r) * ldy + f0 + c] = ctile[i];
7805                }
7806                sycl::group_barrier(sg);
7807            }
7808        }
7809    }
7810}
7811}  // namespace xmx
7812
7813bool xmx_gemm_iq(int ty, const void* gate, const void* up, int64_t K, int n_out, const uint16_t* X, int M, float* Y,
7814                 int64_t ldy, void* stream) {
7815    if (!is_iq(ty) || ty == 16 || ty == 17 || ty == 29 || ty == 23 || ty == 11) return false;   // dq_dispatch covers these; the rest untested here
7816    if (M <= 0 || n_out <= 0 || n_out % xmx::NT != 0 || K <= 0) return false;
7817    const bool by_block = (K % 256) == 0;
7818    const bool whole = !by_block && ((int64_t) xmx::NT * K) % 256 == 0 && K % 16 == 0;
7819    if (!by_block && !whole) return false;
7820    const int slab_k = by_block ? 256 : (int) K;
7821    if (up != nullptr && !by_block) return false;   // gate/up rows are per_row blocks each
7822    const size_t stage_halves = (size_t) xmx::NT * slab_k;
7823    const size_t bytes = stage_halves * 2 /*stage*/ + stage_halves * 2 /*packed*/ + (size_t) xmx::NSG * 16 * (16 + xmx::APAD) * 2 +
7824                         (size_t) xmx::NSG * 256 * 4;
7825    if (bytes > 96 * 1024) return false;
7826    dpct::queue_ptr q = strata::q_of(stream);
7827    xmx::Src src{(const uint8_t*) gate, (const uint8_t*) up, ty, by_block ? K / 256 : 0};
7828    const int groups = n_out / xmx::NT;
7829    strata::kprof::kp(q, __FILE__, __func__, __LINE__)->submit([&](sycl::handler& cgh) {
7830        sycl::local_accessor<uint8_t, 1> slm(sycl::range<1>(bytes), cgh);
7831        cgh.parallel_for(
7832            sycl::nd_range<3>(sycl::range<3>(1, 1, (size_t) groups * xmx::WG), sycl::range<3>(1, 1, xmx::WG)),
7833            [=](sycl::nd_item<3>) [[sycl::reqd_sub_group_size(16)]] {
7834                uint8_t* base = slm.get_multi_ptr<sycl::access::decorated::no>().get();
7835                xmx::Smem sm;
7836                sm.stage = (sycl::half*) base;
7837                sm.packed = sm.stage + stage_halves;
7838                sm.atile = sm.packed + stage_halves;
7839                sm.ctile = (float*) (sm.atile + (size_t) xmx::NSG * 16 * (16 + xmx::APAD));
7840                xmx::gemm_kernel(src, (const sycl::half*) X, (int) K, slab_k, Y, ldy, M, n_out, sm);
7841            });
7842    });
7843    return true;
7844}
7845}  // namespace strata::kernels
7846
7847namespace strata::kernels {
7848namespace {
7849constexpr int kExpertStageMaxGroups = 16;
7850class ExpertStagePlan;
7851class ExpertStageCopy;
7852struct ExpertStageMetadata {
7853    unsigned long long* pointers;
7854    int32_t *starts, *groups, *tokens, *destinations;
7855};
7856ExpertStageMetadata stage_metadata(void* scratch, int64_t cap, int64_t ff) {
7857    const size_t floats = ((size_t)cap * ff * sizeof(float) + 255) & ~size_t(255);
7858    // The original v2 path does not use its third float array.
7859    // 16 pointers + 17 starts + count + two cap-entry maps fit far below cap*640 floats.
7860    auto* base = static_cast<uint8_t*>(scratch) + 2 * floats;
7861    auto* pointers = reinterpret_cast<unsigned long long*>(base);
7862    auto* starts = reinterpret_cast<int32_t*>(pointers + kExpertStageMaxGroups);
7863    auto* groups = starts + kExpertStageMaxGroups + 1;
7864    auto* tokens = groups + 1;
7865    return {pointers, starts, groups, tokens, tokens + cap};
7866}
7867void prepare_expert_stage(sycl::queue& q, const unsigned long long* pointers,
7868                         const int32_t* starts, const int32_t* groups,
7869                         const int32_t* destinations, const int32_t* tokens,
7870                         int begin, int batch, int capacity, ExpertStageMetadata meta) {
7871    auto properties = sycl::ext::oneapi::experimental::properties{
7872        sycl::ext::oneapi::experimental::use_root_sync};
7873    q.parallel_for<ExpertStagePlan>(sycl::nd_range<1>(256,256), properties,
7874        [=](sycl::nd_item<1> item) [[sycl::reqd_sub_group_size(32)]] {
7875            const int tid = item.get_local_linear_id();
7876            const int remaining = *groups - begin;
7877            const int count = remaining > 0 ? sycl::min(remaining,batch) : 0;
7878            if (tid == 0) {
7879                *meta.groups = count;
7880                if (count == 0) meta.starts[0] = 0;
7881            }
7882            if (count == 0) return;
7883            const int first = starts[begin], end = starts[begin+count];
7884            if (tid < count) {
7885                meta.pointers[tid] = pointers[begin+tid];
7886                meta.starts[tid] = starts[begin+tid] - first;
7887            }
7888            if (tid == count) meta.starts[count] = end - first;
7889            if (tid < end-first && tid < capacity) {
7890                meta.tokens[tid] = tokens[first+tid];
7891                meta.destinations[tid] = destinations[first+tid];
7892            }
7893        });
7894}
7895void copy_expert_stage_tiled(sycl::queue& q, const unsigned long long* pointers,
7896                            const int32_t* groups, uint8_t* workspace,
7897                            size_t blob_bytes, int batch) {
7898    const size_t words = blob_bytes / 16;
7899    const size_t rounded = (words + 255) & ~size_t(255);
7900    auto properties = sycl::ext::oneapi::experimental::properties{
7901        sycl::ext::oneapi::experimental::use_root_sync};
7902    q.parallel_for<ExpertStageCopy>(
7903        sycl::nd_range<3>(sycl::range<3>(1,batch,rounded),sycl::range<3>(1,1,256)),
7904        properties, [=](sycl::nd_item<3> item) [[sycl::reqd_sub_group_size(32)]] {
7905            const int group = item.get_group(1);
7906            if (group >= *groups) return;
7907            const size_t word = item.get_global_id(2);
7908            if (word >= words) return;
7909            const auto* source = reinterpret_cast<const uint32_t*>(pointers[group]);
7910            auto* target = reinterpret_cast<uint32_t*>(workspace + size_t(group)*blob_bytes);
7911            sycl::vec<uint32_t,4> value;
7912            value.load(word,source); value.store(word,target);
7913        });
7914}
7915bool stage_layout(const NativeExpertLayout& l) {
7916    if (l.n_embd != 2560 || l.n_ff != 640 || l.d_type != 42 || l.d_row != 180) return false;
7917    const size_t row = l.gu_type == 16 ? 660 : l.gu_type == 22 ? 820 : l.gu_type == 29 ? 560 : 0;
7918    return row != 0 && l.gu_row == row && l.up_off == 640*row &&
7919           l.down_off == 2*l.up_off && l.bytes == l.down_off + 2560*180 &&
7920           l.bytes % 16 == 0;
7921}
7922} // namespace
7923
7924void native_expert_grouped_staged(
7925    const NativeExpertLayout& l, const unsigned long long* pointers,
7926    const int32_t* starts, const int32_t* groups, const int32_t* destinations,
7927    const int32_t* tokens, int64_t cap_groups, int64_t cap_entries,
7928    const void* x_q8_1, void* scratch, float* output, void* stream,
7929    void* workspace, size_t workspace_bytes, int max_batch_groups, int copy_mode) {
7930    auto* q = strata::q_of(stream);
7931    if (!stage_layout(l) || g_grouped_v1 || cap_groups <= 0 || cap_groups > 80 ||
7932        cap_entries <= 0 || cap_entries > 80 || !workspace ||
7933        (reinterpret_cast<uintptr_t>(scratch) & 15) ||
7934        (reinterpret_cast<uintptr_t>(workspace) & 15) ||
7935        !q->has_property<sycl::property::queue::in_order>() ||
7936        max_batch_groups < 1 || max_batch_groups > kExpertStageMaxGroups ||
7937        workspace_bytes < l.bytes) {
7938        native_expert_grouped(l,pointers,starts,groups,destinations,tokens,
7939                             cap_groups,cap_entries,x_q8_1,scratch,output,stream);
7940        return;
7941    }
7942    const int batch = int(std::min<size_t>(size_t(max_batch_groups), workspace_bytes/l.bytes));
7943    auto meta = stage_metadata(scratch,cap_entries,l.n_ff);
7944    for (int first = 0; first < cap_groups; first += batch) {
7945        prepare_expert_stage(*q,pointers,starts,groups,destinations,tokens,
7946                             first,batch,(int)cap_entries,meta);
7947        if (copy_mode == 0)
7948            fetch_blobs(meta.pointers,meta.groups,static_cast<uint8_t*>(workspace),
7949                        (int64_t)l.bytes,batch,stream);
7950        else
7951            copy_expert_stage_tiled(*q,meta.pointers,meta.groups,
7952                                   static_cast<uint8_t*>(workspace),l.bytes,batch);
7953        rebase_ptrs(meta.pointers,meta.groups,static_cast<uint8_t*>(workspace),
7954                    (int64_t)l.bytes,stream);
7955        native_expert_grouped(l,meta.pointers,meta.starts,meta.groups,
7956                             meta.destinations,meta.tokens,cap_groups,cap_entries,
7957                             x_q8_1,scratch,output,stream,std::min<int64_t>(batch,cap_groups));
7958    }
7959}
7960} // namespace strata::kernels